[WinEH] Add some support for code generating catchpad
[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
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
168     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
169   } else if (!Subtarget->useSoftFloat()) {
170     // We have an algorithm for SSE2->double, and we turn this into a
171     // 64-bit FILD followed by conditional FADD for other targets.
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173     // We have an algorithm for SSE2, and we turn this into a 64-bit
174     // FILD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
176   }
177
178   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
179   // this operation.
180   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
181   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
182
183   if (!Subtarget->useSoftFloat()) {
184     // SSE has no i16 to fp conversion, only i32
185     if (X86ScalarSSEf32) {
186       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
187       // f32 and f64 cases are Legal, f80 case is not
188       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
189     } else {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     }
193   } else {
194     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
195     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
196   }
197
198   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
199   // are Legal, f80 is custom lowered.
200   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
201   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (X86ScalarSSEf32) {
209     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
210     // f32 and f64 cases are Legal, f80 case is not
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
212   } else {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   }
216
217   // Handle FP_TO_UINT by promoting the destination to a larger signed
218   // conversion.
219   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
220   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
221   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
222
223   if (Subtarget->is64Bit()) {
224     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
227       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
228     } else {
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
231     }
232   } else if (!Subtarget->useSoftFloat()) {
233     // Since AVX is a superset of SSE3, only check for SSE here.
234     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235       // Expand FP_TO_UINT into a select.
236       // FIXME: We would like to use a Custom expander here eventually to do
237       // the optimal thing for SSE vs. the default expansion in the legalizer.
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
239     else
240       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
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     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
246   }
247
248   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249   if (!X86ScalarSSEf64) {
250     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
251     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
252     if (Subtarget->is64Bit()) {
253       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
254       // Without SSE, i64->f64 goes through memory.
255       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
256     }
257   }
258
259   // Scalar integer divide and remainder are lowered to use operations that
260   // produce two results, to match the available instructions. This exposes
261   // the two-result form to trivial CSE, which is able to combine x/y and x%y
262   // into a single instruction.
263   //
264   // Scalar integer multiply-high is also lowered to use two-result
265   // operations, to match the available instructions. However, plain multiply
266   // (low) operations are left as Legal, as there are single-result
267   // instructions for this in x86. Using the two-result multiply instructions
268   // when both high and low results are needed must be arranged by dagcombine.
269   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
270     MVT VT = IntVTs[i];
271     setOperationAction(ISD::MULHS, VT, Expand);
272     setOperationAction(ISD::MULHU, VT, Expand);
273     setOperationAction(ISD::SDIV, VT, Expand);
274     setOperationAction(ISD::UDIV, VT, Expand);
275     setOperationAction(ISD::SREM, VT, Expand);
276     setOperationAction(ISD::UREM, VT, Expand);
277
278     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279     setOperationAction(ISD::ADDC, VT, Custom);
280     setOperationAction(ISD::ADDE, VT, Custom);
281     setOperationAction(ISD::SUBC, VT, Custom);
282     setOperationAction(ISD::SUBE, VT, Custom);
283   }
284
285   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
286   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
287   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
288   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
289   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
291   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
294   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
295   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
301   if (Subtarget->is64Bit())
302     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
304   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
306   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
307   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
308   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
309   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
310   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
311
312   // Promote the i8 variants and force them on up to i32 which has a shorter
313   // encoding.
314   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
315   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
316   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
317   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
318   if (Subtarget->hasBMI()) {
319     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
320     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
321     if (Subtarget->is64Bit())
322       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
323   } else {
324     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
325     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
326     if (Subtarget->is64Bit())
327       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
328   }
329
330   if (Subtarget->hasLZCNT()) {
331     // When promoting the i8 variants, force them to i32 for a shorter
332     // encoding.
333     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
334     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
335     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
336     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
337     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
338     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
339     if (Subtarget->is64Bit())
340       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
341   } else {
342     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
343     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
344     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
348     if (Subtarget->is64Bit()) {
349       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
350       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
351     }
352   }
353
354   // Special handling for half-precision floating point conversions.
355   // If we don't have F16C support, then lower half float conversions
356   // into library calls.
357   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
358     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
359     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
360   }
361
362   // There's never any support for operations beyond MVT::f32.
363   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
364   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
365   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
366   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
367
368   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
369   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
370   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
371   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
372   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
374
375   if (Subtarget->hasPOPCNT()) {
376     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
377   } else {
378     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
379     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
380     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
381     if (Subtarget->is64Bit())
382       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
383   }
384
385   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
386
387   if (!Subtarget->hasMOVBE())
388     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
389
390   // These should be promoted to a larger select which is supported.
391   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
392   // X86 wants to expand cmov itself.
393   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
394   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
395   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
396   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
397   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
398   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
399   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
400   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
401   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
402   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
403   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
404   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
405   if (Subtarget->is64Bit()) {
406     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
407     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
408   }
409   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
410   setOperationAction(ISD::CATCHRET        , MVT::Other, Custom);
411   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
412   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
413   // support continuation, user-level threading, and etc.. As a result, no
414   // other SjLj exception interfaces are implemented and please don't build
415   // your own exception handling based on them.
416   // LLVM/Clang supports zero-cost DWARF exception handling.
417   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
418   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
419
420   // Darwin ABI issue.
421   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
422   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
423   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
424   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
425   if (Subtarget->is64Bit())
426     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
427   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
428   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
429   if (Subtarget->is64Bit()) {
430     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
431     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
432     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
433     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
434     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
435   }
436   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
437   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
438   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
439   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
440   if (Subtarget->is64Bit()) {
441     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
442     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
443     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
444   }
445
446   if (Subtarget->hasSSE1())
447     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
448
449   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
450
451   // Expand certain atomics
452   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
453     MVT VT = IntVTs[i];
454     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
455     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
456     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
457   }
458
459   if (Subtarget->hasCmpxchg16b()) {
460     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
461   }
462
463   // FIXME - use subtarget debug flags
464   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
465       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
466     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
467   }
468
469   if (Subtarget->isTarget64BitLP64()) {
470     setExceptionPointerRegister(X86::RAX);
471     setExceptionSelectorRegister(X86::RDX);
472   } else {
473     setExceptionPointerRegister(X86::EAX);
474     setExceptionSelectorRegister(X86::EDX);
475   }
476   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
477   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
478
479   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
480   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
481
482   setOperationAction(ISD::TRAP, MVT::Other, Legal);
483   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
484
485   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
486   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
487   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
488   if (Subtarget->is64Bit()) {
489     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
490     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
491   } else {
492     // TargetInfo::CharPtrBuiltinVaList
493     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
495   }
496
497   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
498   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
499
500   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
501
502   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
503   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
504   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
505
506   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
507     // f32 and f64 use SSE.
508     // Set up the FP register classes.
509     addRegisterClass(MVT::f32, &X86::FR32RegClass);
510     addRegisterClass(MVT::f64, &X86::FR64RegClass);
511
512     // Use ANDPD to simulate FABS.
513     setOperationAction(ISD::FABS , MVT::f64, Custom);
514     setOperationAction(ISD::FABS , MVT::f32, Custom);
515
516     // Use XORP to simulate FNEG.
517     setOperationAction(ISD::FNEG , MVT::f64, Custom);
518     setOperationAction(ISD::FNEG , MVT::f32, Custom);
519
520     // Use ANDPD and ORPD to simulate FCOPYSIGN.
521     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
522     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
523
524     // Lower this to FGETSIGNx86 plus an AND.
525     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
526     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
527
528     // We don't support sin/cos/fmod
529     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
530     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
531     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
532     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
533     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
534     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
535
536     // Expand FP immediates into loads from the stack, except for the special
537     // cases we handle.
538     addLegalFPImmediate(APFloat(+0.0)); // xorpd
539     addLegalFPImmediate(APFloat(+0.0f)); // xorps
540   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
541     // Use SSE for f32, x87 for f64.
542     // Set up the FP register classes.
543     addRegisterClass(MVT::f32, &X86::FR32RegClass);
544     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
545
546     // Use ANDPS to simulate FABS.
547     setOperationAction(ISD::FABS , MVT::f32, Custom);
548
549     // Use XORP to simulate FNEG.
550     setOperationAction(ISD::FNEG , MVT::f32, Custom);
551
552     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
553
554     // Use ANDPS and ORPS to simulate FCOPYSIGN.
555     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
556     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
557
558     // We don't support sin/cos/fmod
559     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
560     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
561     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
562
563     // Special cases we handle for FP constants.
564     addLegalFPImmediate(APFloat(+0.0f)); // xorps
565     addLegalFPImmediate(APFloat(+0.0)); // FLD0
566     addLegalFPImmediate(APFloat(+1.0)); // FLD1
567     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
568     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
569
570     if (!TM.Options.UnsafeFPMath) {
571       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
572       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
573       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
574     }
575   } else if (!Subtarget->useSoftFloat()) {
576     // f32 and f64 in x87.
577     // Set up the FP register classes.
578     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
579     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
580
581     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
582     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
583     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
584     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
585
586     if (!TM.Options.UnsafeFPMath) {
587       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
588       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
589       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
590       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
591       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
592       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
593     }
594     addLegalFPImmediate(APFloat(+0.0)); // FLD0
595     addLegalFPImmediate(APFloat(+1.0)); // FLD1
596     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
597     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
598     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
602   }
603
604   // We don't support FMA.
605   setOperationAction(ISD::FMA, MVT::f64, Expand);
606   setOperationAction(ISD::FMA, MVT::f32, Expand);
607
608   // Long double always uses X87.
609   if (!Subtarget->useSoftFloat()) {
610     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
611     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
612     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
613     {
614       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
615       addLegalFPImmediate(TmpFlt);  // FLD0
616       TmpFlt.changeSign();
617       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
618
619       bool ignored;
620       APFloat TmpFlt2(+1.0);
621       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
622                       &ignored);
623       addLegalFPImmediate(TmpFlt2);  // FLD1
624       TmpFlt2.changeSign();
625       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
626     }
627
628     if (!TM.Options.UnsafeFPMath) {
629       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
630       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
631       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
632     }
633
634     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
635     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
636     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
637     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
638     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
639     setOperationAction(ISD::FMA, MVT::f80, Expand);
640   }
641
642   // Always use a library call for pow.
643   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
644   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
645   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
646
647   setOperationAction(ISD::FLOG, MVT::f80, Expand);
648   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
649   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
650   setOperationAction(ISD::FEXP, MVT::f80, Expand);
651   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
652   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
653   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
654
655   // First set operation action for all vector types to either promote
656   // (for widening) or expand (for scalarization). Then we will selectively
657   // turn on ones that can be effectively codegen'd.
658   for (MVT VT : MVT::vector_valuetypes()) {
659     setOperationAction(ISD::ADD , VT, Expand);
660     setOperationAction(ISD::SUB , VT, Expand);
661     setOperationAction(ISD::FADD, VT, Expand);
662     setOperationAction(ISD::FNEG, VT, Expand);
663     setOperationAction(ISD::FSUB, VT, Expand);
664     setOperationAction(ISD::MUL , VT, Expand);
665     setOperationAction(ISD::FMUL, VT, Expand);
666     setOperationAction(ISD::SDIV, VT, Expand);
667     setOperationAction(ISD::UDIV, VT, Expand);
668     setOperationAction(ISD::FDIV, VT, Expand);
669     setOperationAction(ISD::SREM, VT, Expand);
670     setOperationAction(ISD::UREM, VT, Expand);
671     setOperationAction(ISD::LOAD, VT, Expand);
672     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
673     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
674     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
675     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
676     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
677     setOperationAction(ISD::FABS, VT, Expand);
678     setOperationAction(ISD::FSIN, VT, Expand);
679     setOperationAction(ISD::FSINCOS, VT, Expand);
680     setOperationAction(ISD::FCOS, VT, Expand);
681     setOperationAction(ISD::FSINCOS, VT, Expand);
682     setOperationAction(ISD::FREM, VT, Expand);
683     setOperationAction(ISD::FMA,  VT, Expand);
684     setOperationAction(ISD::FPOWI, VT, Expand);
685     setOperationAction(ISD::FSQRT, VT, Expand);
686     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
687     setOperationAction(ISD::FFLOOR, VT, Expand);
688     setOperationAction(ISD::FCEIL, VT, Expand);
689     setOperationAction(ISD::FTRUNC, VT, Expand);
690     setOperationAction(ISD::FRINT, VT, Expand);
691     setOperationAction(ISD::FNEARBYINT, VT, Expand);
692     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
693     setOperationAction(ISD::MULHS, VT, Expand);
694     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
695     setOperationAction(ISD::MULHU, VT, Expand);
696     setOperationAction(ISD::SDIVREM, VT, Expand);
697     setOperationAction(ISD::UDIVREM, VT, Expand);
698     setOperationAction(ISD::FPOW, VT, Expand);
699     setOperationAction(ISD::CTPOP, VT, Expand);
700     setOperationAction(ISD::CTTZ, VT, Expand);
701     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
702     setOperationAction(ISD::CTLZ, VT, Expand);
703     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
704     setOperationAction(ISD::SHL, VT, Expand);
705     setOperationAction(ISD::SRA, VT, Expand);
706     setOperationAction(ISD::SRL, VT, Expand);
707     setOperationAction(ISD::ROTL, VT, Expand);
708     setOperationAction(ISD::ROTR, VT, Expand);
709     setOperationAction(ISD::BSWAP, VT, Expand);
710     setOperationAction(ISD::SETCC, VT, Expand);
711     setOperationAction(ISD::FLOG, VT, Expand);
712     setOperationAction(ISD::FLOG2, VT, Expand);
713     setOperationAction(ISD::FLOG10, VT, Expand);
714     setOperationAction(ISD::FEXP, VT, Expand);
715     setOperationAction(ISD::FEXP2, VT, Expand);
716     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
717     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
718     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
719     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
720     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
721     setOperationAction(ISD::TRUNCATE, VT, Expand);
722     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
723     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
724     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
725     setOperationAction(ISD::VSELECT, VT, Expand);
726     setOperationAction(ISD::SELECT_CC, VT, Expand);
727     for (MVT InnerVT : MVT::vector_valuetypes()) {
728       setTruncStoreAction(InnerVT, VT, Expand);
729
730       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
731       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
732
733       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
734       // types, we have to deal with them whether we ask for Expansion or not.
735       // Setting Expand causes its own optimisation problems though, so leave
736       // them legal.
737       if (VT.getVectorElementType() == MVT::i1)
738         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
739
740       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
741       // split/scalarized right now.
742       if (VT.getVectorElementType() == MVT::f16)
743         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
744     }
745   }
746
747   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
748   // with -msoft-float, disable use of MMX as well.
749   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
750     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
751     // No operations on x86mmx supported, everything uses intrinsics.
752   }
753
754   // MMX-sized vectors (other than x86mmx) are expected to be expanded
755   // into smaller operations.
756   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
757     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
758     setOperationAction(ISD::AND,                MMXTy,      Expand);
759     setOperationAction(ISD::OR,                 MMXTy,      Expand);
760     setOperationAction(ISD::XOR,                MMXTy,      Expand);
761     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
762     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
763     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
764   }
765   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
766
767   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
768     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
769
770     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
771     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
772     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
773     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
774     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
775     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
776     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
777     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
780     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
781     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
782     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
783     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
784   }
785
786   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
787     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
788
789     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
790     // registers cannot be used even for integer operations.
791     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
792     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
793     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
794     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
795
796     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
797     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
798     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
799     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
800     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
801     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
802     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
803     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
804     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
805     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
806     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
807     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
808     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
809     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
810     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
812     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
813     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
814     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
815     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
816     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
817     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
818     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
819
820     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
821     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
822     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
823     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
824
825     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
828     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
829
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
831     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
835
836     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
837     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
838     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
839     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
840
841     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
842     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
843       MVT VT = (MVT::SimpleValueType)i;
844       // Do not attempt to custom lower non-power-of-2 vectors
845       if (!isPowerOf2_32(VT.getVectorNumElements()))
846         continue;
847       // Do not attempt to custom lower non-128-bit vectors
848       if (!VT.is128BitVector())
849         continue;
850       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
851       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
852       setOperationAction(ISD::VSELECT,            VT, Custom);
853       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
854     }
855
856     // We support custom legalizing of sext and anyext loads for specific
857     // memory vector types which we can load as a scalar (or sequence of
858     // scalars) and extend in-register to a legal 128-bit vector type. For sext
859     // loads these must work with a single scalar load.
860     for (MVT VT : MVT::integer_vector_valuetypes()) {
861       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
862       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
863       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
864       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
865       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
866       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
870     }
871
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
876     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
877     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
878     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
879     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
880
881     if (Subtarget->is64Bit()) {
882       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
884     }
885
886     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
887     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
888       MVT VT = (MVT::SimpleValueType)i;
889
890       // Do not attempt to promote non-128-bit vectors
891       if (!VT.is128BitVector())
892         continue;
893
894       setOperationAction(ISD::AND,    VT, Promote);
895       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
896       setOperationAction(ISD::OR,     VT, Promote);
897       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
898       setOperationAction(ISD::XOR,    VT, Promote);
899       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
900       setOperationAction(ISD::LOAD,   VT, Promote);
901       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
902       setOperationAction(ISD::SELECT, VT, Promote);
903       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
904     }
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914
915     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
916
917     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
918     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
919     // As there is no 64-bit GPR available, we need build a special custom
920     // sequence to convert from v2i32 to v2f32.
921     if (!Subtarget->is64Bit())
922       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
923
924     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
925     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
926
927     for (MVT VT : MVT::fp_vector_valuetypes())
928       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
929
930     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
931     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
932     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
933   }
934
935   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
936     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
937       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
938       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
939       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
940       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
941       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
942     }
943
944     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
945     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
946     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
947     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
948     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
952
953     // FIXME: Do we need to handle scalar-to-vector here?
954     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
955
956     // We directly match byte blends in the backend as they match the VSELECT
957     // condition form.
958     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
959
960     // SSE41 brings specific instructions for doing vector sign extend even in
961     // cases where we don't have SRA.
962     for (MVT VT : MVT::integer_vector_valuetypes()) {
963       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
966     }
967
968     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
969     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
975
976     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
982
983     // i8 and i16 vectors are custom because the source register and source
984     // source memory operand types are not the same width.  f32 vectors are
985     // custom since the immediate controlling the insert encodes additional
986     // information.
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
991
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
996
997     // FIXME: these should be Legal, but that's only for the case where
998     // the index is constant.  For now custom expand to deal with that.
999     if (Subtarget->is64Bit()) {
1000       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1001       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002     }
1003   }
1004
1005   if (Subtarget->hasSSE2()) {
1006     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1007     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1008     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1009
1010     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1015
1016     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1017     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1018
1019     // In the customized shift lowering, the legal cases in AVX2 will be
1020     // recognized.
1021     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1025     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1026
1027     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1028     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1029   }
1030
1031   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1066     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1067     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1068
1069     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070     // even though v8i16 is a legal type.
1071     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1073     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1074
1075     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1077     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1080     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1081
1082     for (MVT VT : MVT::fp_vector_valuetypes())
1083       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1084
1085     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1089     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1090
1091     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1092     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1093
1094     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1095     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1096     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1097     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1098
1099     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1100     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1101     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1102
1103     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1104     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1105     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1106     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1107     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1108     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1109     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1110     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1111     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1112     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1113     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1114     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1115
1116     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1117     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1118     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1119     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1120
1121     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1122       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1123       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1124       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1125       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1126       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1127       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1128     }
1129
1130     if (Subtarget->hasInt256()) {
1131       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1132       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1133       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1134       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1135
1136       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1137       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1138       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1139       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1140
1141       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1142       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1143       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1144       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1145
1146       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1147       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1148       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1149       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1150
1151       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1152       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1153       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1154       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1155       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1156       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1157       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1158       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1159       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1160       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1161       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1162       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1163
1164       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1165       // when we have a 256bit-wide blend with immediate.
1166       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1167
1168       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1169       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1170       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1171       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1172       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1173       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1174       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1175
1176       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1177       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1178       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1179       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1180       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1181       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1182     } else {
1183       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1184       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1185       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1186       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1187
1188       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1189       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1190       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1191       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1192
1193       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1195       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1196       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1197
1198       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1199       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1200       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1201       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1202       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1203       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1204       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1205       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1206       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1207       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1208       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1209       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1210     }
1211
1212     // In the customized shift lowering, the legal cases in AVX2 will be
1213     // recognized.
1214     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1215     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1216
1217     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1218     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1219
1220     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1221     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1222
1223     // Custom lower several nodes for 256-bit types.
1224     for (MVT VT : MVT::vector_valuetypes()) {
1225       if (VT.getScalarSizeInBits() >= 32) {
1226         setOperationAction(ISD::MLOAD,  VT, Legal);
1227         setOperationAction(ISD::MSTORE, VT, Legal);
1228       }
1229       // Extract subvector is special because the value type
1230       // (result) is 128-bit but the source is 256-bit wide.
1231       if (VT.is128BitVector()) {
1232         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1233       }
1234       // Do not attempt to custom lower other non-256-bit vectors
1235       if (!VT.is256BitVector())
1236         continue;
1237
1238       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1239       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1240       setOperationAction(ISD::VSELECT,            VT, Custom);
1241       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1242       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1243       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1244       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1245       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1246     }
1247
1248     if (Subtarget->hasInt256())
1249       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1250
1251
1252     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254       MVT VT = (MVT::SimpleValueType)i;
1255
1256       // Do not attempt to promote non-256-bit vectors
1257       if (!VT.is256BitVector())
1258         continue;
1259
1260       setOperationAction(ISD::AND,    VT, Promote);
1261       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1262       setOperationAction(ISD::OR,     VT, Promote);
1263       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1264       setOperationAction(ISD::XOR,    VT, Promote);
1265       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1266       setOperationAction(ISD::LOAD,   VT, Promote);
1267       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1268       setOperationAction(ISD::SELECT, VT, Promote);
1269       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1270     }
1271   }
1272
1273   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1274     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1275     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1276     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1277     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1278
1279     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1280     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1281     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1282
1283     for (MVT VT : MVT::fp_vector_valuetypes())
1284       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1285
1286     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1287     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1288     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1289     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1290     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1291     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1292     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1293     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1294     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1295     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1298
1299     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1300     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1301     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1302     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1303     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1304     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1305     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1306     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1307     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1308     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1309     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1312
1313     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1314     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1315     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1316     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1318     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1319
1320     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1321     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1323     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1325     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1326     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1327     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1328
1329     // FIXME:  [US]INT_TO_FP are not legal for f80.
1330     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1331     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1332     if (Subtarget->is64Bit()) {
1333       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1334       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1335     }
1336     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1339     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1343     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1344     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1348     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1349     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1350     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1351     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1352
1353     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1354     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1355     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1356     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1357     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1358     if (Subtarget->hasVLX()){
1359       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1360       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1361       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1362       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1363       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1364
1365       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1366       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1367       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1368       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1369       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1370     }
1371     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1373     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1374     if (Subtarget->hasDQI()) {
1375       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1376       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1377
1378       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1379       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1380       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1381       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1382       if (Subtarget->hasVLX()) {
1383         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1385         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1386         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1387         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1388         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1389         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1390         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1391       }
1392     }
1393     if (Subtarget->hasVLX()) {
1394       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1395       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1396       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1397       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1398       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1399       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1400       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1401       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1402     }
1403     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1404     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1405     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1406     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1407     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1408     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1409     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1410     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1411     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1412     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1413     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1414     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1415     if (Subtarget->hasDQI()) {
1416       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1417       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1418     }
1419     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1420     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1421     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1422     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1423     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1424     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1425     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1426     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1427     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1428     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1429
1430     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1431     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1432     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1433     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1434     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1435
1436     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1437     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1438
1439     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1440
1441     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1442     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1443     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1444     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1445     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1446     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1447     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1448     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1449     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1450     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1451     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1452
1453     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1455     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1456     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1457     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1458     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1459     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1460     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1461
1462     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1469
1470     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1477     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1478
1479     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1482     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1483     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1484     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1485
1486     if (Subtarget->hasCDI()) {
1487       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1488       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1489     }
1490     if (Subtarget->hasDQI()) {
1491       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1492       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1493       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1494     }
1495     // Custom lower several nodes.
1496     for (MVT VT : MVT::vector_valuetypes()) {
1497       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1498       if (EltSize == 1) {
1499         setOperationAction(ISD::AND, VT, Legal);
1500         setOperationAction(ISD::OR,  VT, Legal);
1501         setOperationAction(ISD::XOR,  VT, Legal);
1502       }
1503       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1504         setOperationAction(ISD::MGATHER,  VT, Custom);
1505         setOperationAction(ISD::MSCATTER, VT, Custom);
1506       }
1507       // Extract subvector is special because the value type
1508       // (result) is 256/128-bit but the source is 512-bit wide.
1509       if (VT.is128BitVector() || VT.is256BitVector()) {
1510         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1511       }
1512       if (VT.getVectorElementType() == MVT::i1)
1513         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1514
1515       // Do not attempt to custom lower other non-512-bit vectors
1516       if (!VT.is512BitVector())
1517         continue;
1518
1519       if (EltSize >= 32) {
1520         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1521         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1522         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1523         setOperationAction(ISD::VSELECT,             VT, Legal);
1524         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1525         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1526         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1527         setOperationAction(ISD::MLOAD,               VT, Legal);
1528         setOperationAction(ISD::MSTORE,              VT, Legal);
1529       }
1530     }
1531     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1532       MVT VT = (MVT::SimpleValueType)i;
1533
1534       // Do not attempt to promote non-512-bit vectors.
1535       if (!VT.is512BitVector())
1536         continue;
1537
1538       setOperationAction(ISD::SELECT, VT, Promote);
1539       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1540     }
1541   }// has  AVX-512
1542
1543   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1544     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1545     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1546
1547     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1548     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1549
1550     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1551     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1552     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1553     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1554     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1555     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1556     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1557     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1558     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1559     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1560     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1561     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1562     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1563     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1564     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1565     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1566     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1567     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1568     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1569     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1570     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1571     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1572     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1573     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1574     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1575     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1576     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1577     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1578     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1579     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1580
1581     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1583     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1584     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1585     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1586     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1587     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1588     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1589
1590     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1591     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1592     if (Subtarget->hasVLX())
1593       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1594
1595     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1596       const MVT VT = (MVT::SimpleValueType)i;
1597
1598       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1599
1600       // Do not attempt to promote non-512-bit vectors.
1601       if (!VT.is512BitVector())
1602         continue;
1603
1604       if (EltSize < 32) {
1605         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1606         setOperationAction(ISD::VSELECT,             VT, Legal);
1607       }
1608     }
1609   }
1610
1611   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1612     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1613     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1614
1615     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1616     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1617     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1618     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1619     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1620     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1621     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1622     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1623     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1624     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1625
1626     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1627     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1628     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1629     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1630     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1631     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1632     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1633     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1634
1635     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1637     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1638     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1639     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1640     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1641     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1642     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1643   }
1644
1645   // We want to custom lower some of our intrinsics.
1646   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1647   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1648   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1649   if (!Subtarget->is64Bit())
1650     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1651
1652   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1653   // handle type legalization for these operations here.
1654   //
1655   // FIXME: We really should do custom legalization for addition and
1656   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1657   // than generic legalization for 64-bit multiplication-with-overflow, though.
1658   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1659     // Add/Sub/Mul with overflow operations are custom lowered.
1660     MVT VT = IntVTs[i];
1661     setOperationAction(ISD::SADDO, VT, Custom);
1662     setOperationAction(ISD::UADDO, VT, Custom);
1663     setOperationAction(ISD::SSUBO, VT, Custom);
1664     setOperationAction(ISD::USUBO, VT, Custom);
1665     setOperationAction(ISD::SMULO, VT, Custom);
1666     setOperationAction(ISD::UMULO, VT, Custom);
1667   }
1668
1669
1670   if (!Subtarget->is64Bit()) {
1671     // These libcalls are not available in 32-bit.
1672     setLibcallName(RTLIB::SHL_I128, nullptr);
1673     setLibcallName(RTLIB::SRL_I128, nullptr);
1674     setLibcallName(RTLIB::SRA_I128, nullptr);
1675   }
1676
1677   // Combine sin / cos into one node or libcall if possible.
1678   if (Subtarget->hasSinCos()) {
1679     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1680     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1681     if (Subtarget->isTargetDarwin()) {
1682       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1683       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1684       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1685       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1686     }
1687   }
1688
1689   if (Subtarget->isTargetWin64()) {
1690     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1691     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1692     setOperationAction(ISD::SREM, MVT::i128, Custom);
1693     setOperationAction(ISD::UREM, MVT::i128, Custom);
1694     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1695     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1696   }
1697
1698   // We have target-specific dag combine patterns for the following nodes:
1699   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1700   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1701   setTargetDAGCombine(ISD::BITCAST);
1702   setTargetDAGCombine(ISD::VSELECT);
1703   setTargetDAGCombine(ISD::SELECT);
1704   setTargetDAGCombine(ISD::SHL);
1705   setTargetDAGCombine(ISD::SRA);
1706   setTargetDAGCombine(ISD::SRL);
1707   setTargetDAGCombine(ISD::OR);
1708   setTargetDAGCombine(ISD::AND);
1709   setTargetDAGCombine(ISD::ADD);
1710   setTargetDAGCombine(ISD::FADD);
1711   setTargetDAGCombine(ISD::FSUB);
1712   setTargetDAGCombine(ISD::FMA);
1713   setTargetDAGCombine(ISD::SUB);
1714   setTargetDAGCombine(ISD::LOAD);
1715   setTargetDAGCombine(ISD::MLOAD);
1716   setTargetDAGCombine(ISD::STORE);
1717   setTargetDAGCombine(ISD::MSTORE);
1718   setTargetDAGCombine(ISD::ZERO_EXTEND);
1719   setTargetDAGCombine(ISD::ANY_EXTEND);
1720   setTargetDAGCombine(ISD::SIGN_EXTEND);
1721   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1722   setTargetDAGCombine(ISD::SINT_TO_FP);
1723   setTargetDAGCombine(ISD::UINT_TO_FP);
1724   setTargetDAGCombine(ISD::SETCC);
1725   setTargetDAGCombine(ISD::BUILD_VECTOR);
1726   setTargetDAGCombine(ISD::MUL);
1727   setTargetDAGCombine(ISD::XOR);
1728
1729   computeRegisterProperties(Subtarget->getRegisterInfo());
1730
1731   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1732   MaxStoresPerMemsetOptSize = 8;
1733   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1734   MaxStoresPerMemcpyOptSize = 4;
1735   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1736   MaxStoresPerMemmoveOptSize = 4;
1737   setPrefLoopAlignment(4); // 2^4 bytes.
1738
1739   // Predictable cmov don't hurt on atom because it's in-order.
1740   PredictableSelectIsExpensive = !Subtarget->isAtom();
1741   EnableExtLdPromotion = true;
1742   setPrefFunctionAlignment(4); // 2^4 bytes.
1743
1744   verifyIntrinsicTables();
1745 }
1746
1747 // This has so far only been implemented for 64-bit MachO.
1748 bool X86TargetLowering::useLoadStackGuardNode() const {
1749   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1750 }
1751
1752 TargetLoweringBase::LegalizeTypeAction
1753 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1754   if (ExperimentalVectorWideningLegalization &&
1755       VT.getVectorNumElements() != 1 &&
1756       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1757     return TypeWidenVector;
1758
1759   return TargetLoweringBase::getPreferredVectorAction(VT);
1760 }
1761
1762 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1763                                           EVT VT) const {
1764   if (!VT.isVector())
1765     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1766
1767   const unsigned NumElts = VT.getVectorNumElements();
1768   const EVT EltVT = VT.getVectorElementType();
1769   if (VT.is512BitVector()) {
1770     if (Subtarget->hasAVX512())
1771       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1772           EltVT == MVT::f32 || EltVT == MVT::f64)
1773         switch(NumElts) {
1774         case  8: return MVT::v8i1;
1775         case 16: return MVT::v16i1;
1776       }
1777     if (Subtarget->hasBWI())
1778       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1779         switch(NumElts) {
1780         case 32: return MVT::v32i1;
1781         case 64: return MVT::v64i1;
1782       }
1783   }
1784
1785   if (VT.is256BitVector() || VT.is128BitVector()) {
1786     if (Subtarget->hasVLX())
1787       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1788           EltVT == MVT::f32 || EltVT == MVT::f64)
1789         switch(NumElts) {
1790         case 2: return MVT::v2i1;
1791         case 4: return MVT::v4i1;
1792         case 8: return MVT::v8i1;
1793       }
1794     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1795       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1796         switch(NumElts) {
1797         case  8: return MVT::v8i1;
1798         case 16: return MVT::v16i1;
1799         case 32: return MVT::v32i1;
1800       }
1801   }
1802
1803   return VT.changeVectorElementTypeToInteger();
1804 }
1805
1806 /// Helper for getByValTypeAlignment to determine
1807 /// the desired ByVal argument alignment.
1808 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1809   if (MaxAlign == 16)
1810     return;
1811   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1812     if (VTy->getBitWidth() == 128)
1813       MaxAlign = 16;
1814   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1815     unsigned EltAlign = 0;
1816     getMaxByValAlign(ATy->getElementType(), EltAlign);
1817     if (EltAlign > MaxAlign)
1818       MaxAlign = EltAlign;
1819   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1820     for (auto *EltTy : STy->elements()) {
1821       unsigned EltAlign = 0;
1822       getMaxByValAlign(EltTy, EltAlign);
1823       if (EltAlign > MaxAlign)
1824         MaxAlign = EltAlign;
1825       if (MaxAlign == 16)
1826         break;
1827     }
1828   }
1829 }
1830
1831 /// Return the desired alignment for ByVal aggregate
1832 /// function arguments in the caller parameter area. For X86, aggregates
1833 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1834 /// are at 4-byte boundaries.
1835 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1836                                                   const DataLayout &DL) const {
1837   if (Subtarget->is64Bit()) {
1838     // Max of 8 and alignment of type.
1839     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1840     if (TyAlign > 8)
1841       return TyAlign;
1842     return 8;
1843   }
1844
1845   unsigned Align = 4;
1846   if (Subtarget->hasSSE1())
1847     getMaxByValAlign(Ty, Align);
1848   return Align;
1849 }
1850
1851 /// Returns the target specific optimal type for load
1852 /// and store operations as a result of memset, memcpy, and memmove
1853 /// lowering. If DstAlign is zero that means it's safe to destination
1854 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1855 /// means there isn't a need to check it against alignment requirement,
1856 /// probably because the source does not need to be loaded. If 'IsMemset' is
1857 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1858 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1859 /// source is constant so it does not need to be loaded.
1860 /// It returns EVT::Other if the type should be determined using generic
1861 /// target-independent logic.
1862 EVT
1863 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1864                                        unsigned DstAlign, unsigned SrcAlign,
1865                                        bool IsMemset, bool ZeroMemset,
1866                                        bool MemcpyStrSrc,
1867                                        MachineFunction &MF) const {
1868   const Function *F = MF.getFunction();
1869   if ((!IsMemset || ZeroMemset) &&
1870       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1871     if (Size >= 16 &&
1872         (!Subtarget->isUnalignedMemUnder32Slow() ||
1873          ((DstAlign == 0 || DstAlign >= 16) &&
1874           (SrcAlign == 0 || SrcAlign >= 16)))) {
1875       if (Size >= 32) {
1876         // FIXME: Check if unaligned 32-byte accesses are slow.
1877         if (Subtarget->hasInt256())
1878           return MVT::v8i32;
1879         if (Subtarget->hasFp256())
1880           return MVT::v8f32;
1881       }
1882       if (Subtarget->hasSSE2())
1883         return MVT::v4i32;
1884       if (Subtarget->hasSSE1())
1885         return MVT::v4f32;
1886     } else if (!MemcpyStrSrc && Size >= 8 &&
1887                !Subtarget->is64Bit() &&
1888                Subtarget->hasSSE2()) {
1889       // Do not use f64 to lower memcpy if source is string constant. It's
1890       // better to use i32 to avoid the loads.
1891       return MVT::f64;
1892     }
1893   }
1894   // This is a compromise. If we reach here, unaligned accesses may be slow on
1895   // this target. However, creating smaller, aligned accesses could be even
1896   // slower and would certainly be a lot more code.
1897   if (Subtarget->is64Bit() && Size >= 8)
1898     return MVT::i64;
1899   return MVT::i32;
1900 }
1901
1902 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1903   if (VT == MVT::f32)
1904     return X86ScalarSSEf32;
1905   else if (VT == MVT::f64)
1906     return X86ScalarSSEf64;
1907   return true;
1908 }
1909
1910 bool
1911 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1912                                                   unsigned,
1913                                                   unsigned,
1914                                                   bool *Fast) const {
1915   if (Fast) {
1916     if (VT.getSizeInBits() == 256)
1917       *Fast = !Subtarget->isUnalignedMem32Slow();
1918     else
1919       *Fast = !Subtarget->isUnalignedMemUnder32Slow();
1920   }
1921   return true;
1922 }
1923
1924 /// Return the entry encoding for a jump table in the
1925 /// current function.  The returned value is a member of the
1926 /// MachineJumpTableInfo::JTEntryKind enum.
1927 unsigned X86TargetLowering::getJumpTableEncoding() const {
1928   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1929   // symbol.
1930   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1931       Subtarget->isPICStyleGOT())
1932     return MachineJumpTableInfo::EK_Custom32;
1933
1934   // Otherwise, use the normal jump table encoding heuristics.
1935   return TargetLowering::getJumpTableEncoding();
1936 }
1937
1938 bool X86TargetLowering::useSoftFloat() const {
1939   return Subtarget->useSoftFloat();
1940 }
1941
1942 const MCExpr *
1943 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1944                                              const MachineBasicBlock *MBB,
1945                                              unsigned uid,MCContext &Ctx) const{
1946   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1947          Subtarget->isPICStyleGOT());
1948   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1949   // entries.
1950   return MCSymbolRefExpr::create(MBB->getSymbol(),
1951                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1952 }
1953
1954 /// Returns relocation base for the given PIC jumptable.
1955 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1956                                                     SelectionDAG &DAG) const {
1957   if (!Subtarget->is64Bit())
1958     // This doesn't have SDLoc associated with it, but is not really the
1959     // same as a Register.
1960     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1961                        getPointerTy(DAG.getDataLayout()));
1962   return Table;
1963 }
1964
1965 /// This returns the relocation base for the given PIC jumptable,
1966 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1967 const MCExpr *X86TargetLowering::
1968 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1969                              MCContext &Ctx) const {
1970   // X86-64 uses RIP relative addressing based on the jump table label.
1971   if (Subtarget->isPICStyleRIPRel())
1972     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1973
1974   // Otherwise, the reference is relative to the PIC base.
1975   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1976 }
1977
1978 std::pair<const TargetRegisterClass *, uint8_t>
1979 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1980                                            MVT VT) const {
1981   const TargetRegisterClass *RRC = nullptr;
1982   uint8_t Cost = 1;
1983   switch (VT.SimpleTy) {
1984   default:
1985     return TargetLowering::findRepresentativeClass(TRI, VT);
1986   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1987     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1988     break;
1989   case MVT::x86mmx:
1990     RRC = &X86::VR64RegClass;
1991     break;
1992   case MVT::f32: case MVT::f64:
1993   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1994   case MVT::v4f32: case MVT::v2f64:
1995   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1996   case MVT::v4f64:
1997     RRC = &X86::VR128RegClass;
1998     break;
1999   }
2000   return std::make_pair(RRC, Cost);
2001 }
2002
2003 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2004                                                unsigned &Offset) const {
2005   if (!Subtarget->isTargetLinux())
2006     return false;
2007
2008   if (Subtarget->is64Bit()) {
2009     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2010     Offset = 0x28;
2011     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2012       AddressSpace = 256;
2013     else
2014       AddressSpace = 257;
2015   } else {
2016     // %gs:0x14 on i386
2017     Offset = 0x14;
2018     AddressSpace = 256;
2019   }
2020   return true;
2021 }
2022
2023 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2024                                             unsigned DestAS) const {
2025   assert(SrcAS != DestAS && "Expected different address spaces!");
2026
2027   return SrcAS < 256 && DestAS < 256;
2028 }
2029
2030 //===----------------------------------------------------------------------===//
2031 //               Return Value Calling Convention Implementation
2032 //===----------------------------------------------------------------------===//
2033
2034 #include "X86GenCallingConv.inc"
2035
2036 bool
2037 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2038                                   MachineFunction &MF, bool isVarArg,
2039                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2040                         LLVMContext &Context) const {
2041   SmallVector<CCValAssign, 16> RVLocs;
2042   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2043   return CCInfo.CheckReturn(Outs, RetCC_X86);
2044 }
2045
2046 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2047   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2048   return ScratchRegs;
2049 }
2050
2051 SDValue
2052 X86TargetLowering::LowerReturn(SDValue Chain,
2053                                CallingConv::ID CallConv, bool isVarArg,
2054                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2055                                const SmallVectorImpl<SDValue> &OutVals,
2056                                SDLoc dl, SelectionDAG &DAG) const {
2057   MachineFunction &MF = DAG.getMachineFunction();
2058   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2059
2060   SmallVector<CCValAssign, 16> RVLocs;
2061   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2062   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2063
2064   SDValue Flag;
2065   SmallVector<SDValue, 6> RetOps;
2066   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2067   // Operand #1 = Bytes To Pop
2068   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2069                    MVT::i16));
2070
2071   // Copy the result values into the output registers.
2072   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2073     CCValAssign &VA = RVLocs[i];
2074     assert(VA.isRegLoc() && "Can only return in registers!");
2075     SDValue ValToCopy = OutVals[i];
2076     EVT ValVT = ValToCopy.getValueType();
2077
2078     // Promote values to the appropriate types.
2079     if (VA.getLocInfo() == CCValAssign::SExt)
2080       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2081     else if (VA.getLocInfo() == CCValAssign::ZExt)
2082       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2083     else if (VA.getLocInfo() == CCValAssign::AExt) {
2084       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2085         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2086       else
2087         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2088     }
2089     else if (VA.getLocInfo() == CCValAssign::BCvt)
2090       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2091
2092     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2093            "Unexpected FP-extend for return value.");
2094
2095     // If this is x86-64, and we disabled SSE, we can't return FP values,
2096     // or SSE or MMX vectors.
2097     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2098          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2099           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2100       report_fatal_error("SSE register return with SSE disabled");
2101     }
2102     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2103     // llvm-gcc has never done it right and no one has noticed, so this
2104     // should be OK for now.
2105     if (ValVT == MVT::f64 &&
2106         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2107       report_fatal_error("SSE2 register return with SSE2 disabled");
2108
2109     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2110     // the RET instruction and handled by the FP Stackifier.
2111     if (VA.getLocReg() == X86::FP0 ||
2112         VA.getLocReg() == X86::FP1) {
2113       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2114       // change the value to the FP stack register class.
2115       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2116         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2117       RetOps.push_back(ValToCopy);
2118       // Don't emit a copytoreg.
2119       continue;
2120     }
2121
2122     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2123     // which is returned in RAX / RDX.
2124     if (Subtarget->is64Bit()) {
2125       if (ValVT == MVT::x86mmx) {
2126         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2127           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2128           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2129                                   ValToCopy);
2130           // If we don't have SSE2 available, convert to v4f32 so the generated
2131           // register is legal.
2132           if (!Subtarget->hasSSE2())
2133             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2134         }
2135       }
2136     }
2137
2138     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2139     Flag = Chain.getValue(1);
2140     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2141   }
2142
2143   // All x86 ABIs require that for returning structs by value we copy
2144   // the sret argument into %rax/%eax (depending on ABI) for the return.
2145   // We saved the argument into a virtual register in the entry block,
2146   // so now we copy the value out and into %rax/%eax.
2147   //
2148   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2149   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2150   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2151   // either case FuncInfo->setSRetReturnReg() will have been called.
2152   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2153     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2154                                      getPointerTy(MF.getDataLayout()));
2155
2156     unsigned RetValReg
2157         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2158           X86::RAX : X86::EAX;
2159     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2160     Flag = Chain.getValue(1);
2161
2162     // RAX/EAX now acts like a return value.
2163     RetOps.push_back(
2164         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2165   }
2166
2167   RetOps[0] = Chain;  // Update chain.
2168
2169   // Add the flag if we have it.
2170   if (Flag.getNode())
2171     RetOps.push_back(Flag);
2172
2173   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2174 }
2175
2176 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2177   if (N->getNumValues() != 1)
2178     return false;
2179   if (!N->hasNUsesOfValue(1, 0))
2180     return false;
2181
2182   SDValue TCChain = Chain;
2183   SDNode *Copy = *N->use_begin();
2184   if (Copy->getOpcode() == ISD::CopyToReg) {
2185     // If the copy has a glue operand, we conservatively assume it isn't safe to
2186     // perform a tail call.
2187     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2188       return false;
2189     TCChain = Copy->getOperand(0);
2190   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2191     return false;
2192
2193   bool HasRet = false;
2194   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2195        UI != UE; ++UI) {
2196     if (UI->getOpcode() != X86ISD::RET_FLAG)
2197       return false;
2198     // If we are returning more than one value, we can definitely
2199     // not make a tail call see PR19530
2200     if (UI->getNumOperands() > 4)
2201       return false;
2202     if (UI->getNumOperands() == 4 &&
2203         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2204       return false;
2205     HasRet = true;
2206   }
2207
2208   if (!HasRet)
2209     return false;
2210
2211   Chain = TCChain;
2212   return true;
2213 }
2214
2215 EVT
2216 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2217                                             ISD::NodeType ExtendKind) const {
2218   MVT ReturnMVT;
2219   // TODO: Is this also valid on 32-bit?
2220   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2221     ReturnMVT = MVT::i8;
2222   else
2223     ReturnMVT = MVT::i32;
2224
2225   EVT MinVT = getRegisterType(Context, ReturnMVT);
2226   return VT.bitsLT(MinVT) ? MinVT : VT;
2227 }
2228
2229 /// Lower the result values of a call into the
2230 /// appropriate copies out of appropriate physical registers.
2231 ///
2232 SDValue
2233 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2234                                    CallingConv::ID CallConv, bool isVarArg,
2235                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2236                                    SDLoc dl, SelectionDAG &DAG,
2237                                    SmallVectorImpl<SDValue> &InVals) const {
2238
2239   // Assign locations to each value returned by this call.
2240   SmallVector<CCValAssign, 16> RVLocs;
2241   bool Is64Bit = Subtarget->is64Bit();
2242   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2243                  *DAG.getContext());
2244   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2245
2246   // Copy all of the result registers out of their specified physreg.
2247   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2248     CCValAssign &VA = RVLocs[i];
2249     EVT CopyVT = VA.getLocVT();
2250
2251     // If this is x86-64, and we disabled SSE, we can't return FP values
2252     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2253         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2254       report_fatal_error("SSE register return with SSE disabled");
2255     }
2256
2257     // If we prefer to use the value in xmm registers, copy it out as f80 and
2258     // use a truncate to move it from fp stack reg to xmm reg.
2259     bool RoundAfterCopy = false;
2260     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2261         isScalarFPTypeInSSEReg(VA.getValVT())) {
2262       CopyVT = MVT::f80;
2263       RoundAfterCopy = (CopyVT != VA.getLocVT());
2264     }
2265
2266     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2267                                CopyVT, InFlag).getValue(1);
2268     SDValue Val = Chain.getValue(0);
2269
2270     if (RoundAfterCopy)
2271       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2272                         // This truncation won't change the value.
2273                         DAG.getIntPtrConstant(1, dl));
2274
2275     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2276       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2277
2278     InFlag = Chain.getValue(2);
2279     InVals.push_back(Val);
2280   }
2281
2282   return Chain;
2283 }
2284
2285 //===----------------------------------------------------------------------===//
2286 //                C & StdCall & Fast Calling Convention implementation
2287 //===----------------------------------------------------------------------===//
2288 //  StdCall calling convention seems to be standard for many Windows' API
2289 //  routines and around. It differs from C calling convention just a little:
2290 //  callee should clean up the stack, not caller. Symbols should be also
2291 //  decorated in some fancy way :) It doesn't support any vector arguments.
2292 //  For info on fast calling convention see Fast Calling Convention (tail call)
2293 //  implementation LowerX86_32FastCCCallTo.
2294
2295 /// CallIsStructReturn - Determines whether a call uses struct return
2296 /// semantics.
2297 enum StructReturnType {
2298   NotStructReturn,
2299   RegStructReturn,
2300   StackStructReturn
2301 };
2302 static StructReturnType
2303 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2304   if (Outs.empty())
2305     return NotStructReturn;
2306
2307   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2308   if (!Flags.isSRet())
2309     return NotStructReturn;
2310   if (Flags.isInReg())
2311     return RegStructReturn;
2312   return StackStructReturn;
2313 }
2314
2315 /// Determines whether a function uses struct return semantics.
2316 static StructReturnType
2317 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2318   if (Ins.empty())
2319     return NotStructReturn;
2320
2321   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2322   if (!Flags.isSRet())
2323     return NotStructReturn;
2324   if (Flags.isInReg())
2325     return RegStructReturn;
2326   return StackStructReturn;
2327 }
2328
2329 /// Make a copy of an aggregate at address specified by "Src" to address
2330 /// "Dst" with size and alignment information specified by the specific
2331 /// parameter attribute. The copy will be passed as a byval function parameter.
2332 static SDValue
2333 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2334                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2335                           SDLoc dl) {
2336   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2337
2338   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2339                        /*isVolatile*/false, /*AlwaysInline=*/true,
2340                        /*isTailCall*/false,
2341                        MachinePointerInfo(), MachinePointerInfo());
2342 }
2343
2344 /// Return true if the calling convention is one that
2345 /// supports tail call optimization.
2346 static bool IsTailCallConvention(CallingConv::ID CC) {
2347   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2348           CC == CallingConv::HiPE);
2349 }
2350
2351 /// \brief Return true if the calling convention is a C calling convention.
2352 static bool IsCCallConvention(CallingConv::ID CC) {
2353   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2354           CC == CallingConv::X86_64_SysV);
2355 }
2356
2357 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2358   auto Attr =
2359       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2360   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2361     return false;
2362
2363   CallSite CS(CI);
2364   CallingConv::ID CalleeCC = CS.getCallingConv();
2365   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2366     return false;
2367
2368   return true;
2369 }
2370
2371 /// Return true if the function is being made into
2372 /// a tailcall target by changing its ABI.
2373 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2374                                    bool GuaranteedTailCallOpt) {
2375   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2376 }
2377
2378 SDValue
2379 X86TargetLowering::LowerMemArgument(SDValue Chain,
2380                                     CallingConv::ID CallConv,
2381                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2382                                     SDLoc dl, SelectionDAG &DAG,
2383                                     const CCValAssign &VA,
2384                                     MachineFrameInfo *MFI,
2385                                     unsigned i) const {
2386   // Create the nodes corresponding to a load from this parameter slot.
2387   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2388   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2389       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2390   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2391   EVT ValVT;
2392
2393   // If value is passed by pointer we have address passed instead of the value
2394   // itself.
2395   bool ExtendedInMem = VA.isExtInLoc() &&
2396     VA.getValVT().getScalarType() == MVT::i1;
2397
2398   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2399     ValVT = VA.getLocVT();
2400   else
2401     ValVT = VA.getValVT();
2402
2403   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2404   // changed with more analysis.
2405   // In case of tail call optimization mark all arguments mutable. Since they
2406   // could be overwritten by lowering of arguments in case of a tail call.
2407   if (Flags.isByVal()) {
2408     unsigned Bytes = Flags.getByValSize();
2409     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2410     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2411     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2412   } else {
2413     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2414                                     VA.getLocMemOffset(), isImmutable);
2415     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2416     SDValue Val = DAG.getLoad(
2417         ValVT, dl, Chain, FIN,
2418         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2419         false, false, 0);
2420     return ExtendedInMem ?
2421       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2422   }
2423 }
2424
2425 // FIXME: Get this from tablegen.
2426 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2427                                                 const X86Subtarget *Subtarget) {
2428   assert(Subtarget->is64Bit());
2429
2430   if (Subtarget->isCallingConvWin64(CallConv)) {
2431     static const MCPhysReg GPR64ArgRegsWin64[] = {
2432       X86::RCX, X86::RDX, X86::R8,  X86::R9
2433     };
2434     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2435   }
2436
2437   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2438     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2439   };
2440   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2441 }
2442
2443 // FIXME: Get this from tablegen.
2444 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2445                                                 CallingConv::ID CallConv,
2446                                                 const X86Subtarget *Subtarget) {
2447   assert(Subtarget->is64Bit());
2448   if (Subtarget->isCallingConvWin64(CallConv)) {
2449     // The XMM registers which might contain var arg parameters are shadowed
2450     // in their paired GPR.  So we only need to save the GPR to their home
2451     // slots.
2452     // TODO: __vectorcall will change this.
2453     return None;
2454   }
2455
2456   const Function *Fn = MF.getFunction();
2457   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2458   bool isSoftFloat = Subtarget->useSoftFloat();
2459   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2460          "SSE register cannot be used when SSE is disabled!");
2461   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2462     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2463     // registers.
2464     return None;
2465
2466   static const MCPhysReg XMMArgRegs64Bit[] = {
2467     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2468     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2469   };
2470   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2471 }
2472
2473 SDValue
2474 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2475                                         CallingConv::ID CallConv,
2476                                         bool isVarArg,
2477                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2478                                         SDLoc dl,
2479                                         SelectionDAG &DAG,
2480                                         SmallVectorImpl<SDValue> &InVals)
2481                                           const {
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2484   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2485
2486   const Function* Fn = MF.getFunction();
2487   if (Fn->hasExternalLinkage() &&
2488       Subtarget->isTargetCygMing() &&
2489       Fn->getName() == "main")
2490     FuncInfo->setForceFramePointer(true);
2491
2492   MachineFrameInfo *MFI = MF.getFrameInfo();
2493   bool Is64Bit = Subtarget->is64Bit();
2494   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2495
2496   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2497          "Var args not supported with calling convention fastcc, ghc or hipe");
2498
2499   // Assign locations to all of the incoming arguments.
2500   SmallVector<CCValAssign, 16> ArgLocs;
2501   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2502
2503   // Allocate shadow area for Win64
2504   if (IsWin64)
2505     CCInfo.AllocateStack(32, 8);
2506
2507   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2508
2509   unsigned LastVal = ~0U;
2510   SDValue ArgValue;
2511   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2512     CCValAssign &VA = ArgLocs[i];
2513     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2514     // places.
2515     assert(VA.getValNo() != LastVal &&
2516            "Don't support value assigned to multiple locs yet");
2517     (void)LastVal;
2518     LastVal = VA.getValNo();
2519
2520     if (VA.isRegLoc()) {
2521       EVT RegVT = VA.getLocVT();
2522       const TargetRegisterClass *RC;
2523       if (RegVT == MVT::i32)
2524         RC = &X86::GR32RegClass;
2525       else if (Is64Bit && RegVT == MVT::i64)
2526         RC = &X86::GR64RegClass;
2527       else if (RegVT == MVT::f32)
2528         RC = &X86::FR32RegClass;
2529       else if (RegVT == MVT::f64)
2530         RC = &X86::FR64RegClass;
2531       else if (RegVT.is512BitVector())
2532         RC = &X86::VR512RegClass;
2533       else if (RegVT.is256BitVector())
2534         RC = &X86::VR256RegClass;
2535       else if (RegVT.is128BitVector())
2536         RC = &X86::VR128RegClass;
2537       else if (RegVT == MVT::x86mmx)
2538         RC = &X86::VR64RegClass;
2539       else if (RegVT == MVT::i1)
2540         RC = &X86::VK1RegClass;
2541       else if (RegVT == MVT::v8i1)
2542         RC = &X86::VK8RegClass;
2543       else if (RegVT == MVT::v16i1)
2544         RC = &X86::VK16RegClass;
2545       else if (RegVT == MVT::v32i1)
2546         RC = &X86::VK32RegClass;
2547       else if (RegVT == MVT::v64i1)
2548         RC = &X86::VK64RegClass;
2549       else
2550         llvm_unreachable("Unknown argument type!");
2551
2552       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2553       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2554
2555       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2556       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2557       // right size.
2558       if (VA.getLocInfo() == CCValAssign::SExt)
2559         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2560                                DAG.getValueType(VA.getValVT()));
2561       else if (VA.getLocInfo() == CCValAssign::ZExt)
2562         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2563                                DAG.getValueType(VA.getValVT()));
2564       else if (VA.getLocInfo() == CCValAssign::BCvt)
2565         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2566
2567       if (VA.isExtInLoc()) {
2568         // Handle MMX values passed in XMM regs.
2569         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2570           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2571         else
2572           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2573       }
2574     } else {
2575       assert(VA.isMemLoc());
2576       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2577     }
2578
2579     // If value is passed via pointer - do a load.
2580     if (VA.getLocInfo() == CCValAssign::Indirect)
2581       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2582                              MachinePointerInfo(), false, false, false, 0);
2583
2584     InVals.push_back(ArgValue);
2585   }
2586
2587   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2588     // All x86 ABIs require that for returning structs by value we copy the
2589     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2590     // the argument into a virtual register so that we can access it from the
2591     // return points.
2592     if (Ins[i].Flags.isSRet()) {
2593       unsigned Reg = FuncInfo->getSRetReturnReg();
2594       if (!Reg) {
2595         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2596         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2597         FuncInfo->setSRetReturnReg(Reg);
2598       }
2599       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2600       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2601       break;
2602     }
2603   }
2604
2605   unsigned StackSize = CCInfo.getNextStackOffset();
2606   // Align stack specially for tail calls.
2607   if (FuncIsMadeTailCallSafe(CallConv,
2608                              MF.getTarget().Options.GuaranteedTailCallOpt))
2609     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2610
2611   // If the function takes variable number of arguments, make a frame index for
2612   // the start of the first vararg value... for expansion of llvm.va_start. We
2613   // can skip this if there are no va_start calls.
2614   if (MFI->hasVAStart() &&
2615       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2616                    CallConv != CallingConv::X86_ThisCall))) {
2617     FuncInfo->setVarArgsFrameIndex(
2618         MFI->CreateFixedObject(1, StackSize, true));
2619   }
2620
2621   MachineModuleInfo &MMI = MF.getMMI();
2622   const Function *WinEHParent = nullptr;
2623   if (MMI.hasWinEHFuncInfo(Fn))
2624     WinEHParent = MMI.getWinEHParent(Fn);
2625   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2626   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2627
2628   // Figure out if XMM registers are in use.
2629   assert(!(Subtarget->useSoftFloat() &&
2630            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2631          "SSE register cannot be used when SSE is disabled!");
2632
2633   // 64-bit calling conventions support varargs and register parameters, so we
2634   // have to do extra work to spill them in the prologue.
2635   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2636     // Find the first unallocated argument registers.
2637     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2638     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2639     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2640     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2641     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2642            "SSE register cannot be used when SSE is disabled!");
2643
2644     // Gather all the live in physical registers.
2645     SmallVector<SDValue, 6> LiveGPRs;
2646     SmallVector<SDValue, 8> LiveXMMRegs;
2647     SDValue ALVal;
2648     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2649       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2650       LiveGPRs.push_back(
2651           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2652     }
2653     if (!ArgXMMs.empty()) {
2654       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2655       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2656       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2657         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2658         LiveXMMRegs.push_back(
2659             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2660       }
2661     }
2662
2663     if (IsWin64) {
2664       // Get to the caller-allocated home save location.  Add 8 to account
2665       // for the return address.
2666       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2667       FuncInfo->setRegSaveFrameIndex(
2668           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2669       // Fixup to set vararg frame on shadow area (4 x i64).
2670       if (NumIntRegs < 4)
2671         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2672     } else {
2673       // For X86-64, if there are vararg parameters that are passed via
2674       // registers, then we must store them to their spots on the stack so
2675       // they may be loaded by deferencing the result of va_next.
2676       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2677       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2678       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2679           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2680     }
2681
2682     // Store the integer parameter registers.
2683     SmallVector<SDValue, 8> MemOps;
2684     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2685                                       getPointerTy(DAG.getDataLayout()));
2686     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2687     for (SDValue Val : LiveGPRs) {
2688       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2689                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2690       SDValue Store =
2691           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2692                        MachinePointerInfo::getFixedStack(
2693                            DAG.getMachineFunction(),
2694                            FuncInfo->getRegSaveFrameIndex(), Offset),
2695                        false, false, 0);
2696       MemOps.push_back(Store);
2697       Offset += 8;
2698     }
2699
2700     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2701       // Now store the XMM (fp + vector) parameter registers.
2702       SmallVector<SDValue, 12> SaveXMMOps;
2703       SaveXMMOps.push_back(Chain);
2704       SaveXMMOps.push_back(ALVal);
2705       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2706                              FuncInfo->getRegSaveFrameIndex(), dl));
2707       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2708                              FuncInfo->getVarArgsFPOffset(), dl));
2709       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2710                         LiveXMMRegs.end());
2711       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2712                                    MVT::Other, SaveXMMOps));
2713     }
2714
2715     if (!MemOps.empty())
2716       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2717   } else if (IsWin64 && IsWinEHOutlined) {
2718     // Get to the caller-allocated home save location.  Add 8 to account
2719     // for the return address.
2720     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2721     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2722         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2723
2724     MMI.getWinEHFuncInfo(Fn)
2725         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2726         FuncInfo->getRegSaveFrameIndex();
2727
2728     // Store the second integer parameter (rdx) into rsp+16 relative to the
2729     // stack pointer at the entry of the function.
2730     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2731                                       getPointerTy(DAG.getDataLayout()));
2732     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2733     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2734     Chain = DAG.getStore(
2735         Val.getValue(1), dl, Val, RSFIN,
2736         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2737                                           FuncInfo->getRegSaveFrameIndex()),
2738         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2739   }
2740
2741   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2742     // Find the largest legal vector type.
2743     MVT VecVT = MVT::Other;
2744     // FIXME: Only some x86_32 calling conventions support AVX512.
2745     if (Subtarget->hasAVX512() &&
2746         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2747                      CallConv == CallingConv::Intel_OCL_BI)))
2748       VecVT = MVT::v16f32;
2749     else if (Subtarget->hasAVX())
2750       VecVT = MVT::v8f32;
2751     else if (Subtarget->hasSSE2())
2752       VecVT = MVT::v4f32;
2753
2754     // We forward some GPRs and some vector types.
2755     SmallVector<MVT, 2> RegParmTypes;
2756     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2757     RegParmTypes.push_back(IntVT);
2758     if (VecVT != MVT::Other)
2759       RegParmTypes.push_back(VecVT);
2760
2761     // Compute the set of forwarded registers. The rest are scratch.
2762     SmallVectorImpl<ForwardedRegister> &Forwards =
2763         FuncInfo->getForwardedMustTailRegParms();
2764     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2765
2766     // Conservatively forward AL on x86_64, since it might be used for varargs.
2767     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2768       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2769       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2770     }
2771
2772     // Copy all forwards from physical to virtual registers.
2773     for (ForwardedRegister &F : Forwards) {
2774       // FIXME: Can we use a less constrained schedule?
2775       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2776       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2777       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2778     }
2779   }
2780
2781   // Some CCs need callee pop.
2782   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2783                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2784     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2785   } else {
2786     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2787     // If this is an sret function, the return should pop the hidden pointer.
2788     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2789         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2790         argsAreStructReturn(Ins) == StackStructReturn)
2791       FuncInfo->setBytesToPopOnReturn(4);
2792   }
2793
2794   if (!Is64Bit) {
2795     // RegSaveFrameIndex is X86-64 only.
2796     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2797     if (CallConv == CallingConv::X86_FastCall ||
2798         CallConv == CallingConv::X86_ThisCall)
2799       // fastcc functions can't have varargs.
2800       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2801   }
2802
2803   FuncInfo->setArgumentStackSize(StackSize);
2804
2805   if (IsWinEHParent) {
2806     if (Is64Bit) {
2807       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2808       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2809       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2810       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2811       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2812                            MachinePointerInfo::getFixedStack(
2813                                DAG.getMachineFunction(), UnwindHelpFI),
2814                            /*isVolatile=*/true,
2815                            /*isNonTemporal=*/false, /*Alignment=*/0);
2816     } else {
2817       // Functions using Win32 EH are considered to have opaque SP adjustments
2818       // to force local variables to be addressed from the frame or base
2819       // pointers.
2820       MFI->setHasOpaqueSPAdjustment(true);
2821     }
2822   }
2823
2824   return Chain;
2825 }
2826
2827 SDValue
2828 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2829                                     SDValue StackPtr, SDValue Arg,
2830                                     SDLoc dl, SelectionDAG &DAG,
2831                                     const CCValAssign &VA,
2832                                     ISD::ArgFlagsTy Flags) const {
2833   unsigned LocMemOffset = VA.getLocMemOffset();
2834   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2835   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2836                        StackPtr, PtrOff);
2837   if (Flags.isByVal())
2838     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2839
2840   return DAG.getStore(
2841       Chain, dl, Arg, PtrOff,
2842       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2843       false, false, 0);
2844 }
2845
2846 /// Emit a load of return address if tail call
2847 /// optimization is performed and it is required.
2848 SDValue
2849 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2850                                            SDValue &OutRetAddr, SDValue Chain,
2851                                            bool IsTailCall, bool Is64Bit,
2852                                            int FPDiff, SDLoc dl) const {
2853   // Adjust the Return address stack slot.
2854   EVT VT = getPointerTy(DAG.getDataLayout());
2855   OutRetAddr = getReturnAddressFrameIndex(DAG);
2856
2857   // Load the "old" Return address.
2858   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2859                            false, false, false, 0);
2860   return SDValue(OutRetAddr.getNode(), 1);
2861 }
2862
2863 /// Emit a store of the return address if tail call
2864 /// optimization is performed and it is required (FPDiff!=0).
2865 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2866                                         SDValue Chain, SDValue RetAddrFrIdx,
2867                                         EVT PtrVT, unsigned SlotSize,
2868                                         int FPDiff, SDLoc dl) {
2869   // Store the return address to the appropriate stack slot.
2870   if (!FPDiff) return Chain;
2871   // Calculate the new stack slot for the return address.
2872   int NewReturnAddrFI =
2873     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2874                                          false);
2875   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2876   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2877                        MachinePointerInfo::getFixedStack(
2878                            DAG.getMachineFunction(), NewReturnAddrFI),
2879                        false, false, 0);
2880   return Chain;
2881 }
2882
2883 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2884 /// operation of specified width.
2885 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2886                        SDValue V2) {
2887   unsigned NumElems = VT.getVectorNumElements();
2888   SmallVector<int, 8> Mask;
2889   Mask.push_back(NumElems);
2890   for (unsigned i = 1; i != NumElems; ++i)
2891     Mask.push_back(i);
2892   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2893 }
2894
2895 SDValue
2896 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2897                              SmallVectorImpl<SDValue> &InVals) const {
2898   SelectionDAG &DAG                     = CLI.DAG;
2899   SDLoc &dl                             = CLI.DL;
2900   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2901   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2902   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2903   SDValue Chain                         = CLI.Chain;
2904   SDValue Callee                        = CLI.Callee;
2905   CallingConv::ID CallConv              = CLI.CallConv;
2906   bool &isTailCall                      = CLI.IsTailCall;
2907   bool isVarArg                         = CLI.IsVarArg;
2908
2909   MachineFunction &MF = DAG.getMachineFunction();
2910   bool Is64Bit        = Subtarget->is64Bit();
2911   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2912   StructReturnType SR = callIsStructReturn(Outs);
2913   bool IsSibcall      = false;
2914   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2915   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2916
2917   if (Attr.getValueAsString() == "true")
2918     isTailCall = false;
2919
2920   if (Subtarget->isPICStyleGOT() &&
2921       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2922     // If we are using a GOT, disable tail calls to external symbols with
2923     // default visibility. Tail calling such a symbol requires using a GOT
2924     // relocation, which forces early binding of the symbol. This breaks code
2925     // that require lazy function symbol resolution. Using musttail or
2926     // GuaranteedTailCallOpt will override this.
2927     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2928     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2929                G->getGlobal()->hasDefaultVisibility()))
2930       isTailCall = false;
2931   }
2932
2933   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2934   if (IsMustTail) {
2935     // Force this to be a tail call.  The verifier rules are enough to ensure
2936     // that we can lower this successfully without moving the return address
2937     // around.
2938     isTailCall = true;
2939   } else if (isTailCall) {
2940     // Check if it's really possible to do a tail call.
2941     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2942                     isVarArg, SR != NotStructReturn,
2943                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2944                     Outs, OutVals, Ins, DAG);
2945
2946     // Sibcalls are automatically detected tailcalls which do not require
2947     // ABI changes.
2948     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2949       IsSibcall = true;
2950
2951     if (isTailCall)
2952       ++NumTailCalls;
2953   }
2954
2955   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2956          "Var args not supported with calling convention fastcc, ghc or hipe");
2957
2958   // Analyze operands of the call, assigning locations to each operand.
2959   SmallVector<CCValAssign, 16> ArgLocs;
2960   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2961
2962   // Allocate shadow area for Win64
2963   if (IsWin64)
2964     CCInfo.AllocateStack(32, 8);
2965
2966   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2967
2968   // Get a count of how many bytes are to be pushed on the stack.
2969   unsigned NumBytes = CCInfo.getNextStackOffset();
2970   if (IsSibcall)
2971     // This is a sibcall. The memory operands are available in caller's
2972     // own caller's stack.
2973     NumBytes = 0;
2974   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2975            IsTailCallConvention(CallConv))
2976     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2977
2978   int FPDiff = 0;
2979   if (isTailCall && !IsSibcall && !IsMustTail) {
2980     // Lower arguments at fp - stackoffset + fpdiff.
2981     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2982
2983     FPDiff = NumBytesCallerPushed - NumBytes;
2984
2985     // Set the delta of movement of the returnaddr stackslot.
2986     // But only set if delta is greater than previous delta.
2987     if (FPDiff < X86Info->getTCReturnAddrDelta())
2988       X86Info->setTCReturnAddrDelta(FPDiff);
2989   }
2990
2991   unsigned NumBytesToPush = NumBytes;
2992   unsigned NumBytesToPop = NumBytes;
2993
2994   // If we have an inalloca argument, all stack space has already been allocated
2995   // for us and be right at the top of the stack.  We don't support multiple
2996   // arguments passed in memory when using inalloca.
2997   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2998     NumBytesToPush = 0;
2999     if (!ArgLocs.back().isMemLoc())
3000       report_fatal_error("cannot use inalloca attribute on a register "
3001                          "parameter");
3002     if (ArgLocs.back().getLocMemOffset() != 0)
3003       report_fatal_error("any parameter with the inalloca attribute must be "
3004                          "the only memory argument");
3005   }
3006
3007   if (!IsSibcall)
3008     Chain = DAG.getCALLSEQ_START(
3009         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3010
3011   SDValue RetAddrFrIdx;
3012   // Load return address for tail calls.
3013   if (isTailCall && FPDiff)
3014     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3015                                     Is64Bit, FPDiff, dl);
3016
3017   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3018   SmallVector<SDValue, 8> MemOpChains;
3019   SDValue StackPtr;
3020
3021   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3022   // of tail call optimization arguments are handle later.
3023   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3024   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3025     // Skip inalloca arguments, they have already been written.
3026     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3027     if (Flags.isInAlloca())
3028       continue;
3029
3030     CCValAssign &VA = ArgLocs[i];
3031     EVT RegVT = VA.getLocVT();
3032     SDValue Arg = OutVals[i];
3033     bool isByVal = Flags.isByVal();
3034
3035     // Promote the value if needed.
3036     switch (VA.getLocInfo()) {
3037     default: llvm_unreachable("Unknown loc info!");
3038     case CCValAssign::Full: break;
3039     case CCValAssign::SExt:
3040       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3041       break;
3042     case CCValAssign::ZExt:
3043       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3044       break;
3045     case CCValAssign::AExt:
3046       if (Arg.getValueType().isVector() &&
3047           Arg.getValueType().getScalarType() == MVT::i1)
3048         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3049       else if (RegVT.is128BitVector()) {
3050         // Special case: passing MMX values in XMM registers.
3051         Arg = DAG.getBitcast(MVT::i64, Arg);
3052         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3053         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3054       } else
3055         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3056       break;
3057     case CCValAssign::BCvt:
3058       Arg = DAG.getBitcast(RegVT, Arg);
3059       break;
3060     case CCValAssign::Indirect: {
3061       // Store the argument.
3062       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3063       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3064       Chain = DAG.getStore(
3065           Chain, dl, Arg, SpillSlot,
3066           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3067           false, false, 0);
3068       Arg = SpillSlot;
3069       break;
3070     }
3071     }
3072
3073     if (VA.isRegLoc()) {
3074       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3075       if (isVarArg && IsWin64) {
3076         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3077         // shadow reg if callee is a varargs function.
3078         unsigned ShadowReg = 0;
3079         switch (VA.getLocReg()) {
3080         case X86::XMM0: ShadowReg = X86::RCX; break;
3081         case X86::XMM1: ShadowReg = X86::RDX; break;
3082         case X86::XMM2: ShadowReg = X86::R8; break;
3083         case X86::XMM3: ShadowReg = X86::R9; break;
3084         }
3085         if (ShadowReg)
3086           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3087       }
3088     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3089       assert(VA.isMemLoc());
3090       if (!StackPtr.getNode())
3091         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3092                                       getPointerTy(DAG.getDataLayout()));
3093       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3094                                              dl, DAG, VA, Flags));
3095     }
3096   }
3097
3098   if (!MemOpChains.empty())
3099     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3100
3101   if (Subtarget->isPICStyleGOT()) {
3102     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3103     // GOT pointer.
3104     if (!isTailCall) {
3105       RegsToPass.push_back(std::make_pair(
3106           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3107                                           getPointerTy(DAG.getDataLayout()))));
3108     } else {
3109       // If we are tail calling and generating PIC/GOT style code load the
3110       // address of the callee into ECX. The value in ecx is used as target of
3111       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3112       // for tail calls on PIC/GOT architectures. Normally we would just put the
3113       // address of GOT into ebx and then call target@PLT. But for tail calls
3114       // ebx would be restored (since ebx is callee saved) before jumping to the
3115       // target@PLT.
3116
3117       // Note: The actual moving to ECX is done further down.
3118       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3119       if (G && !G->getGlobal()->hasLocalLinkage() &&
3120           G->getGlobal()->hasDefaultVisibility())
3121         Callee = LowerGlobalAddress(Callee, DAG);
3122       else if (isa<ExternalSymbolSDNode>(Callee))
3123         Callee = LowerExternalSymbol(Callee, DAG);
3124     }
3125   }
3126
3127   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3128     // From AMD64 ABI document:
3129     // For calls that may call functions that use varargs or stdargs
3130     // (prototype-less calls or calls to functions containing ellipsis (...) in
3131     // the declaration) %al is used as hidden argument to specify the number
3132     // of SSE registers used. The contents of %al do not need to match exactly
3133     // the number of registers, but must be an ubound on the number of SSE
3134     // registers used and is in the range 0 - 8 inclusive.
3135
3136     // Count the number of XMM registers allocated.
3137     static const MCPhysReg XMMArgRegs[] = {
3138       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3139       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3140     };
3141     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3142     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3143            && "SSE registers cannot be used when SSE is disabled");
3144
3145     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3146                                         DAG.getConstant(NumXMMRegs, dl,
3147                                                         MVT::i8)));
3148   }
3149
3150   if (isVarArg && IsMustTail) {
3151     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3152     for (const auto &F : Forwards) {
3153       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3154       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3155     }
3156   }
3157
3158   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3159   // don't need this because the eligibility check rejects calls that require
3160   // shuffling arguments passed in memory.
3161   if (!IsSibcall && isTailCall) {
3162     // Force all the incoming stack arguments to be loaded from the stack
3163     // before any new outgoing arguments are stored to the stack, because the
3164     // outgoing stack slots may alias the incoming argument stack slots, and
3165     // the alias isn't otherwise explicit. This is slightly more conservative
3166     // than necessary, because it means that each store effectively depends
3167     // on every argument instead of just those arguments it would clobber.
3168     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3169
3170     SmallVector<SDValue, 8> MemOpChains2;
3171     SDValue FIN;
3172     int FI = 0;
3173     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3174       CCValAssign &VA = ArgLocs[i];
3175       if (VA.isRegLoc())
3176         continue;
3177       assert(VA.isMemLoc());
3178       SDValue Arg = OutVals[i];
3179       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3180       // Skip inalloca arguments.  They don't require any work.
3181       if (Flags.isInAlloca())
3182         continue;
3183       // Create frame index.
3184       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3185       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3186       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3187       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3188
3189       if (Flags.isByVal()) {
3190         // Copy relative to framepointer.
3191         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3192         if (!StackPtr.getNode())
3193           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3194                                         getPointerTy(DAG.getDataLayout()));
3195         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3196                              StackPtr, Source);
3197
3198         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3199                                                          ArgChain,
3200                                                          Flags, DAG, dl));
3201       } else {
3202         // Store relative to framepointer.
3203         MemOpChains2.push_back(DAG.getStore(
3204             ArgChain, dl, Arg, FIN,
3205             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3206             false, false, 0));
3207       }
3208     }
3209
3210     if (!MemOpChains2.empty())
3211       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3212
3213     // Store the return address to the appropriate stack slot.
3214     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3215                                      getPointerTy(DAG.getDataLayout()),
3216                                      RegInfo->getSlotSize(), FPDiff, dl);
3217   }
3218
3219   // Build a sequence of copy-to-reg nodes chained together with token chain
3220   // and flag operands which copy the outgoing args into registers.
3221   SDValue InFlag;
3222   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3223     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3224                              RegsToPass[i].second, InFlag);
3225     InFlag = Chain.getValue(1);
3226   }
3227
3228   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3229     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3230     // In the 64-bit large code model, we have to make all calls
3231     // through a register, since the call instruction's 32-bit
3232     // pc-relative offset may not be large enough to hold the whole
3233     // address.
3234   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3235     // If the callee is a GlobalAddress node (quite common, every direct call
3236     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3237     // it.
3238     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3239
3240     // We should use extra load for direct calls to dllimported functions in
3241     // non-JIT mode.
3242     const GlobalValue *GV = G->getGlobal();
3243     if (!GV->hasDLLImportStorageClass()) {
3244       unsigned char OpFlags = 0;
3245       bool ExtraLoad = false;
3246       unsigned WrapperKind = ISD::DELETED_NODE;
3247
3248       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3249       // external symbols most go through the PLT in PIC mode.  If the symbol
3250       // has hidden or protected visibility, or if it is static or local, then
3251       // we don't need to use the PLT - we can directly call it.
3252       if (Subtarget->isTargetELF() &&
3253           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3254           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3255         OpFlags = X86II::MO_PLT;
3256       } else if (Subtarget->isPICStyleStubAny() &&
3257                  !GV->isStrongDefinitionForLinker() &&
3258                  (!Subtarget->getTargetTriple().isMacOSX() ||
3259                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3260         // PC-relative references to external symbols should go through $stub,
3261         // unless we're building with the leopard linker or later, which
3262         // automatically synthesizes these stubs.
3263         OpFlags = X86II::MO_DARWIN_STUB;
3264       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3265                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3266         // If the function is marked as non-lazy, generate an indirect call
3267         // which loads from the GOT directly. This avoids runtime overhead
3268         // at the cost of eager binding (and one extra byte of encoding).
3269         OpFlags = X86II::MO_GOTPCREL;
3270         WrapperKind = X86ISD::WrapperRIP;
3271         ExtraLoad = true;
3272       }
3273
3274       Callee = DAG.getTargetGlobalAddress(
3275           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3276
3277       // Add a wrapper if needed.
3278       if (WrapperKind != ISD::DELETED_NODE)
3279         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3280                              getPointerTy(DAG.getDataLayout()), Callee);
3281       // Add extra indirection if needed.
3282       if (ExtraLoad)
3283         Callee = DAG.getLoad(
3284             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3285             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3286             false, 0);
3287     }
3288   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3289     unsigned char OpFlags = 0;
3290
3291     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3292     // external symbols should go through the PLT.
3293     if (Subtarget->isTargetELF() &&
3294         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3295       OpFlags = X86II::MO_PLT;
3296     } else if (Subtarget->isPICStyleStubAny() &&
3297                (!Subtarget->getTargetTriple().isMacOSX() ||
3298                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3299       // PC-relative references to external symbols should go through $stub,
3300       // unless we're building with the leopard linker or later, which
3301       // automatically synthesizes these stubs.
3302       OpFlags = X86II::MO_DARWIN_STUB;
3303     }
3304
3305     Callee = DAG.getTargetExternalSymbol(
3306         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3307   } else if (Subtarget->isTarget64BitILP32() &&
3308              Callee->getValueType(0) == MVT::i32) {
3309     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3310     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3311   }
3312
3313   // Returns a chain & a flag for retval copy to use.
3314   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3315   SmallVector<SDValue, 8> Ops;
3316
3317   if (!IsSibcall && isTailCall) {
3318     Chain = DAG.getCALLSEQ_END(Chain,
3319                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3320                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3321     InFlag = Chain.getValue(1);
3322   }
3323
3324   Ops.push_back(Chain);
3325   Ops.push_back(Callee);
3326
3327   if (isTailCall)
3328     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3329
3330   // Add argument registers to the end of the list so that they are known live
3331   // into the call.
3332   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3333     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3334                                   RegsToPass[i].second.getValueType()));
3335
3336   // Add a register mask operand representing the call-preserved registers.
3337   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3338   assert(Mask && "Missing call preserved mask for calling convention");
3339
3340   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3341   // the function clobbers all registers. If an exception is thrown, the runtime
3342   // will not restore CSRs.
3343   // FIXME: Model this more precisely so that we can register allocate across
3344   // the normal edge and spill and fill across the exceptional edge.
3345   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3346     const Function *CallerFn = MF.getFunction();
3347     EHPersonality Pers =
3348         CallerFn->hasPersonalityFn()
3349             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3350             : EHPersonality::Unknown;
3351     if (isMSVCEHPersonality(Pers))
3352       Mask = RegInfo->getNoPreservedMask();
3353   }
3354
3355   Ops.push_back(DAG.getRegisterMask(Mask));
3356
3357   if (InFlag.getNode())
3358     Ops.push_back(InFlag);
3359
3360   if (isTailCall) {
3361     // We used to do:
3362     //// If this is the first return lowered for this function, add the regs
3363     //// to the liveout set for the function.
3364     // This isn't right, although it's probably harmless on x86; liveouts
3365     // should be computed from returns not tail calls.  Consider a void
3366     // function making a tail call to a function returning int.
3367     MF.getFrameInfo()->setHasTailCall();
3368     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3369   }
3370
3371   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3372   InFlag = Chain.getValue(1);
3373
3374   // Create the CALLSEQ_END node.
3375   unsigned NumBytesForCalleeToPop;
3376   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3377                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3378     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3379   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3380            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3381            SR == StackStructReturn)
3382     // If this is a call to a struct-return function, the callee
3383     // pops the hidden struct pointer, so we have to push it back.
3384     // This is common for Darwin/X86, Linux & Mingw32 targets.
3385     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3386     NumBytesForCalleeToPop = 4;
3387   else
3388     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3389
3390   // Returns a flag for retval copy to use.
3391   if (!IsSibcall) {
3392     Chain = DAG.getCALLSEQ_END(Chain,
3393                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3394                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3395                                                      true),
3396                                InFlag, dl);
3397     InFlag = Chain.getValue(1);
3398   }
3399
3400   // Handle result values, copying them out of physregs into vregs that we
3401   // return.
3402   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3403                          Ins, dl, DAG, InVals);
3404 }
3405
3406 //===----------------------------------------------------------------------===//
3407 //                Fast Calling Convention (tail call) implementation
3408 //===----------------------------------------------------------------------===//
3409
3410 //  Like std call, callee cleans arguments, convention except that ECX is
3411 //  reserved for storing the tail called function address. Only 2 registers are
3412 //  free for argument passing (inreg). Tail call optimization is performed
3413 //  provided:
3414 //                * tailcallopt is enabled
3415 //                * caller/callee are fastcc
3416 //  On X86_64 architecture with GOT-style position independent code only local
3417 //  (within module) calls are supported at the moment.
3418 //  To keep the stack aligned according to platform abi the function
3419 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3420 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3421 //  If a tail called function callee has more arguments than the caller the
3422 //  caller needs to make sure that there is room to move the RETADDR to. This is
3423 //  achieved by reserving an area the size of the argument delta right after the
3424 //  original RETADDR, but before the saved framepointer or the spilled registers
3425 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3426 //  stack layout:
3427 //    arg1
3428 //    arg2
3429 //    RETADDR
3430 //    [ new RETADDR
3431 //      move area ]
3432 //    (possible EBP)
3433 //    ESI
3434 //    EDI
3435 //    local1 ..
3436
3437 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3438 /// requirement.
3439 unsigned
3440 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3441                                                SelectionDAG& DAG) const {
3442   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3443   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3444   unsigned StackAlignment = TFI.getStackAlignment();
3445   uint64_t AlignMask = StackAlignment - 1;
3446   int64_t Offset = StackSize;
3447   unsigned SlotSize = RegInfo->getSlotSize();
3448   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3449     // Number smaller than 12 so just add the difference.
3450     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3451   } else {
3452     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3453     Offset = ((~AlignMask) & Offset) + StackAlignment +
3454       (StackAlignment-SlotSize);
3455   }
3456   return Offset;
3457 }
3458
3459 /// Return true if the given stack call argument is already available in the
3460 /// same position (relatively) of the caller's incoming argument stack.
3461 static
3462 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3463                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3464                          const X86InstrInfo *TII) {
3465   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3466   int FI = INT_MAX;
3467   if (Arg.getOpcode() == ISD::CopyFromReg) {
3468     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3469     if (!TargetRegisterInfo::isVirtualRegister(VR))
3470       return false;
3471     MachineInstr *Def = MRI->getVRegDef(VR);
3472     if (!Def)
3473       return false;
3474     if (!Flags.isByVal()) {
3475       if (!TII->isLoadFromStackSlot(Def, FI))
3476         return false;
3477     } else {
3478       unsigned Opcode = Def->getOpcode();
3479       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3480            Opcode == X86::LEA64_32r) &&
3481           Def->getOperand(1).isFI()) {
3482         FI = Def->getOperand(1).getIndex();
3483         Bytes = Flags.getByValSize();
3484       } else
3485         return false;
3486     }
3487   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3488     if (Flags.isByVal())
3489       // ByVal argument is passed in as a pointer but it's now being
3490       // dereferenced. e.g.
3491       // define @foo(%struct.X* %A) {
3492       //   tail call @bar(%struct.X* byval %A)
3493       // }
3494       return false;
3495     SDValue Ptr = Ld->getBasePtr();
3496     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3497     if (!FINode)
3498       return false;
3499     FI = FINode->getIndex();
3500   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3501     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3502     FI = FINode->getIndex();
3503     Bytes = Flags.getByValSize();
3504   } else
3505     return false;
3506
3507   assert(FI != INT_MAX);
3508   if (!MFI->isFixedObjectIndex(FI))
3509     return false;
3510   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3511 }
3512
3513 /// Check whether the call is eligible for tail call optimization. Targets
3514 /// that want to do tail call optimization should implement this function.
3515 bool
3516 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3517                                                      CallingConv::ID CalleeCC,
3518                                                      bool isVarArg,
3519                                                      bool isCalleeStructRet,
3520                                                      bool isCallerStructRet,
3521                                                      Type *RetTy,
3522                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3523                                     const SmallVectorImpl<SDValue> &OutVals,
3524                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3525                                                      SelectionDAG &DAG) const {
3526   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3527     return false;
3528
3529   // If -tailcallopt is specified, make fastcc functions tail-callable.
3530   const MachineFunction &MF = DAG.getMachineFunction();
3531   const Function *CallerF = MF.getFunction();
3532
3533   // If the function return type is x86_fp80 and the callee return type is not,
3534   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3535   // perform a tailcall optimization here.
3536   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3537     return false;
3538
3539   CallingConv::ID CallerCC = CallerF->getCallingConv();
3540   bool CCMatch = CallerCC == CalleeCC;
3541   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3542   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3543
3544   // Win64 functions have extra shadow space for argument homing. Don't do the
3545   // sibcall if the caller and callee have mismatched expectations for this
3546   // space.
3547   if (IsCalleeWin64 != IsCallerWin64)
3548     return false;
3549
3550   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3551     if (IsTailCallConvention(CalleeCC) && CCMatch)
3552       return true;
3553     return false;
3554   }
3555
3556   // Look for obvious safe cases to perform tail call optimization that do not
3557   // require ABI changes. This is what gcc calls sibcall.
3558
3559   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3560   // emit a special epilogue.
3561   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3562   if (RegInfo->needsStackRealignment(MF))
3563     return false;
3564
3565   // Also avoid sibcall optimization if either caller or callee uses struct
3566   // return semantics.
3567   if (isCalleeStructRet || isCallerStructRet)
3568     return false;
3569
3570   // An stdcall/thiscall caller is expected to clean up its arguments; the
3571   // callee isn't going to do that.
3572   // FIXME: this is more restrictive than needed. We could produce a tailcall
3573   // when the stack adjustment matches. For example, with a thiscall that takes
3574   // only one argument.
3575   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3576                    CallerCC == CallingConv::X86_ThisCall))
3577     return false;
3578
3579   // Do not sibcall optimize vararg calls unless all arguments are passed via
3580   // registers.
3581   if (isVarArg && !Outs.empty()) {
3582
3583     // Optimizing for varargs on Win64 is unlikely to be safe without
3584     // additional testing.
3585     if (IsCalleeWin64 || IsCallerWin64)
3586       return false;
3587
3588     SmallVector<CCValAssign, 16> ArgLocs;
3589     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3590                    *DAG.getContext());
3591
3592     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3593     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3594       if (!ArgLocs[i].isRegLoc())
3595         return false;
3596   }
3597
3598   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3599   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3600   // this into a sibcall.
3601   bool Unused = false;
3602   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3603     if (!Ins[i].Used) {
3604       Unused = true;
3605       break;
3606     }
3607   }
3608   if (Unused) {
3609     SmallVector<CCValAssign, 16> RVLocs;
3610     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3611                    *DAG.getContext());
3612     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3613     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3614       CCValAssign &VA = RVLocs[i];
3615       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3616         return false;
3617     }
3618   }
3619
3620   // If the calling conventions do not match, then we'd better make sure the
3621   // results are returned in the same way as what the caller expects.
3622   if (!CCMatch) {
3623     SmallVector<CCValAssign, 16> RVLocs1;
3624     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3625                     *DAG.getContext());
3626     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3627
3628     SmallVector<CCValAssign, 16> RVLocs2;
3629     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3630                     *DAG.getContext());
3631     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3632
3633     if (RVLocs1.size() != RVLocs2.size())
3634       return false;
3635     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3636       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3637         return false;
3638       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3639         return false;
3640       if (RVLocs1[i].isRegLoc()) {
3641         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3642           return false;
3643       } else {
3644         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3645           return false;
3646       }
3647     }
3648   }
3649
3650   // If the callee takes no arguments then go on to check the results of the
3651   // call.
3652   if (!Outs.empty()) {
3653     // Check if stack adjustment is needed. For now, do not do this if any
3654     // argument is passed on the stack.
3655     SmallVector<CCValAssign, 16> ArgLocs;
3656     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3657                    *DAG.getContext());
3658
3659     // Allocate shadow area for Win64
3660     if (IsCalleeWin64)
3661       CCInfo.AllocateStack(32, 8);
3662
3663     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3664     if (CCInfo.getNextStackOffset()) {
3665       MachineFunction &MF = DAG.getMachineFunction();
3666       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3667         return false;
3668
3669       // Check if the arguments are already laid out in the right way as
3670       // the caller's fixed stack objects.
3671       MachineFrameInfo *MFI = MF.getFrameInfo();
3672       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3673       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3674       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3675         CCValAssign &VA = ArgLocs[i];
3676         SDValue Arg = OutVals[i];
3677         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3678         if (VA.getLocInfo() == CCValAssign::Indirect)
3679           return false;
3680         if (!VA.isRegLoc()) {
3681           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3682                                    MFI, MRI, TII))
3683             return false;
3684         }
3685       }
3686     }
3687
3688     // If the tailcall address may be in a register, then make sure it's
3689     // possible to register allocate for it. In 32-bit, the call address can
3690     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3691     // callee-saved registers are restored. These happen to be the same
3692     // registers used to pass 'inreg' arguments so watch out for those.
3693     if (!Subtarget->is64Bit() &&
3694         ((!isa<GlobalAddressSDNode>(Callee) &&
3695           !isa<ExternalSymbolSDNode>(Callee)) ||
3696          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3697       unsigned NumInRegs = 0;
3698       // In PIC we need an extra register to formulate the address computation
3699       // for the callee.
3700       unsigned MaxInRegs =
3701         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3702
3703       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3704         CCValAssign &VA = ArgLocs[i];
3705         if (!VA.isRegLoc())
3706           continue;
3707         unsigned Reg = VA.getLocReg();
3708         switch (Reg) {
3709         default: break;
3710         case X86::EAX: case X86::EDX: case X86::ECX:
3711           if (++NumInRegs == MaxInRegs)
3712             return false;
3713           break;
3714         }
3715       }
3716     }
3717   }
3718
3719   return true;
3720 }
3721
3722 FastISel *
3723 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3724                                   const TargetLibraryInfo *libInfo) const {
3725   return X86::createFastISel(funcInfo, libInfo);
3726 }
3727
3728 //===----------------------------------------------------------------------===//
3729 //                           Other Lowering Hooks
3730 //===----------------------------------------------------------------------===//
3731
3732 static bool MayFoldLoad(SDValue Op) {
3733   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3734 }
3735
3736 static bool MayFoldIntoStore(SDValue Op) {
3737   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3738 }
3739
3740 static bool isTargetShuffle(unsigned Opcode) {
3741   switch(Opcode) {
3742   default: return false;
3743   case X86ISD::BLENDI:
3744   case X86ISD::PSHUFB:
3745   case X86ISD::PSHUFD:
3746   case X86ISD::PSHUFHW:
3747   case X86ISD::PSHUFLW:
3748   case X86ISD::SHUFP:
3749   case X86ISD::PALIGNR:
3750   case X86ISD::MOVLHPS:
3751   case X86ISD::MOVLHPD:
3752   case X86ISD::MOVHLPS:
3753   case X86ISD::MOVLPS:
3754   case X86ISD::MOVLPD:
3755   case X86ISD::MOVSHDUP:
3756   case X86ISD::MOVSLDUP:
3757   case X86ISD::MOVDDUP:
3758   case X86ISD::MOVSS:
3759   case X86ISD::MOVSD:
3760   case X86ISD::UNPCKL:
3761   case X86ISD::UNPCKH:
3762   case X86ISD::VPERMILPI:
3763   case X86ISD::VPERM2X128:
3764   case X86ISD::VPERMI:
3765     return true;
3766   }
3767 }
3768
3769 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3770                                     SDValue V1, unsigned TargetMask,
3771                                     SelectionDAG &DAG) {
3772   switch(Opc) {
3773   default: llvm_unreachable("Unknown x86 shuffle node");
3774   case X86ISD::PSHUFD:
3775   case X86ISD::PSHUFHW:
3776   case X86ISD::PSHUFLW:
3777   case X86ISD::VPERMILPI:
3778   case X86ISD::VPERMI:
3779     return DAG.getNode(Opc, dl, VT, V1,
3780                        DAG.getConstant(TargetMask, dl, MVT::i8));
3781   }
3782 }
3783
3784 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3785                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3786   switch(Opc) {
3787   default: llvm_unreachable("Unknown x86 shuffle node");
3788   case X86ISD::MOVLHPS:
3789   case X86ISD::MOVLHPD:
3790   case X86ISD::MOVHLPS:
3791   case X86ISD::MOVLPS:
3792   case X86ISD::MOVLPD:
3793   case X86ISD::MOVSS:
3794   case X86ISD::MOVSD:
3795   case X86ISD::UNPCKL:
3796   case X86ISD::UNPCKH:
3797     return DAG.getNode(Opc, dl, VT, V1, V2);
3798   }
3799 }
3800
3801 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3802   MachineFunction &MF = DAG.getMachineFunction();
3803   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3804   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3805   int ReturnAddrIndex = FuncInfo->getRAIndex();
3806
3807   if (ReturnAddrIndex == 0) {
3808     // Set up a frame object for the return address.
3809     unsigned SlotSize = RegInfo->getSlotSize();
3810     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3811                                                            -(int64_t)SlotSize,
3812                                                            false);
3813     FuncInfo->setRAIndex(ReturnAddrIndex);
3814   }
3815
3816   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3817 }
3818
3819 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3820                                        bool hasSymbolicDisplacement) {
3821   // Offset should fit into 32 bit immediate field.
3822   if (!isInt<32>(Offset))
3823     return false;
3824
3825   // If we don't have a symbolic displacement - we don't have any extra
3826   // restrictions.
3827   if (!hasSymbolicDisplacement)
3828     return true;
3829
3830   // FIXME: Some tweaks might be needed for medium code model.
3831   if (M != CodeModel::Small && M != CodeModel::Kernel)
3832     return false;
3833
3834   // For small code model we assume that latest object is 16MB before end of 31
3835   // bits boundary. We may also accept pretty large negative constants knowing
3836   // that all objects are in the positive half of address space.
3837   if (M == CodeModel::Small && Offset < 16*1024*1024)
3838     return true;
3839
3840   // For kernel code model we know that all object resist in the negative half
3841   // of 32bits address space. We may not accept negative offsets, since they may
3842   // be just off and we may accept pretty large positive ones.
3843   if (M == CodeModel::Kernel && Offset >= 0)
3844     return true;
3845
3846   return false;
3847 }
3848
3849 /// Determines whether the callee is required to pop its own arguments.
3850 /// Callee pop is necessary to support tail calls.
3851 bool X86::isCalleePop(CallingConv::ID CallingConv,
3852                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3853   switch (CallingConv) {
3854   default:
3855     return false;
3856   case CallingConv::X86_StdCall:
3857   case CallingConv::X86_FastCall:
3858   case CallingConv::X86_ThisCall:
3859     return !is64Bit;
3860   case CallingConv::Fast:
3861   case CallingConv::GHC:
3862   case CallingConv::HiPE:
3863     if (IsVarArg)
3864       return false;
3865     return TailCallOpt;
3866   }
3867 }
3868
3869 /// \brief Return true if the condition is an unsigned comparison operation.
3870 static bool isX86CCUnsigned(unsigned X86CC) {
3871   switch (X86CC) {
3872   default: llvm_unreachable("Invalid integer condition!");
3873   case X86::COND_E:     return true;
3874   case X86::COND_G:     return false;
3875   case X86::COND_GE:    return false;
3876   case X86::COND_L:     return false;
3877   case X86::COND_LE:    return false;
3878   case X86::COND_NE:    return true;
3879   case X86::COND_B:     return true;
3880   case X86::COND_A:     return true;
3881   case X86::COND_BE:    return true;
3882   case X86::COND_AE:    return true;
3883   }
3884   llvm_unreachable("covered switch fell through?!");
3885 }
3886
3887 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3888 /// condition code, returning the condition code and the LHS/RHS of the
3889 /// comparison to make.
3890 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3891                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3892   if (!isFP) {
3893     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3894       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3895         // X > -1   -> X == 0, jump !sign.
3896         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3897         return X86::COND_NS;
3898       }
3899       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3900         // X < 0   -> X == 0, jump on sign.
3901         return X86::COND_S;
3902       }
3903       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3904         // X < 1   -> X <= 0
3905         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3906         return X86::COND_LE;
3907       }
3908     }
3909
3910     switch (SetCCOpcode) {
3911     default: llvm_unreachable("Invalid integer condition!");
3912     case ISD::SETEQ:  return X86::COND_E;
3913     case ISD::SETGT:  return X86::COND_G;
3914     case ISD::SETGE:  return X86::COND_GE;
3915     case ISD::SETLT:  return X86::COND_L;
3916     case ISD::SETLE:  return X86::COND_LE;
3917     case ISD::SETNE:  return X86::COND_NE;
3918     case ISD::SETULT: return X86::COND_B;
3919     case ISD::SETUGT: return X86::COND_A;
3920     case ISD::SETULE: return X86::COND_BE;
3921     case ISD::SETUGE: return X86::COND_AE;
3922     }
3923   }
3924
3925   // First determine if it is required or is profitable to flip the operands.
3926
3927   // If LHS is a foldable load, but RHS is not, flip the condition.
3928   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3929       !ISD::isNON_EXTLoad(RHS.getNode())) {
3930     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3931     std::swap(LHS, RHS);
3932   }
3933
3934   switch (SetCCOpcode) {
3935   default: break;
3936   case ISD::SETOLT:
3937   case ISD::SETOLE:
3938   case ISD::SETUGT:
3939   case ISD::SETUGE:
3940     std::swap(LHS, RHS);
3941     break;
3942   }
3943
3944   // On a floating point condition, the flags are set as follows:
3945   // ZF  PF  CF   op
3946   //  0 | 0 | 0 | X > Y
3947   //  0 | 0 | 1 | X < Y
3948   //  1 | 0 | 0 | X == Y
3949   //  1 | 1 | 1 | unordered
3950   switch (SetCCOpcode) {
3951   default: llvm_unreachable("Condcode should be pre-legalized away");
3952   case ISD::SETUEQ:
3953   case ISD::SETEQ:   return X86::COND_E;
3954   case ISD::SETOLT:              // flipped
3955   case ISD::SETOGT:
3956   case ISD::SETGT:   return X86::COND_A;
3957   case ISD::SETOLE:              // flipped
3958   case ISD::SETOGE:
3959   case ISD::SETGE:   return X86::COND_AE;
3960   case ISD::SETUGT:              // flipped
3961   case ISD::SETULT:
3962   case ISD::SETLT:   return X86::COND_B;
3963   case ISD::SETUGE:              // flipped
3964   case ISD::SETULE:
3965   case ISD::SETLE:   return X86::COND_BE;
3966   case ISD::SETONE:
3967   case ISD::SETNE:   return X86::COND_NE;
3968   case ISD::SETUO:   return X86::COND_P;
3969   case ISD::SETO:    return X86::COND_NP;
3970   case ISD::SETOEQ:
3971   case ISD::SETUNE:  return X86::COND_INVALID;
3972   }
3973 }
3974
3975 /// Is there a floating point cmov for the specific X86 condition code?
3976 /// Current x86 isa includes the following FP cmov instructions:
3977 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3978 static bool hasFPCMov(unsigned X86CC) {
3979   switch (X86CC) {
3980   default:
3981     return false;
3982   case X86::COND_B:
3983   case X86::COND_BE:
3984   case X86::COND_E:
3985   case X86::COND_P:
3986   case X86::COND_A:
3987   case X86::COND_AE:
3988   case X86::COND_NE:
3989   case X86::COND_NP:
3990     return true;
3991   }
3992 }
3993
3994 /// Returns true if the target can instruction select the
3995 /// specified FP immediate natively. If false, the legalizer will
3996 /// materialize the FP immediate as a load from a constant pool.
3997 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3998   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3999     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4000       return true;
4001   }
4002   return false;
4003 }
4004
4005 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4006                                               ISD::LoadExtType ExtTy,
4007                                               EVT NewVT) const {
4008   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4009   // relocation target a movq or addq instruction: don't let the load shrink.
4010   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4011   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4012     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4013       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4014   return true;
4015 }
4016
4017 /// \brief Returns true if it is beneficial to convert a load of a constant
4018 /// to just the constant itself.
4019 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4020                                                           Type *Ty) const {
4021   assert(Ty->isIntegerTy());
4022
4023   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4024   if (BitSize == 0 || BitSize > 64)
4025     return false;
4026   return true;
4027 }
4028
4029 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4030                                                 unsigned Index) const {
4031   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4032     return false;
4033
4034   return (Index == 0 || Index == ResVT.getVectorNumElements());
4035 }
4036
4037 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4038   // Speculate cttz only if we can directly use TZCNT.
4039   return Subtarget->hasBMI();
4040 }
4041
4042 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4043   // Speculate ctlz only if we can directly use LZCNT.
4044   return Subtarget->hasLZCNT();
4045 }
4046
4047 /// Return true if every element in Mask, beginning
4048 /// from position Pos and ending in Pos+Size is undef.
4049 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4050   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4051     if (0 <= Mask[i])
4052       return false;
4053   return true;
4054 }
4055
4056 /// Return true if Val is undef or if its value falls within the
4057 /// specified range (L, H].
4058 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4059   return (Val < 0) || (Val >= Low && Val < Hi);
4060 }
4061
4062 /// Val is either less than zero (undef) or equal to the specified value.
4063 static bool isUndefOrEqual(int Val, int CmpVal) {
4064   return (Val < 0 || Val == CmpVal);
4065 }
4066
4067 /// Return true if every element in Mask, beginning
4068 /// from position Pos and ending in Pos+Size, falls within the specified
4069 /// sequential range (Low, Low+Size]. or is undef.
4070 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4071                                        unsigned Pos, unsigned Size, int Low) {
4072   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4073     if (!isUndefOrEqual(Mask[i], Low))
4074       return false;
4075   return true;
4076 }
4077
4078 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4079 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4080 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4081   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4082   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4083     return false;
4084
4085   // The index should be aligned on a vecWidth-bit boundary.
4086   uint64_t Index =
4087     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4088
4089   MVT VT = N->getSimpleValueType(0);
4090   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4091   bool Result = (Index * ElSize) % vecWidth == 0;
4092
4093   return Result;
4094 }
4095
4096 /// Return true if the specified INSERT_SUBVECTOR
4097 /// operand specifies a subvector insert that is suitable for input to
4098 /// insertion of 128 or 256-bit subvectors
4099 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4100   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4101   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4102     return false;
4103   // The index should be aligned on a vecWidth-bit boundary.
4104   uint64_t Index =
4105     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4106
4107   MVT VT = N->getSimpleValueType(0);
4108   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4109   bool Result = (Index * ElSize) % vecWidth == 0;
4110
4111   return Result;
4112 }
4113
4114 bool X86::isVINSERT128Index(SDNode *N) {
4115   return isVINSERTIndex(N, 128);
4116 }
4117
4118 bool X86::isVINSERT256Index(SDNode *N) {
4119   return isVINSERTIndex(N, 256);
4120 }
4121
4122 bool X86::isVEXTRACT128Index(SDNode *N) {
4123   return isVEXTRACTIndex(N, 128);
4124 }
4125
4126 bool X86::isVEXTRACT256Index(SDNode *N) {
4127   return isVEXTRACTIndex(N, 256);
4128 }
4129
4130 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4131   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4132   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4133     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4134
4135   uint64_t Index =
4136     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4137
4138   MVT VecVT = N->getOperand(0).getSimpleValueType();
4139   MVT ElVT = VecVT.getVectorElementType();
4140
4141   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4142   return Index / NumElemsPerChunk;
4143 }
4144
4145 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4146   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4147   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4148     llvm_unreachable("Illegal insert subvector for VINSERT");
4149
4150   uint64_t Index =
4151     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4152
4153   MVT VecVT = N->getSimpleValueType(0);
4154   MVT ElVT = VecVT.getVectorElementType();
4155
4156   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4157   return Index / NumElemsPerChunk;
4158 }
4159
4160 /// Return the appropriate immediate to extract the specified
4161 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4162 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4163   return getExtractVEXTRACTImmediate(N, 128);
4164 }
4165
4166 /// Return the appropriate immediate to extract the specified
4167 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4168 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4169   return getExtractVEXTRACTImmediate(N, 256);
4170 }
4171
4172 /// Return the appropriate immediate to insert at the specified
4173 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4174 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4175   return getInsertVINSERTImmediate(N, 128);
4176 }
4177
4178 /// Return the appropriate immediate to insert at the specified
4179 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4180 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4181   return getInsertVINSERTImmediate(N, 256);
4182 }
4183
4184 /// Returns true if Elt is a constant integer zero
4185 static bool isZero(SDValue V) {
4186   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4187   return C && C->isNullValue();
4188 }
4189
4190 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4191 bool X86::isZeroNode(SDValue Elt) {
4192   if (isZero(Elt))
4193     return true;
4194   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4195     return CFP->getValueAPF().isPosZero();
4196   return false;
4197 }
4198
4199 /// Returns a vector of specified type with all zero elements.
4200 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4201                              SelectionDAG &DAG, SDLoc dl) {
4202   assert(VT.isVector() && "Expected a vector type");
4203
4204   // Always build SSE zero vectors as <4 x i32> bitcasted
4205   // to their dest type. This ensures they get CSE'd.
4206   SDValue Vec;
4207   if (VT.is128BitVector()) {  // SSE
4208     if (Subtarget->hasSSE2()) {  // SSE2
4209       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4210       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4211     } else { // SSE1
4212       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4213       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4214     }
4215   } else if (VT.is256BitVector()) { // AVX
4216     if (Subtarget->hasInt256()) { // AVX2
4217       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4218       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4219       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4220     } else {
4221       // 256-bit logic and arithmetic instructions in AVX are all
4222       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4223       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4224       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4225       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4226     }
4227   } else if (VT.is512BitVector()) { // AVX-512
4228       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4229       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4230                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4232   } else if (VT.getScalarType() == MVT::i1) {
4233
4234     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4235             && "Unexpected vector type");
4236     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4237             && "Unexpected vector type");
4238     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4239     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4240     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4241   } else
4242     llvm_unreachable("Unexpected vector type");
4243
4244   return DAG.getBitcast(VT, Vec);
4245 }
4246
4247 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4248                                 SelectionDAG &DAG, SDLoc dl,
4249                                 unsigned vectorWidth) {
4250   assert((vectorWidth == 128 || vectorWidth == 256) &&
4251          "Unsupported vector width");
4252   EVT VT = Vec.getValueType();
4253   EVT ElVT = VT.getVectorElementType();
4254   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4255   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4256                                   VT.getVectorNumElements()/Factor);
4257
4258   // Extract from UNDEF is UNDEF.
4259   if (Vec.getOpcode() == ISD::UNDEF)
4260     return DAG.getUNDEF(ResultVT);
4261
4262   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4263   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4264
4265   // This is the index of the first element of the vectorWidth-bit chunk
4266   // we want.
4267   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4268                                * ElemsPerChunk);
4269
4270   // If the input is a buildvector just emit a smaller one.
4271   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4272     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4273                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4274                                     ElemsPerChunk));
4275
4276   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4277   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4278 }
4279
4280 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4281 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4282 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4283 /// instructions or a simple subregister reference. Idx is an index in the
4284 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4285 /// lowering EXTRACT_VECTOR_ELT operations easier.
4286 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4287                                    SelectionDAG &DAG, SDLoc dl) {
4288   assert((Vec.getValueType().is256BitVector() ||
4289           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4290   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4291 }
4292
4293 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4294 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4295                                    SelectionDAG &DAG, SDLoc dl) {
4296   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4297   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4298 }
4299
4300 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4301                                unsigned IdxVal, SelectionDAG &DAG,
4302                                SDLoc dl, unsigned vectorWidth) {
4303   assert((vectorWidth == 128 || vectorWidth == 256) &&
4304          "Unsupported vector width");
4305   // Inserting UNDEF is Result
4306   if (Vec.getOpcode() == ISD::UNDEF)
4307     return Result;
4308   EVT VT = Vec.getValueType();
4309   EVT ElVT = VT.getVectorElementType();
4310   EVT ResultVT = Result.getValueType();
4311
4312   // Insert the relevant vectorWidth bits.
4313   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4314
4315   // This is the index of the first element of the vectorWidth-bit chunk
4316   // we want.
4317   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4318                                * ElemsPerChunk);
4319
4320   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4321   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4322 }
4323
4324 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4325 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4326 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4327 /// simple superregister reference.  Idx is an index in the 128 bits
4328 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4329 /// lowering INSERT_VECTOR_ELT operations easier.
4330 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4331                                   SelectionDAG &DAG, SDLoc dl) {
4332   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4333
4334   // For insertion into the zero index (low half) of a 256-bit vector, it is
4335   // more efficient to generate a blend with immediate instead of an insert*128.
4336   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4337   // extend the subvector to the size of the result vector. Make sure that
4338   // we are not recursing on that node by checking for undef here.
4339   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4340       Result.getOpcode() != ISD::UNDEF) {
4341     EVT ResultVT = Result.getValueType();
4342     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4343     SDValue Undef = DAG.getUNDEF(ResultVT);
4344     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4345                                  Vec, ZeroIndex);
4346
4347     // The blend instruction, and therefore its mask, depend on the data type.
4348     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4349     if (ScalarType.isFloatingPoint()) {
4350       // Choose either vblendps (float) or vblendpd (double).
4351       unsigned ScalarSize = ScalarType.getSizeInBits();
4352       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4353       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4354       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4355       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4356     }
4357
4358     const X86Subtarget &Subtarget =
4359     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4360
4361     // AVX2 is needed for 256-bit integer blend support.
4362     // Integers must be cast to 32-bit because there is only vpblendd;
4363     // vpblendw can't be used for this because it has a handicapped mask.
4364
4365     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4366     // is still more efficient than using the wrong domain vinsertf128 that
4367     // will be created by InsertSubVector().
4368     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4369
4370     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4371     Vec256 = DAG.getBitcast(CastVT, Vec256);
4372     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4373     return DAG.getBitcast(ResultVT, Vec256);
4374   }
4375
4376   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4377 }
4378
4379 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4380                                   SelectionDAG &DAG, SDLoc dl) {
4381   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4382   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4383 }
4384
4385 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4386 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4387 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4388 /// large BUILD_VECTORS.
4389 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4390                                    unsigned NumElems, SelectionDAG &DAG,
4391                                    SDLoc dl) {
4392   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4393   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4394 }
4395
4396 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4397                                    unsigned NumElems, SelectionDAG &DAG,
4398                                    SDLoc dl) {
4399   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4400   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4401 }
4402
4403 /// Returns a vector of specified type with all bits set.
4404 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4405 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4406 /// Then bitcast to their original type, ensuring they get CSE'd.
4407 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4408                              SDLoc dl) {
4409   assert(VT.isVector() && "Expected a vector type");
4410
4411   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4412   SDValue Vec;
4413   if (VT.is256BitVector()) {
4414     if (HasInt256) { // AVX2
4415       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4416       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4417     } else { // AVX
4418       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4419       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4420     }
4421   } else if (VT.is128BitVector()) {
4422     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4423   } else
4424     llvm_unreachable("Unexpected vector type");
4425
4426   return DAG.getBitcast(VT, Vec);
4427 }
4428
4429 /// Returns a vector_shuffle node for an unpackl operation.
4430 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4431                           SDValue V2) {
4432   unsigned NumElems = VT.getVectorNumElements();
4433   SmallVector<int, 8> Mask;
4434   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4435     Mask.push_back(i);
4436     Mask.push_back(i + NumElems);
4437   }
4438   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4439 }
4440
4441 /// Returns a vector_shuffle node for an unpackh operation.
4442 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4443                           SDValue V2) {
4444   unsigned NumElems = VT.getVectorNumElements();
4445   SmallVector<int, 8> Mask;
4446   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4447     Mask.push_back(i + Half);
4448     Mask.push_back(i + NumElems + Half);
4449   }
4450   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4451 }
4452
4453 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4454 /// This produces a shuffle where the low element of V2 is swizzled into the
4455 /// zero/undef vector, landing at element Idx.
4456 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4457 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4458                                            bool IsZero,
4459                                            const X86Subtarget *Subtarget,
4460                                            SelectionDAG &DAG) {
4461   MVT VT = V2.getSimpleValueType();
4462   SDValue V1 = IsZero
4463     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4464   unsigned NumElems = VT.getVectorNumElements();
4465   SmallVector<int, 16> MaskVec;
4466   for (unsigned i = 0; i != NumElems; ++i)
4467     // If this is the insertion idx, put the low elt of V2 here.
4468     MaskVec.push_back(i == Idx ? NumElems : i);
4469   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4470 }
4471
4472 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4473 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4474 /// uses one source. Note that this will set IsUnary for shuffles which use a
4475 /// single input multiple times, and in those cases it will
4476 /// adjust the mask to only have indices within that single input.
4477 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4478 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4479                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4480   unsigned NumElems = VT.getVectorNumElements();
4481   SDValue ImmN;
4482
4483   IsUnary = false;
4484   bool IsFakeUnary = false;
4485   switch(N->getOpcode()) {
4486   case X86ISD::BLENDI:
4487     ImmN = N->getOperand(N->getNumOperands()-1);
4488     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4489     break;
4490   case X86ISD::SHUFP:
4491     ImmN = N->getOperand(N->getNumOperands()-1);
4492     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4493     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4494     break;
4495   case X86ISD::UNPCKH:
4496     DecodeUNPCKHMask(VT, Mask);
4497     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4498     break;
4499   case X86ISD::UNPCKL:
4500     DecodeUNPCKLMask(VT, Mask);
4501     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4502     break;
4503   case X86ISD::MOVHLPS:
4504     DecodeMOVHLPSMask(NumElems, Mask);
4505     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4506     break;
4507   case X86ISD::MOVLHPS:
4508     DecodeMOVLHPSMask(NumElems, Mask);
4509     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4510     break;
4511   case X86ISD::PALIGNR:
4512     ImmN = N->getOperand(N->getNumOperands()-1);
4513     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514     break;
4515   case X86ISD::PSHUFD:
4516   case X86ISD::VPERMILPI:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     IsUnary = true;
4520     break;
4521   case X86ISD::PSHUFHW:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     IsUnary = true;
4525     break;
4526   case X86ISD::PSHUFLW:
4527     ImmN = N->getOperand(N->getNumOperands()-1);
4528     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529     IsUnary = true;
4530     break;
4531   case X86ISD::PSHUFB: {
4532     IsUnary = true;
4533     SDValue MaskNode = N->getOperand(1);
4534     while (MaskNode->getOpcode() == ISD::BITCAST)
4535       MaskNode = MaskNode->getOperand(0);
4536
4537     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4538       // If we have a build-vector, then things are easy.
4539       EVT VT = MaskNode.getValueType();
4540       assert(VT.isVector() &&
4541              "Can't produce a non-vector with a build_vector!");
4542       if (!VT.isInteger())
4543         return false;
4544
4545       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4546
4547       SmallVector<uint64_t, 32> RawMask;
4548       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4549         SDValue Op = MaskNode->getOperand(i);
4550         if (Op->getOpcode() == ISD::UNDEF) {
4551           RawMask.push_back((uint64_t)SM_SentinelUndef);
4552           continue;
4553         }
4554         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4555         if (!CN)
4556           return false;
4557         APInt MaskElement = CN->getAPIntValue();
4558
4559         // We now have to decode the element which could be any integer size and
4560         // extract each byte of it.
4561         for (int j = 0; j < NumBytesPerElement; ++j) {
4562           // Note that this is x86 and so always little endian: the low byte is
4563           // the first byte of the mask.
4564           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4565           MaskElement = MaskElement.lshr(8);
4566         }
4567       }
4568       DecodePSHUFBMask(RawMask, Mask);
4569       break;
4570     }
4571
4572     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4573     if (!MaskLoad)
4574       return false;
4575
4576     SDValue Ptr = MaskLoad->getBasePtr();
4577     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4578         Ptr->getOpcode() == X86ISD::WrapperRIP)
4579       Ptr = Ptr->getOperand(0);
4580
4581     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4582     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4583       return false;
4584
4585     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4586       DecodePSHUFBMask(C, Mask);
4587       if (Mask.empty())
4588         return false;
4589       break;
4590     }
4591
4592     return false;
4593   }
4594   case X86ISD::VPERMI:
4595     ImmN = N->getOperand(N->getNumOperands()-1);
4596     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4597     IsUnary = true;
4598     break;
4599   case X86ISD::MOVSS:
4600   case X86ISD::MOVSD:
4601     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4602     break;
4603   case X86ISD::VPERM2X128:
4604     ImmN = N->getOperand(N->getNumOperands()-1);
4605     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606     if (Mask.empty()) return false;
4607     // Mask only contains negative index if an element is zero.
4608     if (std::any_of(Mask.begin(), Mask.end(),
4609                     [](int M){ return M == SM_SentinelZero; }))
4610       return false;
4611     break;
4612   case X86ISD::MOVSLDUP:
4613     DecodeMOVSLDUPMask(VT, Mask);
4614     IsUnary = true;
4615     break;
4616   case X86ISD::MOVSHDUP:
4617     DecodeMOVSHDUPMask(VT, Mask);
4618     IsUnary = true;
4619     break;
4620   case X86ISD::MOVDDUP:
4621     DecodeMOVDDUPMask(VT, Mask);
4622     IsUnary = true;
4623     break;
4624   case X86ISD::MOVLHPD:
4625   case X86ISD::MOVLPD:
4626   case X86ISD::MOVLPS:
4627     // Not yet implemented
4628     return false;
4629   default: llvm_unreachable("unknown target shuffle node");
4630   }
4631
4632   // If we have a fake unary shuffle, the shuffle mask is spread across two
4633   // inputs that are actually the same node. Re-map the mask to always point
4634   // into the first input.
4635   if (IsFakeUnary)
4636     for (int &M : Mask)
4637       if (M >= (int)Mask.size())
4638         M -= Mask.size();
4639
4640   return true;
4641 }
4642
4643 /// Returns the scalar element that will make up the ith
4644 /// element of the result of the vector shuffle.
4645 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4646                                    unsigned Depth) {
4647   if (Depth == 6)
4648     return SDValue();  // Limit search depth.
4649
4650   SDValue V = SDValue(N, 0);
4651   EVT VT = V.getValueType();
4652   unsigned Opcode = V.getOpcode();
4653
4654   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4655   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4656     int Elt = SV->getMaskElt(Index);
4657
4658     if (Elt < 0)
4659       return DAG.getUNDEF(VT.getVectorElementType());
4660
4661     unsigned NumElems = VT.getVectorNumElements();
4662     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4663                                          : SV->getOperand(1);
4664     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4665   }
4666
4667   // Recurse into target specific vector shuffles to find scalars.
4668   if (isTargetShuffle(Opcode)) {
4669     MVT ShufVT = V.getSimpleValueType();
4670     unsigned NumElems = ShufVT.getVectorNumElements();
4671     SmallVector<int, 16> ShuffleMask;
4672     bool IsUnary;
4673
4674     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4675       return SDValue();
4676
4677     int Elt = ShuffleMask[Index];
4678     if (Elt < 0)
4679       return DAG.getUNDEF(ShufVT.getVectorElementType());
4680
4681     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4682                                          : N->getOperand(1);
4683     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4684                                Depth+1);
4685   }
4686
4687   // Actual nodes that may contain scalar elements
4688   if (Opcode == ISD::BITCAST) {
4689     V = V.getOperand(0);
4690     EVT SrcVT = V.getValueType();
4691     unsigned NumElems = VT.getVectorNumElements();
4692
4693     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4694       return SDValue();
4695   }
4696
4697   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4698     return (Index == 0) ? V.getOperand(0)
4699                         : DAG.getUNDEF(VT.getVectorElementType());
4700
4701   if (V.getOpcode() == ISD::BUILD_VECTOR)
4702     return V.getOperand(Index);
4703
4704   return SDValue();
4705 }
4706
4707 /// Custom lower build_vector of v16i8.
4708 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4709                                        unsigned NumNonZero, unsigned NumZero,
4710                                        SelectionDAG &DAG,
4711                                        const X86Subtarget* Subtarget,
4712                                        const TargetLowering &TLI) {
4713   if (NumNonZero > 8)
4714     return SDValue();
4715
4716   SDLoc dl(Op);
4717   SDValue V;
4718   bool First = true;
4719
4720   // SSE4.1 - use PINSRB to insert each byte directly.
4721   if (Subtarget->hasSSE41()) {
4722     for (unsigned i = 0; i < 16; ++i) {
4723       bool isNonZero = (NonZeros & (1 << i)) != 0;
4724       if (isNonZero) {
4725         if (First) {
4726           if (NumZero)
4727             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4728           else
4729             V = DAG.getUNDEF(MVT::v16i8);
4730           First = false;
4731         }
4732         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4733                         MVT::v16i8, V, Op.getOperand(i),
4734                         DAG.getIntPtrConstant(i, dl));
4735       }
4736     }
4737
4738     return V;
4739   }
4740
4741   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4742   for (unsigned i = 0; i < 16; ++i) {
4743     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4744     if (ThisIsNonZero && First) {
4745       if (NumZero)
4746         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4747       else
4748         V = DAG.getUNDEF(MVT::v8i16);
4749       First = false;
4750     }
4751
4752     if ((i & 1) != 0) {
4753       SDValue ThisElt, LastElt;
4754       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4755       if (LastIsNonZero) {
4756         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4757                               MVT::i16, Op.getOperand(i-1));
4758       }
4759       if (ThisIsNonZero) {
4760         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4761         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4762                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4763         if (LastIsNonZero)
4764           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4765       } else
4766         ThisElt = LastElt;
4767
4768       if (ThisElt.getNode())
4769         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4770                         DAG.getIntPtrConstant(i/2, dl));
4771     }
4772   }
4773
4774   return DAG.getBitcast(MVT::v16i8, V);
4775 }
4776
4777 /// Custom lower build_vector of v8i16.
4778 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4779                                      unsigned NumNonZero, unsigned NumZero,
4780                                      SelectionDAG &DAG,
4781                                      const X86Subtarget* Subtarget,
4782                                      const TargetLowering &TLI) {
4783   if (NumNonZero > 4)
4784     return SDValue();
4785
4786   SDLoc dl(Op);
4787   SDValue V;
4788   bool First = true;
4789   for (unsigned i = 0; i < 8; ++i) {
4790     bool isNonZero = (NonZeros & (1 << i)) != 0;
4791     if (isNonZero) {
4792       if (First) {
4793         if (NumZero)
4794           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4795         else
4796           V = DAG.getUNDEF(MVT::v8i16);
4797         First = false;
4798       }
4799       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4800                       MVT::v8i16, V, Op.getOperand(i),
4801                       DAG.getIntPtrConstant(i, dl));
4802     }
4803   }
4804
4805   return V;
4806 }
4807
4808 /// Custom lower build_vector of v4i32 or v4f32.
4809 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4810                                      const X86Subtarget *Subtarget,
4811                                      const TargetLowering &TLI) {
4812   // Find all zeroable elements.
4813   std::bitset<4> Zeroable;
4814   for (int i=0; i < 4; ++i) {
4815     SDValue Elt = Op->getOperand(i);
4816     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4817   }
4818   assert(Zeroable.size() - Zeroable.count() > 1 &&
4819          "We expect at least two non-zero elements!");
4820
4821   // We only know how to deal with build_vector nodes where elements are either
4822   // zeroable or extract_vector_elt with constant index.
4823   SDValue FirstNonZero;
4824   unsigned FirstNonZeroIdx;
4825   for (unsigned i=0; i < 4; ++i) {
4826     if (Zeroable[i])
4827       continue;
4828     SDValue Elt = Op->getOperand(i);
4829     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4830         !isa<ConstantSDNode>(Elt.getOperand(1)))
4831       return SDValue();
4832     // Make sure that this node is extracting from a 128-bit vector.
4833     MVT VT = Elt.getOperand(0).getSimpleValueType();
4834     if (!VT.is128BitVector())
4835       return SDValue();
4836     if (!FirstNonZero.getNode()) {
4837       FirstNonZero = Elt;
4838       FirstNonZeroIdx = i;
4839     }
4840   }
4841
4842   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4843   SDValue V1 = FirstNonZero.getOperand(0);
4844   MVT VT = V1.getSimpleValueType();
4845
4846   // See if this build_vector can be lowered as a blend with zero.
4847   SDValue Elt;
4848   unsigned EltMaskIdx, EltIdx;
4849   int Mask[4];
4850   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4851     if (Zeroable[EltIdx]) {
4852       // The zero vector will be on the right hand side.
4853       Mask[EltIdx] = EltIdx+4;
4854       continue;
4855     }
4856
4857     Elt = Op->getOperand(EltIdx);
4858     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4859     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4860     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4861       break;
4862     Mask[EltIdx] = EltIdx;
4863   }
4864
4865   if (EltIdx == 4) {
4866     // Let the shuffle legalizer deal with blend operations.
4867     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4868     if (V1.getSimpleValueType() != VT)
4869       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4870     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4871   }
4872
4873   // See if we can lower this build_vector to a INSERTPS.
4874   if (!Subtarget->hasSSE41())
4875     return SDValue();
4876
4877   SDValue V2 = Elt.getOperand(0);
4878   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4879     V1 = SDValue();
4880
4881   bool CanFold = true;
4882   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4883     if (Zeroable[i])
4884       continue;
4885
4886     SDValue Current = Op->getOperand(i);
4887     SDValue SrcVector = Current->getOperand(0);
4888     if (!V1.getNode())
4889       V1 = SrcVector;
4890     CanFold = SrcVector == V1 &&
4891       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4892   }
4893
4894   if (!CanFold)
4895     return SDValue();
4896
4897   assert(V1.getNode() && "Expected at least two non-zero elements!");
4898   if (V1.getSimpleValueType() != MVT::v4f32)
4899     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4900   if (V2.getSimpleValueType() != MVT::v4f32)
4901     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4902
4903   // Ok, we can emit an INSERTPS instruction.
4904   unsigned ZMask = Zeroable.to_ulong();
4905
4906   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4907   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4908   SDLoc DL(Op);
4909   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4910                                DAG.getIntPtrConstant(InsertPSMask, DL));
4911   return DAG.getBitcast(VT, Result);
4912 }
4913
4914 /// Return a vector logical shift node.
4915 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4916                          unsigned NumBits, SelectionDAG &DAG,
4917                          const TargetLowering &TLI, SDLoc dl) {
4918   assert(VT.is128BitVector() && "Unknown type for VShift");
4919   MVT ShVT = MVT::v2i64;
4920   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4921   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4922   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4923   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4924   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4925   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4926 }
4927
4928 static SDValue
4929 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4930
4931   // Check if the scalar load can be widened into a vector load. And if
4932   // the address is "base + cst" see if the cst can be "absorbed" into
4933   // the shuffle mask.
4934   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4935     SDValue Ptr = LD->getBasePtr();
4936     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4937       return SDValue();
4938     EVT PVT = LD->getValueType(0);
4939     if (PVT != MVT::i32 && PVT != MVT::f32)
4940       return SDValue();
4941
4942     int FI = -1;
4943     int64_t Offset = 0;
4944     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4945       FI = FINode->getIndex();
4946       Offset = 0;
4947     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4948                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4949       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4950       Offset = Ptr.getConstantOperandVal(1);
4951       Ptr = Ptr.getOperand(0);
4952     } else {
4953       return SDValue();
4954     }
4955
4956     // FIXME: 256-bit vector instructions don't require a strict alignment,
4957     // improve this code to support it better.
4958     unsigned RequiredAlign = VT.getSizeInBits()/8;
4959     SDValue Chain = LD->getChain();
4960     // Make sure the stack object alignment is at least 16 or 32.
4961     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4962     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4963       if (MFI->isFixedObjectIndex(FI)) {
4964         // Can't change the alignment. FIXME: It's possible to compute
4965         // the exact stack offset and reference FI + adjust offset instead.
4966         // If someone *really* cares about this. That's the way to implement it.
4967         return SDValue();
4968       } else {
4969         MFI->setObjectAlignment(FI, RequiredAlign);
4970       }
4971     }
4972
4973     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4974     // Ptr + (Offset & ~15).
4975     if (Offset < 0)
4976       return SDValue();
4977     if ((Offset % RequiredAlign) & 3)
4978       return SDValue();
4979     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4980     if (StartOffset) {
4981       SDLoc DL(Ptr);
4982       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4983                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4984     }
4985
4986     int EltNo = (Offset - StartOffset) >> 2;
4987     unsigned NumElems = VT.getVectorNumElements();
4988
4989     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4990     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4991                              LD->getPointerInfo().getWithOffset(StartOffset),
4992                              false, false, false, 0);
4993
4994     SmallVector<int, 8> Mask(NumElems, EltNo);
4995
4996     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4997   }
4998
4999   return SDValue();
5000 }
5001
5002 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5003 /// elements can be replaced by a single large load which has the same value as
5004 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5005 ///
5006 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5007 ///
5008 /// FIXME: we'd also like to handle the case where the last elements are zero
5009 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5010 /// There's even a handy isZeroNode for that purpose.
5011 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5012                                         SDLoc &DL, SelectionDAG &DAG,
5013                                         bool isAfterLegalize) {
5014   unsigned NumElems = Elts.size();
5015
5016   LoadSDNode *LDBase = nullptr;
5017   unsigned LastLoadedElt = -1U;
5018
5019   // For each element in the initializer, see if we've found a load or an undef.
5020   // If we don't find an initial load element, or later load elements are
5021   // non-consecutive, bail out.
5022   for (unsigned i = 0; i < NumElems; ++i) {
5023     SDValue Elt = Elts[i];
5024     // Look through a bitcast.
5025     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5026       Elt = Elt.getOperand(0);
5027     if (!Elt.getNode() ||
5028         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5029       return SDValue();
5030     if (!LDBase) {
5031       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5032         return SDValue();
5033       LDBase = cast<LoadSDNode>(Elt.getNode());
5034       LastLoadedElt = i;
5035       continue;
5036     }
5037     if (Elt.getOpcode() == ISD::UNDEF)
5038       continue;
5039
5040     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5041     EVT LdVT = Elt.getValueType();
5042     // Each loaded element must be the correct fractional portion of the
5043     // requested vector load.
5044     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5045       return SDValue();
5046     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5047       return SDValue();
5048     LastLoadedElt = i;
5049   }
5050
5051   // If we have found an entire vector of loads and undefs, then return a large
5052   // load of the entire vector width starting at the base pointer.  If we found
5053   // consecutive loads for the low half, generate a vzext_load node.
5054   if (LastLoadedElt == NumElems - 1) {
5055     assert(LDBase && "Did not find base load for merging consecutive loads");
5056     EVT EltVT = LDBase->getValueType(0);
5057     // Ensure that the input vector size for the merged loads matches the
5058     // cumulative size of the input elements.
5059     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5060       return SDValue();
5061
5062     if (isAfterLegalize &&
5063         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5064       return SDValue();
5065
5066     SDValue NewLd = SDValue();
5067
5068     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5069                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5070                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5071                         LDBase->getAlignment());
5072
5073     if (LDBase->hasAnyUseOfValue(1)) {
5074       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5075                                      SDValue(LDBase, 1),
5076                                      SDValue(NewLd.getNode(), 1));
5077       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5078       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5079                              SDValue(NewLd.getNode(), 1));
5080     }
5081
5082     return NewLd;
5083   }
5084
5085   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5086   //of a v4i32 / v4f32. It's probably worth generalizing.
5087   EVT EltVT = VT.getVectorElementType();
5088   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5089       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5090     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5091     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5092     SDValue ResNode =
5093         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5094                                 LDBase->getPointerInfo(),
5095                                 LDBase->getAlignment(),
5096                                 false/*isVolatile*/, true/*ReadMem*/,
5097                                 false/*WriteMem*/);
5098
5099     // Make sure the newly-created LOAD is in the same position as LDBase in
5100     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5101     // update uses of LDBase's output chain to use the TokenFactor.
5102     if (LDBase->hasAnyUseOfValue(1)) {
5103       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5104                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5105       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5106       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5107                              SDValue(ResNode.getNode(), 1));
5108     }
5109
5110     return DAG.getBitcast(VT, ResNode);
5111   }
5112   return SDValue();
5113 }
5114
5115 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5116 /// to generate a splat value for the following cases:
5117 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5118 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5119 /// a scalar load, or a constant.
5120 /// The VBROADCAST node is returned when a pattern is found,
5121 /// or SDValue() otherwise.
5122 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5123                                     SelectionDAG &DAG) {
5124   // VBROADCAST requires AVX.
5125   // TODO: Splats could be generated for non-AVX CPUs using SSE
5126   // instructions, but there's less potential gain for only 128-bit vectors.
5127   if (!Subtarget->hasAVX())
5128     return SDValue();
5129
5130   MVT VT = Op.getSimpleValueType();
5131   SDLoc dl(Op);
5132
5133   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5134          "Unsupported vector type for broadcast.");
5135
5136   SDValue Ld;
5137   bool ConstSplatVal;
5138
5139   switch (Op.getOpcode()) {
5140     default:
5141       // Unknown pattern found.
5142       return SDValue();
5143
5144     case ISD::BUILD_VECTOR: {
5145       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5146       BitVector UndefElements;
5147       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5148
5149       // We need a splat of a single value to use broadcast, and it doesn't
5150       // make any sense if the value is only in one element of the vector.
5151       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5152         return SDValue();
5153
5154       Ld = Splat;
5155       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5156                        Ld.getOpcode() == ISD::ConstantFP);
5157
5158       // Make sure that all of the users of a non-constant load are from the
5159       // BUILD_VECTOR node.
5160       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5161         return SDValue();
5162       break;
5163     }
5164
5165     case ISD::VECTOR_SHUFFLE: {
5166       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5167
5168       // Shuffles must have a splat mask where the first element is
5169       // broadcasted.
5170       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5171         return SDValue();
5172
5173       SDValue Sc = Op.getOperand(0);
5174       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5175           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5176
5177         if (!Subtarget->hasInt256())
5178           return SDValue();
5179
5180         // Use the register form of the broadcast instruction available on AVX2.
5181         if (VT.getSizeInBits() >= 256)
5182           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5183         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5184       }
5185
5186       Ld = Sc.getOperand(0);
5187       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5188                        Ld.getOpcode() == ISD::ConstantFP);
5189
5190       // The scalar_to_vector node and the suspected
5191       // load node must have exactly one user.
5192       // Constants may have multiple users.
5193
5194       // AVX-512 has register version of the broadcast
5195       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5196         Ld.getValueType().getSizeInBits() >= 32;
5197       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5198           !hasRegVer))
5199         return SDValue();
5200       break;
5201     }
5202   }
5203
5204   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5205   bool IsGE256 = (VT.getSizeInBits() >= 256);
5206
5207   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5208   // instruction to save 8 or more bytes of constant pool data.
5209   // TODO: If multiple splats are generated to load the same constant,
5210   // it may be detrimental to overall size. There needs to be a way to detect
5211   // that condition to know if this is truly a size win.
5212   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5213
5214   // Handle broadcasting a single constant scalar from the constant pool
5215   // into a vector.
5216   // On Sandybridge (no AVX2), it is still better to load a constant vector
5217   // from the constant pool and not to broadcast it from a scalar.
5218   // But override that restriction when optimizing for size.
5219   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5220   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5221     EVT CVT = Ld.getValueType();
5222     assert(!CVT.isVector() && "Must not broadcast a vector type");
5223
5224     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5225     // For size optimization, also splat v2f64 and v2i64, and for size opt
5226     // with AVX2, also splat i8 and i16.
5227     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5228     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5229         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5230       const Constant *C = nullptr;
5231       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5232         C = CI->getConstantIntValue();
5233       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5234         C = CF->getConstantFPValue();
5235
5236       assert(C && "Invalid constant type");
5237
5238       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5239       SDValue CP =
5240           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5241       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242       Ld = DAG.getLoad(
5243           CVT, dl, DAG.getEntryNode(), CP,
5244           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5245           false, false, Alignment);
5246
5247       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5248     }
5249   }
5250
5251   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5252
5253   // Handle AVX2 in-register broadcasts.
5254   if (!IsLoad && Subtarget->hasInt256() &&
5255       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5256     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5257
5258   // The scalar source must be a normal load.
5259   if (!IsLoad)
5260     return SDValue();
5261
5262   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5263       (Subtarget->hasVLX() && ScalarSize == 64))
5264     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5265
5266   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5267   // double since there is no vbroadcastsd xmm
5268   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5269     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5270       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5271   }
5272
5273   // Unsupported broadcast.
5274   return SDValue();
5275 }
5276
5277 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5278 /// underlying vector and index.
5279 ///
5280 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5281 /// index.
5282 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5283                                          SDValue ExtIdx) {
5284   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5285   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5286     return Idx;
5287
5288   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5289   // lowered this:
5290   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5291   // to:
5292   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5293   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5294   //                           undef)
5295   //                       Constant<0>)
5296   // In this case the vector is the extract_subvector expression and the index
5297   // is 2, as specified by the shuffle.
5298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5299   SDValue ShuffleVec = SVOp->getOperand(0);
5300   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5301   assert(ShuffleVecVT.getVectorElementType() ==
5302          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5303
5304   int ShuffleIdx = SVOp->getMaskElt(Idx);
5305   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5306     ExtractedFromVec = ShuffleVec;
5307     return ShuffleIdx;
5308   }
5309   return Idx;
5310 }
5311
5312 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5313   MVT VT = Op.getSimpleValueType();
5314
5315   // Skip if insert_vec_elt is not supported.
5316   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5317   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5318     return SDValue();
5319
5320   SDLoc DL(Op);
5321   unsigned NumElems = Op.getNumOperands();
5322
5323   SDValue VecIn1;
5324   SDValue VecIn2;
5325   SmallVector<unsigned, 4> InsertIndices;
5326   SmallVector<int, 8> Mask(NumElems, -1);
5327
5328   for (unsigned i = 0; i != NumElems; ++i) {
5329     unsigned Opc = Op.getOperand(i).getOpcode();
5330
5331     if (Opc == ISD::UNDEF)
5332       continue;
5333
5334     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5335       // Quit if more than 1 elements need inserting.
5336       if (InsertIndices.size() > 1)
5337         return SDValue();
5338
5339       InsertIndices.push_back(i);
5340       continue;
5341     }
5342
5343     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5344     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5345     // Quit if non-constant index.
5346     if (!isa<ConstantSDNode>(ExtIdx))
5347       return SDValue();
5348     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5349
5350     // Quit if extracted from vector of different type.
5351     if (ExtractedFromVec.getValueType() != VT)
5352       return SDValue();
5353
5354     if (!VecIn1.getNode())
5355       VecIn1 = ExtractedFromVec;
5356     else if (VecIn1 != ExtractedFromVec) {
5357       if (!VecIn2.getNode())
5358         VecIn2 = ExtractedFromVec;
5359       else if (VecIn2 != ExtractedFromVec)
5360         // Quit if more than 2 vectors to shuffle
5361         return SDValue();
5362     }
5363
5364     if (ExtractedFromVec == VecIn1)
5365       Mask[i] = Idx;
5366     else if (ExtractedFromVec == VecIn2)
5367       Mask[i] = Idx + NumElems;
5368   }
5369
5370   if (!VecIn1.getNode())
5371     return SDValue();
5372
5373   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5374   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5375   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5376     unsigned Idx = InsertIndices[i];
5377     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5378                      DAG.getIntPtrConstant(Idx, DL));
5379   }
5380
5381   return NV;
5382 }
5383
5384 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5385   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5386          Op.getScalarValueSizeInBits() == 1 &&
5387          "Can not convert non-constant vector");
5388   uint64_t Immediate = 0;
5389   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5390     SDValue In = Op.getOperand(idx);
5391     if (In.getOpcode() != ISD::UNDEF)
5392       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5393   }
5394   SDLoc dl(Op);
5395   MVT VT =
5396    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5397   return DAG.getConstant(Immediate, dl, VT);
5398 }
5399 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5400 SDValue
5401 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5402
5403   MVT VT = Op.getSimpleValueType();
5404   assert((VT.getVectorElementType() == MVT::i1) &&
5405          "Unexpected type in LowerBUILD_VECTORvXi1!");
5406
5407   SDLoc dl(Op);
5408   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5409     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5410     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5411     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5412   }
5413
5414   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5415     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5416     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5417     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5418   }
5419
5420   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5421     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5422     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5423       return DAG.getBitcast(VT, Imm);
5424     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5425     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5426                         DAG.getIntPtrConstant(0, dl));
5427   }
5428
5429   // Vector has one or more non-const elements
5430   uint64_t Immediate = 0;
5431   SmallVector<unsigned, 16> NonConstIdx;
5432   bool IsSplat = true;
5433   bool HasConstElts = false;
5434   int SplatIdx = -1;
5435   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5436     SDValue In = Op.getOperand(idx);
5437     if (In.getOpcode() == ISD::UNDEF)
5438       continue;
5439     if (!isa<ConstantSDNode>(In))
5440       NonConstIdx.push_back(idx);
5441     else {
5442       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5443       HasConstElts = true;
5444     }
5445     if (SplatIdx == -1)
5446       SplatIdx = idx;
5447     else if (In != Op.getOperand(SplatIdx))
5448       IsSplat = false;
5449   }
5450
5451   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5452   if (IsSplat)
5453     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5454                        DAG.getConstant(1, dl, VT),
5455                        DAG.getConstant(0, dl, VT));
5456
5457   // insert elements one by one
5458   SDValue DstVec;
5459   SDValue Imm;
5460   if (Immediate) {
5461     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5462     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5463   }
5464   else if (HasConstElts)
5465     Imm = DAG.getConstant(0, dl, VT);
5466   else
5467     Imm = DAG.getUNDEF(VT);
5468   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5469     DstVec = DAG.getBitcast(VT, Imm);
5470   else {
5471     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5472     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5473                          DAG.getIntPtrConstant(0, dl));
5474   }
5475
5476   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5477     unsigned InsertIdx = NonConstIdx[i];
5478     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5479                          Op.getOperand(InsertIdx),
5480                          DAG.getIntPtrConstant(InsertIdx, dl));
5481   }
5482   return DstVec;
5483 }
5484
5485 /// \brief Return true if \p N implements a horizontal binop and return the
5486 /// operands for the horizontal binop into V0 and V1.
5487 ///
5488 /// This is a helper function of LowerToHorizontalOp().
5489 /// This function checks that the build_vector \p N in input implements a
5490 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5491 /// operation to match.
5492 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5493 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5494 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5495 /// arithmetic sub.
5496 ///
5497 /// This function only analyzes elements of \p N whose indices are
5498 /// in range [BaseIdx, LastIdx).
5499 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5500                               SelectionDAG &DAG,
5501                               unsigned BaseIdx, unsigned LastIdx,
5502                               SDValue &V0, SDValue &V1) {
5503   EVT VT = N->getValueType(0);
5504
5505   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5506   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5507          "Invalid Vector in input!");
5508
5509   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5510   bool CanFold = true;
5511   unsigned ExpectedVExtractIdx = BaseIdx;
5512   unsigned NumElts = LastIdx - BaseIdx;
5513   V0 = DAG.getUNDEF(VT);
5514   V1 = DAG.getUNDEF(VT);
5515
5516   // Check if N implements a horizontal binop.
5517   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5518     SDValue Op = N->getOperand(i + BaseIdx);
5519
5520     // Skip UNDEFs.
5521     if (Op->getOpcode() == ISD::UNDEF) {
5522       // Update the expected vector extract index.
5523       if (i * 2 == NumElts)
5524         ExpectedVExtractIdx = BaseIdx;
5525       ExpectedVExtractIdx += 2;
5526       continue;
5527     }
5528
5529     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5530
5531     if (!CanFold)
5532       break;
5533
5534     SDValue Op0 = Op.getOperand(0);
5535     SDValue Op1 = Op.getOperand(1);
5536
5537     // Try to match the following pattern:
5538     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5539     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5540         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5541         Op0.getOperand(0) == Op1.getOperand(0) &&
5542         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5543         isa<ConstantSDNode>(Op1.getOperand(1)));
5544     if (!CanFold)
5545       break;
5546
5547     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5548     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5549
5550     if (i * 2 < NumElts) {
5551       if (V0.getOpcode() == ISD::UNDEF) {
5552         V0 = Op0.getOperand(0);
5553         if (V0.getValueType() != VT)
5554           return false;
5555       }
5556     } else {
5557       if (V1.getOpcode() == ISD::UNDEF) {
5558         V1 = Op0.getOperand(0);
5559         if (V1.getValueType() != VT)
5560           return false;
5561       }
5562       if (i * 2 == NumElts)
5563         ExpectedVExtractIdx = BaseIdx;
5564     }
5565
5566     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5567     if (I0 == ExpectedVExtractIdx)
5568       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5569     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5570       // Try to match the following dag sequence:
5571       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5572       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5573     } else
5574       CanFold = false;
5575
5576     ExpectedVExtractIdx += 2;
5577   }
5578
5579   return CanFold;
5580 }
5581
5582 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5583 /// a concat_vector.
5584 ///
5585 /// This is a helper function of LowerToHorizontalOp().
5586 /// This function expects two 256-bit vectors called V0 and V1.
5587 /// At first, each vector is split into two separate 128-bit vectors.
5588 /// Then, the resulting 128-bit vectors are used to implement two
5589 /// horizontal binary operations.
5590 ///
5591 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5592 ///
5593 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5594 /// the two new horizontal binop.
5595 /// When Mode is set, the first horizontal binop dag node would take as input
5596 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5597 /// horizontal binop dag node would take as input the lower 128-bit of V1
5598 /// and the upper 128-bit of V1.
5599 ///   Example:
5600 ///     HADD V0_LO, V0_HI
5601 ///     HADD V1_LO, V1_HI
5602 ///
5603 /// Otherwise, the first horizontal binop dag node takes as input the lower
5604 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5605 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5606 ///   Example:
5607 ///     HADD V0_LO, V1_LO
5608 ///     HADD V0_HI, V1_HI
5609 ///
5610 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5611 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5612 /// the upper 128-bits of the result.
5613 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5614                                      SDLoc DL, SelectionDAG &DAG,
5615                                      unsigned X86Opcode, bool Mode,
5616                                      bool isUndefLO, bool isUndefHI) {
5617   EVT VT = V0.getValueType();
5618   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5619          "Invalid nodes in input!");
5620
5621   unsigned NumElts = VT.getVectorNumElements();
5622   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5623   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5624   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5625   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5626   EVT NewVT = V0_LO.getValueType();
5627
5628   SDValue LO = DAG.getUNDEF(NewVT);
5629   SDValue HI = DAG.getUNDEF(NewVT);
5630
5631   if (Mode) {
5632     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5633     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5634       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5635     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5636       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5637   } else {
5638     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5639     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5640                        V1_LO->getOpcode() != ISD::UNDEF))
5641       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5642
5643     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5644                        V1_HI->getOpcode() != ISD::UNDEF))
5645       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5646   }
5647
5648   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5649 }
5650
5651 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5652 /// node.
5653 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5654                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5655   EVT VT = BV->getValueType(0);
5656   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5657       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5658     return SDValue();
5659
5660   SDLoc DL(BV);
5661   unsigned NumElts = VT.getVectorNumElements();
5662   SDValue InVec0 = DAG.getUNDEF(VT);
5663   SDValue InVec1 = DAG.getUNDEF(VT);
5664
5665   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5666           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5667
5668   // Odd-numbered elements in the input build vector are obtained from
5669   // adding two integer/float elements.
5670   // Even-numbered elements in the input build vector are obtained from
5671   // subtracting two integer/float elements.
5672   unsigned ExpectedOpcode = ISD::FSUB;
5673   unsigned NextExpectedOpcode = ISD::FADD;
5674   bool AddFound = false;
5675   bool SubFound = false;
5676
5677   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5678     SDValue Op = BV->getOperand(i);
5679
5680     // Skip 'undef' values.
5681     unsigned Opcode = Op.getOpcode();
5682     if (Opcode == ISD::UNDEF) {
5683       std::swap(ExpectedOpcode, NextExpectedOpcode);
5684       continue;
5685     }
5686
5687     // Early exit if we found an unexpected opcode.
5688     if (Opcode != ExpectedOpcode)
5689       return SDValue();
5690
5691     SDValue Op0 = Op.getOperand(0);
5692     SDValue Op1 = Op.getOperand(1);
5693
5694     // Try to match the following pattern:
5695     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5696     // Early exit if we cannot match that sequence.
5697     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5698         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5699         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5700         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5701         Op0.getOperand(1) != Op1.getOperand(1))
5702       return SDValue();
5703
5704     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5705     if (I0 != i)
5706       return SDValue();
5707
5708     // We found a valid add/sub node. Update the information accordingly.
5709     if (i & 1)
5710       AddFound = true;
5711     else
5712       SubFound = true;
5713
5714     // Update InVec0 and InVec1.
5715     if (InVec0.getOpcode() == ISD::UNDEF) {
5716       InVec0 = Op0.getOperand(0);
5717       if (InVec0.getValueType() != VT)
5718         return SDValue();
5719     }
5720     if (InVec1.getOpcode() == ISD::UNDEF) {
5721       InVec1 = Op1.getOperand(0);
5722       if (InVec1.getValueType() != VT)
5723         return SDValue();
5724     }
5725
5726     // Make sure that operands in input to each add/sub node always
5727     // come from a same pair of vectors.
5728     if (InVec0 != Op0.getOperand(0)) {
5729       if (ExpectedOpcode == ISD::FSUB)
5730         return SDValue();
5731
5732       // FADD is commutable. Try to commute the operands
5733       // and then test again.
5734       std::swap(Op0, Op1);
5735       if (InVec0 != Op0.getOperand(0))
5736         return SDValue();
5737     }
5738
5739     if (InVec1 != Op1.getOperand(0))
5740       return SDValue();
5741
5742     // Update the pair of expected opcodes.
5743     std::swap(ExpectedOpcode, NextExpectedOpcode);
5744   }
5745
5746   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5747   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5748       InVec1.getOpcode() != ISD::UNDEF)
5749     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5750
5751   return SDValue();
5752 }
5753
5754 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5755 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5756                                    const X86Subtarget *Subtarget,
5757                                    SelectionDAG &DAG) {
5758   EVT VT = BV->getValueType(0);
5759   unsigned NumElts = VT.getVectorNumElements();
5760   unsigned NumUndefsLO = 0;
5761   unsigned NumUndefsHI = 0;
5762   unsigned Half = NumElts/2;
5763
5764   // Count the number of UNDEF operands in the build_vector in input.
5765   for (unsigned i = 0, e = Half; i != e; ++i)
5766     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5767       NumUndefsLO++;
5768
5769   for (unsigned i = Half, e = NumElts; i != e; ++i)
5770     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5771       NumUndefsHI++;
5772
5773   // Early exit if this is either a build_vector of all UNDEFs or all the
5774   // operands but one are UNDEF.
5775   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5776     return SDValue();
5777
5778   SDLoc DL(BV);
5779   SDValue InVec0, InVec1;
5780   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5781     // Try to match an SSE3 float HADD/HSUB.
5782     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5783       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5784
5785     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5786       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5787   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5788     // Try to match an SSSE3 integer HADD/HSUB.
5789     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5790       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5791
5792     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5793       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5794   }
5795
5796   if (!Subtarget->hasAVX())
5797     return SDValue();
5798
5799   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5800     // Try to match an AVX horizontal add/sub of packed single/double
5801     // precision floating point values from 256-bit vectors.
5802     SDValue InVec2, InVec3;
5803     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5804         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5805         ((InVec0.getOpcode() == ISD::UNDEF ||
5806           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5807         ((InVec1.getOpcode() == ISD::UNDEF ||
5808           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5809       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5810
5811     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5812         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5813         ((InVec0.getOpcode() == ISD::UNDEF ||
5814           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5815         ((InVec1.getOpcode() == ISD::UNDEF ||
5816           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5817       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5818   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5819     // Try to match an AVX2 horizontal add/sub of signed integers.
5820     SDValue InVec2, InVec3;
5821     unsigned X86Opcode;
5822     bool CanFold = true;
5823
5824     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5825         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5826         ((InVec0.getOpcode() == ISD::UNDEF ||
5827           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5828         ((InVec1.getOpcode() == ISD::UNDEF ||
5829           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5830       X86Opcode = X86ISD::HADD;
5831     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5832         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5833         ((InVec0.getOpcode() == ISD::UNDEF ||
5834           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5835         ((InVec1.getOpcode() == ISD::UNDEF ||
5836           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5837       X86Opcode = X86ISD::HSUB;
5838     else
5839       CanFold = false;
5840
5841     if (CanFold) {
5842       // Fold this build_vector into a single horizontal add/sub.
5843       // Do this only if the target has AVX2.
5844       if (Subtarget->hasAVX2())
5845         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5846
5847       // Do not try to expand this build_vector into a pair of horizontal
5848       // add/sub if we can emit a pair of scalar add/sub.
5849       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5850         return SDValue();
5851
5852       // Convert this build_vector into a pair of horizontal binop followed by
5853       // a concat vector.
5854       bool isUndefLO = NumUndefsLO == Half;
5855       bool isUndefHI = NumUndefsHI == Half;
5856       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5857                                    isUndefLO, isUndefHI);
5858     }
5859   }
5860
5861   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5862        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5863     unsigned X86Opcode;
5864     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5865       X86Opcode = X86ISD::HADD;
5866     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5867       X86Opcode = X86ISD::HSUB;
5868     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5869       X86Opcode = X86ISD::FHADD;
5870     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5871       X86Opcode = X86ISD::FHSUB;
5872     else
5873       return SDValue();
5874
5875     // Don't try to expand this build_vector into a pair of horizontal add/sub
5876     // if we can simply emit a pair of scalar add/sub.
5877     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5878       return SDValue();
5879
5880     // Convert this build_vector into two horizontal add/sub followed by
5881     // a concat vector.
5882     bool isUndefLO = NumUndefsLO == Half;
5883     bool isUndefHI = NumUndefsHI == Half;
5884     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5885                                  isUndefLO, isUndefHI);
5886   }
5887
5888   return SDValue();
5889 }
5890
5891 SDValue
5892 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5893   SDLoc dl(Op);
5894
5895   MVT VT = Op.getSimpleValueType();
5896   MVT ExtVT = VT.getVectorElementType();
5897   unsigned NumElems = Op.getNumOperands();
5898
5899   // Generate vectors for predicate vectors.
5900   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5901     return LowerBUILD_VECTORvXi1(Op, DAG);
5902
5903   // Vectors containing all zeros can be matched by pxor and xorps later
5904   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5905     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5906     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5907     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5908       return Op;
5909
5910     return getZeroVector(VT, Subtarget, DAG, dl);
5911   }
5912
5913   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5914   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5915   // vpcmpeqd on 256-bit vectors.
5916   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5917     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5918       return Op;
5919
5920     if (!VT.is512BitVector())
5921       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5922   }
5923
5924   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5925   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5926     return AddSub;
5927   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5928     return HorizontalOp;
5929   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5930     return Broadcast;
5931
5932   unsigned EVTBits = ExtVT.getSizeInBits();
5933
5934   unsigned NumZero  = 0;
5935   unsigned NumNonZero = 0;
5936   unsigned NonZeros = 0;
5937   bool IsAllConstants = true;
5938   SmallSet<SDValue, 8> Values;
5939   for (unsigned i = 0; i < NumElems; ++i) {
5940     SDValue Elt = Op.getOperand(i);
5941     if (Elt.getOpcode() == ISD::UNDEF)
5942       continue;
5943     Values.insert(Elt);
5944     if (Elt.getOpcode() != ISD::Constant &&
5945         Elt.getOpcode() != ISD::ConstantFP)
5946       IsAllConstants = false;
5947     if (X86::isZeroNode(Elt))
5948       NumZero++;
5949     else {
5950       NonZeros |= (1 << i);
5951       NumNonZero++;
5952     }
5953   }
5954
5955   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5956   if (NumNonZero == 0)
5957     return DAG.getUNDEF(VT);
5958
5959   // Special case for single non-zero, non-undef, element.
5960   if (NumNonZero == 1) {
5961     unsigned Idx = countTrailingZeros(NonZeros);
5962     SDValue Item = Op.getOperand(Idx);
5963
5964     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5965     // the value are obviously zero, truncate the value to i32 and do the
5966     // insertion that way.  Only do this if the value is non-constant or if the
5967     // value is a constant being inserted into element 0.  It is cheaper to do
5968     // a constant pool load than it is to do a movd + shuffle.
5969     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5970         (!IsAllConstants || Idx == 0)) {
5971       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5972         // Handle SSE only.
5973         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5974         EVT VecVT = MVT::v4i32;
5975
5976         // Truncate the value (which may itself be a constant) to i32, and
5977         // convert it to a vector with movd (S2V+shuffle to zero extend).
5978         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5979         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5980         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5981                                       Item, Idx * 2, true, Subtarget, DAG));
5982       }
5983     }
5984
5985     // If we have a constant or non-constant insertion into the low element of
5986     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5987     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5988     // depending on what the source datatype is.
5989     if (Idx == 0) {
5990       if (NumZero == 0)
5991         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5992
5993       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5994           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5995         if (VT.is512BitVector()) {
5996           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5997           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5998                              Item, DAG.getIntPtrConstant(0, dl));
5999         }
6000         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6001                "Expected an SSE value type!");
6002         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6003         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6004         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6005       }
6006
6007       // We can't directly insert an i8 or i16 into a vector, so zero extend
6008       // it to i32 first.
6009       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6010         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6011         if (VT.is256BitVector()) {
6012           if (Subtarget->hasAVX()) {
6013             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6014             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6015           } else {
6016             // Without AVX, we need to extend to a 128-bit vector and then
6017             // insert into the 256-bit vector.
6018             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6019             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6020             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6021           }
6022         } else {
6023           assert(VT.is128BitVector() && "Expected an SSE value type!");
6024           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6025           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6026         }
6027         return DAG.getBitcast(VT, Item);
6028       }
6029     }
6030
6031     // Is it a vector logical left shift?
6032     if (NumElems == 2 && Idx == 1 &&
6033         X86::isZeroNode(Op.getOperand(0)) &&
6034         !X86::isZeroNode(Op.getOperand(1))) {
6035       unsigned NumBits = VT.getSizeInBits();
6036       return getVShift(true, VT,
6037                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6038                                    VT, Op.getOperand(1)),
6039                        NumBits/2, DAG, *this, dl);
6040     }
6041
6042     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6043       return SDValue();
6044
6045     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6046     // is a non-constant being inserted into an element other than the low one,
6047     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6048     // movd/movss) to move this into the low element, then shuffle it into
6049     // place.
6050     if (EVTBits == 32) {
6051       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6052       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6053     }
6054   }
6055
6056   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6057   if (Values.size() == 1) {
6058     if (EVTBits == 32) {
6059       // Instead of a shuffle like this:
6060       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6061       // Check if it's possible to issue this instead.
6062       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6063       unsigned Idx = countTrailingZeros(NonZeros);
6064       SDValue Item = Op.getOperand(Idx);
6065       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6066         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6067     }
6068     return SDValue();
6069   }
6070
6071   // A vector full of immediates; various special cases are already
6072   // handled, so this is best done with a single constant-pool load.
6073   if (IsAllConstants)
6074     return SDValue();
6075
6076   // For AVX-length vectors, see if we can use a vector load to get all of the
6077   // elements, otherwise build the individual 128-bit pieces and use
6078   // shuffles to put them in place.
6079   if (VT.is256BitVector() || VT.is512BitVector()) {
6080     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6081
6082     // Check for a build vector of consecutive loads.
6083     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6084       return LD;
6085
6086     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6087
6088     // Build both the lower and upper subvector.
6089     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6090                                 makeArrayRef(&V[0], NumElems/2));
6091     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6092                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6093
6094     // Recreate the wider vector with the lower and upper part.
6095     if (VT.is256BitVector())
6096       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6097     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6098   }
6099
6100   // Let legalizer expand 2-wide build_vectors.
6101   if (EVTBits == 64) {
6102     if (NumNonZero == 1) {
6103       // One half is zero or undef.
6104       unsigned Idx = countTrailingZeros(NonZeros);
6105       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6106                                  Op.getOperand(Idx));
6107       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6108     }
6109     return SDValue();
6110   }
6111
6112   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6113   if (EVTBits == 8 && NumElems == 16)
6114     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6115                                         Subtarget, *this))
6116       return V;
6117
6118   if (EVTBits == 16 && NumElems == 8)
6119     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6120                                       Subtarget, *this))
6121       return V;
6122
6123   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6124   if (EVTBits == 32 && NumElems == 4)
6125     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6126       return V;
6127
6128   // If element VT is == 32 bits, turn it into a number of shuffles.
6129   SmallVector<SDValue, 8> V(NumElems);
6130   if (NumElems == 4 && NumZero > 0) {
6131     for (unsigned i = 0; i < 4; ++i) {
6132       bool isZero = !(NonZeros & (1 << i));
6133       if (isZero)
6134         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6135       else
6136         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6137     }
6138
6139     for (unsigned i = 0; i < 2; ++i) {
6140       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6141         default: break;
6142         case 0:
6143           V[i] = V[i*2];  // Must be a zero vector.
6144           break;
6145         case 1:
6146           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6147           break;
6148         case 2:
6149           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6150           break;
6151         case 3:
6152           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6153           break;
6154       }
6155     }
6156
6157     bool Reverse1 = (NonZeros & 0x3) == 2;
6158     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6159     int MaskVec[] = {
6160       Reverse1 ? 1 : 0,
6161       Reverse1 ? 0 : 1,
6162       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6163       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6164     };
6165     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6166   }
6167
6168   if (Values.size() > 1 && VT.is128BitVector()) {
6169     // Check for a build vector of consecutive loads.
6170     for (unsigned i = 0; i < NumElems; ++i)
6171       V[i] = Op.getOperand(i);
6172
6173     // Check for elements which are consecutive loads.
6174     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6175       return LD;
6176
6177     // Check for a build vector from mostly shuffle plus few inserting.
6178     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6179       return Sh;
6180
6181     // For SSE 4.1, use insertps to put the high elements into the low element.
6182     if (Subtarget->hasSSE41()) {
6183       SDValue Result;
6184       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6185         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6186       else
6187         Result = DAG.getUNDEF(VT);
6188
6189       for (unsigned i = 1; i < NumElems; ++i) {
6190         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6191         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6192                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6193       }
6194       return Result;
6195     }
6196
6197     // Otherwise, expand into a number of unpckl*, start by extending each of
6198     // our (non-undef) elements to the full vector width with the element in the
6199     // bottom slot of the vector (which generates no code for SSE).
6200     for (unsigned i = 0; i < NumElems; ++i) {
6201       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6202         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6203       else
6204         V[i] = DAG.getUNDEF(VT);
6205     }
6206
6207     // Next, we iteratively mix elements, e.g. for v4f32:
6208     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6209     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6210     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6211     unsigned EltStride = NumElems >> 1;
6212     while (EltStride != 0) {
6213       for (unsigned i = 0; i < EltStride; ++i) {
6214         // If V[i+EltStride] is undef and this is the first round of mixing,
6215         // then it is safe to just drop this shuffle: V[i] is already in the
6216         // right place, the one element (since it's the first round) being
6217         // inserted as undef can be dropped.  This isn't safe for successive
6218         // rounds because they will permute elements within both vectors.
6219         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6220             EltStride == NumElems/2)
6221           continue;
6222
6223         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6224       }
6225       EltStride >>= 1;
6226     }
6227     return V[0];
6228   }
6229   return SDValue();
6230 }
6231
6232 // 256-bit AVX can use the vinsertf128 instruction
6233 // to create 256-bit vectors from two other 128-bit ones.
6234 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6235   SDLoc dl(Op);
6236   MVT ResVT = Op.getSimpleValueType();
6237
6238   assert((ResVT.is256BitVector() ||
6239           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6240
6241   SDValue V1 = Op.getOperand(0);
6242   SDValue V2 = Op.getOperand(1);
6243   unsigned NumElems = ResVT.getVectorNumElements();
6244   if (ResVT.is256BitVector())
6245     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6246
6247   if (Op.getNumOperands() == 4) {
6248     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6249                                 ResVT.getVectorNumElements()/2);
6250     SDValue V3 = Op.getOperand(2);
6251     SDValue V4 = Op.getOperand(3);
6252     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6253       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6254   }
6255   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6256 }
6257
6258 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6259                                        const X86Subtarget *Subtarget,
6260                                        SelectionDAG & DAG) {
6261   SDLoc dl(Op);
6262   MVT ResVT = Op.getSimpleValueType();
6263   unsigned NumOfOperands = Op.getNumOperands();
6264
6265   assert(isPowerOf2_32(NumOfOperands) &&
6266          "Unexpected number of operands in CONCAT_VECTORS");
6267
6268   if (NumOfOperands > 2) {
6269     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6270                                   ResVT.getVectorNumElements()/2);
6271     SmallVector<SDValue, 2> Ops;
6272     for (unsigned i = 0; i < NumOfOperands/2; i++)
6273       Ops.push_back(Op.getOperand(i));
6274     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6275     Ops.clear();
6276     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6277       Ops.push_back(Op.getOperand(i));
6278     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6279     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6280   }
6281
6282   SDValue V1 = Op.getOperand(0);
6283   SDValue V2 = Op.getOperand(1);
6284   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6285   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6286
6287   if (IsZeroV1 && IsZeroV2)
6288     return getZeroVector(ResVT, Subtarget, DAG, dl);
6289
6290   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6291   SDValue Undef = DAG.getUNDEF(ResVT);
6292   unsigned NumElems = ResVT.getVectorNumElements();
6293   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6294
6295   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6296   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6297   if (IsZeroV1)
6298     return V2;
6299
6300   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6301   // Zero the upper bits of V1
6302   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6303   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6304   if (IsZeroV2)
6305     return V1;
6306   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6307 }
6308
6309 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6310                                    const X86Subtarget *Subtarget,
6311                                    SelectionDAG &DAG) {
6312   MVT VT = Op.getSimpleValueType();
6313   if (VT.getVectorElementType() == MVT::i1)
6314     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6315
6316   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6317          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6318           Op.getNumOperands() == 4)));
6319
6320   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6321   // from two other 128-bit ones.
6322
6323   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6324   return LowerAVXCONCAT_VECTORS(Op, DAG);
6325 }
6326
6327
6328 //===----------------------------------------------------------------------===//
6329 // Vector shuffle lowering
6330 //
6331 // This is an experimental code path for lowering vector shuffles on x86. It is
6332 // designed to handle arbitrary vector shuffles and blends, gracefully
6333 // degrading performance as necessary. It works hard to recognize idiomatic
6334 // shuffles and lower them to optimal instruction patterns without leaving
6335 // a framework that allows reasonably efficient handling of all vector shuffle
6336 // patterns.
6337 //===----------------------------------------------------------------------===//
6338
6339 /// \brief Tiny helper function to identify a no-op mask.
6340 ///
6341 /// This is a somewhat boring predicate function. It checks whether the mask
6342 /// array input, which is assumed to be a single-input shuffle mask of the kind
6343 /// used by the X86 shuffle instructions (not a fully general
6344 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6345 /// in-place shuffle are 'no-op's.
6346 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6347   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6348     if (Mask[i] != -1 && Mask[i] != i)
6349       return false;
6350   return true;
6351 }
6352
6353 /// \brief Helper function to classify a mask as a single-input mask.
6354 ///
6355 /// This isn't a generic single-input test because in the vector shuffle
6356 /// lowering we canonicalize single inputs to be the first input operand. This
6357 /// means we can more quickly test for a single input by only checking whether
6358 /// an input from the second operand exists. We also assume that the size of
6359 /// mask corresponds to the size of the input vectors which isn't true in the
6360 /// fully general case.
6361 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6362   for (int M : Mask)
6363     if (M >= (int)Mask.size())
6364       return false;
6365   return true;
6366 }
6367
6368 /// \brief Test whether there are elements crossing 128-bit lanes in this
6369 /// shuffle mask.
6370 ///
6371 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6372 /// and we routinely test for these.
6373 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6374   int LaneSize = 128 / VT.getScalarSizeInBits();
6375   int Size = Mask.size();
6376   for (int i = 0; i < Size; ++i)
6377     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6378       return true;
6379   return false;
6380 }
6381
6382 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6383 ///
6384 /// This checks a shuffle mask to see if it is performing the same
6385 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6386 /// that it is also not lane-crossing. It may however involve a blend from the
6387 /// same lane of a second vector.
6388 ///
6389 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6390 /// non-trivial to compute in the face of undef lanes. The representation is
6391 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6392 /// entries from both V1 and V2 inputs to the wider mask.
6393 static bool
6394 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6395                                 SmallVectorImpl<int> &RepeatedMask) {
6396   int LaneSize = 128 / VT.getScalarSizeInBits();
6397   RepeatedMask.resize(LaneSize, -1);
6398   int Size = Mask.size();
6399   for (int i = 0; i < Size; ++i) {
6400     if (Mask[i] < 0)
6401       continue;
6402     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6403       // This entry crosses lanes, so there is no way to model this shuffle.
6404       return false;
6405
6406     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6407     if (RepeatedMask[i % LaneSize] == -1)
6408       // This is the first non-undef entry in this slot of a 128-bit lane.
6409       RepeatedMask[i % LaneSize] =
6410           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6411     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6412       // Found a mismatch with the repeated mask.
6413       return false;
6414   }
6415   return true;
6416 }
6417
6418 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6419 /// arguments.
6420 ///
6421 /// This is a fast way to test a shuffle mask against a fixed pattern:
6422 ///
6423 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6424 ///
6425 /// It returns true if the mask is exactly as wide as the argument list, and
6426 /// each element of the mask is either -1 (signifying undef) or the value given
6427 /// in the argument.
6428 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6429                                 ArrayRef<int> ExpectedMask) {
6430   if (Mask.size() != ExpectedMask.size())
6431     return false;
6432
6433   int Size = Mask.size();
6434
6435   // If the values are build vectors, we can look through them to find
6436   // equivalent inputs that make the shuffles equivalent.
6437   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6438   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6439
6440   for (int i = 0; i < Size; ++i)
6441     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6442       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6443       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6444       if (!MaskBV || !ExpectedBV ||
6445           MaskBV->getOperand(Mask[i] % Size) !=
6446               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6447         return false;
6448     }
6449
6450   return true;
6451 }
6452
6453 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6454 ///
6455 /// This helper function produces an 8-bit shuffle immediate corresponding to
6456 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6457 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6458 /// example.
6459 ///
6460 /// NB: We rely heavily on "undef" masks preserving the input lane.
6461 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6462                                           SelectionDAG &DAG) {
6463   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6464   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6465   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6466   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6467   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6468
6469   unsigned Imm = 0;
6470   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6471   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6472   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6473   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6474   return DAG.getConstant(Imm, DL, MVT::i8);
6475 }
6476
6477 /// \brief Compute whether each element of a shuffle is zeroable.
6478 ///
6479 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6480 /// Either it is an undef element in the shuffle mask, the element of the input
6481 /// referenced is undef, or the element of the input referenced is known to be
6482 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6483 /// as many lanes with this technique as possible to simplify the remaining
6484 /// shuffle.
6485 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6486                                                      SDValue V1, SDValue V2) {
6487   SmallBitVector Zeroable(Mask.size(), false);
6488
6489   while (V1.getOpcode() == ISD::BITCAST)
6490     V1 = V1->getOperand(0);
6491   while (V2.getOpcode() == ISD::BITCAST)
6492     V2 = V2->getOperand(0);
6493
6494   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6495   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6496
6497   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6498     int M = Mask[i];
6499     // Handle the easy cases.
6500     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6501       Zeroable[i] = true;
6502       continue;
6503     }
6504
6505     // If this is an index into a build_vector node (which has the same number
6506     // of elements), dig out the input value and use it.
6507     SDValue V = M < Size ? V1 : V2;
6508     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6509       continue;
6510
6511     SDValue Input = V.getOperand(M % Size);
6512     // The UNDEF opcode check really should be dead code here, but not quite
6513     // worth asserting on (it isn't invalid, just unexpected).
6514     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6515       Zeroable[i] = true;
6516   }
6517
6518   return Zeroable;
6519 }
6520
6521 /// \brief Try to emit a bitmask instruction for a shuffle.
6522 ///
6523 /// This handles cases where we can model a blend exactly as a bitmask due to
6524 /// one of the inputs being zeroable.
6525 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6526                                            SDValue V2, ArrayRef<int> Mask,
6527                                            SelectionDAG &DAG) {
6528   MVT EltVT = VT.getScalarType();
6529   int NumEltBits = EltVT.getSizeInBits();
6530   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6531   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6532   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6533                                     IntEltVT);
6534   if (EltVT.isFloatingPoint()) {
6535     Zero = DAG.getBitcast(EltVT, Zero);
6536     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6537   }
6538   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6539   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6540   SDValue V;
6541   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6542     if (Zeroable[i])
6543       continue;
6544     if (Mask[i] % Size != i)
6545       return SDValue(); // Not a blend.
6546     if (!V)
6547       V = Mask[i] < Size ? V1 : V2;
6548     else if (V != (Mask[i] < Size ? V1 : V2))
6549       return SDValue(); // Can only let one input through the mask.
6550
6551     VMaskOps[i] = AllOnes;
6552   }
6553   if (!V)
6554     return SDValue(); // No non-zeroable elements!
6555
6556   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6557   V = DAG.getNode(VT.isFloatingPoint()
6558                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6559                   DL, VT, V, VMask);
6560   return V;
6561 }
6562
6563 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6564 ///
6565 /// This is used as a fallback approach when first class blend instructions are
6566 /// unavailable. Currently it is only suitable for integer vectors, but could
6567 /// be generalized for floating point vectors if desirable.
6568 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6569                                             SDValue V2, ArrayRef<int> Mask,
6570                                             SelectionDAG &DAG) {
6571   assert(VT.isInteger() && "Only supports integer vector types!");
6572   MVT EltVT = VT.getScalarType();
6573   int NumEltBits = EltVT.getSizeInBits();
6574   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6575   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6576                                     EltVT);
6577   SmallVector<SDValue, 16> MaskOps;
6578   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6579     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6580       return SDValue(); // Shuffled input!
6581     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6582   }
6583
6584   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6585   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6586   // We have to cast V2 around.
6587   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6588   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6589                                       DAG.getBitcast(MaskVT, V1Mask),
6590                                       DAG.getBitcast(MaskVT, V2)));
6591   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6592 }
6593
6594 /// \brief Try to emit a blend instruction for a shuffle.
6595 ///
6596 /// This doesn't do any checks for the availability of instructions for blending
6597 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6598 /// be matched in the backend with the type given. What it does check for is
6599 /// that the shuffle mask is in fact a blend.
6600 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6601                                          SDValue V2, ArrayRef<int> Mask,
6602                                          const X86Subtarget *Subtarget,
6603                                          SelectionDAG &DAG) {
6604   unsigned BlendMask = 0;
6605   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6606     if (Mask[i] >= Size) {
6607       if (Mask[i] != i + Size)
6608         return SDValue(); // Shuffled V2 input!
6609       BlendMask |= 1u << i;
6610       continue;
6611     }
6612     if (Mask[i] >= 0 && Mask[i] != i)
6613       return SDValue(); // Shuffled V1 input!
6614   }
6615   switch (VT.SimpleTy) {
6616   case MVT::v2f64:
6617   case MVT::v4f32:
6618   case MVT::v4f64:
6619   case MVT::v8f32:
6620     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6621                        DAG.getConstant(BlendMask, DL, MVT::i8));
6622
6623   case MVT::v4i64:
6624   case MVT::v8i32:
6625     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6626     // FALLTHROUGH
6627   case MVT::v2i64:
6628   case MVT::v4i32:
6629     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6630     // that instruction.
6631     if (Subtarget->hasAVX2()) {
6632       // Scale the blend by the number of 32-bit dwords per element.
6633       int Scale =  VT.getScalarSizeInBits() / 32;
6634       BlendMask = 0;
6635       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6636         if (Mask[i] >= Size)
6637           for (int j = 0; j < Scale; ++j)
6638             BlendMask |= 1u << (i * Scale + j);
6639
6640       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6641       V1 = DAG.getBitcast(BlendVT, V1);
6642       V2 = DAG.getBitcast(BlendVT, V2);
6643       return DAG.getBitcast(
6644           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6645                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6646     }
6647     // FALLTHROUGH
6648   case MVT::v8i16: {
6649     // For integer shuffles we need to expand the mask and cast the inputs to
6650     // v8i16s prior to blending.
6651     int Scale = 8 / VT.getVectorNumElements();
6652     BlendMask = 0;
6653     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6654       if (Mask[i] >= Size)
6655         for (int j = 0; j < Scale; ++j)
6656           BlendMask |= 1u << (i * Scale + j);
6657
6658     V1 = DAG.getBitcast(MVT::v8i16, V1);
6659     V2 = DAG.getBitcast(MVT::v8i16, V2);
6660     return DAG.getBitcast(VT,
6661                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6662                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6663   }
6664
6665   case MVT::v16i16: {
6666     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6667     SmallVector<int, 8> RepeatedMask;
6668     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6669       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6670       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6671       BlendMask = 0;
6672       for (int i = 0; i < 8; ++i)
6673         if (RepeatedMask[i] >= 16)
6674           BlendMask |= 1u << i;
6675       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6676                          DAG.getConstant(BlendMask, DL, MVT::i8));
6677     }
6678   }
6679     // FALLTHROUGH
6680   case MVT::v16i8:
6681   case MVT::v32i8: {
6682     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6683            "256-bit byte-blends require AVX2 support!");
6684
6685     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6686     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6687       return Masked;
6688
6689     // Scale the blend by the number of bytes per element.
6690     int Scale = VT.getScalarSizeInBits() / 8;
6691
6692     // This form of blend is always done on bytes. Compute the byte vector
6693     // type.
6694     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6695
6696     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6697     // mix of LLVM's code generator and the x86 backend. We tell the code
6698     // generator that boolean values in the elements of an x86 vector register
6699     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6700     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6701     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6702     // of the element (the remaining are ignored) and 0 in that high bit would
6703     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6704     // the LLVM model for boolean values in vector elements gets the relevant
6705     // bit set, it is set backwards and over constrained relative to x86's
6706     // actual model.
6707     SmallVector<SDValue, 32> VSELECTMask;
6708     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6709       for (int j = 0; j < Scale; ++j)
6710         VSELECTMask.push_back(
6711             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6712                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6713                                           MVT::i8));
6714
6715     V1 = DAG.getBitcast(BlendVT, V1);
6716     V2 = DAG.getBitcast(BlendVT, V2);
6717     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6718                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6719                                                       BlendVT, VSELECTMask),
6720                                           V1, V2));
6721   }
6722
6723   default:
6724     llvm_unreachable("Not a supported integer vector type!");
6725   }
6726 }
6727
6728 /// \brief Try to lower as a blend of elements from two inputs followed by
6729 /// a single-input permutation.
6730 ///
6731 /// This matches the pattern where we can blend elements from two inputs and
6732 /// then reduce the shuffle to a single-input permutation.
6733 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6734                                                    SDValue V2,
6735                                                    ArrayRef<int> Mask,
6736                                                    SelectionDAG &DAG) {
6737   // We build up the blend mask while checking whether a blend is a viable way
6738   // to reduce the shuffle.
6739   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6740   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6741
6742   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6743     if (Mask[i] < 0)
6744       continue;
6745
6746     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6747
6748     if (BlendMask[Mask[i] % Size] == -1)
6749       BlendMask[Mask[i] % Size] = Mask[i];
6750     else if (BlendMask[Mask[i] % Size] != Mask[i])
6751       return SDValue(); // Can't blend in the needed input!
6752
6753     PermuteMask[i] = Mask[i] % Size;
6754   }
6755
6756   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6757   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6758 }
6759
6760 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6761 /// blends and permutes.
6762 ///
6763 /// This matches the extremely common pattern for handling combined
6764 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6765 /// operations. It will try to pick the best arrangement of shuffles and
6766 /// blends.
6767 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6768                                                           SDValue V1,
6769                                                           SDValue V2,
6770                                                           ArrayRef<int> Mask,
6771                                                           SelectionDAG &DAG) {
6772   // Shuffle the input elements into the desired positions in V1 and V2 and
6773   // blend them together.
6774   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6775   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6776   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6777   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6778     if (Mask[i] >= 0 && Mask[i] < Size) {
6779       V1Mask[i] = Mask[i];
6780       BlendMask[i] = i;
6781     } else if (Mask[i] >= Size) {
6782       V2Mask[i] = Mask[i] - Size;
6783       BlendMask[i] = i + Size;
6784     }
6785
6786   // Try to lower with the simpler initial blend strategy unless one of the
6787   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6788   // shuffle may be able to fold with a load or other benefit. However, when
6789   // we'll have to do 2x as many shuffles in order to achieve this, blending
6790   // first is a better strategy.
6791   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6792     if (SDValue BlendPerm =
6793             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6794       return BlendPerm;
6795
6796   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6797   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6798   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6799 }
6800
6801 /// \brief Try to lower a vector shuffle as a byte rotation.
6802 ///
6803 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6804 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6805 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6806 /// try to generically lower a vector shuffle through such an pattern. It
6807 /// does not check for the profitability of lowering either as PALIGNR or
6808 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6809 /// This matches shuffle vectors that look like:
6810 ///
6811 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6812 ///
6813 /// Essentially it concatenates V1 and V2, shifts right by some number of
6814 /// elements, and takes the low elements as the result. Note that while this is
6815 /// specified as a *right shift* because x86 is little-endian, it is a *left
6816 /// rotate* of the vector lanes.
6817 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6818                                               SDValue V2,
6819                                               ArrayRef<int> Mask,
6820                                               const X86Subtarget *Subtarget,
6821                                               SelectionDAG &DAG) {
6822   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6823
6824   int NumElts = Mask.size();
6825   int NumLanes = VT.getSizeInBits() / 128;
6826   int NumLaneElts = NumElts / NumLanes;
6827
6828   // We need to detect various ways of spelling a rotation:
6829   //   [11, 12, 13, 14, 15,  0,  1,  2]
6830   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6831   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6832   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6833   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6834   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6835   int Rotation = 0;
6836   SDValue Lo, Hi;
6837   for (int l = 0; l < NumElts; l += NumLaneElts) {
6838     for (int i = 0; i < NumLaneElts; ++i) {
6839       if (Mask[l + i] == -1)
6840         continue;
6841       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6842
6843       // Get the mod-Size index and lane correct it.
6844       int LaneIdx = (Mask[l + i] % NumElts) - l;
6845       // Make sure it was in this lane.
6846       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6847         return SDValue();
6848
6849       // Determine where a rotated vector would have started.
6850       int StartIdx = i - LaneIdx;
6851       if (StartIdx == 0)
6852         // The identity rotation isn't interesting, stop.
6853         return SDValue();
6854
6855       // If we found the tail of a vector the rotation must be the missing
6856       // front. If we found the head of a vector, it must be how much of the
6857       // head.
6858       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6859
6860       if (Rotation == 0)
6861         Rotation = CandidateRotation;
6862       else if (Rotation != CandidateRotation)
6863         // The rotations don't match, so we can't match this mask.
6864         return SDValue();
6865
6866       // Compute which value this mask is pointing at.
6867       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6868
6869       // Compute which of the two target values this index should be assigned
6870       // to. This reflects whether the high elements are remaining or the low
6871       // elements are remaining.
6872       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6873
6874       // Either set up this value if we've not encountered it before, or check
6875       // that it remains consistent.
6876       if (!TargetV)
6877         TargetV = MaskV;
6878       else if (TargetV != MaskV)
6879         // This may be a rotation, but it pulls from the inputs in some
6880         // unsupported interleaving.
6881         return SDValue();
6882     }
6883   }
6884
6885   // Check that we successfully analyzed the mask, and normalize the results.
6886   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6887   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6888   if (!Lo)
6889     Lo = Hi;
6890   else if (!Hi)
6891     Hi = Lo;
6892
6893   // The actual rotate instruction rotates bytes, so we need to scale the
6894   // rotation based on how many bytes are in the vector lane.
6895   int Scale = 16 / NumLaneElts;
6896
6897   // SSSE3 targets can use the palignr instruction.
6898   if (Subtarget->hasSSSE3()) {
6899     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6900     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6901     Lo = DAG.getBitcast(AlignVT, Lo);
6902     Hi = DAG.getBitcast(AlignVT, Hi);
6903
6904     return DAG.getBitcast(
6905         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6906                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6907   }
6908
6909   assert(VT.getSizeInBits() == 128 &&
6910          "Rotate-based lowering only supports 128-bit lowering!");
6911   assert(Mask.size() <= 16 &&
6912          "Can shuffle at most 16 bytes in a 128-bit vector!");
6913
6914   // Default SSE2 implementation
6915   int LoByteShift = 16 - Rotation * Scale;
6916   int HiByteShift = Rotation * Scale;
6917
6918   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6919   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6920   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6921
6922   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6923                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6924   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6925                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6926   return DAG.getBitcast(VT,
6927                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6928 }
6929
6930 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6931 ///
6932 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6933 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6934 /// matches elements from one of the input vectors shuffled to the left or
6935 /// right with zeroable elements 'shifted in'. It handles both the strictly
6936 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6937 /// quad word lane.
6938 ///
6939 /// PSHL : (little-endian) left bit shift.
6940 /// [ zz, 0, zz,  2 ]
6941 /// [ -1, 4, zz, -1 ]
6942 /// PSRL : (little-endian) right bit shift.
6943 /// [  1, zz,  3, zz]
6944 /// [ -1, -1,  7, zz]
6945 /// PSLLDQ : (little-endian) left byte shift
6946 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6947 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6948 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6949 /// PSRLDQ : (little-endian) right byte shift
6950 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6951 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6952 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6953 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6954                                          SDValue V2, ArrayRef<int> Mask,
6955                                          SelectionDAG &DAG) {
6956   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6957
6958   int Size = Mask.size();
6959   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6960
6961   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6962     for (int i = 0; i < Size; i += Scale)
6963       for (int j = 0; j < Shift; ++j)
6964         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6965           return false;
6966
6967     return true;
6968   };
6969
6970   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6971     for (int i = 0; i != Size; i += Scale) {
6972       unsigned Pos = Left ? i + Shift : i;
6973       unsigned Low = Left ? i : i + Shift;
6974       unsigned Len = Scale - Shift;
6975       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6976                                       Low + (V == V1 ? 0 : Size)))
6977         return SDValue();
6978     }
6979
6980     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6981     bool ByteShift = ShiftEltBits > 64;
6982     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6983                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6984     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6985
6986     // Normalize the scale for byte shifts to still produce an i64 element
6987     // type.
6988     Scale = ByteShift ? Scale / 2 : Scale;
6989
6990     // We need to round trip through the appropriate type for the shift.
6991     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6992     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6993     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6994            "Illegal integer vector type");
6995     V = DAG.getBitcast(ShiftVT, V);
6996
6997     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6998                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6999     return DAG.getBitcast(VT, V);
7000   };
7001
7002   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7003   // keep doubling the size of the integer elements up to that. We can
7004   // then shift the elements of the integer vector by whole multiples of
7005   // their width within the elements of the larger integer vector. Test each
7006   // multiple to see if we can find a match with the moved element indices
7007   // and that the shifted in elements are all zeroable.
7008   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7009     for (int Shift = 1; Shift != Scale; ++Shift)
7010       for (bool Left : {true, false})
7011         if (CheckZeros(Shift, Scale, Left))
7012           for (SDValue V : {V1, V2})
7013             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7014               return Match;
7015
7016   // no match
7017   return SDValue();
7018 }
7019
7020 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7021 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7022                                            SDValue V2, ArrayRef<int> Mask,
7023                                            SelectionDAG &DAG) {
7024   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7025   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7026
7027   int Size = Mask.size();
7028   int HalfSize = Size / 2;
7029   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7030
7031   // Upper half must be undefined.
7032   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7033     return SDValue();
7034
7035   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7036   // Remainder of lower half result is zero and upper half is all undef.
7037   auto LowerAsEXTRQ = [&]() {
7038     // Determine the extraction length from the part of the
7039     // lower half that isn't zeroable.
7040     int Len = HalfSize;
7041     for (; Len >= 0; --Len)
7042       if (!Zeroable[Len - 1])
7043         break;
7044     assert(Len > 0 && "Zeroable shuffle mask");
7045
7046     // Attempt to match first Len sequential elements from the lower half.
7047     SDValue Src;
7048     int Idx = -1;
7049     for (int i = 0; i != Len; ++i) {
7050       int M = Mask[i];
7051       if (M < 0)
7052         continue;
7053       SDValue &V = (M < Size ? V1 : V2);
7054       M = M % Size;
7055
7056       // All mask elements must be in the lower half.
7057       if (M > HalfSize)
7058         return SDValue();
7059
7060       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7061         Src = V;
7062         Idx = M - i;
7063         continue;
7064       }
7065       return SDValue();
7066     }
7067
7068     if (Idx < 0)
7069       return SDValue();
7070
7071     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7072     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7073     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7074     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7075                        DAG.getConstant(BitLen, DL, MVT::i8),
7076                        DAG.getConstant(BitIdx, DL, MVT::i8));
7077   };
7078
7079   if (SDValue ExtrQ = LowerAsEXTRQ())
7080     return ExtrQ;
7081
7082   // INSERTQ: Extract lowest Len elements from lower half of second source and
7083   // insert over first source, starting at Idx.
7084   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7085   auto LowerAsInsertQ = [&]() {
7086     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7087       SDValue Base;
7088
7089       // Attempt to match first source from mask before insertion point.
7090       if (isUndefInRange(Mask, 0, Idx)) {
7091         /* EMPTY */
7092       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7093         Base = V1;
7094       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7095         Base = V2;
7096       } else {
7097         continue;
7098       }
7099
7100       // Extend the extraction length looking to match both the insertion of
7101       // the second source and the remaining elements of the first.
7102       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7103         SDValue Insert;
7104         int Len = Hi - Idx;
7105
7106         // Match insertion.
7107         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7108           Insert = V1;
7109         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7110           Insert = V2;
7111         } else {
7112           continue;
7113         }
7114
7115         // Match the remaining elements of the lower half.
7116         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7117           /* EMPTY */
7118         } else if ((!Base || (Base == V1)) &&
7119                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7120           Base = V1;
7121         } else if ((!Base || (Base == V2)) &&
7122                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7123                                               Size + Hi)) {
7124           Base = V2;
7125         } else {
7126           continue;
7127         }
7128
7129         // We may not have a base (first source) - this can safely be undefined.
7130         if (!Base)
7131           Base = DAG.getUNDEF(VT);
7132
7133         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7134         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7135         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7136                            DAG.getConstant(BitLen, DL, MVT::i8),
7137                            DAG.getConstant(BitIdx, DL, MVT::i8));
7138       }
7139     }
7140
7141     return SDValue();
7142   };
7143
7144   if (SDValue InsertQ = LowerAsInsertQ())
7145     return InsertQ;
7146
7147   return SDValue();
7148 }
7149
7150 /// \brief Lower a vector shuffle as a zero or any extension.
7151 ///
7152 /// Given a specific number of elements, element bit width, and extension
7153 /// stride, produce either a zero or any extension based on the available
7154 /// features of the subtarget.
7155 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7156     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7157     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7158   assert(Scale > 1 && "Need a scale to extend.");
7159   int NumElements = VT.getVectorNumElements();
7160   int EltBits = VT.getScalarSizeInBits();
7161   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7162          "Only 8, 16, and 32 bit elements can be extended.");
7163   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7164
7165   // Found a valid zext mask! Try various lowering strategies based on the
7166   // input type and available ISA extensions.
7167   if (Subtarget->hasSSE41()) {
7168     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7169                                  NumElements / Scale);
7170     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7171   }
7172
7173   // For any extends we can cheat for larger element sizes and use shuffle
7174   // instructions that can fold with a load and/or copy.
7175   if (AnyExt && EltBits == 32) {
7176     int PSHUFDMask[4] = {0, -1, 1, -1};
7177     return DAG.getBitcast(
7178         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7179                         DAG.getBitcast(MVT::v4i32, InputV),
7180                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7181   }
7182   if (AnyExt && EltBits == 16 && Scale > 2) {
7183     int PSHUFDMask[4] = {0, -1, 0, -1};
7184     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7185                          DAG.getBitcast(MVT::v4i32, InputV),
7186                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7187     int PSHUFHWMask[4] = {1, -1, -1, -1};
7188     return DAG.getBitcast(
7189         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7190                         DAG.getBitcast(MVT::v8i16, InputV),
7191                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7192   }
7193
7194   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7195   // to 64-bits.
7196   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7197     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7198     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7199
7200     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7201                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7202                                          DAG.getConstant(EltBits, DL, MVT::i8),
7203                                          DAG.getConstant(0, DL, MVT::i8)));
7204     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7205       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7206
7207     SDValue Hi =
7208         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7209                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7210                                 DAG.getConstant(EltBits, DL, MVT::i8),
7211                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7212     return DAG.getNode(ISD::BITCAST, DL, VT,
7213                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7214   }
7215
7216   // If this would require more than 2 unpack instructions to expand, use
7217   // pshufb when available. We can only use more than 2 unpack instructions
7218   // when zero extending i8 elements which also makes it easier to use pshufb.
7219   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7220     assert(NumElements == 16 && "Unexpected byte vector width!");
7221     SDValue PSHUFBMask[16];
7222     for (int i = 0; i < 16; ++i)
7223       PSHUFBMask[i] =
7224           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7225     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7226     return DAG.getBitcast(VT,
7227                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7228                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7229                                                   MVT::v16i8, PSHUFBMask)));
7230   }
7231
7232   // Otherwise emit a sequence of unpacks.
7233   do {
7234     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7235     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7236                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7237     InputV = DAG.getBitcast(InputVT, InputV);
7238     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7239     Scale /= 2;
7240     EltBits *= 2;
7241     NumElements /= 2;
7242   } while (Scale > 1);
7243   return DAG.getBitcast(VT, InputV);
7244 }
7245
7246 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7247 ///
7248 /// This routine will try to do everything in its power to cleverly lower
7249 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7250 /// check for the profitability of this lowering,  it tries to aggressively
7251 /// match this pattern. It will use all of the micro-architectural details it
7252 /// can to emit an efficient lowering. It handles both blends with all-zero
7253 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7254 /// masking out later).
7255 ///
7256 /// The reason we have dedicated lowering for zext-style shuffles is that they
7257 /// are both incredibly common and often quite performance sensitive.
7258 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7259     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7260     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7261   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7262
7263   int Bits = VT.getSizeInBits();
7264   int NumElements = VT.getVectorNumElements();
7265   assert(VT.getScalarSizeInBits() <= 32 &&
7266          "Exceeds 32-bit integer zero extension limit");
7267   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7268
7269   // Define a helper function to check a particular ext-scale and lower to it if
7270   // valid.
7271   auto Lower = [&](int Scale) -> SDValue {
7272     SDValue InputV;
7273     bool AnyExt = true;
7274     for (int i = 0; i < NumElements; ++i) {
7275       if (Mask[i] == -1)
7276         continue; // Valid anywhere but doesn't tell us anything.
7277       if (i % Scale != 0) {
7278         // Each of the extended elements need to be zeroable.
7279         if (!Zeroable[i])
7280           return SDValue();
7281
7282         // We no longer are in the anyext case.
7283         AnyExt = false;
7284         continue;
7285       }
7286
7287       // Each of the base elements needs to be consecutive indices into the
7288       // same input vector.
7289       SDValue V = Mask[i] < NumElements ? V1 : V2;
7290       if (!InputV)
7291         InputV = V;
7292       else if (InputV != V)
7293         return SDValue(); // Flip-flopping inputs.
7294
7295       if (Mask[i] % NumElements != i / Scale)
7296         return SDValue(); // Non-consecutive strided elements.
7297     }
7298
7299     // If we fail to find an input, we have a zero-shuffle which should always
7300     // have already been handled.
7301     // FIXME: Maybe handle this here in case during blending we end up with one?
7302     if (!InputV)
7303       return SDValue();
7304
7305     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7306         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7307   };
7308
7309   // The widest scale possible for extending is to a 64-bit integer.
7310   assert(Bits % 64 == 0 &&
7311          "The number of bits in a vector must be divisible by 64 on x86!");
7312   int NumExtElements = Bits / 64;
7313
7314   // Each iteration, try extending the elements half as much, but into twice as
7315   // many elements.
7316   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7317     assert(NumElements % NumExtElements == 0 &&
7318            "The input vector size must be divisible by the extended size.");
7319     if (SDValue V = Lower(NumElements / NumExtElements))
7320       return V;
7321   }
7322
7323   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7324   if (Bits != 128)
7325     return SDValue();
7326
7327   // Returns one of the source operands if the shuffle can be reduced to a
7328   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7329   auto CanZExtLowHalf = [&]() {
7330     for (int i = NumElements / 2; i != NumElements; ++i)
7331       if (!Zeroable[i])
7332         return SDValue();
7333     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7334       return V1;
7335     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7336       return V2;
7337     return SDValue();
7338   };
7339
7340   if (SDValue V = CanZExtLowHalf()) {
7341     V = DAG.getBitcast(MVT::v2i64, V);
7342     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7343     return DAG.getBitcast(VT, V);
7344   }
7345
7346   // No viable ext lowering found.
7347   return SDValue();
7348 }
7349
7350 /// \brief Try to get a scalar value for a specific element of a vector.
7351 ///
7352 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7353 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7354                                               SelectionDAG &DAG) {
7355   MVT VT = V.getSimpleValueType();
7356   MVT EltVT = VT.getVectorElementType();
7357   while (V.getOpcode() == ISD::BITCAST)
7358     V = V.getOperand(0);
7359   // If the bitcasts shift the element size, we can't extract an equivalent
7360   // element from it.
7361   MVT NewVT = V.getSimpleValueType();
7362   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7363     return SDValue();
7364
7365   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7366       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7367     // Ensure the scalar operand is the same size as the destination.
7368     // FIXME: Add support for scalar truncation where possible.
7369     SDValue S = V.getOperand(Idx);
7370     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7371       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7372   }
7373
7374   return SDValue();
7375 }
7376
7377 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7378 ///
7379 /// This is particularly important because the set of instructions varies
7380 /// significantly based on whether the operand is a load or not.
7381 static bool isShuffleFoldableLoad(SDValue V) {
7382   while (V.getOpcode() == ISD::BITCAST)
7383     V = V.getOperand(0);
7384
7385   return ISD::isNON_EXTLoad(V.getNode());
7386 }
7387
7388 /// \brief Try to lower insertion of a single element into a zero vector.
7389 ///
7390 /// This is a common pattern that we have especially efficient patterns to lower
7391 /// across all subtarget feature sets.
7392 static SDValue lowerVectorShuffleAsElementInsertion(
7393     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7394     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7395   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7396   MVT ExtVT = VT;
7397   MVT EltVT = VT.getVectorElementType();
7398
7399   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7400                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7401                 Mask.begin();
7402   bool IsV1Zeroable = true;
7403   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7404     if (i != V2Index && !Zeroable[i]) {
7405       IsV1Zeroable = false;
7406       break;
7407     }
7408
7409   // Check for a single input from a SCALAR_TO_VECTOR node.
7410   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7411   // all the smarts here sunk into that routine. However, the current
7412   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7413   // vector shuffle lowering is dead.
7414   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7415                                                DAG);
7416   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7417     // We need to zext the scalar if it is smaller than an i32.
7418     V2S = DAG.getBitcast(EltVT, V2S);
7419     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7420       // Using zext to expand a narrow element won't work for non-zero
7421       // insertions.
7422       if (!IsV1Zeroable)
7423         return SDValue();
7424
7425       // Zero-extend directly to i32.
7426       ExtVT = MVT::v4i32;
7427       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7428     }
7429     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7430   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7431              EltVT == MVT::i16) {
7432     // Either not inserting from the low element of the input or the input
7433     // element size is too small to use VZEXT_MOVL to clear the high bits.
7434     return SDValue();
7435   }
7436
7437   if (!IsV1Zeroable) {
7438     // If V1 can't be treated as a zero vector we have fewer options to lower
7439     // this. We can't support integer vectors or non-zero targets cheaply, and
7440     // the V1 elements can't be permuted in any way.
7441     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7442     if (!VT.isFloatingPoint() || V2Index != 0)
7443       return SDValue();
7444     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7445     V1Mask[V2Index] = -1;
7446     if (!isNoopShuffleMask(V1Mask))
7447       return SDValue();
7448     // This is essentially a special case blend operation, but if we have
7449     // general purpose blend operations, they are always faster. Bail and let
7450     // the rest of the lowering handle these as blends.
7451     if (Subtarget->hasSSE41())
7452       return SDValue();
7453
7454     // Otherwise, use MOVSD or MOVSS.
7455     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7456            "Only two types of floating point element types to handle!");
7457     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7458                        ExtVT, V1, V2);
7459   }
7460
7461   // This lowering only works for the low element with floating point vectors.
7462   if (VT.isFloatingPoint() && V2Index != 0)
7463     return SDValue();
7464
7465   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7466   if (ExtVT != VT)
7467     V2 = DAG.getBitcast(VT, V2);
7468
7469   if (V2Index != 0) {
7470     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7471     // the desired position. Otherwise it is more efficient to do a vector
7472     // shift left. We know that we can do a vector shift left because all
7473     // the inputs are zero.
7474     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7475       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7476       V2Shuffle[V2Index] = 0;
7477       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7478     } else {
7479       V2 = DAG.getBitcast(MVT::v2i64, V2);
7480       V2 = DAG.getNode(
7481           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7482           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7483                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7484                               DAG.getDataLayout(), VT)));
7485       V2 = DAG.getBitcast(VT, V2);
7486     }
7487   }
7488   return V2;
7489 }
7490
7491 /// \brief Try to lower broadcast of a single element.
7492 ///
7493 /// For convenience, this code also bundles all of the subtarget feature set
7494 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7495 /// a convenient way to factor it out.
7496 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7497                                              ArrayRef<int> Mask,
7498                                              const X86Subtarget *Subtarget,
7499                                              SelectionDAG &DAG) {
7500   if (!Subtarget->hasAVX())
7501     return SDValue();
7502   if (VT.isInteger() && !Subtarget->hasAVX2())
7503     return SDValue();
7504
7505   // Check that the mask is a broadcast.
7506   int BroadcastIdx = -1;
7507   for (int M : Mask)
7508     if (M >= 0 && BroadcastIdx == -1)
7509       BroadcastIdx = M;
7510     else if (M >= 0 && M != BroadcastIdx)
7511       return SDValue();
7512
7513   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7514                                             "a sorted mask where the broadcast "
7515                                             "comes from V1.");
7516
7517   // Go up the chain of (vector) values to find a scalar load that we can
7518   // combine with the broadcast.
7519   for (;;) {
7520     switch (V.getOpcode()) {
7521     case ISD::CONCAT_VECTORS: {
7522       int OperandSize = Mask.size() / V.getNumOperands();
7523       V = V.getOperand(BroadcastIdx / OperandSize);
7524       BroadcastIdx %= OperandSize;
7525       continue;
7526     }
7527
7528     case ISD::INSERT_SUBVECTOR: {
7529       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7530       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7531       if (!ConstantIdx)
7532         break;
7533
7534       int BeginIdx = (int)ConstantIdx->getZExtValue();
7535       int EndIdx =
7536           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7537       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7538         BroadcastIdx -= BeginIdx;
7539         V = VInner;
7540       } else {
7541         V = VOuter;
7542       }
7543       continue;
7544     }
7545     }
7546     break;
7547   }
7548
7549   // Check if this is a broadcast of a scalar. We special case lowering
7550   // for scalars so that we can more effectively fold with loads.
7551   // First, look through bitcast: if the original value has a larger element
7552   // type than the shuffle, the broadcast element is in essence truncated.
7553   // Make that explicit to ease folding.
7554   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7555     EVT EltVT = VT.getVectorElementType();
7556     SDValue V0 = V.getOperand(0);
7557     EVT V0VT = V0.getValueType();
7558
7559     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7560         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7561          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7562       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7563       BroadcastIdx = 0;
7564     }
7565   }
7566
7567   // Also check the simpler case, where we can directly reuse the scalar.
7568   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7569       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7570     V = V.getOperand(BroadcastIdx);
7571
7572     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7573     // Only AVX2 has register broadcasts.
7574     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7575       return SDValue();
7576   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7577     // We can't broadcast from a vector register without AVX2, and we can only
7578     // broadcast from the zero-element of a vector register.
7579     return SDValue();
7580   }
7581
7582   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7583 }
7584
7585 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7586 // INSERTPS when the V1 elements are already in the correct locations
7587 // because otherwise we can just always use two SHUFPS instructions which
7588 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7589 // perform INSERTPS if a single V1 element is out of place and all V2
7590 // elements are zeroable.
7591 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7592                                             ArrayRef<int> Mask,
7593                                             SelectionDAG &DAG) {
7594   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7595   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7596   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7597   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7598
7599   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7600
7601   unsigned ZMask = 0;
7602   int V1DstIndex = -1;
7603   int V2DstIndex = -1;
7604   bool V1UsedInPlace = false;
7605
7606   for (int i = 0; i < 4; ++i) {
7607     // Synthesize a zero mask from the zeroable elements (includes undefs).
7608     if (Zeroable[i]) {
7609       ZMask |= 1 << i;
7610       continue;
7611     }
7612
7613     // Flag if we use any V1 inputs in place.
7614     if (i == Mask[i]) {
7615       V1UsedInPlace = true;
7616       continue;
7617     }
7618
7619     // We can only insert a single non-zeroable element.
7620     if (V1DstIndex != -1 || V2DstIndex != -1)
7621       return SDValue();
7622
7623     if (Mask[i] < 4) {
7624       // V1 input out of place for insertion.
7625       V1DstIndex = i;
7626     } else {
7627       // V2 input for insertion.
7628       V2DstIndex = i;
7629     }
7630   }
7631
7632   // Don't bother if we have no (non-zeroable) element for insertion.
7633   if (V1DstIndex == -1 && V2DstIndex == -1)
7634     return SDValue();
7635
7636   // Determine element insertion src/dst indices. The src index is from the
7637   // start of the inserted vector, not the start of the concatenated vector.
7638   unsigned V2SrcIndex = 0;
7639   if (V1DstIndex != -1) {
7640     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7641     // and don't use the original V2 at all.
7642     V2SrcIndex = Mask[V1DstIndex];
7643     V2DstIndex = V1DstIndex;
7644     V2 = V1;
7645   } else {
7646     V2SrcIndex = Mask[V2DstIndex] - 4;
7647   }
7648
7649   // If no V1 inputs are used in place, then the result is created only from
7650   // the zero mask and the V2 insertion - so remove V1 dependency.
7651   if (!V1UsedInPlace)
7652     V1 = DAG.getUNDEF(MVT::v4f32);
7653
7654   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7655   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7656
7657   // Insert the V2 element into the desired position.
7658   SDLoc DL(Op);
7659   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7660                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7661 }
7662
7663 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7664 /// UNPCK instruction.
7665 ///
7666 /// This specifically targets cases where we end up with alternating between
7667 /// the two inputs, and so can permute them into something that feeds a single
7668 /// UNPCK instruction. Note that this routine only targets integer vectors
7669 /// because for floating point vectors we have a generalized SHUFPS lowering
7670 /// strategy that handles everything that doesn't *exactly* match an unpack,
7671 /// making this clever lowering unnecessary.
7672 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7673                                           SDValue V2, ArrayRef<int> Mask,
7674                                           SelectionDAG &DAG) {
7675   assert(!VT.isFloatingPoint() &&
7676          "This routine only supports integer vectors.");
7677   assert(!isSingleInputShuffleMask(Mask) &&
7678          "This routine should only be used when blending two inputs.");
7679   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7680
7681   int Size = Mask.size();
7682
7683   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7684     return M >= 0 && M % Size < Size / 2;
7685   });
7686   int NumHiInputs = std::count_if(
7687       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7688
7689   bool UnpackLo = NumLoInputs >= NumHiInputs;
7690
7691   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7692     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7693     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7694
7695     for (int i = 0; i < Size; ++i) {
7696       if (Mask[i] < 0)
7697         continue;
7698
7699       // Each element of the unpack contains Scale elements from this mask.
7700       int UnpackIdx = i / Scale;
7701
7702       // We only handle the case where V1 feeds the first slots of the unpack.
7703       // We rely on canonicalization to ensure this is the case.
7704       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7705         return SDValue();
7706
7707       // Setup the mask for this input. The indexing is tricky as we have to
7708       // handle the unpack stride.
7709       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7710       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7711           Mask[i] % Size;
7712     }
7713
7714     // If we will have to shuffle both inputs to use the unpack, check whether
7715     // we can just unpack first and shuffle the result. If so, skip this unpack.
7716     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7717         !isNoopShuffleMask(V2Mask))
7718       return SDValue();
7719
7720     // Shuffle the inputs into place.
7721     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7722     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7723
7724     // Cast the inputs to the type we will use to unpack them.
7725     V1 = DAG.getBitcast(UnpackVT, V1);
7726     V2 = DAG.getBitcast(UnpackVT, V2);
7727
7728     // Unpack the inputs and cast the result back to the desired type.
7729     return DAG.getBitcast(
7730         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7731                         UnpackVT, V1, V2));
7732   };
7733
7734   // We try each unpack from the largest to the smallest to try and find one
7735   // that fits this mask.
7736   int OrigNumElements = VT.getVectorNumElements();
7737   int OrigScalarSize = VT.getScalarSizeInBits();
7738   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7739     int Scale = ScalarSize / OrigScalarSize;
7740     int NumElements = OrigNumElements / Scale;
7741     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7742     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7743       return Unpack;
7744   }
7745
7746   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7747   // initial unpack.
7748   if (NumLoInputs == 0 || NumHiInputs == 0) {
7749     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7750            "We have to have *some* inputs!");
7751     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7752
7753     // FIXME: We could consider the total complexity of the permute of each
7754     // possible unpacking. Or at the least we should consider how many
7755     // half-crossings are created.
7756     // FIXME: We could consider commuting the unpacks.
7757
7758     SmallVector<int, 32> PermMask;
7759     PermMask.assign(Size, -1);
7760     for (int i = 0; i < Size; ++i) {
7761       if (Mask[i] < 0)
7762         continue;
7763
7764       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7765
7766       PermMask[i] =
7767           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7768     }
7769     return DAG.getVectorShuffle(
7770         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7771                             DL, VT, V1, V2),
7772         DAG.getUNDEF(VT), PermMask);
7773   }
7774
7775   return SDValue();
7776 }
7777
7778 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7779 ///
7780 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7781 /// support for floating point shuffles but not integer shuffles. These
7782 /// instructions will incur a domain crossing penalty on some chips though so
7783 /// it is better to avoid lowering through this for integer vectors where
7784 /// possible.
7785 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7786                                        const X86Subtarget *Subtarget,
7787                                        SelectionDAG &DAG) {
7788   SDLoc DL(Op);
7789   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7790   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7791   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7793   ArrayRef<int> Mask = SVOp->getMask();
7794   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7795
7796   if (isSingleInputShuffleMask(Mask)) {
7797     // Use low duplicate instructions for masks that match their pattern.
7798     if (Subtarget->hasSSE3())
7799       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7800         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7801
7802     // Straight shuffle of a single input vector. Simulate this by using the
7803     // single input as both of the "inputs" to this instruction..
7804     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7805
7806     if (Subtarget->hasAVX()) {
7807       // If we have AVX, we can use VPERMILPS which will allow folding a load
7808       // into the shuffle.
7809       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7810                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7811     }
7812
7813     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7814                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7815   }
7816   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7817   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7818
7819   // If we have a single input, insert that into V1 if we can do so cheaply.
7820   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7821     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7822             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7823       return Insertion;
7824     // Try inverting the insertion since for v2 masks it is easy to do and we
7825     // can't reliably sort the mask one way or the other.
7826     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7827                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7828     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7829             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7830       return Insertion;
7831   }
7832
7833   // Try to use one of the special instruction patterns to handle two common
7834   // blend patterns if a zero-blend above didn't work.
7835   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7836       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7837     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7838       // We can either use a special instruction to load over the low double or
7839       // to move just the low double.
7840       return DAG.getNode(
7841           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7842           DL, MVT::v2f64, V2,
7843           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7844
7845   if (Subtarget->hasSSE41())
7846     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7847                                                   Subtarget, DAG))
7848       return Blend;
7849
7850   // Use dedicated unpack instructions for masks that match their pattern.
7851   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7852     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7853   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7854     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7855
7856   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7857   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7858                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7859 }
7860
7861 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7862 ///
7863 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7864 /// the integer unit to minimize domain crossing penalties. However, for blends
7865 /// it falls back to the floating point shuffle operation with appropriate bit
7866 /// casting.
7867 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7868                                        const X86Subtarget *Subtarget,
7869                                        SelectionDAG &DAG) {
7870   SDLoc DL(Op);
7871   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7872   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7873   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7875   ArrayRef<int> Mask = SVOp->getMask();
7876   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7877
7878   if (isSingleInputShuffleMask(Mask)) {
7879     // Check for being able to broadcast a single element.
7880     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7881                                                           Mask, Subtarget, DAG))
7882       return Broadcast;
7883
7884     // Straight shuffle of a single input vector. For everything from SSE2
7885     // onward this has a single fast instruction with no scary immediates.
7886     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7887     V1 = DAG.getBitcast(MVT::v4i32, V1);
7888     int WidenedMask[4] = {
7889         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7890         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7891     return DAG.getBitcast(
7892         MVT::v2i64,
7893         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7894                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7895   }
7896   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7897   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7898   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7899   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7900
7901   // If we have a blend of two PACKUS operations an the blend aligns with the
7902   // low and half halves, we can just merge the PACKUS operations. This is
7903   // particularly important as it lets us merge shuffles that this routine itself
7904   // creates.
7905   auto GetPackNode = [](SDValue V) {
7906     while (V.getOpcode() == ISD::BITCAST)
7907       V = V.getOperand(0);
7908
7909     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7910   };
7911   if (SDValue V1Pack = GetPackNode(V1))
7912     if (SDValue V2Pack = GetPackNode(V2))
7913       return DAG.getBitcast(MVT::v2i64,
7914                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7915                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7916                                                      : V1Pack.getOperand(1),
7917                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7918                                                      : V2Pack.getOperand(1)));
7919
7920   // Try to use shift instructions.
7921   if (SDValue Shift =
7922           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7923     return Shift;
7924
7925   // When loading a scalar and then shuffling it into a vector we can often do
7926   // the insertion cheaply.
7927   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7928           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7929     return Insertion;
7930   // Try inverting the insertion since for v2 masks it is easy to do and we
7931   // can't reliably sort the mask one way or the other.
7932   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7933   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7934           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7935     return Insertion;
7936
7937   // We have different paths for blend lowering, but they all must use the
7938   // *exact* same predicate.
7939   bool IsBlendSupported = Subtarget->hasSSE41();
7940   if (IsBlendSupported)
7941     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7942                                                   Subtarget, DAG))
7943       return Blend;
7944
7945   // Use dedicated unpack instructions for masks that match their pattern.
7946   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7947     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7948   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7949     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7950
7951   // Try to use byte rotation instructions.
7952   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7953   if (Subtarget->hasSSSE3())
7954     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7955             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7956       return Rotate;
7957
7958   // If we have direct support for blends, we should lower by decomposing into
7959   // a permute. That will be faster than the domain cross.
7960   if (IsBlendSupported)
7961     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7962                                                       Mask, DAG);
7963
7964   // We implement this with SHUFPD which is pretty lame because it will likely
7965   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7966   // However, all the alternatives are still more cycles and newer chips don't
7967   // have this problem. It would be really nice if x86 had better shuffles here.
7968   V1 = DAG.getBitcast(MVT::v2f64, V1);
7969   V2 = DAG.getBitcast(MVT::v2f64, V2);
7970   return DAG.getBitcast(MVT::v2i64,
7971                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7972 }
7973
7974 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7975 ///
7976 /// This is used to disable more specialized lowerings when the shufps lowering
7977 /// will happen to be efficient.
7978 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7979   // This routine only handles 128-bit shufps.
7980   assert(Mask.size() == 4 && "Unsupported mask size!");
7981
7982   // To lower with a single SHUFPS we need to have the low half and high half
7983   // each requiring a single input.
7984   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7985     return false;
7986   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7987     return false;
7988
7989   return true;
7990 }
7991
7992 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7993 ///
7994 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7995 /// It makes no assumptions about whether this is the *best* lowering, it simply
7996 /// uses it.
7997 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7998                                             ArrayRef<int> Mask, SDValue V1,
7999                                             SDValue V2, SelectionDAG &DAG) {
8000   SDValue LowV = V1, HighV = V2;
8001   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8002
8003   int NumV2Elements =
8004       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8005
8006   if (NumV2Elements == 1) {
8007     int V2Index =
8008         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8009         Mask.begin();
8010
8011     // Compute the index adjacent to V2Index and in the same half by toggling
8012     // the low bit.
8013     int V2AdjIndex = V2Index ^ 1;
8014
8015     if (Mask[V2AdjIndex] == -1) {
8016       // Handles all the cases where we have a single V2 element and an undef.
8017       // This will only ever happen in the high lanes because we commute the
8018       // vector otherwise.
8019       if (V2Index < 2)
8020         std::swap(LowV, HighV);
8021       NewMask[V2Index] -= 4;
8022     } else {
8023       // Handle the case where the V2 element ends up adjacent to a V1 element.
8024       // To make this work, blend them together as the first step.
8025       int V1Index = V2AdjIndex;
8026       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8027       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8028                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8029
8030       // Now proceed to reconstruct the final blend as we have the necessary
8031       // high or low half formed.
8032       if (V2Index < 2) {
8033         LowV = V2;
8034         HighV = V1;
8035       } else {
8036         HighV = V2;
8037       }
8038       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8039       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8040     }
8041   } else if (NumV2Elements == 2) {
8042     if (Mask[0] < 4 && Mask[1] < 4) {
8043       // Handle the easy case where we have V1 in the low lanes and V2 in the
8044       // high lanes.
8045       NewMask[2] -= 4;
8046       NewMask[3] -= 4;
8047     } else if (Mask[2] < 4 && Mask[3] < 4) {
8048       // We also handle the reversed case because this utility may get called
8049       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8050       // arrange things in the right direction.
8051       NewMask[0] -= 4;
8052       NewMask[1] -= 4;
8053       HighV = V1;
8054       LowV = V2;
8055     } else {
8056       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8057       // trying to place elements directly, just blend them and set up the final
8058       // shuffle to place them.
8059
8060       // The first two blend mask elements are for V1, the second two are for
8061       // V2.
8062       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8063                           Mask[2] < 4 ? Mask[2] : Mask[3],
8064                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8065                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8066       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8067                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8068
8069       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8070       // a blend.
8071       LowV = HighV = V1;
8072       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8073       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8074       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8075       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8076     }
8077   }
8078   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8079                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8080 }
8081
8082 /// \brief Lower 4-lane 32-bit floating point shuffles.
8083 ///
8084 /// Uses instructions exclusively from the floating point unit to minimize
8085 /// domain crossing penalties, as these are sufficient to implement all v4f32
8086 /// shuffles.
8087 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8088                                        const X86Subtarget *Subtarget,
8089                                        SelectionDAG &DAG) {
8090   SDLoc DL(Op);
8091   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8092   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8093   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8094   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8095   ArrayRef<int> Mask = SVOp->getMask();
8096   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8097
8098   int NumV2Elements =
8099       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8100
8101   if (NumV2Elements == 0) {
8102     // Check for being able to broadcast a single element.
8103     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8104                                                           Mask, Subtarget, DAG))
8105       return Broadcast;
8106
8107     // Use even/odd duplicate instructions for masks that match their pattern.
8108     if (Subtarget->hasSSE3()) {
8109       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8110         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8111       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8112         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8113     }
8114
8115     if (Subtarget->hasAVX()) {
8116       // If we have AVX, we can use VPERMILPS which will allow folding a load
8117       // into the shuffle.
8118       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8119                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8120     }
8121
8122     // Otherwise, use a straight shuffle of a single input vector. We pass the
8123     // input vector to both operands to simulate this with a SHUFPS.
8124     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8125                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8126   }
8127
8128   // There are special ways we can lower some single-element blends. However, we
8129   // have custom ways we can lower more complex single-element blends below that
8130   // we defer to if both this and BLENDPS fail to match, so restrict this to
8131   // when the V2 input is targeting element 0 of the mask -- that is the fast
8132   // case here.
8133   if (NumV2Elements == 1 && Mask[0] >= 4)
8134     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8135                                                          Mask, Subtarget, DAG))
8136       return V;
8137
8138   if (Subtarget->hasSSE41()) {
8139     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8140                                                   Subtarget, DAG))
8141       return Blend;
8142
8143     // Use INSERTPS if we can complete the shuffle efficiently.
8144     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8145       return V;
8146
8147     if (!isSingleSHUFPSMask(Mask))
8148       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8149               DL, MVT::v4f32, V1, V2, Mask, DAG))
8150         return BlendPerm;
8151   }
8152
8153   // Use dedicated unpack instructions for masks that match their pattern.
8154   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8155     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8156   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8157     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8158   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8159     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8160   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8161     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8162
8163   // Otherwise fall back to a SHUFPS lowering strategy.
8164   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8165 }
8166
8167 /// \brief Lower 4-lane i32 vector shuffles.
8168 ///
8169 /// We try to handle these with integer-domain shuffles where we can, but for
8170 /// blends we use the floating point domain blend instructions.
8171 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8172                                        const X86Subtarget *Subtarget,
8173                                        SelectionDAG &DAG) {
8174   SDLoc DL(Op);
8175   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8176   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8177   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8178   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8179   ArrayRef<int> Mask = SVOp->getMask();
8180   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8181
8182   // Whenever we can lower this as a zext, that instruction is strictly faster
8183   // than any alternative. It also allows us to fold memory operands into the
8184   // shuffle in many cases.
8185   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8186                                                          Mask, Subtarget, DAG))
8187     return ZExt;
8188
8189   int NumV2Elements =
8190       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8191
8192   if (NumV2Elements == 0) {
8193     // Check for being able to broadcast a single element.
8194     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8195                                                           Mask, Subtarget, DAG))
8196       return Broadcast;
8197
8198     // Straight shuffle of a single input vector. For everything from SSE2
8199     // onward this has a single fast instruction with no scary immediates.
8200     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8201     // but we aren't actually going to use the UNPCK instruction because doing
8202     // so prevents folding a load into this instruction or making a copy.
8203     const int UnpackLoMask[] = {0, 0, 1, 1};
8204     const int UnpackHiMask[] = {2, 2, 3, 3};
8205     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8206       Mask = UnpackLoMask;
8207     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8208       Mask = UnpackHiMask;
8209
8210     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8211                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8212   }
8213
8214   // Try to use shift instructions.
8215   if (SDValue Shift =
8216           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8217     return Shift;
8218
8219   // There are special ways we can lower some single-element blends.
8220   if (NumV2Elements == 1)
8221     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8222                                                          Mask, Subtarget, DAG))
8223       return V;
8224
8225   // We have different paths for blend lowering, but they all must use the
8226   // *exact* same predicate.
8227   bool IsBlendSupported = Subtarget->hasSSE41();
8228   if (IsBlendSupported)
8229     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8230                                                   Subtarget, DAG))
8231       return Blend;
8232
8233   if (SDValue Masked =
8234           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8235     return Masked;
8236
8237   // Use dedicated unpack instructions for masks that match their pattern.
8238   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8239     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8240   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8241     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8242   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8243     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8244   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8245     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8246
8247   // Try to use byte rotation instructions.
8248   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8249   if (Subtarget->hasSSSE3())
8250     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8251             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8252       return Rotate;
8253
8254   // If we have direct support for blends, we should lower by decomposing into
8255   // a permute. That will be faster than the domain cross.
8256   if (IsBlendSupported)
8257     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8258                                                       Mask, DAG);
8259
8260   // Try to lower by permuting the inputs into an unpack instruction.
8261   if (SDValue Unpack =
8262           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8263     return Unpack;
8264
8265   // We implement this with SHUFPS because it can blend from two vectors.
8266   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8267   // up the inputs, bypassing domain shift penalties that we would encur if we
8268   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8269   // relevant.
8270   return DAG.getBitcast(
8271       MVT::v4i32,
8272       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8273                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8274 }
8275
8276 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8277 /// shuffle lowering, and the most complex part.
8278 ///
8279 /// The lowering strategy is to try to form pairs of input lanes which are
8280 /// targeted at the same half of the final vector, and then use a dword shuffle
8281 /// to place them onto the right half, and finally unpack the paired lanes into
8282 /// their final position.
8283 ///
8284 /// The exact breakdown of how to form these dword pairs and align them on the
8285 /// correct sides is really tricky. See the comments within the function for
8286 /// more of the details.
8287 ///
8288 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8289 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8290 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8291 /// vector, form the analogous 128-bit 8-element Mask.
8292 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8293     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8294     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8295   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8296   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8297
8298   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8299   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8300   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8301
8302   SmallVector<int, 4> LoInputs;
8303   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8304                [](int M) { return M >= 0; });
8305   std::sort(LoInputs.begin(), LoInputs.end());
8306   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8307   SmallVector<int, 4> HiInputs;
8308   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8309                [](int M) { return M >= 0; });
8310   std::sort(HiInputs.begin(), HiInputs.end());
8311   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8312   int NumLToL =
8313       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8314   int NumHToL = LoInputs.size() - NumLToL;
8315   int NumLToH =
8316       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8317   int NumHToH = HiInputs.size() - NumLToH;
8318   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8319   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8320   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8321   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8322
8323   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8324   // such inputs we can swap two of the dwords across the half mark and end up
8325   // with <=2 inputs to each half in each half. Once there, we can fall through
8326   // to the generic code below. For example:
8327   //
8328   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8329   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8330   //
8331   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8332   // and an existing 2-into-2 on the other half. In this case we may have to
8333   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8334   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8335   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8336   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8337   // half than the one we target for fixing) will be fixed when we re-enter this
8338   // path. We will also combine away any sequence of PSHUFD instructions that
8339   // result into a single instruction. Here is an example of the tricky case:
8340   //
8341   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8342   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8343   //
8344   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8345   //
8346   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8347   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8348   //
8349   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8350   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8351   //
8352   // The result is fine to be handled by the generic logic.
8353   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8354                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8355                           int AOffset, int BOffset) {
8356     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8357            "Must call this with A having 3 or 1 inputs from the A half.");
8358     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8359            "Must call this with B having 1 or 3 inputs from the B half.");
8360     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8361            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8362
8363     bool ThreeAInputs = AToAInputs.size() == 3;
8364
8365     // Compute the index of dword with only one word among the three inputs in
8366     // a half by taking the sum of the half with three inputs and subtracting
8367     // the sum of the actual three inputs. The difference is the remaining
8368     // slot.
8369     int ADWord, BDWord;
8370     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8371     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8372     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8373     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8374     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8375     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8376     int TripleNonInputIdx =
8377         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8378     TripleDWord = TripleNonInputIdx / 2;
8379
8380     // We use xor with one to compute the adjacent DWord to whichever one the
8381     // OneInput is in.
8382     OneInputDWord = (OneInput / 2) ^ 1;
8383
8384     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8385     // and BToA inputs. If there is also such a problem with the BToB and AToB
8386     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8387     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8388     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8389     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8390       // Compute how many inputs will be flipped by swapping these DWords. We
8391       // need
8392       // to balance this to ensure we don't form a 3-1 shuffle in the other
8393       // half.
8394       int NumFlippedAToBInputs =
8395           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8396           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8397       int NumFlippedBToBInputs =
8398           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8399           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8400       if ((NumFlippedAToBInputs == 1 &&
8401            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8402           (NumFlippedBToBInputs == 1 &&
8403            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8404         // We choose whether to fix the A half or B half based on whether that
8405         // half has zero flipped inputs. At zero, we may not be able to fix it
8406         // with that half. We also bias towards fixing the B half because that
8407         // will more commonly be the high half, and we have to bias one way.
8408         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8409                                                        ArrayRef<int> Inputs) {
8410           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8411           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8412                                          PinnedIdx ^ 1) != Inputs.end();
8413           // Determine whether the free index is in the flipped dword or the
8414           // unflipped dword based on where the pinned index is. We use this bit
8415           // in an xor to conditionally select the adjacent dword.
8416           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8417           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8418                                              FixFreeIdx) != Inputs.end();
8419           if (IsFixIdxInput == IsFixFreeIdxInput)
8420             FixFreeIdx += 1;
8421           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8422                                         FixFreeIdx) != Inputs.end();
8423           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8424                  "We need to be changing the number of flipped inputs!");
8425           int PSHUFHalfMask[] = {0, 1, 2, 3};
8426           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8427           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8428                           MVT::v8i16, V,
8429                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8430
8431           for (int &M : Mask)
8432             if (M != -1 && M == FixIdx)
8433               M = FixFreeIdx;
8434             else if (M != -1 && M == FixFreeIdx)
8435               M = FixIdx;
8436         };
8437         if (NumFlippedBToBInputs != 0) {
8438           int BPinnedIdx =
8439               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8440           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8441         } else {
8442           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8443           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8444           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8445         }
8446       }
8447     }
8448
8449     int PSHUFDMask[] = {0, 1, 2, 3};
8450     PSHUFDMask[ADWord] = BDWord;
8451     PSHUFDMask[BDWord] = ADWord;
8452     V = DAG.getBitcast(
8453         VT,
8454         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8455                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8456
8457     // Adjust the mask to match the new locations of A and B.
8458     for (int &M : Mask)
8459       if (M != -1 && M/2 == ADWord)
8460         M = 2 * BDWord + M % 2;
8461       else if (M != -1 && M/2 == BDWord)
8462         M = 2 * ADWord + M % 2;
8463
8464     // Recurse back into this routine to re-compute state now that this isn't
8465     // a 3 and 1 problem.
8466     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8467                                                      DAG);
8468   };
8469   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8470     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8471   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8472     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8473
8474   // At this point there are at most two inputs to the low and high halves from
8475   // each half. That means the inputs can always be grouped into dwords and
8476   // those dwords can then be moved to the correct half with a dword shuffle.
8477   // We use at most one low and one high word shuffle to collect these paired
8478   // inputs into dwords, and finally a dword shuffle to place them.
8479   int PSHUFLMask[4] = {-1, -1, -1, -1};
8480   int PSHUFHMask[4] = {-1, -1, -1, -1};
8481   int PSHUFDMask[4] = {-1, -1, -1, -1};
8482
8483   // First fix the masks for all the inputs that are staying in their
8484   // original halves. This will then dictate the targets of the cross-half
8485   // shuffles.
8486   auto fixInPlaceInputs =
8487       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8488                     MutableArrayRef<int> SourceHalfMask,
8489                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8490     if (InPlaceInputs.empty())
8491       return;
8492     if (InPlaceInputs.size() == 1) {
8493       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8494           InPlaceInputs[0] - HalfOffset;
8495       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8496       return;
8497     }
8498     if (IncomingInputs.empty()) {
8499       // Just fix all of the in place inputs.
8500       for (int Input : InPlaceInputs) {
8501         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8502         PSHUFDMask[Input / 2] = Input / 2;
8503       }
8504       return;
8505     }
8506
8507     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8508     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8509         InPlaceInputs[0] - HalfOffset;
8510     // Put the second input next to the first so that they are packed into
8511     // a dword. We find the adjacent index by toggling the low bit.
8512     int AdjIndex = InPlaceInputs[0] ^ 1;
8513     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8514     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8515     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8516   };
8517   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8518   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8519
8520   // Now gather the cross-half inputs and place them into a free dword of
8521   // their target half.
8522   // FIXME: This operation could almost certainly be simplified dramatically to
8523   // look more like the 3-1 fixing operation.
8524   auto moveInputsToRightHalf = [&PSHUFDMask](
8525       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8526       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8527       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8528       int DestOffset) {
8529     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8530       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8531     };
8532     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8533                                                int Word) {
8534       int LowWord = Word & ~1;
8535       int HighWord = Word | 1;
8536       return isWordClobbered(SourceHalfMask, LowWord) ||
8537              isWordClobbered(SourceHalfMask, HighWord);
8538     };
8539
8540     if (IncomingInputs.empty())
8541       return;
8542
8543     if (ExistingInputs.empty()) {
8544       // Map any dwords with inputs from them into the right half.
8545       for (int Input : IncomingInputs) {
8546         // If the source half mask maps over the inputs, turn those into
8547         // swaps and use the swapped lane.
8548         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8549           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8550             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8551                 Input - SourceOffset;
8552             // We have to swap the uses in our half mask in one sweep.
8553             for (int &M : HalfMask)
8554               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8555                 M = Input;
8556               else if (M == Input)
8557                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8558           } else {
8559             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8560                        Input - SourceOffset &&
8561                    "Previous placement doesn't match!");
8562           }
8563           // Note that this correctly re-maps both when we do a swap and when
8564           // we observe the other side of the swap above. We rely on that to
8565           // avoid swapping the members of the input list directly.
8566           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8567         }
8568
8569         // Map the input's dword into the correct half.
8570         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8571           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8572         else
8573           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8574                      Input / 2 &&
8575                  "Previous placement doesn't match!");
8576       }
8577
8578       // And just directly shift any other-half mask elements to be same-half
8579       // as we will have mirrored the dword containing the element into the
8580       // same position within that half.
8581       for (int &M : HalfMask)
8582         if (M >= SourceOffset && M < SourceOffset + 4) {
8583           M = M - SourceOffset + DestOffset;
8584           assert(M >= 0 && "This should never wrap below zero!");
8585         }
8586       return;
8587     }
8588
8589     // Ensure we have the input in a viable dword of its current half. This
8590     // is particularly tricky because the original position may be clobbered
8591     // by inputs being moved and *staying* in that half.
8592     if (IncomingInputs.size() == 1) {
8593       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8594         int InputFixed = std::find(std::begin(SourceHalfMask),
8595                                    std::end(SourceHalfMask), -1) -
8596                          std::begin(SourceHalfMask) + SourceOffset;
8597         SourceHalfMask[InputFixed - SourceOffset] =
8598             IncomingInputs[0] - SourceOffset;
8599         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8600                      InputFixed);
8601         IncomingInputs[0] = InputFixed;
8602       }
8603     } else if (IncomingInputs.size() == 2) {
8604       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8605           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8606         // We have two non-adjacent or clobbered inputs we need to extract from
8607         // the source half. To do this, we need to map them into some adjacent
8608         // dword slot in the source mask.
8609         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8610                               IncomingInputs[1] - SourceOffset};
8611
8612         // If there is a free slot in the source half mask adjacent to one of
8613         // the inputs, place the other input in it. We use (Index XOR 1) to
8614         // compute an adjacent index.
8615         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8616             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8617           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8618           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8619           InputsFixed[1] = InputsFixed[0] ^ 1;
8620         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8621                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8622           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8623           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8624           InputsFixed[0] = InputsFixed[1] ^ 1;
8625         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8626                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8627           // The two inputs are in the same DWord but it is clobbered and the
8628           // adjacent DWord isn't used at all. Move both inputs to the free
8629           // slot.
8630           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8631           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8632           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8633           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8634         } else {
8635           // The only way we hit this point is if there is no clobbering
8636           // (because there are no off-half inputs to this half) and there is no
8637           // free slot adjacent to one of the inputs. In this case, we have to
8638           // swap an input with a non-input.
8639           for (int i = 0; i < 4; ++i)
8640             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8641                    "We can't handle any clobbers here!");
8642           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8643                  "Cannot have adjacent inputs here!");
8644
8645           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8646           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8647
8648           // We also have to update the final source mask in this case because
8649           // it may need to undo the above swap.
8650           for (int &M : FinalSourceHalfMask)
8651             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8652               M = InputsFixed[1] + SourceOffset;
8653             else if (M == InputsFixed[1] + SourceOffset)
8654               M = (InputsFixed[0] ^ 1) + SourceOffset;
8655
8656           InputsFixed[1] = InputsFixed[0] ^ 1;
8657         }
8658
8659         // Point everything at the fixed inputs.
8660         for (int &M : HalfMask)
8661           if (M == IncomingInputs[0])
8662             M = InputsFixed[0] + SourceOffset;
8663           else if (M == IncomingInputs[1])
8664             M = InputsFixed[1] + SourceOffset;
8665
8666         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8667         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8668       }
8669     } else {
8670       llvm_unreachable("Unhandled input size!");
8671     }
8672
8673     // Now hoist the DWord down to the right half.
8674     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8675     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8676     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8677     for (int &M : HalfMask)
8678       for (int Input : IncomingInputs)
8679         if (M == Input)
8680           M = FreeDWord * 2 + Input % 2;
8681   };
8682   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8683                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8684   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8685                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8686
8687   // Now enact all the shuffles we've computed to move the inputs into their
8688   // target half.
8689   if (!isNoopShuffleMask(PSHUFLMask))
8690     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8691                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8692   if (!isNoopShuffleMask(PSHUFHMask))
8693     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8694                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8695   if (!isNoopShuffleMask(PSHUFDMask))
8696     V = DAG.getBitcast(
8697         VT,
8698         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8699                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8700
8701   // At this point, each half should contain all its inputs, and we can then
8702   // just shuffle them into their final position.
8703   assert(std::count_if(LoMask.begin(), LoMask.end(),
8704                        [](int M) { return M >= 4; }) == 0 &&
8705          "Failed to lift all the high half inputs to the low mask!");
8706   assert(std::count_if(HiMask.begin(), HiMask.end(),
8707                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8708          "Failed to lift all the low half inputs to the high mask!");
8709
8710   // Do a half shuffle for the low mask.
8711   if (!isNoopShuffleMask(LoMask))
8712     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8713                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8714
8715   // Do a half shuffle with the high mask after shifting its values down.
8716   for (int &M : HiMask)
8717     if (M >= 0)
8718       M -= 4;
8719   if (!isNoopShuffleMask(HiMask))
8720     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8721                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8722
8723   return V;
8724 }
8725
8726 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8727 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8728                                           SDValue V2, ArrayRef<int> Mask,
8729                                           SelectionDAG &DAG, bool &V1InUse,
8730                                           bool &V2InUse) {
8731   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8732   SDValue V1Mask[16];
8733   SDValue V2Mask[16];
8734   V1InUse = false;
8735   V2InUse = false;
8736
8737   int Size = Mask.size();
8738   int Scale = 16 / Size;
8739   for (int i = 0; i < 16; ++i) {
8740     if (Mask[i / Scale] == -1) {
8741       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8742     } else {
8743       const int ZeroMask = 0x80;
8744       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8745                                           : ZeroMask;
8746       int V2Idx = Mask[i / Scale] < Size
8747                       ? ZeroMask
8748                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8749       if (Zeroable[i / Scale])
8750         V1Idx = V2Idx = ZeroMask;
8751       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8752       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8753       V1InUse |= (ZeroMask != V1Idx);
8754       V2InUse |= (ZeroMask != V2Idx);
8755     }
8756   }
8757
8758   if (V1InUse)
8759     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8760                      DAG.getBitcast(MVT::v16i8, V1),
8761                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8762   if (V2InUse)
8763     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8764                      DAG.getBitcast(MVT::v16i8, V2),
8765                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8766
8767   // If we need shuffled inputs from both, blend the two.
8768   SDValue V;
8769   if (V1InUse && V2InUse)
8770     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8771   else
8772     V = V1InUse ? V1 : V2;
8773
8774   // Cast the result back to the correct type.
8775   return DAG.getBitcast(VT, V);
8776 }
8777
8778 /// \brief Generic lowering of 8-lane i16 shuffles.
8779 ///
8780 /// This handles both single-input shuffles and combined shuffle/blends with
8781 /// two inputs. The single input shuffles are immediately delegated to
8782 /// a dedicated lowering routine.
8783 ///
8784 /// The blends are lowered in one of three fundamental ways. If there are few
8785 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8786 /// of the input is significantly cheaper when lowered as an interleaving of
8787 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8788 /// halves of the inputs separately (making them have relatively few inputs)
8789 /// and then concatenate them.
8790 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8791                                        const X86Subtarget *Subtarget,
8792                                        SelectionDAG &DAG) {
8793   SDLoc DL(Op);
8794   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8795   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8796   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8798   ArrayRef<int> OrigMask = SVOp->getMask();
8799   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8800                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8801   MutableArrayRef<int> Mask(MaskStorage);
8802
8803   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8804
8805   // Whenever we can lower this as a zext, that instruction is strictly faster
8806   // than any alternative.
8807   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8808           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8809     return ZExt;
8810
8811   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8812   (void)isV1;
8813   auto isV2 = [](int M) { return M >= 8; };
8814
8815   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8816
8817   if (NumV2Inputs == 0) {
8818     // Check for being able to broadcast a single element.
8819     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8820                                                           Mask, Subtarget, DAG))
8821       return Broadcast;
8822
8823     // Try to use shift instructions.
8824     if (SDValue Shift =
8825             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8826       return Shift;
8827
8828     // Use dedicated unpack instructions for masks that match their pattern.
8829     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8830       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8831     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8832       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8833
8834     // Try to use byte rotation instructions.
8835     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8836                                                         Mask, Subtarget, DAG))
8837       return Rotate;
8838
8839     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8840                                                      Subtarget, DAG);
8841   }
8842
8843   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8844          "All single-input shuffles should be canonicalized to be V1-input "
8845          "shuffles.");
8846
8847   // Try to use shift instructions.
8848   if (SDValue Shift =
8849           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8850     return Shift;
8851
8852   // See if we can use SSE4A Extraction / Insertion.
8853   if (Subtarget->hasSSE4A())
8854     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8855       return V;
8856
8857   // There are special ways we can lower some single-element blends.
8858   if (NumV2Inputs == 1)
8859     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8860                                                          Mask, Subtarget, DAG))
8861       return V;
8862
8863   // We have different paths for blend lowering, but they all must use the
8864   // *exact* same predicate.
8865   bool IsBlendSupported = Subtarget->hasSSE41();
8866   if (IsBlendSupported)
8867     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8868                                                   Subtarget, DAG))
8869       return Blend;
8870
8871   if (SDValue Masked =
8872           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8873     return Masked;
8874
8875   // Use dedicated unpack instructions for masks that match their pattern.
8876   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8877     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8878   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8879     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8880
8881   // Try to use byte rotation instructions.
8882   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8883           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8884     return Rotate;
8885
8886   if (SDValue BitBlend =
8887           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8888     return BitBlend;
8889
8890   if (SDValue Unpack =
8891           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8892     return Unpack;
8893
8894   // If we can't directly blend but can use PSHUFB, that will be better as it
8895   // can both shuffle and set up the inefficient blend.
8896   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8897     bool V1InUse, V2InUse;
8898     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8899                                       V1InUse, V2InUse);
8900   }
8901
8902   // We can always bit-blend if we have to so the fallback strategy is to
8903   // decompose into single-input permutes and blends.
8904   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8905                                                       Mask, DAG);
8906 }
8907
8908 /// \brief Check whether a compaction lowering can be done by dropping even
8909 /// elements and compute how many times even elements must be dropped.
8910 ///
8911 /// This handles shuffles which take every Nth element where N is a power of
8912 /// two. Example shuffle masks:
8913 ///
8914 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8915 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8916 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8917 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8918 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8919 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8920 ///
8921 /// Any of these lanes can of course be undef.
8922 ///
8923 /// This routine only supports N <= 3.
8924 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8925 /// for larger N.
8926 ///
8927 /// \returns N above, or the number of times even elements must be dropped if
8928 /// there is such a number. Otherwise returns zero.
8929 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8930   // Figure out whether we're looping over two inputs or just one.
8931   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8932
8933   // The modulus for the shuffle vector entries is based on whether this is
8934   // a single input or not.
8935   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8936   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8937          "We should only be called with masks with a power-of-2 size!");
8938
8939   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8940
8941   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8942   // and 2^3 simultaneously. This is because we may have ambiguity with
8943   // partially undef inputs.
8944   bool ViableForN[3] = {true, true, true};
8945
8946   for (int i = 0, e = Mask.size(); i < e; ++i) {
8947     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8948     // want.
8949     if (Mask[i] == -1)
8950       continue;
8951
8952     bool IsAnyViable = false;
8953     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8954       if (ViableForN[j]) {
8955         uint64_t N = j + 1;
8956
8957         // The shuffle mask must be equal to (i * 2^N) % M.
8958         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8959           IsAnyViable = true;
8960         else
8961           ViableForN[j] = false;
8962       }
8963     // Early exit if we exhaust the possible powers of two.
8964     if (!IsAnyViable)
8965       break;
8966   }
8967
8968   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8969     if (ViableForN[j])
8970       return j + 1;
8971
8972   // Return 0 as there is no viable power of two.
8973   return 0;
8974 }
8975
8976 /// \brief Generic lowering of v16i8 shuffles.
8977 ///
8978 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8979 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8980 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8981 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8982 /// back together.
8983 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8984                                        const X86Subtarget *Subtarget,
8985                                        SelectionDAG &DAG) {
8986   SDLoc DL(Op);
8987   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8988   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8989   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8990   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8991   ArrayRef<int> Mask = SVOp->getMask();
8992   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8993
8994   // Try to use shift instructions.
8995   if (SDValue Shift =
8996           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8997     return Shift;
8998
8999   // Try to use byte rotation instructions.
9000   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9001           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9002     return Rotate;
9003
9004   // Try to use a zext lowering.
9005   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9006           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9007     return ZExt;
9008
9009   // See if we can use SSE4A Extraction / Insertion.
9010   if (Subtarget->hasSSE4A())
9011     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9012       return V;
9013
9014   int NumV2Elements =
9015       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9016
9017   // For single-input shuffles, there are some nicer lowering tricks we can use.
9018   if (NumV2Elements == 0) {
9019     // Check for being able to broadcast a single element.
9020     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9021                                                           Mask, Subtarget, DAG))
9022       return Broadcast;
9023
9024     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9025     // Notably, this handles splat and partial-splat shuffles more efficiently.
9026     // However, it only makes sense if the pre-duplication shuffle simplifies
9027     // things significantly. Currently, this means we need to be able to
9028     // express the pre-duplication shuffle as an i16 shuffle.
9029     //
9030     // FIXME: We should check for other patterns which can be widened into an
9031     // i16 shuffle as well.
9032     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9033       for (int i = 0; i < 16; i += 2)
9034         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9035           return false;
9036
9037       return true;
9038     };
9039     auto tryToWidenViaDuplication = [&]() -> SDValue {
9040       if (!canWidenViaDuplication(Mask))
9041         return SDValue();
9042       SmallVector<int, 4> LoInputs;
9043       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9044                    [](int M) { return M >= 0 && M < 8; });
9045       std::sort(LoInputs.begin(), LoInputs.end());
9046       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9047                      LoInputs.end());
9048       SmallVector<int, 4> HiInputs;
9049       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9050                    [](int M) { return M >= 8; });
9051       std::sort(HiInputs.begin(), HiInputs.end());
9052       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9053                      HiInputs.end());
9054
9055       bool TargetLo = LoInputs.size() >= HiInputs.size();
9056       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9057       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9058
9059       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9060       SmallDenseMap<int, int, 8> LaneMap;
9061       for (int I : InPlaceInputs) {
9062         PreDupI16Shuffle[I/2] = I/2;
9063         LaneMap[I] = I;
9064       }
9065       int j = TargetLo ? 0 : 4, je = j + 4;
9066       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9067         // Check if j is already a shuffle of this input. This happens when
9068         // there are two adjacent bytes after we move the low one.
9069         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9070           // If we haven't yet mapped the input, search for a slot into which
9071           // we can map it.
9072           while (j < je && PreDupI16Shuffle[j] != -1)
9073             ++j;
9074
9075           if (j == je)
9076             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9077             return SDValue();
9078
9079           // Map this input with the i16 shuffle.
9080           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9081         }
9082
9083         // Update the lane map based on the mapping we ended up with.
9084         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9085       }
9086       V1 = DAG.getBitcast(
9087           MVT::v16i8,
9088           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9089                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9090
9091       // Unpack the bytes to form the i16s that will be shuffled into place.
9092       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9093                        MVT::v16i8, V1, V1);
9094
9095       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9096       for (int i = 0; i < 16; ++i)
9097         if (Mask[i] != -1) {
9098           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9099           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9100           if (PostDupI16Shuffle[i / 2] == -1)
9101             PostDupI16Shuffle[i / 2] = MappedMask;
9102           else
9103             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9104                    "Conflicting entrties in the original shuffle!");
9105         }
9106       return DAG.getBitcast(
9107           MVT::v16i8,
9108           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9109                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9110     };
9111     if (SDValue V = tryToWidenViaDuplication())
9112       return V;
9113   }
9114
9115   if (SDValue Masked =
9116           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9117     return Masked;
9118
9119   // Use dedicated unpack instructions for masks that match their pattern.
9120   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9121                                          0, 16, 1, 17, 2, 18, 3, 19,
9122                                          // High half.
9123                                          4, 20, 5, 21, 6, 22, 7, 23}))
9124     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9125   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9126                                          8, 24, 9, 25, 10, 26, 11, 27,
9127                                          // High half.
9128                                          12, 28, 13, 29, 14, 30, 15, 31}))
9129     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9130
9131   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9132   // with PSHUFB. It is important to do this before we attempt to generate any
9133   // blends but after all of the single-input lowerings. If the single input
9134   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9135   // want to preserve that and we can DAG combine any longer sequences into
9136   // a PSHUFB in the end. But once we start blending from multiple inputs,
9137   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9138   // and there are *very* few patterns that would actually be faster than the
9139   // PSHUFB approach because of its ability to zero lanes.
9140   //
9141   // FIXME: The only exceptions to the above are blends which are exact
9142   // interleavings with direct instructions supporting them. We currently don't
9143   // handle those well here.
9144   if (Subtarget->hasSSSE3()) {
9145     bool V1InUse = false;
9146     bool V2InUse = false;
9147
9148     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9149                                                 DAG, V1InUse, V2InUse);
9150
9151     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9152     // do so. This avoids using them to handle blends-with-zero which is
9153     // important as a single pshufb is significantly faster for that.
9154     if (V1InUse && V2InUse) {
9155       if (Subtarget->hasSSE41())
9156         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9157                                                       Mask, Subtarget, DAG))
9158           return Blend;
9159
9160       // We can use an unpack to do the blending rather than an or in some
9161       // cases. Even though the or may be (very minorly) more efficient, we
9162       // preference this lowering because there are common cases where part of
9163       // the complexity of the shuffles goes away when we do the final blend as
9164       // an unpack.
9165       // FIXME: It might be worth trying to detect if the unpack-feeding
9166       // shuffles will both be pshufb, in which case we shouldn't bother with
9167       // this.
9168       if (SDValue Unpack =
9169               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9170         return Unpack;
9171     }
9172
9173     return PSHUFB;
9174   }
9175
9176   // There are special ways we can lower some single-element blends.
9177   if (NumV2Elements == 1)
9178     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9179                                                          Mask, Subtarget, DAG))
9180       return V;
9181
9182   if (SDValue BitBlend =
9183           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9184     return BitBlend;
9185
9186   // Check whether a compaction lowering can be done. This handles shuffles
9187   // which take every Nth element for some even N. See the helper function for
9188   // details.
9189   //
9190   // We special case these as they can be particularly efficiently handled with
9191   // the PACKUSB instruction on x86 and they show up in common patterns of
9192   // rearranging bytes to truncate wide elements.
9193   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9194     // NumEvenDrops is the power of two stride of the elements. Another way of
9195     // thinking about it is that we need to drop the even elements this many
9196     // times to get the original input.
9197     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9198
9199     // First we need to zero all the dropped bytes.
9200     assert(NumEvenDrops <= 3 &&
9201            "No support for dropping even elements more than 3 times.");
9202     // We use the mask type to pick which bytes are preserved based on how many
9203     // elements are dropped.
9204     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9205     SDValue ByteClearMask = DAG.getBitcast(
9206         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9207     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9208     if (!IsSingleInput)
9209       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9210
9211     // Now pack things back together.
9212     V1 = DAG.getBitcast(MVT::v8i16, V1);
9213     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9214     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9215     for (int i = 1; i < NumEvenDrops; ++i) {
9216       Result = DAG.getBitcast(MVT::v8i16, Result);
9217       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9218     }
9219
9220     return Result;
9221   }
9222
9223   // Handle multi-input cases by blending single-input shuffles.
9224   if (NumV2Elements > 0)
9225     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9226                                                       Mask, DAG);
9227
9228   // The fallback path for single-input shuffles widens this into two v8i16
9229   // vectors with unpacks, shuffles those, and then pulls them back together
9230   // with a pack.
9231   SDValue V = V1;
9232
9233   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9234   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9235   for (int i = 0; i < 16; ++i)
9236     if (Mask[i] >= 0)
9237       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9238
9239   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9240
9241   SDValue VLoHalf, VHiHalf;
9242   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9243   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9244   // i16s.
9245   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9246                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9247       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9248                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9249     // Use a mask to drop the high bytes.
9250     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9251     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9252                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9253
9254     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9255     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9256
9257     // Squash the masks to point directly into VLoHalf.
9258     for (int &M : LoBlendMask)
9259       if (M >= 0)
9260         M /= 2;
9261     for (int &M : HiBlendMask)
9262       if (M >= 0)
9263         M /= 2;
9264   } else {
9265     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9266     // VHiHalf so that we can blend them as i16s.
9267     VLoHalf = DAG.getBitcast(
9268         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9269     VHiHalf = DAG.getBitcast(
9270         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9271   }
9272
9273   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9274   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9275
9276   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9277 }
9278
9279 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9280 ///
9281 /// This routine breaks down the specific type of 128-bit shuffle and
9282 /// dispatches to the lowering routines accordingly.
9283 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9284                                         MVT VT, const X86Subtarget *Subtarget,
9285                                         SelectionDAG &DAG) {
9286   switch (VT.SimpleTy) {
9287   case MVT::v2i64:
9288     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9289   case MVT::v2f64:
9290     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9291   case MVT::v4i32:
9292     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9293   case MVT::v4f32:
9294     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9295   case MVT::v8i16:
9296     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9297   case MVT::v16i8:
9298     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9299
9300   default:
9301     llvm_unreachable("Unimplemented!");
9302   }
9303 }
9304
9305 /// \brief Helper function to test whether a shuffle mask could be
9306 /// simplified by widening the elements being shuffled.
9307 ///
9308 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9309 /// leaves it in an unspecified state.
9310 ///
9311 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9312 /// shuffle masks. The latter have the special property of a '-2' representing
9313 /// a zero-ed lane of a vector.
9314 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9315                                     SmallVectorImpl<int> &WidenedMask) {
9316   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9317     // If both elements are undef, its trivial.
9318     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9319       WidenedMask.push_back(SM_SentinelUndef);
9320       continue;
9321     }
9322
9323     // Check for an undef mask and a mask value properly aligned to fit with
9324     // a pair of values. If we find such a case, use the non-undef mask's value.
9325     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9326       WidenedMask.push_back(Mask[i + 1] / 2);
9327       continue;
9328     }
9329     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9330       WidenedMask.push_back(Mask[i] / 2);
9331       continue;
9332     }
9333
9334     // When zeroing, we need to spread the zeroing across both lanes to widen.
9335     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9336       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9337           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9338         WidenedMask.push_back(SM_SentinelZero);
9339         continue;
9340       }
9341       return false;
9342     }
9343
9344     // Finally check if the two mask values are adjacent and aligned with
9345     // a pair.
9346     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9347       WidenedMask.push_back(Mask[i] / 2);
9348       continue;
9349     }
9350
9351     // Otherwise we can't safely widen the elements used in this shuffle.
9352     return false;
9353   }
9354   assert(WidenedMask.size() == Mask.size() / 2 &&
9355          "Incorrect size of mask after widening the elements!");
9356
9357   return true;
9358 }
9359
9360 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9361 ///
9362 /// This routine just extracts two subvectors, shuffles them independently, and
9363 /// then concatenates them back together. This should work effectively with all
9364 /// AVX vector shuffle types.
9365 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9366                                           SDValue V2, ArrayRef<int> Mask,
9367                                           SelectionDAG &DAG) {
9368   assert(VT.getSizeInBits() >= 256 &&
9369          "Only for 256-bit or wider vector shuffles!");
9370   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9371   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9372
9373   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9374   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9375
9376   int NumElements = VT.getVectorNumElements();
9377   int SplitNumElements = NumElements / 2;
9378   MVT ScalarVT = VT.getScalarType();
9379   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9380
9381   // Rather than splitting build-vectors, just build two narrower build
9382   // vectors. This helps shuffling with splats and zeros.
9383   auto SplitVector = [&](SDValue V) {
9384     while (V.getOpcode() == ISD::BITCAST)
9385       V = V->getOperand(0);
9386
9387     MVT OrigVT = V.getSimpleValueType();
9388     int OrigNumElements = OrigVT.getVectorNumElements();
9389     int OrigSplitNumElements = OrigNumElements / 2;
9390     MVT OrigScalarVT = OrigVT.getScalarType();
9391     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9392
9393     SDValue LoV, HiV;
9394
9395     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9396     if (!BV) {
9397       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9398                         DAG.getIntPtrConstant(0, DL));
9399       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9400                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9401     } else {
9402
9403       SmallVector<SDValue, 16> LoOps, HiOps;
9404       for (int i = 0; i < OrigSplitNumElements; ++i) {
9405         LoOps.push_back(BV->getOperand(i));
9406         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9407       }
9408       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9409       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9410     }
9411     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9412                           DAG.getBitcast(SplitVT, HiV));
9413   };
9414
9415   SDValue LoV1, HiV1, LoV2, HiV2;
9416   std::tie(LoV1, HiV1) = SplitVector(V1);
9417   std::tie(LoV2, HiV2) = SplitVector(V2);
9418
9419   // Now create two 4-way blends of these half-width vectors.
9420   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9421     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9422     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9423     for (int i = 0; i < SplitNumElements; ++i) {
9424       int M = HalfMask[i];
9425       if (M >= NumElements) {
9426         if (M >= NumElements + SplitNumElements)
9427           UseHiV2 = true;
9428         else
9429           UseLoV2 = true;
9430         V2BlendMask.push_back(M - NumElements);
9431         V1BlendMask.push_back(-1);
9432         BlendMask.push_back(SplitNumElements + i);
9433       } else if (M >= 0) {
9434         if (M >= SplitNumElements)
9435           UseHiV1 = true;
9436         else
9437           UseLoV1 = true;
9438         V2BlendMask.push_back(-1);
9439         V1BlendMask.push_back(M);
9440         BlendMask.push_back(i);
9441       } else {
9442         V2BlendMask.push_back(-1);
9443         V1BlendMask.push_back(-1);
9444         BlendMask.push_back(-1);
9445       }
9446     }
9447
9448     // Because the lowering happens after all combining takes place, we need to
9449     // manually combine these blend masks as much as possible so that we create
9450     // a minimal number of high-level vector shuffle nodes.
9451
9452     // First try just blending the halves of V1 or V2.
9453     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9454       return DAG.getUNDEF(SplitVT);
9455     if (!UseLoV2 && !UseHiV2)
9456       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9457     if (!UseLoV1 && !UseHiV1)
9458       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9459
9460     SDValue V1Blend, V2Blend;
9461     if (UseLoV1 && UseHiV1) {
9462       V1Blend =
9463         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9464     } else {
9465       // We only use half of V1 so map the usage down into the final blend mask.
9466       V1Blend = UseLoV1 ? LoV1 : HiV1;
9467       for (int i = 0; i < SplitNumElements; ++i)
9468         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9469           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9470     }
9471     if (UseLoV2 && UseHiV2) {
9472       V2Blend =
9473         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9474     } else {
9475       // We only use half of V2 so map the usage down into the final blend mask.
9476       V2Blend = UseLoV2 ? LoV2 : HiV2;
9477       for (int i = 0; i < SplitNumElements; ++i)
9478         if (BlendMask[i] >= SplitNumElements)
9479           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9480     }
9481     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9482   };
9483   SDValue Lo = HalfBlend(LoMask);
9484   SDValue Hi = HalfBlend(HiMask);
9485   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9486 }
9487
9488 /// \brief Either split a vector in halves or decompose the shuffles and the
9489 /// blend.
9490 ///
9491 /// This is provided as a good fallback for many lowerings of non-single-input
9492 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9493 /// between splitting the shuffle into 128-bit components and stitching those
9494 /// back together vs. extracting the single-input shuffles and blending those
9495 /// results.
9496 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9497                                                 SDValue V2, ArrayRef<int> Mask,
9498                                                 SelectionDAG &DAG) {
9499   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9500                                             "lower single-input shuffles as it "
9501                                             "could then recurse on itself.");
9502   int Size = Mask.size();
9503
9504   // If this can be modeled as a broadcast of two elements followed by a blend,
9505   // prefer that lowering. This is especially important because broadcasts can
9506   // often fold with memory operands.
9507   auto DoBothBroadcast = [&] {
9508     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9509     for (int M : Mask)
9510       if (M >= Size) {
9511         if (V2BroadcastIdx == -1)
9512           V2BroadcastIdx = M - Size;
9513         else if (M - Size != V2BroadcastIdx)
9514           return false;
9515       } else if (M >= 0) {
9516         if (V1BroadcastIdx == -1)
9517           V1BroadcastIdx = M;
9518         else if (M != V1BroadcastIdx)
9519           return false;
9520       }
9521     return true;
9522   };
9523   if (DoBothBroadcast())
9524     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9525                                                       DAG);
9526
9527   // If the inputs all stem from a single 128-bit lane of each input, then we
9528   // split them rather than blending because the split will decompose to
9529   // unusually few instructions.
9530   int LaneCount = VT.getSizeInBits() / 128;
9531   int LaneSize = Size / LaneCount;
9532   SmallBitVector LaneInputs[2];
9533   LaneInputs[0].resize(LaneCount, false);
9534   LaneInputs[1].resize(LaneCount, false);
9535   for (int i = 0; i < Size; ++i)
9536     if (Mask[i] >= 0)
9537       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9538   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9539     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9540
9541   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9542   // that the decomposed single-input shuffles don't end up here.
9543   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9544 }
9545
9546 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9547 /// a permutation and blend of those lanes.
9548 ///
9549 /// This essentially blends the out-of-lane inputs to each lane into the lane
9550 /// from a permuted copy of the vector. This lowering strategy results in four
9551 /// instructions in the worst case for a single-input cross lane shuffle which
9552 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9553 /// of. Special cases for each particular shuffle pattern should be handled
9554 /// prior to trying this lowering.
9555 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9556                                                        SDValue V1, SDValue V2,
9557                                                        ArrayRef<int> Mask,
9558                                                        SelectionDAG &DAG) {
9559   // FIXME: This should probably be generalized for 512-bit vectors as well.
9560   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9561   int LaneSize = Mask.size() / 2;
9562
9563   // If there are only inputs from one 128-bit lane, splitting will in fact be
9564   // less expensive. The flags track whether the given lane contains an element
9565   // that crosses to another lane.
9566   bool LaneCrossing[2] = {false, false};
9567   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9568     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9569       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9570   if (!LaneCrossing[0] || !LaneCrossing[1])
9571     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9572
9573   if (isSingleInputShuffleMask(Mask)) {
9574     SmallVector<int, 32> FlippedBlendMask;
9575     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9576       FlippedBlendMask.push_back(
9577           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9578                                   ? Mask[i]
9579                                   : Mask[i] % LaneSize +
9580                                         (i / LaneSize) * LaneSize + Size));
9581
9582     // Flip the vector, and blend the results which should now be in-lane. The
9583     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9584     // 5 for the high source. The value 3 selects the high half of source 2 and
9585     // the value 2 selects the low half of source 2. We only use source 2 to
9586     // allow folding it into a memory operand.
9587     unsigned PERMMask = 3 | 2 << 4;
9588     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9589                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9590     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9591   }
9592
9593   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9594   // will be handled by the above logic and a blend of the results, much like
9595   // other patterns in AVX.
9596   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9597 }
9598
9599 /// \brief Handle lowering 2-lane 128-bit shuffles.
9600 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9601                                         SDValue V2, ArrayRef<int> Mask,
9602                                         const X86Subtarget *Subtarget,
9603                                         SelectionDAG &DAG) {
9604   // TODO: If minimizing size and one of the inputs is a zero vector and the
9605   // the zero vector has only one use, we could use a VPERM2X128 to save the
9606   // instruction bytes needed to explicitly generate the zero vector.
9607
9608   // Blends are faster and handle all the non-lane-crossing cases.
9609   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9610                                                 Subtarget, DAG))
9611     return Blend;
9612
9613   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9614   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9615
9616   // If either input operand is a zero vector, use VPERM2X128 because its mask
9617   // allows us to replace the zero input with an implicit zero.
9618   if (!IsV1Zero && !IsV2Zero) {
9619     // Check for patterns which can be matched with a single insert of a 128-bit
9620     // subvector.
9621     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9622     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9623       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9624                                    VT.getVectorNumElements() / 2);
9625       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9626                                 DAG.getIntPtrConstant(0, DL));
9627       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9628                                 OnlyUsesV1 ? V1 : V2,
9629                                 DAG.getIntPtrConstant(0, DL));
9630       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9631     }
9632   }
9633
9634   // Otherwise form a 128-bit permutation. After accounting for undefs,
9635   // convert the 64-bit shuffle mask selection values into 128-bit
9636   // selection bits by dividing the indexes by 2 and shifting into positions
9637   // defined by a vperm2*128 instruction's immediate control byte.
9638
9639   // The immediate permute control byte looks like this:
9640   //    [1:0] - select 128 bits from sources for low half of destination
9641   //    [2]   - ignore
9642   //    [3]   - zero low half of destination
9643   //    [5:4] - select 128 bits from sources for high half of destination
9644   //    [6]   - ignore
9645   //    [7]   - zero high half of destination
9646
9647   int MaskLO = Mask[0];
9648   if (MaskLO == SM_SentinelUndef)
9649     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9650
9651   int MaskHI = Mask[2];
9652   if (MaskHI == SM_SentinelUndef)
9653     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9654
9655   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9656
9657   // If either input is a zero vector, replace it with an undef input.
9658   // Shuffle mask values <  4 are selecting elements of V1.
9659   // Shuffle mask values >= 4 are selecting elements of V2.
9660   // Adjust each half of the permute mask by clearing the half that was
9661   // selecting the zero vector and setting the zero mask bit.
9662   if (IsV1Zero) {
9663     V1 = DAG.getUNDEF(VT);
9664     if (MaskLO < 4)
9665       PermMask = (PermMask & 0xf0) | 0x08;
9666     if (MaskHI < 4)
9667       PermMask = (PermMask & 0x0f) | 0x80;
9668   }
9669   if (IsV2Zero) {
9670     V2 = DAG.getUNDEF(VT);
9671     if (MaskLO >= 4)
9672       PermMask = (PermMask & 0xf0) | 0x08;
9673     if (MaskHI >= 4)
9674       PermMask = (PermMask & 0x0f) | 0x80;
9675   }
9676
9677   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9678                      DAG.getConstant(PermMask, DL, MVT::i8));
9679 }
9680
9681 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9682 /// shuffling each lane.
9683 ///
9684 /// This will only succeed when the result of fixing the 128-bit lanes results
9685 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9686 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9687 /// the lane crosses early and then use simpler shuffles within each lane.
9688 ///
9689 /// FIXME: It might be worthwhile at some point to support this without
9690 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9691 /// in x86 only floating point has interesting non-repeating shuffles, and even
9692 /// those are still *marginally* more expensive.
9693 static SDValue lowerVectorShuffleByMerging128BitLanes(
9694     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9695     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9696   assert(!isSingleInputShuffleMask(Mask) &&
9697          "This is only useful with multiple inputs.");
9698
9699   int Size = Mask.size();
9700   int LaneSize = 128 / VT.getScalarSizeInBits();
9701   int NumLanes = Size / LaneSize;
9702   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9703
9704   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9705   // check whether the in-128-bit lane shuffles share a repeating pattern.
9706   SmallVector<int, 4> Lanes;
9707   Lanes.resize(NumLanes, -1);
9708   SmallVector<int, 4> InLaneMask;
9709   InLaneMask.resize(LaneSize, -1);
9710   for (int i = 0; i < Size; ++i) {
9711     if (Mask[i] < 0)
9712       continue;
9713
9714     int j = i / LaneSize;
9715
9716     if (Lanes[j] < 0) {
9717       // First entry we've seen for this lane.
9718       Lanes[j] = Mask[i] / LaneSize;
9719     } else if (Lanes[j] != Mask[i] / LaneSize) {
9720       // This doesn't match the lane selected previously!
9721       return SDValue();
9722     }
9723
9724     // Check that within each lane we have a consistent shuffle mask.
9725     int k = i % LaneSize;
9726     if (InLaneMask[k] < 0) {
9727       InLaneMask[k] = Mask[i] % LaneSize;
9728     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9729       // This doesn't fit a repeating in-lane mask.
9730       return SDValue();
9731     }
9732   }
9733
9734   // First shuffle the lanes into place.
9735   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9736                                 VT.getSizeInBits() / 64);
9737   SmallVector<int, 8> LaneMask;
9738   LaneMask.resize(NumLanes * 2, -1);
9739   for (int i = 0; i < NumLanes; ++i)
9740     if (Lanes[i] >= 0) {
9741       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9742       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9743     }
9744
9745   V1 = DAG.getBitcast(LaneVT, V1);
9746   V2 = DAG.getBitcast(LaneVT, V2);
9747   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9748
9749   // Cast it back to the type we actually want.
9750   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9751
9752   // Now do a simple shuffle that isn't lane crossing.
9753   SmallVector<int, 8> NewMask;
9754   NewMask.resize(Size, -1);
9755   for (int i = 0; i < Size; ++i)
9756     if (Mask[i] >= 0)
9757       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9758   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9759          "Must not introduce lane crosses at this point!");
9760
9761   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9762 }
9763
9764 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9765 /// given mask.
9766 ///
9767 /// This returns true if the elements from a particular input are already in the
9768 /// slot required by the given mask and require no permutation.
9769 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9770   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9771   int Size = Mask.size();
9772   for (int i = 0; i < Size; ++i)
9773     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9774       return false;
9775
9776   return true;
9777 }
9778
9779 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9780                                             ArrayRef<int> Mask, SDValue V1,
9781                                             SDValue V2, SelectionDAG &DAG) {
9782
9783   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9784   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9785   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9786   int NumElts = VT.getVectorNumElements();
9787   bool ShufpdMask = true;
9788   bool CommutableMask = true;
9789   unsigned Immediate = 0;
9790   for (int i = 0; i < NumElts; ++i) {
9791     if (Mask[i] < 0)
9792       continue;
9793     int Val = (i & 6) + NumElts * (i & 1);
9794     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9795     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9796       ShufpdMask = false;
9797     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9798       CommutableMask = false;
9799     Immediate |= (Mask[i] % 2) << i;
9800   }
9801   if (ShufpdMask)
9802     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9803                        DAG.getConstant(Immediate, DL, MVT::i8));
9804   if (CommutableMask)
9805     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9806                        DAG.getConstant(Immediate, DL, MVT::i8));
9807   return SDValue();
9808 }
9809
9810 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9811 ///
9812 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9813 /// isn't available.
9814 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9815                                        const X86Subtarget *Subtarget,
9816                                        SelectionDAG &DAG) {
9817   SDLoc DL(Op);
9818   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9819   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9820   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9821   ArrayRef<int> Mask = SVOp->getMask();
9822   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9823
9824   SmallVector<int, 4> WidenedMask;
9825   if (canWidenShuffleElements(Mask, WidenedMask))
9826     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9827                                     DAG);
9828
9829   if (isSingleInputShuffleMask(Mask)) {
9830     // Check for being able to broadcast a single element.
9831     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9832                                                           Mask, Subtarget, DAG))
9833       return Broadcast;
9834
9835     // Use low duplicate instructions for masks that match their pattern.
9836     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9837       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9838
9839     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9840       // Non-half-crossing single input shuffles can be lowerid with an
9841       // interleaved permutation.
9842       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9843                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9844       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9845                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9846     }
9847
9848     // With AVX2 we have direct support for this permutation.
9849     if (Subtarget->hasAVX2())
9850       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9851                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9852
9853     // Otherwise, fall back.
9854     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9855                                                    DAG);
9856   }
9857
9858   // X86 has dedicated unpack instructions that can handle specific blend
9859   // operations: UNPCKH and UNPCKL.
9860   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9861     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9862   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9863     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9864   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9865     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9866   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9867     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9868
9869   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9870                                                 Subtarget, DAG))
9871     return Blend;
9872
9873   // Check if the blend happens to exactly fit that of SHUFPD.
9874   if (SDValue Op =
9875       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9876     return Op;
9877
9878   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9879   // shuffle. However, if we have AVX2 and either inputs are already in place,
9880   // we will be able to shuffle even across lanes the other input in a single
9881   // instruction so skip this pattern.
9882   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9883                                  isShuffleMaskInputInPlace(1, Mask))))
9884     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9885             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9886       return Result;
9887
9888   // If we have AVX2 then we always want to lower with a blend because an v4 we
9889   // can fully permute the elements.
9890   if (Subtarget->hasAVX2())
9891     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9892                                                       Mask, DAG);
9893
9894   // Otherwise fall back on generic lowering.
9895   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9896 }
9897
9898 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9899 ///
9900 /// This routine is only called when we have AVX2 and thus a reasonable
9901 /// instruction set for v4i64 shuffling..
9902 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9903                                        const X86Subtarget *Subtarget,
9904                                        SelectionDAG &DAG) {
9905   SDLoc DL(Op);
9906   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9907   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9908   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9909   ArrayRef<int> Mask = SVOp->getMask();
9910   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9911   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9912
9913   SmallVector<int, 4> WidenedMask;
9914   if (canWidenShuffleElements(Mask, WidenedMask))
9915     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9916                                     DAG);
9917
9918   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9919                                                 Subtarget, DAG))
9920     return Blend;
9921
9922   // Check for being able to broadcast a single element.
9923   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9924                                                         Mask, Subtarget, DAG))
9925     return Broadcast;
9926
9927   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9928   // use lower latency instructions that will operate on both 128-bit lanes.
9929   SmallVector<int, 2> RepeatedMask;
9930   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9931     if (isSingleInputShuffleMask(Mask)) {
9932       int PSHUFDMask[] = {-1, -1, -1, -1};
9933       for (int i = 0; i < 2; ++i)
9934         if (RepeatedMask[i] >= 0) {
9935           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9936           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9937         }
9938       return DAG.getBitcast(
9939           MVT::v4i64,
9940           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9941                       DAG.getBitcast(MVT::v8i32, V1),
9942                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9943     }
9944   }
9945
9946   // AVX2 provides a direct instruction for permuting a single input across
9947   // lanes.
9948   if (isSingleInputShuffleMask(Mask))
9949     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9950                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9951
9952   // Try to use shift instructions.
9953   if (SDValue Shift =
9954           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9955     return Shift;
9956
9957   // Use dedicated unpack instructions for masks that match their pattern.
9958   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9959     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9960   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9961     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9962   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9963     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9964   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9965     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9966
9967   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9968   // shuffle. However, if we have AVX2 and either inputs are already in place,
9969   // we will be able to shuffle even across lanes the other input in a single
9970   // instruction so skip this pattern.
9971   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9972                                  isShuffleMaskInputInPlace(1, Mask))))
9973     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9974             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9975       return Result;
9976
9977   // Otherwise fall back on generic blend lowering.
9978   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9979                                                     Mask, DAG);
9980 }
9981
9982 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9983 ///
9984 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9985 /// isn't available.
9986 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9987                                        const X86Subtarget *Subtarget,
9988                                        SelectionDAG &DAG) {
9989   SDLoc DL(Op);
9990   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9991   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9992   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9993   ArrayRef<int> Mask = SVOp->getMask();
9994   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9995
9996   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9997                                                 Subtarget, DAG))
9998     return Blend;
9999
10000   // Check for being able to broadcast a single element.
10001   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10002                                                         Mask, Subtarget, DAG))
10003     return Broadcast;
10004
10005   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10006   // options to efficiently lower the shuffle.
10007   SmallVector<int, 4> RepeatedMask;
10008   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10009     assert(RepeatedMask.size() == 4 &&
10010            "Repeated masks must be half the mask width!");
10011
10012     // Use even/odd duplicate instructions for masks that match their pattern.
10013     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10014       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10015     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10016       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10017
10018     if (isSingleInputShuffleMask(Mask))
10019       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10020                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10021
10022     // Use dedicated unpack instructions for masks that match their pattern.
10023     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10024       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10025     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10026       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10027     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10028       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10029     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10030       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10031
10032     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10033     // have already handled any direct blends. We also need to squash the
10034     // repeated mask into a simulated v4f32 mask.
10035     for (int i = 0; i < 4; ++i)
10036       if (RepeatedMask[i] >= 8)
10037         RepeatedMask[i] -= 4;
10038     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10039   }
10040
10041   // If we have a single input shuffle with different shuffle patterns in the
10042   // two 128-bit lanes use the variable mask to VPERMILPS.
10043   if (isSingleInputShuffleMask(Mask)) {
10044     SDValue VPermMask[8];
10045     for (int i = 0; i < 8; ++i)
10046       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10047                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10048     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10049       return DAG.getNode(
10050           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10051           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10052
10053     if (Subtarget->hasAVX2())
10054       return DAG.getNode(
10055           X86ISD::VPERMV, DL, MVT::v8f32,
10056           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10057                                                  MVT::v8i32, VPermMask)),
10058           V1);
10059
10060     // Otherwise, fall back.
10061     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10062                                                    DAG);
10063   }
10064
10065   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10066   // shuffle.
10067   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10068           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10069     return Result;
10070
10071   // If we have AVX2 then we always want to lower with a blend because at v8 we
10072   // can fully permute the elements.
10073   if (Subtarget->hasAVX2())
10074     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10075                                                       Mask, DAG);
10076
10077   // Otherwise fall back on generic lowering.
10078   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10079 }
10080
10081 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10082 ///
10083 /// This routine is only called when we have AVX2 and thus a reasonable
10084 /// instruction set for v8i32 shuffling..
10085 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10086                                        const X86Subtarget *Subtarget,
10087                                        SelectionDAG &DAG) {
10088   SDLoc DL(Op);
10089   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10090   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10091   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10092   ArrayRef<int> Mask = SVOp->getMask();
10093   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10094   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10095
10096   // Whenever we can lower this as a zext, that instruction is strictly faster
10097   // than any alternative. It also allows us to fold memory operands into the
10098   // shuffle in many cases.
10099   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10100                                                          Mask, Subtarget, DAG))
10101     return ZExt;
10102
10103   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10104                                                 Subtarget, DAG))
10105     return Blend;
10106
10107   // Check for being able to broadcast a single element.
10108   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10109                                                         Mask, Subtarget, DAG))
10110     return Broadcast;
10111
10112   // If the shuffle mask is repeated in each 128-bit lane we can use more
10113   // efficient instructions that mirror the shuffles across the two 128-bit
10114   // lanes.
10115   SmallVector<int, 4> RepeatedMask;
10116   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10117     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10118     if (isSingleInputShuffleMask(Mask))
10119       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10120                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10121
10122     // Use dedicated unpack instructions for masks that match their pattern.
10123     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10124       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10125     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10126       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10127     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10128       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10129     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10130       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10131   }
10132
10133   // Try to use shift instructions.
10134   if (SDValue Shift =
10135           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10136     return Shift;
10137
10138   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10139           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10140     return Rotate;
10141
10142   // If the shuffle patterns aren't repeated but it is a single input, directly
10143   // generate a cross-lane VPERMD instruction.
10144   if (isSingleInputShuffleMask(Mask)) {
10145     SDValue VPermMask[8];
10146     for (int i = 0; i < 8; ++i)
10147       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10148                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10149     return DAG.getNode(
10150         X86ISD::VPERMV, DL, MVT::v8i32,
10151         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10152   }
10153
10154   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10155   // shuffle.
10156   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10157           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10158     return Result;
10159
10160   // Otherwise fall back on generic blend lowering.
10161   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10162                                                     Mask, DAG);
10163 }
10164
10165 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10166 ///
10167 /// This routine is only called when we have AVX2 and thus a reasonable
10168 /// instruction set for v16i16 shuffling..
10169 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10170                                         const X86Subtarget *Subtarget,
10171                                         SelectionDAG &DAG) {
10172   SDLoc DL(Op);
10173   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10174   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10176   ArrayRef<int> Mask = SVOp->getMask();
10177   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10178   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10179
10180   // Whenever we can lower this as a zext, that instruction is strictly faster
10181   // than any alternative. It also allows us to fold memory operands into the
10182   // shuffle in many cases.
10183   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10184                                                          Mask, Subtarget, DAG))
10185     return ZExt;
10186
10187   // Check for being able to broadcast a single element.
10188   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10189                                                         Mask, Subtarget, DAG))
10190     return Broadcast;
10191
10192   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10193                                                 Subtarget, DAG))
10194     return Blend;
10195
10196   // Use dedicated unpack instructions for masks that match their pattern.
10197   if (isShuffleEquivalent(V1, V2, Mask,
10198                           {// First 128-bit lane:
10199                            0, 16, 1, 17, 2, 18, 3, 19,
10200                            // Second 128-bit lane:
10201                            8, 24, 9, 25, 10, 26, 11, 27}))
10202     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10203   if (isShuffleEquivalent(V1, V2, Mask,
10204                           {// First 128-bit lane:
10205                            4, 20, 5, 21, 6, 22, 7, 23,
10206                            // Second 128-bit lane:
10207                            12, 28, 13, 29, 14, 30, 15, 31}))
10208     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10209
10210   // Try to use shift instructions.
10211   if (SDValue Shift =
10212           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10213     return Shift;
10214
10215   // Try to use byte rotation instructions.
10216   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10217           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10218     return Rotate;
10219
10220   if (isSingleInputShuffleMask(Mask)) {
10221     // There are no generalized cross-lane shuffle operations available on i16
10222     // element types.
10223     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10224       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10225                                                      Mask, DAG);
10226
10227     SmallVector<int, 8> RepeatedMask;
10228     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10229       // As this is a single-input shuffle, the repeated mask should be
10230       // a strictly valid v8i16 mask that we can pass through to the v8i16
10231       // lowering to handle even the v16 case.
10232       return lowerV8I16GeneralSingleInputVectorShuffle(
10233           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10234     }
10235
10236     SDValue PSHUFBMask[32];
10237     for (int i = 0; i < 16; ++i) {
10238       if (Mask[i] == -1) {
10239         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10240         continue;
10241       }
10242
10243       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10244       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10245       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10246       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10247     }
10248     return DAG.getBitcast(MVT::v16i16,
10249                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10250                                       DAG.getBitcast(MVT::v32i8, V1),
10251                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10252                                                   MVT::v32i8, PSHUFBMask)));
10253   }
10254
10255   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10256   // shuffle.
10257   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10258           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10259     return Result;
10260
10261   // Otherwise fall back on generic lowering.
10262   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10263 }
10264
10265 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10266 ///
10267 /// This routine is only called when we have AVX2 and thus a reasonable
10268 /// instruction set for v32i8 shuffling..
10269 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10270                                        const X86Subtarget *Subtarget,
10271                                        SelectionDAG &DAG) {
10272   SDLoc DL(Op);
10273   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10274   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10275   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10276   ArrayRef<int> Mask = SVOp->getMask();
10277   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10278   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10279
10280   // Whenever we can lower this as a zext, that instruction is strictly faster
10281   // than any alternative. It also allows us to fold memory operands into the
10282   // shuffle in many cases.
10283   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10284                                                          Mask, Subtarget, DAG))
10285     return ZExt;
10286
10287   // Check for being able to broadcast a single element.
10288   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10289                                                         Mask, Subtarget, DAG))
10290     return Broadcast;
10291
10292   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10293                                                 Subtarget, DAG))
10294     return Blend;
10295
10296   // Use dedicated unpack instructions for masks that match their pattern.
10297   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10298   // 256-bit lanes.
10299   if (isShuffleEquivalent(
10300           V1, V2, Mask,
10301           {// First 128-bit lane:
10302            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10303            // Second 128-bit lane:
10304            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10305     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10306   if (isShuffleEquivalent(
10307           V1, V2, Mask,
10308           {// First 128-bit lane:
10309            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10310            // Second 128-bit lane:
10311            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10312     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10313
10314   // Try to use shift instructions.
10315   if (SDValue Shift =
10316           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10317     return Shift;
10318
10319   // Try to use byte rotation instructions.
10320   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10321           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10322     return Rotate;
10323
10324   if (isSingleInputShuffleMask(Mask)) {
10325     // There are no generalized cross-lane shuffle operations available on i8
10326     // element types.
10327     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10328       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10329                                                      Mask, DAG);
10330
10331     SDValue PSHUFBMask[32];
10332     for (int i = 0; i < 32; ++i)
10333       PSHUFBMask[i] =
10334           Mask[i] < 0
10335               ? DAG.getUNDEF(MVT::i8)
10336               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10337                                 MVT::i8);
10338
10339     return DAG.getNode(
10340         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10341         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10342   }
10343
10344   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10345   // shuffle.
10346   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10347           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10348     return Result;
10349
10350   // Otherwise fall back on generic lowering.
10351   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10352 }
10353
10354 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10355 ///
10356 /// This routine either breaks down the specific type of a 256-bit x86 vector
10357 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10358 /// together based on the available instructions.
10359 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10360                                         MVT VT, const X86Subtarget *Subtarget,
10361                                         SelectionDAG &DAG) {
10362   SDLoc DL(Op);
10363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10364   ArrayRef<int> Mask = SVOp->getMask();
10365
10366   // If we have a single input to the zero element, insert that into V1 if we
10367   // can do so cheaply.
10368   int NumElts = VT.getVectorNumElements();
10369   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10370     return M >= NumElts;
10371   });
10372
10373   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10374     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10375                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10376       return Insertion;
10377
10378   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10379   // check for those subtargets here and avoid much of the subtarget querying in
10380   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10381   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10382   // floating point types there eventually, just immediately cast everything to
10383   // a float and operate entirely in that domain.
10384   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10385     int ElementBits = VT.getScalarSizeInBits();
10386     if (ElementBits < 32)
10387       // No floating point type available, decompose into 128-bit vectors.
10388       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10389
10390     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10391                                 VT.getVectorNumElements());
10392     V1 = DAG.getBitcast(FpVT, V1);
10393     V2 = DAG.getBitcast(FpVT, V2);
10394     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10395   }
10396
10397   switch (VT.SimpleTy) {
10398   case MVT::v4f64:
10399     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10400   case MVT::v4i64:
10401     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10402   case MVT::v8f32:
10403     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10404   case MVT::v8i32:
10405     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10406   case MVT::v16i16:
10407     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10408   case MVT::v32i8:
10409     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10410
10411   default:
10412     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10413   }
10414 }
10415
10416 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10417 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10418                                        const X86Subtarget *Subtarget,
10419                                        SelectionDAG &DAG) {
10420   SDLoc DL(Op);
10421   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10422   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10424   ArrayRef<int> Mask = SVOp->getMask();
10425   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10426
10427   // X86 has dedicated unpack instructions that can handle specific blend
10428   // operations: UNPCKH and UNPCKL.
10429   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10430     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10431   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10432     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10433
10434   // FIXME: Implement direct support for this type!
10435   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10436 }
10437
10438 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10439 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10440                                        const X86Subtarget *Subtarget,
10441                                        SelectionDAG &DAG) {
10442   SDLoc DL(Op);
10443   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10444   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10445   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10446   ArrayRef<int> Mask = SVOp->getMask();
10447   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10448
10449   // Use dedicated unpack instructions for masks that match their pattern.
10450   if (isShuffleEquivalent(V1, V2, Mask,
10451                           {// First 128-bit lane.
10452                            0, 16, 1, 17, 4, 20, 5, 21,
10453                            // Second 128-bit lane.
10454                            8, 24, 9, 25, 12, 28, 13, 29}))
10455     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10456   if (isShuffleEquivalent(V1, V2, Mask,
10457                           {// First 128-bit lane.
10458                            2, 18, 3, 19, 6, 22, 7, 23,
10459                            // Second 128-bit lane.
10460                            10, 26, 11, 27, 14, 30, 15, 31}))
10461     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10462
10463   // FIXME: Implement direct support for this type!
10464   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10465 }
10466
10467 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10468 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10469                                        const X86Subtarget *Subtarget,
10470                                        SelectionDAG &DAG) {
10471   SDLoc DL(Op);
10472   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10473   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10475   ArrayRef<int> Mask = SVOp->getMask();
10476   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10477
10478   // X86 has dedicated unpack instructions that can handle specific blend
10479   // operations: UNPCKH and UNPCKL.
10480   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10481     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10482   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10483     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10484
10485   // FIXME: Implement direct support for this type!
10486   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10487 }
10488
10489 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10490 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10491                                        const X86Subtarget *Subtarget,
10492                                        SelectionDAG &DAG) {
10493   SDLoc DL(Op);
10494   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10495   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10497   ArrayRef<int> Mask = SVOp->getMask();
10498   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10499
10500   // Use dedicated unpack instructions for masks that match their pattern.
10501   if (isShuffleEquivalent(V1, V2, Mask,
10502                           {// First 128-bit lane.
10503                            0, 16, 1, 17, 4, 20, 5, 21,
10504                            // Second 128-bit lane.
10505                            8, 24, 9, 25, 12, 28, 13, 29}))
10506     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10507   if (isShuffleEquivalent(V1, V2, Mask,
10508                           {// First 128-bit lane.
10509                            2, 18, 3, 19, 6, 22, 7, 23,
10510                            // Second 128-bit lane.
10511                            10, 26, 11, 27, 14, 30, 15, 31}))
10512     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10513
10514   // FIXME: Implement direct support for this type!
10515   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10516 }
10517
10518 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10519 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10520                                         const X86Subtarget *Subtarget,
10521                                         SelectionDAG &DAG) {
10522   SDLoc DL(Op);
10523   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10524   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10526   ArrayRef<int> Mask = SVOp->getMask();
10527   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10528   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10529
10530   // FIXME: Implement direct support for this type!
10531   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10532 }
10533
10534 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10535 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10536                                        const X86Subtarget *Subtarget,
10537                                        SelectionDAG &DAG) {
10538   SDLoc DL(Op);
10539   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10540   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10541   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10542   ArrayRef<int> Mask = SVOp->getMask();
10543   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10544   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10545
10546   // FIXME: Implement direct support for this type!
10547   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10548 }
10549
10550 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10551 ///
10552 /// This routine either breaks down the specific type of a 512-bit x86 vector
10553 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10554 /// together based on the available instructions.
10555 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10556                                         MVT VT, const X86Subtarget *Subtarget,
10557                                         SelectionDAG &DAG) {
10558   SDLoc DL(Op);
10559   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10560   ArrayRef<int> Mask = SVOp->getMask();
10561   assert(Subtarget->hasAVX512() &&
10562          "Cannot lower 512-bit vectors w/ basic ISA!");
10563
10564   // Check for being able to broadcast a single element.
10565   if (SDValue Broadcast =
10566           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10567     return Broadcast;
10568
10569   // Dispatch to each element type for lowering. If we don't have supprot for
10570   // specific element type shuffles at 512 bits, immediately split them and
10571   // lower them. Each lowering routine of a given type is allowed to assume that
10572   // the requisite ISA extensions for that element type are available.
10573   switch (VT.SimpleTy) {
10574   case MVT::v8f64:
10575     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10576   case MVT::v16f32:
10577     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10578   case MVT::v8i64:
10579     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10580   case MVT::v16i32:
10581     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10582   case MVT::v32i16:
10583     if (Subtarget->hasBWI())
10584       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10585     break;
10586   case MVT::v64i8:
10587     if (Subtarget->hasBWI())
10588       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10589     break;
10590
10591   default:
10592     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10593   }
10594
10595   // Otherwise fall back on splitting.
10596   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10597 }
10598
10599 /// \brief Top-level lowering for x86 vector shuffles.
10600 ///
10601 /// This handles decomposition, canonicalization, and lowering of all x86
10602 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10603 /// above in helper routines. The canonicalization attempts to widen shuffles
10604 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10605 /// s.t. only one of the two inputs needs to be tested, etc.
10606 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10607                                   SelectionDAG &DAG) {
10608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10609   ArrayRef<int> Mask = SVOp->getMask();
10610   SDValue V1 = Op.getOperand(0);
10611   SDValue V2 = Op.getOperand(1);
10612   MVT VT = Op.getSimpleValueType();
10613   int NumElements = VT.getVectorNumElements();
10614   SDLoc dl(Op);
10615
10616   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10617
10618   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10619   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10620   if (V1IsUndef && V2IsUndef)
10621     return DAG.getUNDEF(VT);
10622
10623   // When we create a shuffle node we put the UNDEF node to second operand,
10624   // but in some cases the first operand may be transformed to UNDEF.
10625   // In this case we should just commute the node.
10626   if (V1IsUndef)
10627     return DAG.getCommutedVectorShuffle(*SVOp);
10628
10629   // Check for non-undef masks pointing at an undef vector and make the masks
10630   // undef as well. This makes it easier to match the shuffle based solely on
10631   // the mask.
10632   if (V2IsUndef)
10633     for (int M : Mask)
10634       if (M >= NumElements) {
10635         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10636         for (int &M : NewMask)
10637           if (M >= NumElements)
10638             M = -1;
10639         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10640       }
10641
10642   // We actually see shuffles that are entirely re-arrangements of a set of
10643   // zero inputs. This mostly happens while decomposing complex shuffles into
10644   // simple ones. Directly lower these as a buildvector of zeros.
10645   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10646   if (Zeroable.all())
10647     return getZeroVector(VT, Subtarget, DAG, dl);
10648
10649   // Try to collapse shuffles into using a vector type with fewer elements but
10650   // wider element types. We cap this to not form integers or floating point
10651   // elements wider than 64 bits, but it might be interesting to form i128
10652   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10653   SmallVector<int, 16> WidenedMask;
10654   if (VT.getScalarSizeInBits() < 64 &&
10655       canWidenShuffleElements(Mask, WidenedMask)) {
10656     MVT NewEltVT = VT.isFloatingPoint()
10657                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10658                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10659     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10660     // Make sure that the new vector type is legal. For example, v2f64 isn't
10661     // legal on SSE1.
10662     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10663       V1 = DAG.getBitcast(NewVT, V1);
10664       V2 = DAG.getBitcast(NewVT, V2);
10665       return DAG.getBitcast(
10666           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10667     }
10668   }
10669
10670   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10671   for (int M : SVOp->getMask())
10672     if (M < 0)
10673       ++NumUndefElements;
10674     else if (M < NumElements)
10675       ++NumV1Elements;
10676     else
10677       ++NumV2Elements;
10678
10679   // Commute the shuffle as needed such that more elements come from V1 than
10680   // V2. This allows us to match the shuffle pattern strictly on how many
10681   // elements come from V1 without handling the symmetric cases.
10682   if (NumV2Elements > NumV1Elements)
10683     return DAG.getCommutedVectorShuffle(*SVOp);
10684
10685   // When the number of V1 and V2 elements are the same, try to minimize the
10686   // number of uses of V2 in the low half of the vector. When that is tied,
10687   // ensure that the sum of indices for V1 is equal to or lower than the sum
10688   // indices for V2. When those are equal, try to ensure that the number of odd
10689   // indices for V1 is lower than the number of odd indices for V2.
10690   if (NumV1Elements == NumV2Elements) {
10691     int LowV1Elements = 0, LowV2Elements = 0;
10692     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10693       if (M >= NumElements)
10694         ++LowV2Elements;
10695       else if (M >= 0)
10696         ++LowV1Elements;
10697     if (LowV2Elements > LowV1Elements) {
10698       return DAG.getCommutedVectorShuffle(*SVOp);
10699     } else if (LowV2Elements == LowV1Elements) {
10700       int SumV1Indices = 0, SumV2Indices = 0;
10701       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10702         if (SVOp->getMask()[i] >= NumElements)
10703           SumV2Indices += i;
10704         else if (SVOp->getMask()[i] >= 0)
10705           SumV1Indices += i;
10706       if (SumV2Indices < SumV1Indices) {
10707         return DAG.getCommutedVectorShuffle(*SVOp);
10708       } else if (SumV2Indices == SumV1Indices) {
10709         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10710         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10711           if (SVOp->getMask()[i] >= NumElements)
10712             NumV2OddIndices += i % 2;
10713           else if (SVOp->getMask()[i] >= 0)
10714             NumV1OddIndices += i % 2;
10715         if (NumV2OddIndices < NumV1OddIndices)
10716           return DAG.getCommutedVectorShuffle(*SVOp);
10717       }
10718     }
10719   }
10720
10721   // For each vector width, delegate to a specialized lowering routine.
10722   if (VT.getSizeInBits() == 128)
10723     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10724
10725   if (VT.getSizeInBits() == 256)
10726     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10727
10728   // Force AVX-512 vectors to be scalarized for now.
10729   // FIXME: Implement AVX-512 support!
10730   if (VT.getSizeInBits() == 512)
10731     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10732
10733   llvm_unreachable("Unimplemented!");
10734 }
10735
10736 // This function assumes its argument is a BUILD_VECTOR of constants or
10737 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10738 // true.
10739 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10740                                     unsigned &MaskValue) {
10741   MaskValue = 0;
10742   unsigned NumElems = BuildVector->getNumOperands();
10743   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10744   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10745   unsigned NumElemsInLane = NumElems / NumLanes;
10746
10747   // Blend for v16i16 should be symmetric for the both lanes.
10748   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10749     SDValue EltCond = BuildVector->getOperand(i);
10750     SDValue SndLaneEltCond =
10751         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10752
10753     int Lane1Cond = -1, Lane2Cond = -1;
10754     if (isa<ConstantSDNode>(EltCond))
10755       Lane1Cond = !isZero(EltCond);
10756     if (isa<ConstantSDNode>(SndLaneEltCond))
10757       Lane2Cond = !isZero(SndLaneEltCond);
10758
10759     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10760       // Lane1Cond != 0, means we want the first argument.
10761       // Lane1Cond == 0, means we want the second argument.
10762       // The encoding of this argument is 0 for the first argument, 1
10763       // for the second. Therefore, invert the condition.
10764       MaskValue |= !Lane1Cond << i;
10765     else if (Lane1Cond < 0)
10766       MaskValue |= !Lane2Cond << i;
10767     else
10768       return false;
10769   }
10770   return true;
10771 }
10772
10773 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10774 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10775                                            const X86Subtarget *Subtarget,
10776                                            SelectionDAG &DAG) {
10777   SDValue Cond = Op.getOperand(0);
10778   SDValue LHS = Op.getOperand(1);
10779   SDValue RHS = Op.getOperand(2);
10780   SDLoc dl(Op);
10781   MVT VT = Op.getSimpleValueType();
10782
10783   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10784     return SDValue();
10785   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10786
10787   // Only non-legal VSELECTs reach this lowering, convert those into generic
10788   // shuffles and re-use the shuffle lowering path for blends.
10789   SmallVector<int, 32> Mask;
10790   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10791     SDValue CondElt = CondBV->getOperand(i);
10792     Mask.push_back(
10793         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10794   }
10795   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10796 }
10797
10798 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10799   // A vselect where all conditions and data are constants can be optimized into
10800   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10801   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10802       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10803       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10804     return SDValue();
10805
10806   // Try to lower this to a blend-style vector shuffle. This can handle all
10807   // constant condition cases.
10808   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10809     return BlendOp;
10810
10811   // Variable blends are only legal from SSE4.1 onward.
10812   if (!Subtarget->hasSSE41())
10813     return SDValue();
10814
10815   // Only some types will be legal on some subtargets. If we can emit a legal
10816   // VSELECT-matching blend, return Op, and but if we need to expand, return
10817   // a null value.
10818   switch (Op.getSimpleValueType().SimpleTy) {
10819   default:
10820     // Most of the vector types have blends past SSE4.1.
10821     return Op;
10822
10823   case MVT::v32i8:
10824     // The byte blends for AVX vectors were introduced only in AVX2.
10825     if (Subtarget->hasAVX2())
10826       return Op;
10827
10828     return SDValue();
10829
10830   case MVT::v8i16:
10831   case MVT::v16i16:
10832     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10833     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10834       return Op;
10835
10836     // FIXME: We should custom lower this by fixing the condition and using i8
10837     // blends.
10838     return SDValue();
10839   }
10840 }
10841
10842 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10843   MVT VT = Op.getSimpleValueType();
10844   SDLoc dl(Op);
10845
10846   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10847     return SDValue();
10848
10849   if (VT.getSizeInBits() == 8) {
10850     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10851                                   Op.getOperand(0), Op.getOperand(1));
10852     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10853                                   DAG.getValueType(VT));
10854     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10855   }
10856
10857   if (VT.getSizeInBits() == 16) {
10858     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10859     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10860     if (Idx == 0)
10861       return DAG.getNode(
10862           ISD::TRUNCATE, dl, MVT::i16,
10863           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10864                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10865                       Op.getOperand(1)));
10866     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10867                                   Op.getOperand(0), Op.getOperand(1));
10868     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10869                                   DAG.getValueType(VT));
10870     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10871   }
10872
10873   if (VT == MVT::f32) {
10874     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10875     // the result back to FR32 register. It's only worth matching if the
10876     // result has a single use which is a store or a bitcast to i32.  And in
10877     // the case of a store, it's not worth it if the index is a constant 0,
10878     // because a MOVSSmr can be used instead, which is smaller and faster.
10879     if (!Op.hasOneUse())
10880       return SDValue();
10881     SDNode *User = *Op.getNode()->use_begin();
10882     if ((User->getOpcode() != ISD::STORE ||
10883          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10884           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10885         (User->getOpcode() != ISD::BITCAST ||
10886          User->getValueType(0) != MVT::i32))
10887       return SDValue();
10888     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10889                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10890                                   Op.getOperand(1));
10891     return DAG.getBitcast(MVT::f32, Extract);
10892   }
10893
10894   if (VT == MVT::i32 || VT == MVT::i64) {
10895     // ExtractPS/pextrq works with constant index.
10896     if (isa<ConstantSDNode>(Op.getOperand(1)))
10897       return Op;
10898   }
10899   return SDValue();
10900 }
10901
10902 /// Extract one bit from mask vector, like v16i1 or v8i1.
10903 /// AVX-512 feature.
10904 SDValue
10905 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10906   SDValue Vec = Op.getOperand(0);
10907   SDLoc dl(Vec);
10908   MVT VecVT = Vec.getSimpleValueType();
10909   SDValue Idx = Op.getOperand(1);
10910   MVT EltVT = Op.getSimpleValueType();
10911
10912   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10913   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10914          "Unexpected vector type in ExtractBitFromMaskVector");
10915
10916   // variable index can't be handled in mask registers,
10917   // extend vector to VR512
10918   if (!isa<ConstantSDNode>(Idx)) {
10919     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10920     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10921     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10922                               ExtVT.getVectorElementType(), Ext, Idx);
10923     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10924   }
10925
10926   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10927   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10928   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10929     rc = getRegClassFor(MVT::v16i1);
10930   unsigned MaxSift = rc->getSize()*8 - 1;
10931   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10932                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10933   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10934                     DAG.getConstant(MaxSift, dl, MVT::i8));
10935   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10936                        DAG.getIntPtrConstant(0, dl));
10937 }
10938
10939 SDValue
10940 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10941                                            SelectionDAG &DAG) const {
10942   SDLoc dl(Op);
10943   SDValue Vec = Op.getOperand(0);
10944   MVT VecVT = Vec.getSimpleValueType();
10945   SDValue Idx = Op.getOperand(1);
10946
10947   if (Op.getSimpleValueType() == MVT::i1)
10948     return ExtractBitFromMaskVector(Op, DAG);
10949
10950   if (!isa<ConstantSDNode>(Idx)) {
10951     if (VecVT.is512BitVector() ||
10952         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10953          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10954
10955       MVT MaskEltVT =
10956         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10957       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10958                                     MaskEltVT.getSizeInBits());
10959
10960       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10961       auto PtrVT = getPointerTy(DAG.getDataLayout());
10962       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10963                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10964                                  DAG.getConstant(0, dl, PtrVT));
10965       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10966       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10967                          DAG.getConstant(0, dl, PtrVT));
10968     }
10969     return SDValue();
10970   }
10971
10972   // If this is a 256-bit vector result, first extract the 128-bit vector and
10973   // then extract the element from the 128-bit vector.
10974   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10975
10976     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10977     // Get the 128-bit vector.
10978     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10979     MVT EltVT = VecVT.getVectorElementType();
10980
10981     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10982
10983     //if (IdxVal >= NumElems/2)
10984     //  IdxVal -= NumElems/2;
10985     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10986     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10987                        DAG.getConstant(IdxVal, dl, MVT::i32));
10988   }
10989
10990   assert(VecVT.is128BitVector() && "Unexpected vector length");
10991
10992   if (Subtarget->hasSSE41())
10993     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10994       return Res;
10995
10996   MVT VT = Op.getSimpleValueType();
10997   // TODO: handle v16i8.
10998   if (VT.getSizeInBits() == 16) {
10999     SDValue Vec = Op.getOperand(0);
11000     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11001     if (Idx == 0)
11002       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11003                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11004                                      DAG.getBitcast(MVT::v4i32, Vec),
11005                                      Op.getOperand(1)));
11006     // Transform it so it match pextrw which produces a 32-bit result.
11007     MVT EltVT = MVT::i32;
11008     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11009                                   Op.getOperand(0), Op.getOperand(1));
11010     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11011                                   DAG.getValueType(VT));
11012     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11013   }
11014
11015   if (VT.getSizeInBits() == 32) {
11016     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11017     if (Idx == 0)
11018       return Op;
11019
11020     // SHUFPS the element to the lowest double word, then movss.
11021     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11022     MVT VVT = Op.getOperand(0).getSimpleValueType();
11023     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11024                                        DAG.getUNDEF(VVT), Mask);
11025     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11026                        DAG.getIntPtrConstant(0, dl));
11027   }
11028
11029   if (VT.getSizeInBits() == 64) {
11030     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11031     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11032     //        to match extract_elt for f64.
11033     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11034     if (Idx == 0)
11035       return Op;
11036
11037     // UNPCKHPD the element to the lowest double word, then movsd.
11038     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11039     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11040     int Mask[2] = { 1, -1 };
11041     MVT VVT = Op.getOperand(0).getSimpleValueType();
11042     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11043                                        DAG.getUNDEF(VVT), Mask);
11044     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11045                        DAG.getIntPtrConstant(0, dl));
11046   }
11047
11048   return SDValue();
11049 }
11050
11051 /// Insert one bit to mask vector, like v16i1 or v8i1.
11052 /// AVX-512 feature.
11053 SDValue
11054 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11055   SDLoc dl(Op);
11056   SDValue Vec = Op.getOperand(0);
11057   SDValue Elt = Op.getOperand(1);
11058   SDValue Idx = Op.getOperand(2);
11059   MVT VecVT = Vec.getSimpleValueType();
11060
11061   if (!isa<ConstantSDNode>(Idx)) {
11062     // Non constant index. Extend source and destination,
11063     // insert element and then truncate the result.
11064     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11065     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11066     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11067       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11068       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11069     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11070   }
11071
11072   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11073   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11074   if (IdxVal)
11075     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11076                            DAG.getConstant(IdxVal, dl, MVT::i8));
11077   if (Vec.getOpcode() == ISD::UNDEF)
11078     return EltInVec;
11079   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11080 }
11081
11082 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11083                                                   SelectionDAG &DAG) const {
11084   MVT VT = Op.getSimpleValueType();
11085   MVT EltVT = VT.getVectorElementType();
11086
11087   if (EltVT == MVT::i1)
11088     return InsertBitToMaskVector(Op, DAG);
11089
11090   SDLoc dl(Op);
11091   SDValue N0 = Op.getOperand(0);
11092   SDValue N1 = Op.getOperand(1);
11093   SDValue N2 = Op.getOperand(2);
11094   if (!isa<ConstantSDNode>(N2))
11095     return SDValue();
11096   auto *N2C = cast<ConstantSDNode>(N2);
11097   unsigned IdxVal = N2C->getZExtValue();
11098
11099   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11100   // into that, and then insert the subvector back into the result.
11101   if (VT.is256BitVector() || VT.is512BitVector()) {
11102     // With a 256-bit vector, we can insert into the zero element efficiently
11103     // using a blend if we have AVX or AVX2 and the right data type.
11104     if (VT.is256BitVector() && IdxVal == 0) {
11105       // TODO: It is worthwhile to cast integer to floating point and back
11106       // and incur a domain crossing penalty if that's what we'll end up
11107       // doing anyway after extracting to a 128-bit vector.
11108       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11109           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11110         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11111         N2 = DAG.getIntPtrConstant(1, dl);
11112         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11113       }
11114     }
11115
11116     // Get the desired 128-bit vector chunk.
11117     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11118
11119     // Insert the element into the desired chunk.
11120     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11121     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11122
11123     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11124                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11125
11126     // Insert the changed part back into the bigger vector
11127     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11128   }
11129   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11130
11131   if (Subtarget->hasSSE41()) {
11132     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11133       unsigned Opc;
11134       if (VT == MVT::v8i16) {
11135         Opc = X86ISD::PINSRW;
11136       } else {
11137         assert(VT == MVT::v16i8);
11138         Opc = X86ISD::PINSRB;
11139       }
11140
11141       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11142       // argument.
11143       if (N1.getValueType() != MVT::i32)
11144         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11145       if (N2.getValueType() != MVT::i32)
11146         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11147       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11148     }
11149
11150     if (EltVT == MVT::f32) {
11151       // Bits [7:6] of the constant are the source select. This will always be
11152       //   zero here. The DAG Combiner may combine an extract_elt index into
11153       //   these bits. For example (insert (extract, 3), 2) could be matched by
11154       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11155       // Bits [5:4] of the constant are the destination select. This is the
11156       //   value of the incoming immediate.
11157       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11158       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11159
11160       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11161       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11162         // If this is an insertion of 32-bits into the low 32-bits of
11163         // a vector, we prefer to generate a blend with immediate rather
11164         // than an insertps. Blends are simpler operations in hardware and so
11165         // will always have equal or better performance than insertps.
11166         // But if optimizing for size and there's a load folding opportunity,
11167         // generate insertps because blendps does not have a 32-bit memory
11168         // operand form.
11169         N2 = DAG.getIntPtrConstant(1, dl);
11170         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11171         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11172       }
11173       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11174       // Create this as a scalar to vector..
11175       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11176       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11177     }
11178
11179     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11180       // PINSR* works with constant index.
11181       return Op;
11182     }
11183   }
11184
11185   if (EltVT == MVT::i8)
11186     return SDValue();
11187
11188   if (EltVT.getSizeInBits() == 16) {
11189     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11190     // as its second argument.
11191     if (N1.getValueType() != MVT::i32)
11192       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11193     if (N2.getValueType() != MVT::i32)
11194       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11195     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11196   }
11197   return SDValue();
11198 }
11199
11200 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11201   SDLoc dl(Op);
11202   MVT OpVT = Op.getSimpleValueType();
11203
11204   // If this is a 256-bit vector result, first insert into a 128-bit
11205   // vector and then insert into the 256-bit vector.
11206   if (!OpVT.is128BitVector()) {
11207     // Insert into a 128-bit vector.
11208     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11209     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11210                                  OpVT.getVectorNumElements() / SizeFactor);
11211
11212     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11213
11214     // Insert the 128-bit vector.
11215     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11216   }
11217
11218   if (OpVT == MVT::v1i64 &&
11219       Op.getOperand(0).getValueType() == MVT::i64)
11220     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11221
11222   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11223   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11224   return DAG.getBitcast(
11225       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11226 }
11227
11228 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11229 // a simple subregister reference or explicit instructions to grab
11230 // upper bits of a vector.
11231 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11232                                       SelectionDAG &DAG) {
11233   SDLoc dl(Op);
11234   SDValue In =  Op.getOperand(0);
11235   SDValue Idx = Op.getOperand(1);
11236   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11237   MVT ResVT   = Op.getSimpleValueType();
11238   MVT InVT    = In.getSimpleValueType();
11239
11240   if (Subtarget->hasFp256()) {
11241     if (ResVT.is128BitVector() &&
11242         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11243         isa<ConstantSDNode>(Idx)) {
11244       return Extract128BitVector(In, IdxVal, DAG, dl);
11245     }
11246     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11247         isa<ConstantSDNode>(Idx)) {
11248       return Extract256BitVector(In, IdxVal, DAG, dl);
11249     }
11250   }
11251   return SDValue();
11252 }
11253
11254 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11255 // simple superregister reference or explicit instructions to insert
11256 // the upper bits of a vector.
11257 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11258                                      SelectionDAG &DAG) {
11259   if (!Subtarget->hasAVX())
11260     return SDValue();
11261
11262   SDLoc dl(Op);
11263   SDValue Vec = Op.getOperand(0);
11264   SDValue SubVec = Op.getOperand(1);
11265   SDValue Idx = Op.getOperand(2);
11266
11267   if (!isa<ConstantSDNode>(Idx))
11268     return SDValue();
11269
11270   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11271   MVT OpVT = Op.getSimpleValueType();
11272   MVT SubVecVT = SubVec.getSimpleValueType();
11273
11274   // Fold two 16-byte subvector loads into one 32-byte load:
11275   // (insert_subvector (insert_subvector undef, (load addr), 0),
11276   //                   (load addr + 16), Elts/2)
11277   // --> load32 addr
11278   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11279       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11280       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11281     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11282     if (Idx2 && Idx2->getZExtValue() == 0) {
11283       SDValue SubVec2 = Vec.getOperand(1);
11284       // If needed, look through a bitcast to get to the load.
11285       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11286         SubVec2 = SubVec2.getOperand(0);
11287       
11288       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11289         bool Fast;
11290         unsigned Alignment = FirstLd->getAlignment();
11291         unsigned AS = FirstLd->getAddressSpace();
11292         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11293         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11294                                     OpVT, AS, Alignment, &Fast) && Fast) {
11295           SDValue Ops[] = { SubVec2, SubVec };
11296           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11297             return Ld;
11298         }
11299       }
11300     }
11301   }
11302
11303   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11304       SubVecVT.is128BitVector())
11305     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11306
11307   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11308     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11309
11310   if (OpVT.getVectorElementType() == MVT::i1) {
11311     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11312       return Op;
11313     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11314     SDValue Undef = DAG.getUNDEF(OpVT);
11315     unsigned NumElems = OpVT.getVectorNumElements();
11316     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11317
11318     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11319       // Zero upper bits of the Vec
11320       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11321       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11322
11323       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11324                                  SubVec, ZeroIdx);
11325       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11326       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11327     }
11328     if (IdxVal == 0) {
11329       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11330                                  SubVec, ZeroIdx);
11331       // Zero upper bits of the Vec2
11332       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11333       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11334       // Zero lower bits of the Vec
11335       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11336       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11337       // Merge them together
11338       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11339     }
11340   }
11341   return SDValue();
11342 }
11343
11344 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11345 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11346 // one of the above mentioned nodes. It has to be wrapped because otherwise
11347 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11348 // be used to form addressing mode. These wrapped nodes will be selected
11349 // into MOV32ri.
11350 SDValue
11351 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11352   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11353
11354   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11355   // global base reg.
11356   unsigned char OpFlag = 0;
11357   unsigned WrapperKind = X86ISD::Wrapper;
11358   CodeModel::Model M = DAG.getTarget().getCodeModel();
11359
11360   if (Subtarget->isPICStyleRIPRel() &&
11361       (M == CodeModel::Small || M == CodeModel::Kernel))
11362     WrapperKind = X86ISD::WrapperRIP;
11363   else if (Subtarget->isPICStyleGOT())
11364     OpFlag = X86II::MO_GOTOFF;
11365   else if (Subtarget->isPICStyleStubPIC())
11366     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11367
11368   auto PtrVT = getPointerTy(DAG.getDataLayout());
11369   SDValue Result = DAG.getTargetConstantPool(
11370       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11371   SDLoc DL(CP);
11372   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11373   // With PIC, the address is actually $g + Offset.
11374   if (OpFlag) {
11375     Result =
11376         DAG.getNode(ISD::ADD, DL, PtrVT,
11377                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11378   }
11379
11380   return Result;
11381 }
11382
11383 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11384   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11385
11386   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11387   // global base reg.
11388   unsigned char OpFlag = 0;
11389   unsigned WrapperKind = X86ISD::Wrapper;
11390   CodeModel::Model M = DAG.getTarget().getCodeModel();
11391
11392   if (Subtarget->isPICStyleRIPRel() &&
11393       (M == CodeModel::Small || M == CodeModel::Kernel))
11394     WrapperKind = X86ISD::WrapperRIP;
11395   else if (Subtarget->isPICStyleGOT())
11396     OpFlag = X86II::MO_GOTOFF;
11397   else if (Subtarget->isPICStyleStubPIC())
11398     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11399
11400   auto PtrVT = getPointerTy(DAG.getDataLayout());
11401   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11402   SDLoc DL(JT);
11403   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11404
11405   // With PIC, the address is actually $g + Offset.
11406   if (OpFlag)
11407     Result =
11408         DAG.getNode(ISD::ADD, DL, PtrVT,
11409                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11410
11411   return Result;
11412 }
11413
11414 SDValue
11415 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11416   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11417
11418   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11419   // global base reg.
11420   unsigned char OpFlag = 0;
11421   unsigned WrapperKind = X86ISD::Wrapper;
11422   CodeModel::Model M = DAG.getTarget().getCodeModel();
11423
11424   if (Subtarget->isPICStyleRIPRel() &&
11425       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11426     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11427       OpFlag = X86II::MO_GOTPCREL;
11428     WrapperKind = X86ISD::WrapperRIP;
11429   } else if (Subtarget->isPICStyleGOT()) {
11430     OpFlag = X86II::MO_GOT;
11431   } else if (Subtarget->isPICStyleStubPIC()) {
11432     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11433   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11434     OpFlag = X86II::MO_DARWIN_NONLAZY;
11435   }
11436
11437   auto PtrVT = getPointerTy(DAG.getDataLayout());
11438   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11439
11440   SDLoc DL(Op);
11441   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11442
11443   // With PIC, the address is actually $g + Offset.
11444   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11445       !Subtarget->is64Bit()) {
11446     Result =
11447         DAG.getNode(ISD::ADD, DL, PtrVT,
11448                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11449   }
11450
11451   // For symbols that require a load from a stub to get the address, emit the
11452   // load.
11453   if (isGlobalStubReference(OpFlag))
11454     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11455                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11456                          false, false, false, 0);
11457
11458   return Result;
11459 }
11460
11461 SDValue
11462 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11463   // Create the TargetBlockAddressAddress node.
11464   unsigned char OpFlags =
11465     Subtarget->ClassifyBlockAddressReference();
11466   CodeModel::Model M = DAG.getTarget().getCodeModel();
11467   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11468   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11469   SDLoc dl(Op);
11470   auto PtrVT = getPointerTy(DAG.getDataLayout());
11471   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11472
11473   if (Subtarget->isPICStyleRIPRel() &&
11474       (M == CodeModel::Small || M == CodeModel::Kernel))
11475     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11476   else
11477     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11478
11479   // With PIC, the address is actually $g + Offset.
11480   if (isGlobalRelativeToPICBase(OpFlags)) {
11481     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11482                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11483   }
11484
11485   return Result;
11486 }
11487
11488 SDValue
11489 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11490                                       int64_t Offset, SelectionDAG &DAG) const {
11491   // Create the TargetGlobalAddress node, folding in the constant
11492   // offset if it is legal.
11493   unsigned char OpFlags =
11494       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11495   CodeModel::Model M = DAG.getTarget().getCodeModel();
11496   auto PtrVT = getPointerTy(DAG.getDataLayout());
11497   SDValue Result;
11498   if (OpFlags == X86II::MO_NO_FLAG &&
11499       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11500     // A direct static reference to a global.
11501     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11502     Offset = 0;
11503   } else {
11504     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11505   }
11506
11507   if (Subtarget->isPICStyleRIPRel() &&
11508       (M == CodeModel::Small || M == CodeModel::Kernel))
11509     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11510   else
11511     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11512
11513   // With PIC, the address is actually $g + Offset.
11514   if (isGlobalRelativeToPICBase(OpFlags)) {
11515     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11516                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11517   }
11518
11519   // For globals that require a load from a stub to get the address, emit the
11520   // load.
11521   if (isGlobalStubReference(OpFlags))
11522     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11523                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11524                          false, false, false, 0);
11525
11526   // If there was a non-zero offset that we didn't fold, create an explicit
11527   // addition for it.
11528   if (Offset != 0)
11529     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11530                          DAG.getConstant(Offset, dl, PtrVT));
11531
11532   return Result;
11533 }
11534
11535 SDValue
11536 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11537   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11538   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11539   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11540 }
11541
11542 static SDValue
11543 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11544            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11545            unsigned char OperandFlags, bool LocalDynamic = false) {
11546   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11547   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11548   SDLoc dl(GA);
11549   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11550                                            GA->getValueType(0),
11551                                            GA->getOffset(),
11552                                            OperandFlags);
11553
11554   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11555                                            : X86ISD::TLSADDR;
11556
11557   if (InFlag) {
11558     SDValue Ops[] = { Chain,  TGA, *InFlag };
11559     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11560   } else {
11561     SDValue Ops[]  = { Chain, TGA };
11562     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11563   }
11564
11565   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11566   MFI->setAdjustsStack(true);
11567   MFI->setHasCalls(true);
11568
11569   SDValue Flag = Chain.getValue(1);
11570   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11571 }
11572
11573 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11574 static SDValue
11575 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11576                                 const EVT PtrVT) {
11577   SDValue InFlag;
11578   SDLoc dl(GA);  // ? function entry point might be better
11579   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11580                                    DAG.getNode(X86ISD::GlobalBaseReg,
11581                                                SDLoc(), PtrVT), InFlag);
11582   InFlag = Chain.getValue(1);
11583
11584   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11585 }
11586
11587 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11588 static SDValue
11589 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11590                                 const EVT PtrVT) {
11591   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11592                     X86::RAX, X86II::MO_TLSGD);
11593 }
11594
11595 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11596                                            SelectionDAG &DAG,
11597                                            const EVT PtrVT,
11598                                            bool is64Bit) {
11599   SDLoc dl(GA);
11600
11601   // Get the start address of the TLS block for this module.
11602   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11603       .getInfo<X86MachineFunctionInfo>();
11604   MFI->incNumLocalDynamicTLSAccesses();
11605
11606   SDValue Base;
11607   if (is64Bit) {
11608     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11609                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11610   } else {
11611     SDValue InFlag;
11612     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11613         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11614     InFlag = Chain.getValue(1);
11615     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11616                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11617   }
11618
11619   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11620   // of Base.
11621
11622   // Build x@dtpoff.
11623   unsigned char OperandFlags = X86II::MO_DTPOFF;
11624   unsigned WrapperKind = X86ISD::Wrapper;
11625   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11626                                            GA->getValueType(0),
11627                                            GA->getOffset(), OperandFlags);
11628   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11629
11630   // Add x@dtpoff with the base.
11631   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11632 }
11633
11634 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11635 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11636                                    const EVT PtrVT, TLSModel::Model model,
11637                                    bool is64Bit, bool isPIC) {
11638   SDLoc dl(GA);
11639
11640   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11641   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11642                                                          is64Bit ? 257 : 256));
11643
11644   SDValue ThreadPointer =
11645       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11646                   MachinePointerInfo(Ptr), false, false, false, 0);
11647
11648   unsigned char OperandFlags = 0;
11649   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11650   // initialexec.
11651   unsigned WrapperKind = X86ISD::Wrapper;
11652   if (model == TLSModel::LocalExec) {
11653     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11654   } else if (model == TLSModel::InitialExec) {
11655     if (is64Bit) {
11656       OperandFlags = X86II::MO_GOTTPOFF;
11657       WrapperKind = X86ISD::WrapperRIP;
11658     } else {
11659       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11660     }
11661   } else {
11662     llvm_unreachable("Unexpected model");
11663   }
11664
11665   // emit "addl x@ntpoff,%eax" (local exec)
11666   // or "addl x@indntpoff,%eax" (initial exec)
11667   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11668   SDValue TGA =
11669       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11670                                  GA->getOffset(), OperandFlags);
11671   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11672
11673   if (model == TLSModel::InitialExec) {
11674     if (isPIC && !is64Bit) {
11675       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11676                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11677                            Offset);
11678     }
11679
11680     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11681                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11682                          false, false, false, 0);
11683   }
11684
11685   // The address of the thread local variable is the add of the thread
11686   // pointer with the offset of the variable.
11687   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11688 }
11689
11690 SDValue
11691 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11692
11693   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11694   const GlobalValue *GV = GA->getGlobal();
11695   auto PtrVT = getPointerTy(DAG.getDataLayout());
11696
11697   if (Subtarget->isTargetELF()) {
11698     if (DAG.getTarget().Options.EmulatedTLS)
11699       return LowerToTLSEmulatedModel(GA, DAG);
11700     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11701     switch (model) {
11702       case TLSModel::GeneralDynamic:
11703         if (Subtarget->is64Bit())
11704           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11705         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11706       case TLSModel::LocalDynamic:
11707         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11708                                            Subtarget->is64Bit());
11709       case TLSModel::InitialExec:
11710       case TLSModel::LocalExec:
11711         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11712                                    DAG.getTarget().getRelocationModel() ==
11713                                        Reloc::PIC_);
11714     }
11715     llvm_unreachable("Unknown TLS model.");
11716   }
11717
11718   if (Subtarget->isTargetDarwin()) {
11719     // Darwin only has one model of TLS.  Lower to that.
11720     unsigned char OpFlag = 0;
11721     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11722                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11723
11724     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11725     // global base reg.
11726     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11727                  !Subtarget->is64Bit();
11728     if (PIC32)
11729       OpFlag = X86II::MO_TLVP_PIC_BASE;
11730     else
11731       OpFlag = X86II::MO_TLVP;
11732     SDLoc DL(Op);
11733     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11734                                                 GA->getValueType(0),
11735                                                 GA->getOffset(), OpFlag);
11736     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11737
11738     // With PIC32, the address is actually $g + Offset.
11739     if (PIC32)
11740       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11741                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11742                            Offset);
11743
11744     // Lowering the machine isd will make sure everything is in the right
11745     // location.
11746     SDValue Chain = DAG.getEntryNode();
11747     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11748     SDValue Args[] = { Chain, Offset };
11749     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11750
11751     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11752     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11753     MFI->setAdjustsStack(true);
11754
11755     // And our return value (tls address) is in the standard call return value
11756     // location.
11757     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11758     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11759   }
11760
11761   if (Subtarget->isTargetKnownWindowsMSVC() ||
11762       Subtarget->isTargetWindowsGNU()) {
11763     // Just use the implicit TLS architecture
11764     // Need to generate someting similar to:
11765     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11766     //                                  ; from TEB
11767     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11768     //   mov     rcx, qword [rdx+rcx*8]
11769     //   mov     eax, .tls$:tlsvar
11770     //   [rax+rcx] contains the address
11771     // Windows 64bit: gs:0x58
11772     // Windows 32bit: fs:__tls_array
11773
11774     SDLoc dl(GA);
11775     SDValue Chain = DAG.getEntryNode();
11776
11777     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11778     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11779     // use its literal value of 0x2C.
11780     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11781                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11782                                                              256)
11783                                         : Type::getInt32PtrTy(*DAG.getContext(),
11784                                                               257));
11785
11786     SDValue TlsArray = Subtarget->is64Bit()
11787                            ? DAG.getIntPtrConstant(0x58, dl)
11788                            : (Subtarget->isTargetWindowsGNU()
11789                                   ? DAG.getIntPtrConstant(0x2C, dl)
11790                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11791
11792     SDValue ThreadPointer =
11793         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11794                     false, false, 0);
11795
11796     SDValue res;
11797     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11798       res = ThreadPointer;
11799     } else {
11800       // Load the _tls_index variable
11801       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11802       if (Subtarget->is64Bit())
11803         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11804                              MachinePointerInfo(), MVT::i32, false, false,
11805                              false, 0);
11806       else
11807         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11808                           false, false, 0);
11809
11810       auto &DL = DAG.getDataLayout();
11811       SDValue Scale =
11812           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11813       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11814
11815       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11816     }
11817
11818     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11819                       false, 0);
11820
11821     // Get the offset of start of .tls section
11822     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11823                                              GA->getValueType(0),
11824                                              GA->getOffset(), X86II::MO_SECREL);
11825     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11826
11827     // The address of the thread local variable is the add of the thread
11828     // pointer with the offset of the variable.
11829     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11830   }
11831
11832   llvm_unreachable("TLS not implemented for this target.");
11833 }
11834
11835 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11836 /// and take a 2 x i32 value to shift plus a shift amount.
11837 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11838   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11839   MVT VT = Op.getSimpleValueType();
11840   unsigned VTBits = VT.getSizeInBits();
11841   SDLoc dl(Op);
11842   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11843   SDValue ShOpLo = Op.getOperand(0);
11844   SDValue ShOpHi = Op.getOperand(1);
11845   SDValue ShAmt  = Op.getOperand(2);
11846   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11847   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11848   // during isel.
11849   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11850                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11851   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11852                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11853                        : DAG.getConstant(0, dl, VT);
11854
11855   SDValue Tmp2, Tmp3;
11856   if (Op.getOpcode() == ISD::SHL_PARTS) {
11857     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11858     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11859   } else {
11860     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11861     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11862   }
11863
11864   // If the shift amount is larger or equal than the width of a part we can't
11865   // rely on the results of shld/shrd. Insert a test and select the appropriate
11866   // values for large shift amounts.
11867   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11868                                 DAG.getConstant(VTBits, dl, MVT::i8));
11869   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11870                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11871
11872   SDValue Hi, Lo;
11873   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11874   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11875   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11876
11877   if (Op.getOpcode() == ISD::SHL_PARTS) {
11878     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11879     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11880   } else {
11881     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11882     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11883   }
11884
11885   SDValue Ops[2] = { Lo, Hi };
11886   return DAG.getMergeValues(Ops, dl);
11887 }
11888
11889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11890                                            SelectionDAG &DAG) const {
11891   SDValue Src = Op.getOperand(0);
11892   MVT SrcVT = Src.getSimpleValueType();
11893   MVT VT = Op.getSimpleValueType();
11894   SDLoc dl(Op);
11895
11896   if (SrcVT.isVector()) {
11897     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11898       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11899                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11900                          DAG.getUNDEF(SrcVT)));
11901     }
11902     if (SrcVT.getVectorElementType() == MVT::i1) {
11903       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11904       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11905                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11906     }
11907     return SDValue();
11908   }
11909
11910   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11911          "Unknown SINT_TO_FP to lower!");
11912
11913   // These are really Legal; return the operand so the caller accepts it as
11914   // Legal.
11915   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11916     return Op;
11917   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11918       Subtarget->is64Bit()) {
11919     return Op;
11920   }
11921
11922   unsigned Size = SrcVT.getSizeInBits()/8;
11923   MachineFunction &MF = DAG.getMachineFunction();
11924   auto PtrVT = getPointerTy(MF.getDataLayout());
11925   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11926   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11927   SDValue Chain = DAG.getStore(
11928       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11929       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11930       false, 0);
11931   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11932 }
11933
11934 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11935                                      SDValue StackSlot,
11936                                      SelectionDAG &DAG) const {
11937   // Build the FILD
11938   SDLoc DL(Op);
11939   SDVTList Tys;
11940   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11941   if (useSSE)
11942     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11943   else
11944     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11945
11946   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11947
11948   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11949   MachineMemOperand *MMO;
11950   if (FI) {
11951     int SSFI = FI->getIndex();
11952     MMO = DAG.getMachineFunction().getMachineMemOperand(
11953         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11954         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11955   } else {
11956     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11957     StackSlot = StackSlot.getOperand(1);
11958   }
11959   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11960   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11961                                            X86ISD::FILD, DL,
11962                                            Tys, Ops, SrcVT, MMO);
11963
11964   if (useSSE) {
11965     Chain = Result.getValue(1);
11966     SDValue InFlag = Result.getValue(2);
11967
11968     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11969     // shouldn't be necessary except that RFP cannot be live across
11970     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11971     MachineFunction &MF = DAG.getMachineFunction();
11972     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11973     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11974     auto PtrVT = getPointerTy(MF.getDataLayout());
11975     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11976     Tys = DAG.getVTList(MVT::Other);
11977     SDValue Ops[] = {
11978       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11979     };
11980     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11981         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11982         MachineMemOperand::MOStore, SSFISize, SSFISize);
11983
11984     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11985                                     Ops, Op.getValueType(), MMO);
11986     Result = DAG.getLoad(
11987         Op.getValueType(), DL, Chain, StackSlot,
11988         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11989         false, false, false, 0);
11990   }
11991
11992   return Result;
11993 }
11994
11995 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11996 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11997                                                SelectionDAG &DAG) const {
11998   // This algorithm is not obvious. Here it is what we're trying to output:
11999   /*
12000      movq       %rax,  %xmm0
12001      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12002      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12003      #ifdef __SSE3__
12004        haddpd   %xmm0, %xmm0
12005      #else
12006        pshufd   $0x4e, %xmm0, %xmm1
12007        addpd    %xmm1, %xmm0
12008      #endif
12009   */
12010
12011   SDLoc dl(Op);
12012   LLVMContext *Context = DAG.getContext();
12013
12014   // Build some magic constants.
12015   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12016   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12017   auto PtrVT = getPointerTy(DAG.getDataLayout());
12018   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12019
12020   SmallVector<Constant*,2> CV1;
12021   CV1.push_back(
12022     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12023                                       APInt(64, 0x4330000000000000ULL))));
12024   CV1.push_back(
12025     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12026                                       APInt(64, 0x4530000000000000ULL))));
12027   Constant *C1 = ConstantVector::get(CV1);
12028   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12029
12030   // Load the 64-bit value into an XMM register.
12031   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12032                             Op.getOperand(0));
12033   SDValue CLod0 =
12034       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12035                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12036                   false, false, false, 16);
12037   SDValue Unpck1 =
12038       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12039
12040   SDValue CLod1 =
12041       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12042                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12043                   false, false, false, 16);
12044   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12045   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12046   SDValue Result;
12047
12048   if (Subtarget->hasSSE3()) {
12049     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12050     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12051   } else {
12052     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12053     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12054                                            S2F, 0x4E, DAG);
12055     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12056                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12057   }
12058
12059   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12060                      DAG.getIntPtrConstant(0, dl));
12061 }
12062
12063 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12064 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12065                                                SelectionDAG &DAG) const {
12066   SDLoc dl(Op);
12067   // FP constant to bias correct the final result.
12068   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12069                                    MVT::f64);
12070
12071   // Load the 32-bit value into an XMM register.
12072   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12073                              Op.getOperand(0));
12074
12075   // Zero out the upper parts of the register.
12076   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12077
12078   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12079                      DAG.getBitcast(MVT::v2f64, Load),
12080                      DAG.getIntPtrConstant(0, dl));
12081
12082   // Or the load with the bias.
12083   SDValue Or = DAG.getNode(
12084       ISD::OR, dl, MVT::v2i64,
12085       DAG.getBitcast(MVT::v2i64,
12086                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12087       DAG.getBitcast(MVT::v2i64,
12088                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12089   Or =
12090       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12091                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12092
12093   // Subtract the bias.
12094   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12095
12096   // Handle final rounding.
12097   EVT DestVT = Op.getValueType();
12098
12099   if (DestVT.bitsLT(MVT::f64))
12100     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12101                        DAG.getIntPtrConstant(0, dl));
12102   if (DestVT.bitsGT(MVT::f64))
12103     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12104
12105   // Handle final rounding.
12106   return Sub;
12107 }
12108
12109 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12110                                      const X86Subtarget &Subtarget) {
12111   // The algorithm is the following:
12112   // #ifdef __SSE4_1__
12113   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12114   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12115   //                                 (uint4) 0x53000000, 0xaa);
12116   // #else
12117   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12118   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12119   // #endif
12120   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12121   //     return (float4) lo + fhi;
12122
12123   SDLoc DL(Op);
12124   SDValue V = Op->getOperand(0);
12125   EVT VecIntVT = V.getValueType();
12126   bool Is128 = VecIntVT == MVT::v4i32;
12127   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12128   // If we convert to something else than the supported type, e.g., to v4f64,
12129   // abort early.
12130   if (VecFloatVT != Op->getValueType(0))
12131     return SDValue();
12132
12133   unsigned NumElts = VecIntVT.getVectorNumElements();
12134   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12135          "Unsupported custom type");
12136   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12137
12138   // In the #idef/#else code, we have in common:
12139   // - The vector of constants:
12140   // -- 0x4b000000
12141   // -- 0x53000000
12142   // - A shift:
12143   // -- v >> 16
12144
12145   // Create the splat vector for 0x4b000000.
12146   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12147   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12148                            CstLow, CstLow, CstLow, CstLow};
12149   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12150                                   makeArrayRef(&CstLowArray[0], NumElts));
12151   // Create the splat vector for 0x53000000.
12152   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12153   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12154                             CstHigh, CstHigh, CstHigh, CstHigh};
12155   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12156                                    makeArrayRef(&CstHighArray[0], NumElts));
12157
12158   // Create the right shift.
12159   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12160   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12161                              CstShift, CstShift, CstShift, CstShift};
12162   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12163                                     makeArrayRef(&CstShiftArray[0], NumElts));
12164   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12165
12166   SDValue Low, High;
12167   if (Subtarget.hasSSE41()) {
12168     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12169     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12170     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12171     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12172     // Low will be bitcasted right away, so do not bother bitcasting back to its
12173     // original type.
12174     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12175                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12176     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12177     //                                 (uint4) 0x53000000, 0xaa);
12178     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12179     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12180     // High will be bitcasted right away, so do not bother bitcasting back to
12181     // its original type.
12182     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12183                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12184   } else {
12185     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12186     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12187                                      CstMask, CstMask, CstMask);
12188     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12189     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12190     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12191
12192     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12193     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12194   }
12195
12196   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12197   SDValue CstFAdd = DAG.getConstantFP(
12198       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12199   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12200                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12201   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12202                                    makeArrayRef(&CstFAddArray[0], NumElts));
12203
12204   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12205   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12206   SDValue FHigh =
12207       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12208   //     return (float4) lo + fhi;
12209   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12210   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12211 }
12212
12213 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12214                                                SelectionDAG &DAG) const {
12215   SDValue N0 = Op.getOperand(0);
12216   MVT SVT = N0.getSimpleValueType();
12217   SDLoc dl(Op);
12218
12219   switch (SVT.SimpleTy) {
12220   default:
12221     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12222   case MVT::v4i8:
12223   case MVT::v4i16:
12224   case MVT::v8i8:
12225   case MVT::v8i16: {
12226     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12227     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12228                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12229   }
12230   case MVT::v4i32:
12231   case MVT::v8i32:
12232     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12233   case MVT::v16i8:
12234   case MVT::v16i16:
12235     if (Subtarget->hasAVX512())
12236       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12237                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12238   }
12239   llvm_unreachable(nullptr);
12240 }
12241
12242 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12243                                            SelectionDAG &DAG) const {
12244   SDValue N0 = Op.getOperand(0);
12245   SDLoc dl(Op);
12246   auto PtrVT = getPointerTy(DAG.getDataLayout());
12247
12248   if (Op.getValueType().isVector())
12249     return lowerUINT_TO_FP_vec(Op, DAG);
12250
12251   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12252   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12253   // the optimization here.
12254   if (DAG.SignBitIsZero(N0))
12255     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12256
12257   MVT SrcVT = N0.getSimpleValueType();
12258   MVT DstVT = Op.getSimpleValueType();
12259   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12260     return LowerUINT_TO_FP_i64(Op, DAG);
12261   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12262     return LowerUINT_TO_FP_i32(Op, DAG);
12263   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12264     return SDValue();
12265
12266   // Make a 64-bit buffer, and use it to build an FILD.
12267   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12268   if (SrcVT == MVT::i32) {
12269     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12270     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12271     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12272                                   StackSlot, MachinePointerInfo(),
12273                                   false, false, 0);
12274     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12275                                   OffsetSlot, MachinePointerInfo(),
12276                                   false, false, 0);
12277     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12278     return Fild;
12279   }
12280
12281   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12282   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12283                                StackSlot, MachinePointerInfo(),
12284                                false, false, 0);
12285   // For i64 source, we need to add the appropriate power of 2 if the input
12286   // was negative.  This is the same as the optimization in
12287   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12288   // we must be careful to do the computation in x87 extended precision, not
12289   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12290   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12291   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12292       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12293       MachineMemOperand::MOLoad, 8, 8);
12294
12295   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12296   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12297   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12298                                          MVT::i64, MMO);
12299
12300   APInt FF(32, 0x5F800000ULL);
12301
12302   // Check whether the sign bit is set.
12303   SDValue SignSet = DAG.getSetCC(
12304       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12305       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12306
12307   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12308   SDValue FudgePtr = DAG.getConstantPool(
12309       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12310
12311   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12312   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12313   SDValue Four = DAG.getIntPtrConstant(4, dl);
12314   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12315                                Zero, Four);
12316   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12317
12318   // Load the value out, extending it from f32 to f80.
12319   // FIXME: Avoid the extend by constructing the right constant pool?
12320   SDValue Fudge = DAG.getExtLoad(
12321       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12322       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12323       false, false, false, 4);
12324   // Extend everything to 80 bits to force it to be done on x87.
12325   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12326   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12327                      DAG.getIntPtrConstant(0, dl));
12328 }
12329
12330 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12331 // is legal, or has an f16 source (which needs to be promoted to f32),
12332 // just return an <SDValue(), SDValue()> pair.
12333 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12334 // to i16, i32 or i64, and we lower it to a legal sequence.
12335 // If lowered to the final integer result we return a <result, SDValue()> pair.
12336 // Otherwise we lower it to a sequence ending with a FIST, return a
12337 // <FIST, StackSlot> pair, and the caller is responsible for loading
12338 // the final integer result from StackSlot.
12339 std::pair<SDValue,SDValue>
12340 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12341                                    bool IsSigned, bool IsReplace) const {
12342   SDLoc DL(Op);
12343
12344   EVT DstTy = Op.getValueType();
12345   EVT TheVT = Op.getOperand(0).getValueType();
12346   auto PtrVT = getPointerTy(DAG.getDataLayout());
12347
12348   if (TheVT == MVT::f16)
12349     // We need to promote the f16 to f32 before using the lowering
12350     // in this routine.
12351     return std::make_pair(SDValue(), SDValue());
12352
12353   assert((TheVT == MVT::f32 ||
12354           TheVT == MVT::f64 ||
12355           TheVT == MVT::f80) &&
12356          "Unexpected FP operand type in FP_TO_INTHelper");
12357
12358   // If using FIST to compute an unsigned i64, we'll need some fixup
12359   // to handle values above the maximum signed i64.  A FIST is always
12360   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12361   bool UnsignedFixup = !IsSigned &&
12362                        DstTy == MVT::i64 &&
12363                        (!Subtarget->is64Bit() ||
12364                         !isScalarFPTypeInSSEReg(TheVT));
12365
12366   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12367     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12368     // The low 32 bits of the fist result will have the correct uint32 result.
12369     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12370     DstTy = MVT::i64;
12371   }
12372
12373   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12374          DstTy.getSimpleVT() >= MVT::i16 &&
12375          "Unknown FP_TO_INT to lower!");
12376
12377   // These are really Legal.
12378   if (DstTy == MVT::i32 &&
12379       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12380     return std::make_pair(SDValue(), SDValue());
12381   if (Subtarget->is64Bit() &&
12382       DstTy == MVT::i64 &&
12383       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12384     return std::make_pair(SDValue(), SDValue());
12385
12386   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12387   // stack slot.
12388   MachineFunction &MF = DAG.getMachineFunction();
12389   unsigned MemSize = DstTy.getSizeInBits()/8;
12390   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12391   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12392
12393   unsigned Opc;
12394   switch (DstTy.getSimpleVT().SimpleTy) {
12395   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12396   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12397   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12398   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12399   }
12400
12401   SDValue Chain = DAG.getEntryNode();
12402   SDValue Value = Op.getOperand(0);
12403   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12404
12405   if (UnsignedFixup) {
12406     //
12407     // Conversion to unsigned i64 is implemented with a select,
12408     // depending on whether the source value fits in the range
12409     // of a signed i64.  Let Thresh be the FP equivalent of
12410     // 0x8000000000000000ULL.
12411     //
12412     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12413     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12414     //  Fist-to-mem64 FistSrc
12415     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12416     //  to XOR'ing the high 32 bits with Adjust.
12417     //
12418     // Being a power of 2, Thresh is exactly representable in all FP formats.
12419     // For X87 we'd like to use the smallest FP type for this constant, but
12420     // for DAG type consistency we have to match the FP operand type.
12421
12422     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12423     APFloat::opStatus Status = APFloat::opOK;
12424     bool LosesInfo = false;
12425     if (TheVT == MVT::f64)
12426       // The rounding mode is irrelevant as the conversion should be exact.
12427       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12428                               &LosesInfo);
12429     else if (TheVT == MVT::f80)
12430       Status = Thresh.convert(APFloat::x87DoubleExtended,
12431                               APFloat::rmNearestTiesToEven, &LosesInfo);
12432
12433     assert(Status == APFloat::opOK && !LosesInfo &&
12434            "FP conversion should have been exact");
12435
12436     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12437
12438     SDValue Cmp = DAG.getSetCC(DL,
12439                                getSetCCResultType(DAG.getDataLayout(),
12440                                                   *DAG.getContext(), TheVT),
12441                                Value, ThreshVal, ISD::SETLT);
12442     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12443                            DAG.getConstant(0, DL, MVT::i32),
12444                            DAG.getConstant(0x80000000, DL, MVT::i32));
12445     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12446     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12447                                               *DAG.getContext(), TheVT),
12448                        Value, ThreshVal, ISD::SETLT);
12449     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12450   }
12451
12452   // FIXME This causes a redundant load/store if the SSE-class value is already
12453   // in memory, such as if it is on the callstack.
12454   if (isScalarFPTypeInSSEReg(TheVT)) {
12455     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12456     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12457                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12458                          false, 0);
12459     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12460     SDValue Ops[] = {
12461       Chain, StackSlot, DAG.getValueType(TheVT)
12462     };
12463
12464     MachineMemOperand *MMO =
12465         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12466                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12467     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12468     Chain = Value.getValue(1);
12469     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12470     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12471   }
12472
12473   MachineMemOperand *MMO =
12474       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12475                               MachineMemOperand::MOStore, MemSize, MemSize);
12476
12477   if (UnsignedFixup) {
12478
12479     // Insert the FIST, load its result as two i32's,
12480     // and XOR the high i32 with Adjust.
12481
12482     SDValue FistOps[] = { Chain, Value, StackSlot };
12483     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12484                                            FistOps, DstTy, MMO);
12485
12486     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12487                                 MachinePointerInfo(),
12488                                 false, false, false, 0);
12489     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12490                                    DAG.getConstant(4, DL, PtrVT));
12491
12492     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12493                                  MachinePointerInfo(),
12494                                  false, false, false, 0);
12495     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12496
12497     if (Subtarget->is64Bit()) {
12498       // Join High32 and Low32 into a 64-bit result.
12499       // (High32 << 32) | Low32
12500       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12501       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12502       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12503                            DAG.getConstant(32, DL, MVT::i8));
12504       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12505       return std::make_pair(Result, SDValue());
12506     }
12507
12508     SDValue ResultOps[] = { Low32, High32 };
12509
12510     SDValue pair = IsReplace
12511       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12512       : DAG.getMergeValues(ResultOps, DL);
12513     return std::make_pair(pair, SDValue());
12514   } else {
12515     // Build the FP_TO_INT*_IN_MEM
12516     SDValue Ops[] = { Chain, Value, StackSlot };
12517     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12518                                            Ops, DstTy, MMO);
12519     return std::make_pair(FIST, StackSlot);
12520   }
12521 }
12522
12523 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12524                               const X86Subtarget *Subtarget) {
12525   MVT VT = Op->getSimpleValueType(0);
12526   SDValue In = Op->getOperand(0);
12527   MVT InVT = In.getSimpleValueType();
12528   SDLoc dl(Op);
12529
12530   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12531     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12532
12533   // Optimize vectors in AVX mode:
12534   //
12535   //   v8i16 -> v8i32
12536   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12537   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12538   //   Concat upper and lower parts.
12539   //
12540   //   v4i32 -> v4i64
12541   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12542   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12543   //   Concat upper and lower parts.
12544   //
12545
12546   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12547       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12548       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12549     return SDValue();
12550
12551   if (Subtarget->hasInt256())
12552     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12553
12554   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12555   SDValue Undef = DAG.getUNDEF(InVT);
12556   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12557   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12558   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12559
12560   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12561                              VT.getVectorNumElements()/2);
12562
12563   OpLo = DAG.getBitcast(HVT, OpLo);
12564   OpHi = DAG.getBitcast(HVT, OpHi);
12565
12566   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12567 }
12568
12569 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12570                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12571   MVT VT = Op->getSimpleValueType(0);
12572   SDValue In = Op->getOperand(0);
12573   MVT InVT = In.getSimpleValueType();
12574   SDLoc DL(Op);
12575   unsigned int NumElts = VT.getVectorNumElements();
12576   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12577     return SDValue();
12578
12579   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12580     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12581
12582   assert(InVT.getVectorElementType() == MVT::i1);
12583   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12584   SDValue One =
12585    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12586   SDValue Zero =
12587    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12588
12589   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12590   if (VT.is512BitVector())
12591     return V;
12592   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12593 }
12594
12595 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12596                                SelectionDAG &DAG) {
12597   if (Subtarget->hasFp256())
12598     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12599       return Res;
12600
12601   return SDValue();
12602 }
12603
12604 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12605                                 SelectionDAG &DAG) {
12606   SDLoc DL(Op);
12607   MVT VT = Op.getSimpleValueType();
12608   SDValue In = Op.getOperand(0);
12609   MVT SVT = In.getSimpleValueType();
12610
12611   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12612     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12613
12614   if (Subtarget->hasFp256())
12615     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12616       return Res;
12617
12618   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12619          VT.getVectorNumElements() != SVT.getVectorNumElements());
12620   return SDValue();
12621 }
12622
12623 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12624   SDLoc DL(Op);
12625   MVT VT = Op.getSimpleValueType();
12626   SDValue In = Op.getOperand(0);
12627   MVT InVT = In.getSimpleValueType();
12628
12629   if (VT == MVT::i1) {
12630     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12631            "Invalid scalar TRUNCATE operation");
12632     if (InVT.getSizeInBits() >= 32)
12633       return SDValue();
12634     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12635     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12636   }
12637   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12638          "Invalid TRUNCATE operation");
12639
12640   // move vector to mask - truncate solution for SKX
12641   if (VT.getVectorElementType() == MVT::i1) {
12642     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12643         Subtarget->hasBWI())
12644       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12645     if ((InVT.is256BitVector() || InVT.is128BitVector())
12646         && InVT.getScalarSizeInBits() <= 16 &&
12647         Subtarget->hasBWI() && Subtarget->hasVLX())
12648       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12649     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12650         Subtarget->hasDQI())
12651       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12652     if ((InVT.is256BitVector() || InVT.is128BitVector())
12653         && InVT.getScalarSizeInBits() >= 32 &&
12654         Subtarget->hasDQI() && Subtarget->hasVLX())
12655       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12656   }
12657
12658   if (VT.getVectorElementType() == MVT::i1) {
12659     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12660     unsigned NumElts = InVT.getVectorNumElements();
12661     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12662     if (InVT.getSizeInBits() < 512) {
12663       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12664       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12665       InVT = ExtVT;
12666     }
12667
12668     SDValue OneV =
12669      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12670     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12671     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12672   }
12673
12674   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12675   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12676       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12677     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12678
12679   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12680     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12681     if (Subtarget->hasInt256()) {
12682       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12683       In = DAG.getBitcast(MVT::v8i32, In);
12684       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12685                                 ShufMask);
12686       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12687                          DAG.getIntPtrConstant(0, DL));
12688     }
12689
12690     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12691                                DAG.getIntPtrConstant(0, DL));
12692     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12693                                DAG.getIntPtrConstant(2, DL));
12694     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12695     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12696     static const int ShufMask[] = {0, 2, 4, 6};
12697     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12698   }
12699
12700   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12701     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12702     if (Subtarget->hasInt256()) {
12703       In = DAG.getBitcast(MVT::v32i8, In);
12704
12705       SmallVector<SDValue,32> pshufbMask;
12706       for (unsigned i = 0; i < 2; ++i) {
12707         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12708         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12709         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12710         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12711         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12712         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12713         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12714         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12715         for (unsigned j = 0; j < 8; ++j)
12716           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12717       }
12718       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12719       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12720       In = DAG.getBitcast(MVT::v4i64, In);
12721
12722       static const int ShufMask[] = {0,  2,  -1,  -1};
12723       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12724                                 &ShufMask[0]);
12725       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12726                        DAG.getIntPtrConstant(0, DL));
12727       return DAG.getBitcast(VT, In);
12728     }
12729
12730     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12731                                DAG.getIntPtrConstant(0, DL));
12732
12733     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12734                                DAG.getIntPtrConstant(4, DL));
12735
12736     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12737     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12738
12739     // The PSHUFB mask:
12740     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12741                                    -1, -1, -1, -1, -1, -1, -1, -1};
12742
12743     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12744     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12745     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12746
12747     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12748     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12749
12750     // The MOVLHPS Mask:
12751     static const int ShufMask2[] = {0, 1, 4, 5};
12752     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12753     return DAG.getBitcast(MVT::v8i16, res);
12754   }
12755
12756   // Handle truncation of V256 to V128 using shuffles.
12757   if (!VT.is128BitVector() || !InVT.is256BitVector())
12758     return SDValue();
12759
12760   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12761
12762   unsigned NumElems = VT.getVectorNumElements();
12763   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12764
12765   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12766   // Prepare truncation shuffle mask
12767   for (unsigned i = 0; i != NumElems; ++i)
12768     MaskVec[i] = i * 2;
12769   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12770                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12771   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12772                      DAG.getIntPtrConstant(0, DL));
12773 }
12774
12775 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12776                                            SelectionDAG &DAG) const {
12777   assert(!Op.getSimpleValueType().isVector());
12778
12779   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12780     /*IsSigned=*/ true, /*IsReplace=*/ false);
12781   SDValue FIST = Vals.first, StackSlot = Vals.second;
12782   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12783   if (!FIST.getNode())
12784     return Op;
12785
12786   if (StackSlot.getNode())
12787     // Load the result.
12788     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12789                        FIST, StackSlot, MachinePointerInfo(),
12790                        false, false, false, 0);
12791
12792   // The node is the result.
12793   return FIST;
12794 }
12795
12796 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12797                                            SelectionDAG &DAG) const {
12798   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12799     /*IsSigned=*/ false, /*IsReplace=*/ false);
12800   SDValue FIST = Vals.first, StackSlot = Vals.second;
12801   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12802   if (!FIST.getNode())
12803     return Op;
12804
12805   if (StackSlot.getNode())
12806     // Load the result.
12807     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12808                        FIST, StackSlot, MachinePointerInfo(),
12809                        false, false, false, 0);
12810
12811   // The node is the result.
12812   return FIST;
12813 }
12814
12815 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12816   SDLoc DL(Op);
12817   MVT VT = Op.getSimpleValueType();
12818   SDValue In = Op.getOperand(0);
12819   MVT SVT = In.getSimpleValueType();
12820
12821   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12822
12823   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12824                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12825                                  In, DAG.getUNDEF(SVT)));
12826 }
12827
12828 /// The only differences between FABS and FNEG are the mask and the logic op.
12829 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12830 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12831   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12832          "Wrong opcode for lowering FABS or FNEG.");
12833
12834   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12835
12836   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12837   // into an FNABS. We'll lower the FABS after that if it is still in use.
12838   if (IsFABS)
12839     for (SDNode *User : Op->uses())
12840       if (User->getOpcode() == ISD::FNEG)
12841         return Op;
12842
12843   SDLoc dl(Op);
12844   MVT VT = Op.getSimpleValueType();
12845
12846   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12847   // decide if we should generate a 16-byte constant mask when we only need 4 or
12848   // 8 bytes for the scalar case.
12849
12850   MVT LogicVT;
12851   MVT EltVT;
12852   unsigned NumElts;
12853
12854   if (VT.isVector()) {
12855     LogicVT = VT;
12856     EltVT = VT.getVectorElementType();
12857     NumElts = VT.getVectorNumElements();
12858   } else {
12859     // There are no scalar bitwise logical SSE/AVX instructions, so we
12860     // generate a 16-byte vector constant and logic op even for the scalar case.
12861     // Using a 16-byte mask allows folding the load of the mask with
12862     // the logic op, so it can save (~4 bytes) on code size.
12863     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12864     EltVT = VT;
12865     NumElts = (VT == MVT::f64) ? 2 : 4;
12866   }
12867
12868   unsigned EltBits = EltVT.getSizeInBits();
12869   LLVMContext *Context = DAG.getContext();
12870   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12871   APInt MaskElt =
12872     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12873   Constant *C = ConstantInt::get(*Context, MaskElt);
12874   C = ConstantVector::getSplat(NumElts, C);
12875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12876   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12877   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12878   SDValue Mask =
12879       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12880                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12881                   false, false, false, Alignment);
12882
12883   SDValue Op0 = Op.getOperand(0);
12884   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12885   unsigned LogicOp =
12886     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12887   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12888
12889   if (VT.isVector())
12890     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12891
12892   // For the scalar case extend to a 128-bit vector, perform the logic op,
12893   // and extract the scalar result back out.
12894   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12895   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12896   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12897                      DAG.getIntPtrConstant(0, dl));
12898 }
12899
12900 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12902   LLVMContext *Context = DAG.getContext();
12903   SDValue Op0 = Op.getOperand(0);
12904   SDValue Op1 = Op.getOperand(1);
12905   SDLoc dl(Op);
12906   MVT VT = Op.getSimpleValueType();
12907   MVT SrcVT = Op1.getSimpleValueType();
12908
12909   // If second operand is smaller, extend it first.
12910   if (SrcVT.bitsLT(VT)) {
12911     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12912     SrcVT = VT;
12913   }
12914   // And if it is bigger, shrink it first.
12915   if (SrcVT.bitsGT(VT)) {
12916     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12917     SrcVT = VT;
12918   }
12919
12920   // At this point the operands and the result should have the same
12921   // type, and that won't be f80 since that is not custom lowered.
12922
12923   const fltSemantics &Sem =
12924       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12925   const unsigned SizeInBits = VT.getSizeInBits();
12926
12927   SmallVector<Constant *, 4> CV(
12928       VT == MVT::f64 ? 2 : 4,
12929       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12930
12931   // First, clear all bits but the sign bit from the second operand (sign).
12932   CV[0] = ConstantFP::get(*Context,
12933                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12934   Constant *C = ConstantVector::get(CV);
12935   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12936   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12937
12938   // Perform all logic operations as 16-byte vectors because there are no
12939   // scalar FP logic instructions in SSE. This allows load folding of the
12940   // constants into the logic instructions.
12941   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12942   SDValue Mask1 =
12943       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12944                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12945                   false, false, false, 16);
12946   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12947   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12948
12949   // Next, clear the sign bit from the first operand (magnitude).
12950   // If it's a constant, we can clear it here.
12951   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12952     APFloat APF = Op0CN->getValueAPF();
12953     // If the magnitude is a positive zero, the sign bit alone is enough.
12954     if (APF.isPosZero())
12955       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12956                          DAG.getIntPtrConstant(0, dl));
12957     APF.clearSign();
12958     CV[0] = ConstantFP::get(*Context, APF);
12959   } else {
12960     CV[0] = ConstantFP::get(
12961         *Context,
12962         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12963   }
12964   C = ConstantVector::get(CV);
12965   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12966   SDValue Val =
12967       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12968                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12969                   false, false, false, 16);
12970   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12971   if (!isa<ConstantFPSDNode>(Op0)) {
12972     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12973     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12974   }
12975   // OR the magnitude value with the sign bit.
12976   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12977   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12978                      DAG.getIntPtrConstant(0, dl));
12979 }
12980
12981 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12982   SDValue N0 = Op.getOperand(0);
12983   SDLoc dl(Op);
12984   MVT VT = Op.getSimpleValueType();
12985
12986   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12987   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12988                                   DAG.getConstant(1, dl, VT));
12989   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12990 }
12991
12992 // Check whether an OR'd tree is PTEST-able.
12993 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12994                                       SelectionDAG &DAG) {
12995   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12996
12997   if (!Subtarget->hasSSE41())
12998     return SDValue();
12999
13000   if (!Op->hasOneUse())
13001     return SDValue();
13002
13003   SDNode *N = Op.getNode();
13004   SDLoc DL(N);
13005
13006   SmallVector<SDValue, 8> Opnds;
13007   DenseMap<SDValue, unsigned> VecInMap;
13008   SmallVector<SDValue, 8> VecIns;
13009   EVT VT = MVT::Other;
13010
13011   // Recognize a special case where a vector is casted into wide integer to
13012   // test all 0s.
13013   Opnds.push_back(N->getOperand(0));
13014   Opnds.push_back(N->getOperand(1));
13015
13016   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13017     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13018     // BFS traverse all OR'd operands.
13019     if (I->getOpcode() == ISD::OR) {
13020       Opnds.push_back(I->getOperand(0));
13021       Opnds.push_back(I->getOperand(1));
13022       // Re-evaluate the number of nodes to be traversed.
13023       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13024       continue;
13025     }
13026
13027     // Quit if a non-EXTRACT_VECTOR_ELT
13028     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13029       return SDValue();
13030
13031     // Quit if without a constant index.
13032     SDValue Idx = I->getOperand(1);
13033     if (!isa<ConstantSDNode>(Idx))
13034       return SDValue();
13035
13036     SDValue ExtractedFromVec = I->getOperand(0);
13037     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13038     if (M == VecInMap.end()) {
13039       VT = ExtractedFromVec.getValueType();
13040       // Quit if not 128/256-bit vector.
13041       if (!VT.is128BitVector() && !VT.is256BitVector())
13042         return SDValue();
13043       // Quit if not the same type.
13044       if (VecInMap.begin() != VecInMap.end() &&
13045           VT != VecInMap.begin()->first.getValueType())
13046         return SDValue();
13047       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13048       VecIns.push_back(ExtractedFromVec);
13049     }
13050     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13051   }
13052
13053   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13054          "Not extracted from 128-/256-bit vector.");
13055
13056   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13057
13058   for (DenseMap<SDValue, unsigned>::const_iterator
13059         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13060     // Quit if not all elements are used.
13061     if (I->second != FullMask)
13062       return SDValue();
13063   }
13064
13065   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13066
13067   // Cast all vectors into TestVT for PTEST.
13068   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13069     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13070
13071   // If more than one full vectors are evaluated, OR them first before PTEST.
13072   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13073     // Each iteration will OR 2 nodes and append the result until there is only
13074     // 1 node left, i.e. the final OR'd value of all vectors.
13075     SDValue LHS = VecIns[Slot];
13076     SDValue RHS = VecIns[Slot + 1];
13077     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13078   }
13079
13080   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13081                      VecIns.back(), VecIns.back());
13082 }
13083
13084 /// \brief return true if \c Op has a use that doesn't just read flags.
13085 static bool hasNonFlagsUse(SDValue Op) {
13086   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13087        ++UI) {
13088     SDNode *User = *UI;
13089     unsigned UOpNo = UI.getOperandNo();
13090     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13091       // Look pass truncate.
13092       UOpNo = User->use_begin().getOperandNo();
13093       User = *User->use_begin();
13094     }
13095
13096     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13097         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13098       return true;
13099   }
13100   return false;
13101 }
13102
13103 /// Emit nodes that will be selected as "test Op0,Op0", or something
13104 /// equivalent.
13105 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13106                                     SelectionDAG &DAG) const {
13107   if (Op.getValueType() == MVT::i1) {
13108     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13109     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13110                        DAG.getConstant(0, dl, MVT::i8));
13111   }
13112   // CF and OF aren't always set the way we want. Determine which
13113   // of these we need.
13114   bool NeedCF = false;
13115   bool NeedOF = false;
13116   switch (X86CC) {
13117   default: break;
13118   case X86::COND_A: case X86::COND_AE:
13119   case X86::COND_B: case X86::COND_BE:
13120     NeedCF = true;
13121     break;
13122   case X86::COND_G: case X86::COND_GE:
13123   case X86::COND_L: case X86::COND_LE:
13124   case X86::COND_O: case X86::COND_NO: {
13125     // Check if we really need to set the
13126     // Overflow flag. If NoSignedWrap is present
13127     // that is not actually needed.
13128     switch (Op->getOpcode()) {
13129     case ISD::ADD:
13130     case ISD::SUB:
13131     case ISD::MUL:
13132     case ISD::SHL: {
13133       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13134       if (BinNode->Flags.hasNoSignedWrap())
13135         break;
13136     }
13137     default:
13138       NeedOF = true;
13139       break;
13140     }
13141     break;
13142   }
13143   }
13144   // See if we can use the EFLAGS value from the operand instead of
13145   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13146   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13147   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13148     // Emit a CMP with 0, which is the TEST pattern.
13149     //if (Op.getValueType() == MVT::i1)
13150     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13151     //                     DAG.getConstant(0, MVT::i1));
13152     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13153                        DAG.getConstant(0, dl, Op.getValueType()));
13154   }
13155   unsigned Opcode = 0;
13156   unsigned NumOperands = 0;
13157
13158   // Truncate operations may prevent the merge of the SETCC instruction
13159   // and the arithmetic instruction before it. Attempt to truncate the operands
13160   // of the arithmetic instruction and use a reduced bit-width instruction.
13161   bool NeedTruncation = false;
13162   SDValue ArithOp = Op;
13163   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13164     SDValue Arith = Op->getOperand(0);
13165     // Both the trunc and the arithmetic op need to have one user each.
13166     if (Arith->hasOneUse())
13167       switch (Arith.getOpcode()) {
13168         default: break;
13169         case ISD::ADD:
13170         case ISD::SUB:
13171         case ISD::AND:
13172         case ISD::OR:
13173         case ISD::XOR: {
13174           NeedTruncation = true;
13175           ArithOp = Arith;
13176         }
13177       }
13178   }
13179
13180   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13181   // which may be the result of a CAST.  We use the variable 'Op', which is the
13182   // non-casted variable when we check for possible users.
13183   switch (ArithOp.getOpcode()) {
13184   case ISD::ADD:
13185     // Due to an isel shortcoming, be conservative if this add is likely to be
13186     // selected as part of a load-modify-store instruction. When the root node
13187     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13188     // uses of other nodes in the match, such as the ADD in this case. This
13189     // leads to the ADD being left around and reselected, with the result being
13190     // two adds in the output.  Alas, even if none our users are stores, that
13191     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13192     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13193     // climbing the DAG back to the root, and it doesn't seem to be worth the
13194     // effort.
13195     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13196          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13197       if (UI->getOpcode() != ISD::CopyToReg &&
13198           UI->getOpcode() != ISD::SETCC &&
13199           UI->getOpcode() != ISD::STORE)
13200         goto default_case;
13201
13202     if (ConstantSDNode *C =
13203         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13204       // An add of one will be selected as an INC.
13205       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13206         Opcode = X86ISD::INC;
13207         NumOperands = 1;
13208         break;
13209       }
13210
13211       // An add of negative one (subtract of one) will be selected as a DEC.
13212       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13213         Opcode = X86ISD::DEC;
13214         NumOperands = 1;
13215         break;
13216       }
13217     }
13218
13219     // Otherwise use a regular EFLAGS-setting add.
13220     Opcode = X86ISD::ADD;
13221     NumOperands = 2;
13222     break;
13223   case ISD::SHL:
13224   case ISD::SRL:
13225     // If we have a constant logical shift that's only used in a comparison
13226     // against zero turn it into an equivalent AND. This allows turning it into
13227     // a TEST instruction later.
13228     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13229         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13230       EVT VT = Op.getValueType();
13231       unsigned BitWidth = VT.getSizeInBits();
13232       unsigned ShAmt = Op->getConstantOperandVal(1);
13233       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13234         break;
13235       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13236                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13237                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13238       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13239         break;
13240       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13241                                 DAG.getConstant(Mask, dl, VT));
13242       DAG.ReplaceAllUsesWith(Op, New);
13243       Op = New;
13244     }
13245     break;
13246
13247   case ISD::AND:
13248     // If the primary and result isn't used, don't bother using X86ISD::AND,
13249     // because a TEST instruction will be better.
13250     if (!hasNonFlagsUse(Op))
13251       break;
13252     // FALL THROUGH
13253   case ISD::SUB:
13254   case ISD::OR:
13255   case ISD::XOR:
13256     // Due to the ISEL shortcoming noted above, be conservative if this op is
13257     // likely to be selected as part of a load-modify-store instruction.
13258     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13259            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13260       if (UI->getOpcode() == ISD::STORE)
13261         goto default_case;
13262
13263     // Otherwise use a regular EFLAGS-setting instruction.
13264     switch (ArithOp.getOpcode()) {
13265     default: llvm_unreachable("unexpected operator!");
13266     case ISD::SUB: Opcode = X86ISD::SUB; break;
13267     case ISD::XOR: Opcode = X86ISD::XOR; break;
13268     case ISD::AND: Opcode = X86ISD::AND; break;
13269     case ISD::OR: {
13270       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13271         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13272         if (EFLAGS.getNode())
13273           return EFLAGS;
13274       }
13275       Opcode = X86ISD::OR;
13276       break;
13277     }
13278     }
13279
13280     NumOperands = 2;
13281     break;
13282   case X86ISD::ADD:
13283   case X86ISD::SUB:
13284   case X86ISD::INC:
13285   case X86ISD::DEC:
13286   case X86ISD::OR:
13287   case X86ISD::XOR:
13288   case X86ISD::AND:
13289     return SDValue(Op.getNode(), 1);
13290   default:
13291   default_case:
13292     break;
13293   }
13294
13295   // If we found that truncation is beneficial, perform the truncation and
13296   // update 'Op'.
13297   if (NeedTruncation) {
13298     EVT VT = Op.getValueType();
13299     SDValue WideVal = Op->getOperand(0);
13300     EVT WideVT = WideVal.getValueType();
13301     unsigned ConvertedOp = 0;
13302     // Use a target machine opcode to prevent further DAGCombine
13303     // optimizations that may separate the arithmetic operations
13304     // from the setcc node.
13305     switch (WideVal.getOpcode()) {
13306       default: break;
13307       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13308       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13309       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13310       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13311       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13312     }
13313
13314     if (ConvertedOp) {
13315       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13316       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13317         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13318         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13319         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13320       }
13321     }
13322   }
13323
13324   if (Opcode == 0)
13325     // Emit a CMP with 0, which is the TEST pattern.
13326     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13327                        DAG.getConstant(0, dl, Op.getValueType()));
13328
13329   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13330   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13331
13332   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13333   DAG.ReplaceAllUsesWith(Op, New);
13334   return SDValue(New.getNode(), 1);
13335 }
13336
13337 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13338 /// equivalent.
13339 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13340                                    SDLoc dl, SelectionDAG &DAG) const {
13341   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13342     if (C->getAPIntValue() == 0)
13343       return EmitTest(Op0, X86CC, dl, DAG);
13344
13345      if (Op0.getValueType() == MVT::i1)
13346        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13347   }
13348
13349   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13350        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13351     // Do the comparison at i32 if it's smaller, besides the Atom case.
13352     // This avoids subregister aliasing issues. Keep the smaller reference
13353     // if we're optimizing for size, however, as that'll allow better folding
13354     // of memory operations.
13355     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13356         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13357         !Subtarget->isAtom()) {
13358       unsigned ExtendOp =
13359           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13360       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13361       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13362     }
13363     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13364     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13365     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13366                               Op0, Op1);
13367     return SDValue(Sub.getNode(), 1);
13368   }
13369   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13370 }
13371
13372 /// Convert a comparison if required by the subtarget.
13373 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13374                                                  SelectionDAG &DAG) const {
13375   // If the subtarget does not support the FUCOMI instruction, floating-point
13376   // comparisons have to be converted.
13377   if (Subtarget->hasCMov() ||
13378       Cmp.getOpcode() != X86ISD::CMP ||
13379       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13380       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13381     return Cmp;
13382
13383   // The instruction selector will select an FUCOM instruction instead of
13384   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13385   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13386   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13387   SDLoc dl(Cmp);
13388   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13389   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13390   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13391                             DAG.getConstant(8, dl, MVT::i8));
13392   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13393   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13394 }
13395
13396 /// The minimum architected relative accuracy is 2^-12. We need one
13397 /// Newton-Raphson step to have a good float result (24 bits of precision).
13398 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13399                                             DAGCombinerInfo &DCI,
13400                                             unsigned &RefinementSteps,
13401                                             bool &UseOneConstNR) const {
13402   EVT VT = Op.getValueType();
13403   const char *RecipOp;
13404
13405   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13406   // TODO: Add support for AVX512 (v16f32).
13407   // It is likely not profitable to do this for f64 because a double-precision
13408   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13409   // instructions: convert to single, rsqrtss, convert back to double, refine
13410   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13411   // along with FMA, this could be a throughput win.
13412   if (VT == MVT::f32 && Subtarget->hasSSE1())
13413     RecipOp = "sqrtf";
13414   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13415            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13416     RecipOp = "vec-sqrtf";
13417   else
13418     return SDValue();
13419
13420   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13421   if (!Recips.isEnabled(RecipOp))
13422     return SDValue();
13423
13424   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13425   UseOneConstNR = false;
13426   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13427 }
13428
13429 /// The minimum architected relative accuracy is 2^-12. We need one
13430 /// Newton-Raphson step to have a good float result (24 bits of precision).
13431 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13432                                             DAGCombinerInfo &DCI,
13433                                             unsigned &RefinementSteps) const {
13434   EVT VT = Op.getValueType();
13435   const char *RecipOp;
13436
13437   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13438   // TODO: Add support for AVX512 (v16f32).
13439   // It is likely not profitable to do this for f64 because a double-precision
13440   // reciprocal estimate with refinement on x86 prior to FMA requires
13441   // 15 instructions: convert to single, rcpss, convert back to double, refine
13442   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13443   // along with FMA, this could be a throughput win.
13444   if (VT == MVT::f32 && Subtarget->hasSSE1())
13445     RecipOp = "divf";
13446   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13447            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13448     RecipOp = "vec-divf";
13449   else
13450     return SDValue();
13451
13452   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13453   if (!Recips.isEnabled(RecipOp))
13454     return SDValue();
13455
13456   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13457   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13458 }
13459
13460 /// If we have at least two divisions that use the same divisor, convert to
13461 /// multplication by a reciprocal. This may need to be adjusted for a given
13462 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13463 /// This is because we still need one division to calculate the reciprocal and
13464 /// then we need two multiplies by that reciprocal as replacements for the
13465 /// original divisions.
13466 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13467   return 2;
13468 }
13469
13470 static bool isAllOnes(SDValue V) {
13471   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13472   return C && C->isAllOnesValue();
13473 }
13474
13475 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13476 /// if it's possible.
13477 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13478                                      SDLoc dl, SelectionDAG &DAG) const {
13479   SDValue Op0 = And.getOperand(0);
13480   SDValue Op1 = And.getOperand(1);
13481   if (Op0.getOpcode() == ISD::TRUNCATE)
13482     Op0 = Op0.getOperand(0);
13483   if (Op1.getOpcode() == ISD::TRUNCATE)
13484     Op1 = Op1.getOperand(0);
13485
13486   SDValue LHS, RHS;
13487   if (Op1.getOpcode() == ISD::SHL)
13488     std::swap(Op0, Op1);
13489   if (Op0.getOpcode() == ISD::SHL) {
13490     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13491       if (And00C->getZExtValue() == 1) {
13492         // If we looked past a truncate, check that it's only truncating away
13493         // known zeros.
13494         unsigned BitWidth = Op0.getValueSizeInBits();
13495         unsigned AndBitWidth = And.getValueSizeInBits();
13496         if (BitWidth > AndBitWidth) {
13497           APInt Zeros, Ones;
13498           DAG.computeKnownBits(Op0, Zeros, Ones);
13499           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13500             return SDValue();
13501         }
13502         LHS = Op1;
13503         RHS = Op0.getOperand(1);
13504       }
13505   } else if (Op1.getOpcode() == ISD::Constant) {
13506     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13507     uint64_t AndRHSVal = AndRHS->getZExtValue();
13508     SDValue AndLHS = Op0;
13509
13510     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13511       LHS = AndLHS.getOperand(0);
13512       RHS = AndLHS.getOperand(1);
13513     }
13514
13515     // Use BT if the immediate can't be encoded in a TEST instruction.
13516     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13517       LHS = AndLHS;
13518       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13519     }
13520   }
13521
13522   if (LHS.getNode()) {
13523     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13524     // instruction.  Since the shift amount is in-range-or-undefined, we know
13525     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13526     // the encoding for the i16 version is larger than the i32 version.
13527     // Also promote i16 to i32 for performance / code size reason.
13528     if (LHS.getValueType() == MVT::i8 ||
13529         LHS.getValueType() == MVT::i16)
13530       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13531
13532     // If the operand types disagree, extend the shift amount to match.  Since
13533     // BT ignores high bits (like shifts) we can use anyextend.
13534     if (LHS.getValueType() != RHS.getValueType())
13535       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13536
13537     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13538     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13539     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13540                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13541   }
13542
13543   return SDValue();
13544 }
13545
13546 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13547 /// mask CMPs.
13548 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13549                               SDValue &Op1) {
13550   unsigned SSECC;
13551   bool Swap = false;
13552
13553   // SSE Condition code mapping:
13554   //  0 - EQ
13555   //  1 - LT
13556   //  2 - LE
13557   //  3 - UNORD
13558   //  4 - NEQ
13559   //  5 - NLT
13560   //  6 - NLE
13561   //  7 - ORD
13562   switch (SetCCOpcode) {
13563   default: llvm_unreachable("Unexpected SETCC condition");
13564   case ISD::SETOEQ:
13565   case ISD::SETEQ:  SSECC = 0; break;
13566   case ISD::SETOGT:
13567   case ISD::SETGT:  Swap = true; // Fallthrough
13568   case ISD::SETLT:
13569   case ISD::SETOLT: SSECC = 1; break;
13570   case ISD::SETOGE:
13571   case ISD::SETGE:  Swap = true; // Fallthrough
13572   case ISD::SETLE:
13573   case ISD::SETOLE: SSECC = 2; break;
13574   case ISD::SETUO:  SSECC = 3; break;
13575   case ISD::SETUNE:
13576   case ISD::SETNE:  SSECC = 4; break;
13577   case ISD::SETULE: Swap = true; // Fallthrough
13578   case ISD::SETUGE: SSECC = 5; break;
13579   case ISD::SETULT: Swap = true; // Fallthrough
13580   case ISD::SETUGT: SSECC = 6; break;
13581   case ISD::SETO:   SSECC = 7; break;
13582   case ISD::SETUEQ:
13583   case ISD::SETONE: SSECC = 8; break;
13584   }
13585   if (Swap)
13586     std::swap(Op0, Op1);
13587
13588   return SSECC;
13589 }
13590
13591 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13592 // ones, and then concatenate the result back.
13593 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13594   MVT VT = Op.getSimpleValueType();
13595
13596   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13597          "Unsupported value type for operation");
13598
13599   unsigned NumElems = VT.getVectorNumElements();
13600   SDLoc dl(Op);
13601   SDValue CC = Op.getOperand(2);
13602
13603   // Extract the LHS vectors
13604   SDValue LHS = Op.getOperand(0);
13605   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13606   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13607
13608   // Extract the RHS vectors
13609   SDValue RHS = Op.getOperand(1);
13610   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13611   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13612
13613   // Issue the operation on the smaller types and concatenate the result back
13614   MVT EltVT = VT.getVectorElementType();
13615   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13616   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13617                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13618                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13619 }
13620
13621 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13622   SDValue Op0 = Op.getOperand(0);
13623   SDValue Op1 = Op.getOperand(1);
13624   SDValue CC = Op.getOperand(2);
13625   MVT VT = Op.getSimpleValueType();
13626   SDLoc dl(Op);
13627
13628   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13629          "Unexpected type for boolean compare operation");
13630   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13631   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13632                                DAG.getConstant(-1, dl, VT));
13633   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13634                                DAG.getConstant(-1, dl, VT));
13635   switch (SetCCOpcode) {
13636   default: llvm_unreachable("Unexpected SETCC condition");
13637   case ISD::SETEQ:
13638     // (x == y) -> ~(x ^ y)
13639     return DAG.getNode(ISD::XOR, dl, VT,
13640                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13641                        DAG.getConstant(-1, dl, VT));
13642   case ISD::SETNE:
13643     // (x != y) -> (x ^ y)
13644     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13645   case ISD::SETUGT:
13646   case ISD::SETGT:
13647     // (x > y) -> (x & ~y)
13648     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13649   case ISD::SETULT:
13650   case ISD::SETLT:
13651     // (x < y) -> (~x & y)
13652     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13653   case ISD::SETULE:
13654   case ISD::SETLE:
13655     // (x <= y) -> (~x | y)
13656     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13657   case ISD::SETUGE:
13658   case ISD::SETGE:
13659     // (x >=y) -> (x | ~y)
13660     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13661   }
13662 }
13663
13664 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13665                                      const X86Subtarget *Subtarget) {
13666   SDValue Op0 = Op.getOperand(0);
13667   SDValue Op1 = Op.getOperand(1);
13668   SDValue CC = Op.getOperand(2);
13669   MVT VT = Op.getSimpleValueType();
13670   SDLoc dl(Op);
13671
13672   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13673          Op.getValueType().getScalarType() == MVT::i1 &&
13674          "Cannot set masked compare for this operation");
13675
13676   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13677   unsigned  Opc = 0;
13678   bool Unsigned = false;
13679   bool Swap = false;
13680   unsigned SSECC;
13681   switch (SetCCOpcode) {
13682   default: llvm_unreachable("Unexpected SETCC condition");
13683   case ISD::SETNE:  SSECC = 4; break;
13684   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13685   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13686   case ISD::SETLT:  Swap = true; //fall-through
13687   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13688   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13689   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13690   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13691   case ISD::SETULE: Unsigned = true; //fall-through
13692   case ISD::SETLE:  SSECC = 2; break;
13693   }
13694
13695   if (Swap)
13696     std::swap(Op0, Op1);
13697   if (Opc)
13698     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13699   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13700   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13701                      DAG.getConstant(SSECC, dl, MVT::i8));
13702 }
13703
13704 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13705 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13706 /// return an empty value.
13707 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13708 {
13709   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13710   if (!BV)
13711     return SDValue();
13712
13713   MVT VT = Op1.getSimpleValueType();
13714   MVT EVT = VT.getVectorElementType();
13715   unsigned n = VT.getVectorNumElements();
13716   SmallVector<SDValue, 8> ULTOp1;
13717
13718   for (unsigned i = 0; i < n; ++i) {
13719     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13720     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13721       return SDValue();
13722
13723     // Avoid underflow.
13724     APInt Val = Elt->getAPIntValue();
13725     if (Val == 0)
13726       return SDValue();
13727
13728     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13729   }
13730
13731   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13732 }
13733
13734 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13735                            SelectionDAG &DAG) {
13736   SDValue Op0 = Op.getOperand(0);
13737   SDValue Op1 = Op.getOperand(1);
13738   SDValue CC = Op.getOperand(2);
13739   MVT VT = Op.getSimpleValueType();
13740   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13741   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13742   SDLoc dl(Op);
13743
13744   if (isFP) {
13745 #ifndef NDEBUG
13746     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13747     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13748 #endif
13749
13750     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13751     unsigned Opc = X86ISD::CMPP;
13752     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13753       assert(VT.getVectorNumElements() <= 16);
13754       Opc = X86ISD::CMPM;
13755     }
13756     // In the two special cases we can't handle, emit two comparisons.
13757     if (SSECC == 8) {
13758       unsigned CC0, CC1;
13759       unsigned CombineOpc;
13760       if (SetCCOpcode == ISD::SETUEQ) {
13761         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13762       } else {
13763         assert(SetCCOpcode == ISD::SETONE);
13764         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13765       }
13766
13767       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13768                                  DAG.getConstant(CC0, dl, MVT::i8));
13769       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13770                                  DAG.getConstant(CC1, dl, MVT::i8));
13771       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13772     }
13773     // Handle all other FP comparisons here.
13774     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13775                        DAG.getConstant(SSECC, dl, MVT::i8));
13776   }
13777
13778   // Break 256-bit integer vector compare into smaller ones.
13779   if (VT.is256BitVector() && !Subtarget->hasInt256())
13780     return Lower256IntVSETCC(Op, DAG);
13781
13782   EVT OpVT = Op1.getValueType();
13783   if (OpVT.getVectorElementType() == MVT::i1)
13784     return LowerBoolVSETCC_AVX512(Op, DAG);
13785
13786   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13787   if (Subtarget->hasAVX512()) {
13788     if (Op1.getValueType().is512BitVector() ||
13789         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13790         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13791       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13792
13793     // In AVX-512 architecture setcc returns mask with i1 elements,
13794     // But there is no compare instruction for i8 and i16 elements in KNL.
13795     // We are not talking about 512-bit operands in this case, these
13796     // types are illegal.
13797     if (MaskResult &&
13798         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13799          OpVT.getVectorElementType().getSizeInBits() >= 8))
13800       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13801                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13802   }
13803
13804   // We are handling one of the integer comparisons here.  Since SSE only has
13805   // GT and EQ comparisons for integer, swapping operands and multiple
13806   // operations may be required for some comparisons.
13807   unsigned Opc;
13808   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13809   bool Subus = false;
13810
13811   switch (SetCCOpcode) {
13812   default: llvm_unreachable("Unexpected SETCC condition");
13813   case ISD::SETNE:  Invert = true;
13814   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13815   case ISD::SETLT:  Swap = true;
13816   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13817   case ISD::SETGE:  Swap = true;
13818   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13819                     Invert = true; break;
13820   case ISD::SETULT: Swap = true;
13821   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13822                     FlipSigns = true; break;
13823   case ISD::SETUGE: Swap = true;
13824   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13825                     FlipSigns = true; Invert = true; break;
13826   }
13827
13828   // Special case: Use min/max operations for SETULE/SETUGE
13829   MVT VET = VT.getVectorElementType();
13830   bool hasMinMax =
13831        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13832     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13833
13834   if (hasMinMax) {
13835     switch (SetCCOpcode) {
13836     default: break;
13837     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13838     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13839     }
13840
13841     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13842   }
13843
13844   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13845   if (!MinMax && hasSubus) {
13846     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13847     // Op0 u<= Op1:
13848     //   t = psubus Op0, Op1
13849     //   pcmpeq t, <0..0>
13850     switch (SetCCOpcode) {
13851     default: break;
13852     case ISD::SETULT: {
13853       // If the comparison is against a constant we can turn this into a
13854       // setule.  With psubus, setule does not require a swap.  This is
13855       // beneficial because the constant in the register is no longer
13856       // destructed as the destination so it can be hoisted out of a loop.
13857       // Only do this pre-AVX since vpcmp* is no longer destructive.
13858       if (Subtarget->hasAVX())
13859         break;
13860       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13861       if (ULEOp1.getNode()) {
13862         Op1 = ULEOp1;
13863         Subus = true; Invert = false; Swap = false;
13864       }
13865       break;
13866     }
13867     // Psubus is better than flip-sign because it requires no inversion.
13868     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13869     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13870     }
13871
13872     if (Subus) {
13873       Opc = X86ISD::SUBUS;
13874       FlipSigns = false;
13875     }
13876   }
13877
13878   if (Swap)
13879     std::swap(Op0, Op1);
13880
13881   // Check that the operation in question is available (most are plain SSE2,
13882   // but PCMPGTQ and PCMPEQQ have different requirements).
13883   if (VT == MVT::v2i64) {
13884     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13885       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13886
13887       // First cast everything to the right type.
13888       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13889       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13890
13891       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13892       // bits of the inputs before performing those operations. The lower
13893       // compare is always unsigned.
13894       SDValue SB;
13895       if (FlipSigns) {
13896         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13897       } else {
13898         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13899         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13900         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13901                          Sign, Zero, Sign, Zero);
13902       }
13903       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13904       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13905
13906       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13907       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13908       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13909
13910       // Create masks for only the low parts/high parts of the 64 bit integers.
13911       static const int MaskHi[] = { 1, 1, 3, 3 };
13912       static const int MaskLo[] = { 0, 0, 2, 2 };
13913       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13914       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13915       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13916
13917       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13918       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13919
13920       if (Invert)
13921         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13922
13923       return DAG.getBitcast(VT, Result);
13924     }
13925
13926     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13927       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13928       // pcmpeqd + pshufd + pand.
13929       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13930
13931       // First cast everything to the right type.
13932       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13933       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13934
13935       // Do the compare.
13936       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13937
13938       // Make sure the lower and upper halves are both all-ones.
13939       static const int Mask[] = { 1, 0, 3, 2 };
13940       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13941       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13942
13943       if (Invert)
13944         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13945
13946       return DAG.getBitcast(VT, Result);
13947     }
13948   }
13949
13950   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13951   // bits of the inputs before performing those operations.
13952   if (FlipSigns) {
13953     EVT EltVT = VT.getVectorElementType();
13954     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13955                                  VT);
13956     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13957     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13958   }
13959
13960   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13961
13962   // If the logical-not of the result is required, perform that now.
13963   if (Invert)
13964     Result = DAG.getNOT(dl, Result, VT);
13965
13966   if (MinMax)
13967     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13968
13969   if (Subus)
13970     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13971                          getZeroVector(VT, Subtarget, DAG, dl));
13972
13973   return Result;
13974 }
13975
13976 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13977
13978   MVT VT = Op.getSimpleValueType();
13979
13980   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13981
13982   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13983          && "SetCC type must be 8-bit or 1-bit integer");
13984   SDValue Op0 = Op.getOperand(0);
13985   SDValue Op1 = Op.getOperand(1);
13986   SDLoc dl(Op);
13987   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13988
13989   // Optimize to BT if possible.
13990   // Lower (X & (1 << N)) == 0 to BT(X, N).
13991   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13992   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13993   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13994       Op1.getOpcode() == ISD::Constant &&
13995       cast<ConstantSDNode>(Op1)->isNullValue() &&
13996       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13997     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13998     if (NewSetCC.getNode()) {
13999       if (VT == MVT::i1)
14000         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14001       return NewSetCC;
14002     }
14003   }
14004
14005   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14006   // these.
14007   if (Op1.getOpcode() == ISD::Constant &&
14008       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14009        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14010       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14011
14012     // If the input is a setcc, then reuse the input setcc or use a new one with
14013     // the inverted condition.
14014     if (Op0.getOpcode() == X86ISD::SETCC) {
14015       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14016       bool Invert = (CC == ISD::SETNE) ^
14017         cast<ConstantSDNode>(Op1)->isNullValue();
14018       if (!Invert)
14019         return Op0;
14020
14021       CCode = X86::GetOppositeBranchCondition(CCode);
14022       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14023                                   DAG.getConstant(CCode, dl, MVT::i8),
14024                                   Op0.getOperand(1));
14025       if (VT == MVT::i1)
14026         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14027       return SetCC;
14028     }
14029   }
14030   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14031       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14032       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14033
14034     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14035     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14036   }
14037
14038   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14039   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14040   if (X86CC == X86::COND_INVALID)
14041     return SDValue();
14042
14043   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14044   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14045   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14046                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14047   if (VT == MVT::i1)
14048     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14049   return SetCC;
14050 }
14051
14052 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14053 static bool isX86LogicalCmp(SDValue Op) {
14054   unsigned Opc = Op.getNode()->getOpcode();
14055   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14056       Opc == X86ISD::SAHF)
14057     return true;
14058   if (Op.getResNo() == 1 &&
14059       (Opc == X86ISD::ADD ||
14060        Opc == X86ISD::SUB ||
14061        Opc == X86ISD::ADC ||
14062        Opc == X86ISD::SBB ||
14063        Opc == X86ISD::SMUL ||
14064        Opc == X86ISD::UMUL ||
14065        Opc == X86ISD::INC ||
14066        Opc == X86ISD::DEC ||
14067        Opc == X86ISD::OR ||
14068        Opc == X86ISD::XOR ||
14069        Opc == X86ISD::AND))
14070     return true;
14071
14072   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14073     return true;
14074
14075   return false;
14076 }
14077
14078 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14079   if (V.getOpcode() != ISD::TRUNCATE)
14080     return false;
14081
14082   SDValue VOp0 = V.getOperand(0);
14083   unsigned InBits = VOp0.getValueSizeInBits();
14084   unsigned Bits = V.getValueSizeInBits();
14085   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14086 }
14087
14088 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14089   bool addTest = true;
14090   SDValue Cond  = Op.getOperand(0);
14091   SDValue Op1 = Op.getOperand(1);
14092   SDValue Op2 = Op.getOperand(2);
14093   SDLoc DL(Op);
14094   EVT VT = Op1.getValueType();
14095   SDValue CC;
14096
14097   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14098   // are available or VBLENDV if AVX is available.
14099   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14100   if (Cond.getOpcode() == ISD::SETCC &&
14101       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14102        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14103       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14104     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14105     int SSECC = translateX86FSETCC(
14106         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14107
14108     if (SSECC != 8) {
14109       if (Subtarget->hasAVX512()) {
14110         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14111                                   DAG.getConstant(SSECC, DL, MVT::i8));
14112         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14113       }
14114
14115       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14116                                 DAG.getConstant(SSECC, DL, MVT::i8));
14117
14118       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14119       // of 3 logic instructions for size savings and potentially speed.
14120       // Unfortunately, there is no scalar form of VBLENDV.
14121
14122       // If either operand is a constant, don't try this. We can expect to
14123       // optimize away at least one of the logic instructions later in that
14124       // case, so that sequence would be faster than a variable blend.
14125
14126       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14127       // uses XMM0 as the selection register. That may need just as many
14128       // instructions as the AND/ANDN/OR sequence due to register moves, so
14129       // don't bother.
14130
14131       if (Subtarget->hasAVX() &&
14132           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14133
14134         // Convert to vectors, do a VSELECT, and convert back to scalar.
14135         // All of the conversions should be optimized away.
14136
14137         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14138         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14139         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14140         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14141
14142         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14143         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14144
14145         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14146
14147         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14148                            VSel, DAG.getIntPtrConstant(0, DL));
14149       }
14150       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14151       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14152       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14153     }
14154   }
14155
14156   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14157     SDValue Op1Scalar;
14158     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14159       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14160     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14161       Op1Scalar = Op1.getOperand(0);
14162     SDValue Op2Scalar;
14163     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14164       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14165     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14166       Op2Scalar = Op2.getOperand(0);
14167     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14168       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14169                                       Op1Scalar.getValueType(),
14170                                       Cond, Op1Scalar, Op2Scalar);
14171       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14172         return DAG.getBitcast(VT, newSelect);
14173       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14174       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14175                          DAG.getIntPtrConstant(0, DL));
14176     }
14177   }
14178
14179   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14180     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14181     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14182                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14183     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14184                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14185     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14186                                     Cond, Op1, Op2);
14187     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14188   }
14189
14190   if (Cond.getOpcode() == ISD::SETCC) {
14191     SDValue NewCond = LowerSETCC(Cond, DAG);
14192     if (NewCond.getNode())
14193       Cond = NewCond;
14194   }
14195
14196   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14197   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14198   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14199   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14200   if (Cond.getOpcode() == X86ISD::SETCC &&
14201       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14202       isZero(Cond.getOperand(1).getOperand(1))) {
14203     SDValue Cmp = Cond.getOperand(1);
14204
14205     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14206
14207     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14208         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14209       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14210
14211       SDValue CmpOp0 = Cmp.getOperand(0);
14212       // Apply further optimizations for special cases
14213       // (select (x != 0), -1, 0) -> neg & sbb
14214       // (select (x == 0), 0, -1) -> neg & sbb
14215       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14216         if (YC->isNullValue() &&
14217             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14218           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14219           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14220                                     DAG.getConstant(0, DL,
14221                                                     CmpOp0.getValueType()),
14222                                     CmpOp0);
14223           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14224                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14225                                     SDValue(Neg.getNode(), 1));
14226           return Res;
14227         }
14228
14229       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14230                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14231       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14232
14233       SDValue Res =   // Res = 0 or -1.
14234         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14235                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14236
14237       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14238         Res = DAG.getNOT(DL, Res, Res.getValueType());
14239
14240       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14241       if (!N2C || !N2C->isNullValue())
14242         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14243       return Res;
14244     }
14245   }
14246
14247   // Look past (and (setcc_carry (cmp ...)), 1).
14248   if (Cond.getOpcode() == ISD::AND &&
14249       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14250     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14251     if (C && C->getAPIntValue() == 1)
14252       Cond = Cond.getOperand(0);
14253   }
14254
14255   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14256   // setting operand in place of the X86ISD::SETCC.
14257   unsigned CondOpcode = Cond.getOpcode();
14258   if (CondOpcode == X86ISD::SETCC ||
14259       CondOpcode == X86ISD::SETCC_CARRY) {
14260     CC = Cond.getOperand(0);
14261
14262     SDValue Cmp = Cond.getOperand(1);
14263     unsigned Opc = Cmp.getOpcode();
14264     MVT VT = Op.getSimpleValueType();
14265
14266     bool IllegalFPCMov = false;
14267     if (VT.isFloatingPoint() && !VT.isVector() &&
14268         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14269       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14270
14271     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14272         Opc == X86ISD::BT) { // FIXME
14273       Cond = Cmp;
14274       addTest = false;
14275     }
14276   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14277              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14278              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14279               Cond.getOperand(0).getValueType() != MVT::i8)) {
14280     SDValue LHS = Cond.getOperand(0);
14281     SDValue RHS = Cond.getOperand(1);
14282     unsigned X86Opcode;
14283     unsigned X86Cond;
14284     SDVTList VTs;
14285     switch (CondOpcode) {
14286     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14287     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14288     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14289     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14290     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14291     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14292     default: llvm_unreachable("unexpected overflowing operator");
14293     }
14294     if (CondOpcode == ISD::UMULO)
14295       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14296                           MVT::i32);
14297     else
14298       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14299
14300     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14301
14302     if (CondOpcode == ISD::UMULO)
14303       Cond = X86Op.getValue(2);
14304     else
14305       Cond = X86Op.getValue(1);
14306
14307     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14308     addTest = false;
14309   }
14310
14311   if (addTest) {
14312     // Look past the truncate if the high bits are known zero.
14313     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14314       Cond = Cond.getOperand(0);
14315
14316     // We know the result of AND is compared against zero. Try to match
14317     // it to BT.
14318     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14319       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14320       if (NewSetCC.getNode()) {
14321         CC = NewSetCC.getOperand(0);
14322         Cond = NewSetCC.getOperand(1);
14323         addTest = false;
14324       }
14325     }
14326   }
14327
14328   if (addTest) {
14329     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14330     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14331   }
14332
14333   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14334   // a <  b ?  0 : -1 -> RES = setcc_carry
14335   // a >= b ? -1 :  0 -> RES = setcc_carry
14336   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14337   if (Cond.getOpcode() == X86ISD::SUB) {
14338     Cond = ConvertCmpIfNecessary(Cond, DAG);
14339     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14340
14341     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14342         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14343       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14344                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14345                                 Cond);
14346       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14347         return DAG.getNOT(DL, Res, Res.getValueType());
14348       return Res;
14349     }
14350   }
14351
14352   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14353   // widen the cmov and push the truncate through. This avoids introducing a new
14354   // branch during isel and doesn't add any extensions.
14355   if (Op.getValueType() == MVT::i8 &&
14356       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14357     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14358     if (T1.getValueType() == T2.getValueType() &&
14359         // Blacklist CopyFromReg to avoid partial register stalls.
14360         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14361       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14362       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14363       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14364     }
14365   }
14366
14367   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14368   // condition is true.
14369   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14370   SDValue Ops[] = { Op2, Op1, CC, Cond };
14371   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14372 }
14373
14374 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14375                                        const X86Subtarget *Subtarget,
14376                                        SelectionDAG &DAG) {
14377   MVT VT = Op->getSimpleValueType(0);
14378   SDValue In = Op->getOperand(0);
14379   MVT InVT = In.getSimpleValueType();
14380   MVT VTElt = VT.getVectorElementType();
14381   MVT InVTElt = InVT.getVectorElementType();
14382   SDLoc dl(Op);
14383
14384   // SKX processor
14385   if ((InVTElt == MVT::i1) &&
14386       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14387         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14388
14389        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14390         VTElt.getSizeInBits() <= 16)) ||
14391
14392        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14393         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14394
14395        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14396         VTElt.getSizeInBits() >= 32))))
14397     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14398
14399   unsigned int NumElts = VT.getVectorNumElements();
14400
14401   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14402     return SDValue();
14403
14404   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14405     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14406       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14407     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14408   }
14409
14410   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14411   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14412   SDValue NegOne =
14413    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14414                    ExtVT);
14415   SDValue Zero =
14416    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14417
14418   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14419   if (VT.is512BitVector())
14420     return V;
14421   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14422 }
14423
14424 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14425                                              const X86Subtarget *Subtarget,
14426                                              SelectionDAG &DAG) {
14427   SDValue In = Op->getOperand(0);
14428   MVT VT = Op->getSimpleValueType(0);
14429   MVT InVT = In.getSimpleValueType();
14430   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14431
14432   MVT InSVT = InVT.getScalarType();
14433   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14434
14435   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14436     return SDValue();
14437   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14438     return SDValue();
14439
14440   SDLoc dl(Op);
14441
14442   // SSE41 targets can use the pmovsx* instructions directly.
14443   if (Subtarget->hasSSE41())
14444     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14445
14446   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14447   SDValue Curr = In;
14448   MVT CurrVT = InVT;
14449
14450   // As SRAI is only available on i16/i32 types, we expand only up to i32
14451   // and handle i64 separately.
14452   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14453     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14454     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14455     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14456     Curr = DAG.getBitcast(CurrVT, Curr);
14457   }
14458
14459   SDValue SignExt = Curr;
14460   if (CurrVT != InVT) {
14461     unsigned SignExtShift =
14462         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14463     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14464                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14465   }
14466
14467   if (CurrVT == VT)
14468     return SignExt;
14469
14470   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14471     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14472                                DAG.getConstant(31, dl, MVT::i8));
14473     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14474     return DAG.getBitcast(VT, Ext);
14475   }
14476
14477   return SDValue();
14478 }
14479
14480 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14481                                 SelectionDAG &DAG) {
14482   MVT VT = Op->getSimpleValueType(0);
14483   SDValue In = Op->getOperand(0);
14484   MVT InVT = In.getSimpleValueType();
14485   SDLoc dl(Op);
14486
14487   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14488     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14489
14490   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14491       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14492       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14493     return SDValue();
14494
14495   if (Subtarget->hasInt256())
14496     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14497
14498   // Optimize vectors in AVX mode
14499   // Sign extend  v8i16 to v8i32 and
14500   //              v4i32 to v4i64
14501   //
14502   // Divide input vector into two parts
14503   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14504   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14505   // concat the vectors to original VT
14506
14507   unsigned NumElems = InVT.getVectorNumElements();
14508   SDValue Undef = DAG.getUNDEF(InVT);
14509
14510   SmallVector<int,8> ShufMask1(NumElems, -1);
14511   for (unsigned i = 0; i != NumElems/2; ++i)
14512     ShufMask1[i] = i;
14513
14514   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14515
14516   SmallVector<int,8> ShufMask2(NumElems, -1);
14517   for (unsigned i = 0; i != NumElems/2; ++i)
14518     ShufMask2[i] = i + NumElems/2;
14519
14520   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14521
14522   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14523                                 VT.getVectorNumElements()/2);
14524
14525   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14526   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14527
14528   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14529 }
14530
14531 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14532 // may emit an illegal shuffle but the expansion is still better than scalar
14533 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14534 // we'll emit a shuffle and a arithmetic shift.
14535 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14536 // TODO: It is possible to support ZExt by zeroing the undef values during
14537 // the shuffle phase or after the shuffle.
14538 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14539                                  SelectionDAG &DAG) {
14540   MVT RegVT = Op.getSimpleValueType();
14541   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14542   assert(RegVT.isInteger() &&
14543          "We only custom lower integer vector sext loads.");
14544
14545   // Nothing useful we can do without SSE2 shuffles.
14546   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14547
14548   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14549   SDLoc dl(Ld);
14550   EVT MemVT = Ld->getMemoryVT();
14551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14552   unsigned RegSz = RegVT.getSizeInBits();
14553
14554   ISD::LoadExtType Ext = Ld->getExtensionType();
14555
14556   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14557          && "Only anyext and sext are currently implemented.");
14558   assert(MemVT != RegVT && "Cannot extend to the same type");
14559   assert(MemVT.isVector() && "Must load a vector from memory");
14560
14561   unsigned NumElems = RegVT.getVectorNumElements();
14562   unsigned MemSz = MemVT.getSizeInBits();
14563   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14564
14565   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14566     // The only way in which we have a legal 256-bit vector result but not the
14567     // integer 256-bit operations needed to directly lower a sextload is if we
14568     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14569     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14570     // correctly legalized. We do this late to allow the canonical form of
14571     // sextload to persist throughout the rest of the DAG combiner -- it wants
14572     // to fold together any extensions it can, and so will fuse a sign_extend
14573     // of an sextload into a sextload targeting a wider value.
14574     SDValue Load;
14575     if (MemSz == 128) {
14576       // Just switch this to a normal load.
14577       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14578                                        "it must be a legal 128-bit vector "
14579                                        "type!");
14580       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14581                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14582                   Ld->isInvariant(), Ld->getAlignment());
14583     } else {
14584       assert(MemSz < 128 &&
14585              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14586       // Do an sext load to a 128-bit vector type. We want to use the same
14587       // number of elements, but elements half as wide. This will end up being
14588       // recursively lowered by this routine, but will succeed as we definitely
14589       // have all the necessary features if we're using AVX1.
14590       EVT HalfEltVT =
14591           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14592       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14593       Load =
14594           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14595                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14596                          Ld->isNonTemporal(), Ld->isInvariant(),
14597                          Ld->getAlignment());
14598     }
14599
14600     // Replace chain users with the new chain.
14601     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14602     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14603
14604     // Finally, do a normal sign-extend to the desired register.
14605     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14606   }
14607
14608   // All sizes must be a power of two.
14609   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14610          "Non-power-of-two elements are not custom lowered!");
14611
14612   // Attempt to load the original value using scalar loads.
14613   // Find the largest scalar type that divides the total loaded size.
14614   MVT SclrLoadTy = MVT::i8;
14615   for (MVT Tp : MVT::integer_valuetypes()) {
14616     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14617       SclrLoadTy = Tp;
14618     }
14619   }
14620
14621   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14622   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14623       (64 <= MemSz))
14624     SclrLoadTy = MVT::f64;
14625
14626   // Calculate the number of scalar loads that we need to perform
14627   // in order to load our vector from memory.
14628   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14629
14630   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14631          "Can only lower sext loads with a single scalar load!");
14632
14633   unsigned loadRegZize = RegSz;
14634   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14635     loadRegZize = 128;
14636
14637   // Represent our vector as a sequence of elements which are the
14638   // largest scalar that we can load.
14639   EVT LoadUnitVecVT = EVT::getVectorVT(
14640       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14641
14642   // Represent the data using the same element type that is stored in
14643   // memory. In practice, we ''widen'' MemVT.
14644   EVT WideVecVT =
14645       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14646                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14647
14648   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14649          "Invalid vector type");
14650
14651   // We can't shuffle using an illegal type.
14652   assert(TLI.isTypeLegal(WideVecVT) &&
14653          "We only lower types that form legal widened vector types");
14654
14655   SmallVector<SDValue, 8> Chains;
14656   SDValue Ptr = Ld->getBasePtr();
14657   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14658                                       TLI.getPointerTy(DAG.getDataLayout()));
14659   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14660
14661   for (unsigned i = 0; i < NumLoads; ++i) {
14662     // Perform a single load.
14663     SDValue ScalarLoad =
14664         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14665                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14666                     Ld->getAlignment());
14667     Chains.push_back(ScalarLoad.getValue(1));
14668     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14669     // another round of DAGCombining.
14670     if (i == 0)
14671       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14672     else
14673       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14674                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14675
14676     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14677   }
14678
14679   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14680
14681   // Bitcast the loaded value to a vector of the original element type, in
14682   // the size of the target vector type.
14683   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14684   unsigned SizeRatio = RegSz / MemSz;
14685
14686   if (Ext == ISD::SEXTLOAD) {
14687     // If we have SSE4.1, we can directly emit a VSEXT node.
14688     if (Subtarget->hasSSE41()) {
14689       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14690       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14691       return Sext;
14692     }
14693
14694     // Otherwise we'll shuffle the small elements in the high bits of the
14695     // larger type and perform an arithmetic shift. If the shift is not legal
14696     // it's better to scalarize.
14697     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14698            "We can't implement a sext load without an arithmetic right shift!");
14699
14700     // Redistribute the loaded elements into the different locations.
14701     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14702     for (unsigned i = 0; i != NumElems; ++i)
14703       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14704
14705     SDValue Shuff = DAG.getVectorShuffle(
14706         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14707
14708     Shuff = DAG.getBitcast(RegVT, Shuff);
14709
14710     // Build the arithmetic shift.
14711     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14712                    MemVT.getVectorElementType().getSizeInBits();
14713     Shuff =
14714         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14715                     DAG.getConstant(Amt, dl, RegVT));
14716
14717     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14718     return Shuff;
14719   }
14720
14721   // Redistribute the loaded elements into the different locations.
14722   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14723   for (unsigned i = 0; i != NumElems; ++i)
14724     ShuffleVec[i * SizeRatio] = i;
14725
14726   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14727                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14728
14729   // Bitcast to the requested type.
14730   Shuff = DAG.getBitcast(RegVT, Shuff);
14731   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14732   return Shuff;
14733 }
14734
14735 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14736 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14737 // from the AND / OR.
14738 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14739   Opc = Op.getOpcode();
14740   if (Opc != ISD::OR && Opc != ISD::AND)
14741     return false;
14742   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14743           Op.getOperand(0).hasOneUse() &&
14744           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14745           Op.getOperand(1).hasOneUse());
14746 }
14747
14748 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14749 // 1 and that the SETCC node has a single use.
14750 static bool isXor1OfSetCC(SDValue Op) {
14751   if (Op.getOpcode() != ISD::XOR)
14752     return false;
14753   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14754   if (N1C && N1C->getAPIntValue() == 1) {
14755     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14756       Op.getOperand(0).hasOneUse();
14757   }
14758   return false;
14759 }
14760
14761 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14762   bool addTest = true;
14763   SDValue Chain = Op.getOperand(0);
14764   SDValue Cond  = Op.getOperand(1);
14765   SDValue Dest  = Op.getOperand(2);
14766   SDLoc dl(Op);
14767   SDValue CC;
14768   bool Inverted = false;
14769
14770   if (Cond.getOpcode() == ISD::SETCC) {
14771     // Check for setcc([su]{add,sub,mul}o == 0).
14772     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14773         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14774         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14775         Cond.getOperand(0).getResNo() == 1 &&
14776         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14777          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14778          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14779          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14780          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14781          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14782       Inverted = true;
14783       Cond = Cond.getOperand(0);
14784     } else {
14785       SDValue NewCond = LowerSETCC(Cond, DAG);
14786       if (NewCond.getNode())
14787         Cond = NewCond;
14788     }
14789   }
14790 #if 0
14791   // FIXME: LowerXALUO doesn't handle these!!
14792   else if (Cond.getOpcode() == X86ISD::ADD  ||
14793            Cond.getOpcode() == X86ISD::SUB  ||
14794            Cond.getOpcode() == X86ISD::SMUL ||
14795            Cond.getOpcode() == X86ISD::UMUL)
14796     Cond = LowerXALUO(Cond, DAG);
14797 #endif
14798
14799   // Look pass (and (setcc_carry (cmp ...)), 1).
14800   if (Cond.getOpcode() == ISD::AND &&
14801       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14802     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14803     if (C && C->getAPIntValue() == 1)
14804       Cond = Cond.getOperand(0);
14805   }
14806
14807   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14808   // setting operand in place of the X86ISD::SETCC.
14809   unsigned CondOpcode = Cond.getOpcode();
14810   if (CondOpcode == X86ISD::SETCC ||
14811       CondOpcode == X86ISD::SETCC_CARRY) {
14812     CC = Cond.getOperand(0);
14813
14814     SDValue Cmp = Cond.getOperand(1);
14815     unsigned Opc = Cmp.getOpcode();
14816     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14817     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14818       Cond = Cmp;
14819       addTest = false;
14820     } else {
14821       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14822       default: break;
14823       case X86::COND_O:
14824       case X86::COND_B:
14825         // These can only come from an arithmetic instruction with overflow,
14826         // e.g. SADDO, UADDO.
14827         Cond = Cond.getNode()->getOperand(1);
14828         addTest = false;
14829         break;
14830       }
14831     }
14832   }
14833   CondOpcode = Cond.getOpcode();
14834   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14835       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14836       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14837        Cond.getOperand(0).getValueType() != MVT::i8)) {
14838     SDValue LHS = Cond.getOperand(0);
14839     SDValue RHS = Cond.getOperand(1);
14840     unsigned X86Opcode;
14841     unsigned X86Cond;
14842     SDVTList VTs;
14843     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14844     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14845     // X86ISD::INC).
14846     switch (CondOpcode) {
14847     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14848     case ISD::SADDO:
14849       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14850         if (C->isOne()) {
14851           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14852           break;
14853         }
14854       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14855     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14856     case ISD::SSUBO:
14857       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14858         if (C->isOne()) {
14859           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14860           break;
14861         }
14862       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14863     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14864     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14865     default: llvm_unreachable("unexpected overflowing operator");
14866     }
14867     if (Inverted)
14868       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14869     if (CondOpcode == ISD::UMULO)
14870       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14871                           MVT::i32);
14872     else
14873       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14874
14875     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14876
14877     if (CondOpcode == ISD::UMULO)
14878       Cond = X86Op.getValue(2);
14879     else
14880       Cond = X86Op.getValue(1);
14881
14882     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14883     addTest = false;
14884   } else {
14885     unsigned CondOpc;
14886     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14887       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14888       if (CondOpc == ISD::OR) {
14889         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14890         // two branches instead of an explicit OR instruction with a
14891         // separate test.
14892         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14893             isX86LogicalCmp(Cmp)) {
14894           CC = Cond.getOperand(0).getOperand(0);
14895           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14896                               Chain, Dest, CC, Cmp);
14897           CC = Cond.getOperand(1).getOperand(0);
14898           Cond = Cmp;
14899           addTest = false;
14900         }
14901       } else { // ISD::AND
14902         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14903         // two branches instead of an explicit AND instruction with a
14904         // separate test. However, we only do this if this block doesn't
14905         // have a fall-through edge, because this requires an explicit
14906         // jmp when the condition is false.
14907         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14908             isX86LogicalCmp(Cmp) &&
14909             Op.getNode()->hasOneUse()) {
14910           X86::CondCode CCode =
14911             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14912           CCode = X86::GetOppositeBranchCondition(CCode);
14913           CC = DAG.getConstant(CCode, dl, MVT::i8);
14914           SDNode *User = *Op.getNode()->use_begin();
14915           // Look for an unconditional branch following this conditional branch.
14916           // We need this because we need to reverse the successors in order
14917           // to implement FCMP_OEQ.
14918           if (User->getOpcode() == ISD::BR) {
14919             SDValue FalseBB = User->getOperand(1);
14920             SDNode *NewBR =
14921               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14922             assert(NewBR == User);
14923             (void)NewBR;
14924             Dest = FalseBB;
14925
14926             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14927                                 Chain, Dest, CC, Cmp);
14928             X86::CondCode CCode =
14929               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14930             CCode = X86::GetOppositeBranchCondition(CCode);
14931             CC = DAG.getConstant(CCode, dl, MVT::i8);
14932             Cond = Cmp;
14933             addTest = false;
14934           }
14935         }
14936       }
14937     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14938       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14939       // It should be transformed during dag combiner except when the condition
14940       // is set by a arithmetics with overflow node.
14941       X86::CondCode CCode =
14942         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14943       CCode = X86::GetOppositeBranchCondition(CCode);
14944       CC = DAG.getConstant(CCode, dl, MVT::i8);
14945       Cond = Cond.getOperand(0).getOperand(1);
14946       addTest = false;
14947     } else if (Cond.getOpcode() == ISD::SETCC &&
14948                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14949       // For FCMP_OEQ, we can emit
14950       // two branches instead of an explicit AND instruction with a
14951       // separate test. However, we only do this if this block doesn't
14952       // have a fall-through edge, because this requires an explicit
14953       // jmp when the condition is false.
14954       if (Op.getNode()->hasOneUse()) {
14955         SDNode *User = *Op.getNode()->use_begin();
14956         // Look for an unconditional branch following this conditional branch.
14957         // We need this because we need to reverse the successors in order
14958         // to implement FCMP_OEQ.
14959         if (User->getOpcode() == ISD::BR) {
14960           SDValue FalseBB = User->getOperand(1);
14961           SDNode *NewBR =
14962             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14963           assert(NewBR == User);
14964           (void)NewBR;
14965           Dest = FalseBB;
14966
14967           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14968                                     Cond.getOperand(0), Cond.getOperand(1));
14969           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14970           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14971           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14972                               Chain, Dest, CC, Cmp);
14973           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14974           Cond = Cmp;
14975           addTest = false;
14976         }
14977       }
14978     } else if (Cond.getOpcode() == ISD::SETCC &&
14979                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14980       // For FCMP_UNE, we can emit
14981       // two branches instead of an explicit AND instruction with a
14982       // separate test. However, we only do this if this block doesn't
14983       // have a fall-through edge, because this requires an explicit
14984       // jmp when the condition is false.
14985       if (Op.getNode()->hasOneUse()) {
14986         SDNode *User = *Op.getNode()->use_begin();
14987         // Look for an unconditional branch following this conditional branch.
14988         // We need this because we need to reverse the successors in order
14989         // to implement FCMP_UNE.
14990         if (User->getOpcode() == ISD::BR) {
14991           SDValue FalseBB = User->getOperand(1);
14992           SDNode *NewBR =
14993             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14994           assert(NewBR == User);
14995           (void)NewBR;
14996
14997           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14998                                     Cond.getOperand(0), Cond.getOperand(1));
14999           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15000           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15001           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15002                               Chain, Dest, CC, Cmp);
15003           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15004           Cond = Cmp;
15005           addTest = false;
15006           Dest = FalseBB;
15007         }
15008       }
15009     }
15010   }
15011
15012   if (addTest) {
15013     // Look pass the truncate if the high bits are known zero.
15014     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15015         Cond = Cond.getOperand(0);
15016
15017     // We know the result of AND is compared against zero. Try to match
15018     // it to BT.
15019     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15020       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15021       if (NewSetCC.getNode()) {
15022         CC = NewSetCC.getOperand(0);
15023         Cond = NewSetCC.getOperand(1);
15024         addTest = false;
15025       }
15026     }
15027   }
15028
15029   if (addTest) {
15030     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15031     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15032     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15033   }
15034   Cond = ConvertCmpIfNecessary(Cond, DAG);
15035   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15036                      Chain, Dest, CC, Cond);
15037 }
15038
15039 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15040 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15041 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15042 // that the guard pages used by the OS virtual memory manager are allocated in
15043 // correct sequence.
15044 SDValue
15045 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15046                                            SelectionDAG &DAG) const {
15047   MachineFunction &MF = DAG.getMachineFunction();
15048   bool SplitStack = MF.shouldSplitStack();
15049   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15050                SplitStack;
15051   SDLoc dl(Op);
15052
15053   if (!Lower) {
15054     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15055     SDNode* Node = Op.getNode();
15056
15057     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15058     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15059         " not tell us which reg is the stack pointer!");
15060     EVT VT = Node->getValueType(0);
15061     SDValue Tmp1 = SDValue(Node, 0);
15062     SDValue Tmp2 = SDValue(Node, 1);
15063     SDValue Tmp3 = Node->getOperand(2);
15064     SDValue Chain = Tmp1.getOperand(0);
15065
15066     // Chain the dynamic stack allocation so that it doesn't modify the stack
15067     // pointer when other instructions are using the stack.
15068     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15069         SDLoc(Node));
15070
15071     SDValue Size = Tmp2.getOperand(1);
15072     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15073     Chain = SP.getValue(1);
15074     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15075     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15076     unsigned StackAlign = TFI.getStackAlignment();
15077     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15078     if (Align > StackAlign)
15079       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15080           DAG.getConstant(-(uint64_t)Align, dl, VT));
15081     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15082
15083     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15084         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15085         SDLoc(Node));
15086
15087     SDValue Ops[2] = { Tmp1, Tmp2 };
15088     return DAG.getMergeValues(Ops, dl);
15089   }
15090
15091   // Get the inputs.
15092   SDValue Chain = Op.getOperand(0);
15093   SDValue Size  = Op.getOperand(1);
15094   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15095   EVT VT = Op.getNode()->getValueType(0);
15096
15097   bool Is64Bit = Subtarget->is64Bit();
15098   MVT SPTy = getPointerTy(DAG.getDataLayout());
15099
15100   if (SplitStack) {
15101     MachineRegisterInfo &MRI = MF.getRegInfo();
15102
15103     if (Is64Bit) {
15104       // The 64 bit implementation of segmented stacks needs to clobber both r10
15105       // r11. This makes it impossible to use it along with nested parameters.
15106       const Function *F = MF.getFunction();
15107
15108       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15109            I != E; ++I)
15110         if (I->hasNestAttr())
15111           report_fatal_error("Cannot use segmented stacks with functions that "
15112                              "have nested arguments.");
15113     }
15114
15115     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15116     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15117     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15118     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15119                                 DAG.getRegister(Vreg, SPTy));
15120     SDValue Ops1[2] = { Value, Chain };
15121     return DAG.getMergeValues(Ops1, dl);
15122   } else {
15123     SDValue Flag;
15124     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15125
15126     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15127     Flag = Chain.getValue(1);
15128     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15129
15130     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15131
15132     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15133     unsigned SPReg = RegInfo->getStackRegister();
15134     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15135     Chain = SP.getValue(1);
15136
15137     if (Align) {
15138       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15139                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15140       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15141     }
15142
15143     SDValue Ops1[2] = { SP, Chain };
15144     return DAG.getMergeValues(Ops1, dl);
15145   }
15146 }
15147
15148 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15149   MachineFunction &MF = DAG.getMachineFunction();
15150   auto PtrVT = getPointerTy(MF.getDataLayout());
15151   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15152
15153   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15154   SDLoc DL(Op);
15155
15156   if (!Subtarget->is64Bit() ||
15157       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15158     // vastart just stores the address of the VarArgsFrameIndex slot into the
15159     // memory location argument.
15160     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15161     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15162                         MachinePointerInfo(SV), false, false, 0);
15163   }
15164
15165   // __va_list_tag:
15166   //   gp_offset         (0 - 6 * 8)
15167   //   fp_offset         (48 - 48 + 8 * 16)
15168   //   overflow_arg_area (point to parameters coming in memory).
15169   //   reg_save_area
15170   SmallVector<SDValue, 8> MemOps;
15171   SDValue FIN = Op.getOperand(1);
15172   // Store gp_offset
15173   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15174                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15175                                                DL, MVT::i32),
15176                                FIN, MachinePointerInfo(SV), false, false, 0);
15177   MemOps.push_back(Store);
15178
15179   // Store fp_offset
15180   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15181   Store = DAG.getStore(Op.getOperand(0), DL,
15182                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15183                                        MVT::i32),
15184                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15185   MemOps.push_back(Store);
15186
15187   // Store ptr to overflow_arg_area
15188   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15189   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15190   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15191                        MachinePointerInfo(SV, 8),
15192                        false, false, 0);
15193   MemOps.push_back(Store);
15194
15195   // Store ptr to reg_save_area.
15196   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15197   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15198   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15199                        MachinePointerInfo(SV, 16), false, false, 0);
15200   MemOps.push_back(Store);
15201   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15202 }
15203
15204 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15205   assert(Subtarget->is64Bit() &&
15206          "LowerVAARG only handles 64-bit va_arg!");
15207   assert(Op.getNode()->getNumOperands() == 4);
15208
15209   MachineFunction &MF = DAG.getMachineFunction();
15210   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15211     // The Win64 ABI uses char* instead of a structure.
15212     return DAG.expandVAArg(Op.getNode());
15213
15214   SDValue Chain = Op.getOperand(0);
15215   SDValue SrcPtr = Op.getOperand(1);
15216   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15217   unsigned Align = Op.getConstantOperandVal(3);
15218   SDLoc dl(Op);
15219
15220   EVT ArgVT = Op.getNode()->getValueType(0);
15221   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15222   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15223   uint8_t ArgMode;
15224
15225   // Decide which area this value should be read from.
15226   // TODO: Implement the AMD64 ABI in its entirety. This simple
15227   // selection mechanism works only for the basic types.
15228   if (ArgVT == MVT::f80) {
15229     llvm_unreachable("va_arg for f80 not yet implemented");
15230   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15231     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15232   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15233     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15234   } else {
15235     llvm_unreachable("Unhandled argument type in LowerVAARG");
15236   }
15237
15238   if (ArgMode == 2) {
15239     // Sanity Check: Make sure using fp_offset makes sense.
15240     assert(!Subtarget->useSoftFloat() &&
15241            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15242            Subtarget->hasSSE1());
15243   }
15244
15245   // Insert VAARG_64 node into the DAG
15246   // VAARG_64 returns two values: Variable Argument Address, Chain
15247   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15248                        DAG.getConstant(ArgMode, dl, MVT::i8),
15249                        DAG.getConstant(Align, dl, MVT::i32)};
15250   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15251   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15252                                           VTs, InstOps, MVT::i64,
15253                                           MachinePointerInfo(SV),
15254                                           /*Align=*/0,
15255                                           /*Volatile=*/false,
15256                                           /*ReadMem=*/true,
15257                                           /*WriteMem=*/true);
15258   Chain = VAARG.getValue(1);
15259
15260   // Load the next argument and return it
15261   return DAG.getLoad(ArgVT, dl,
15262                      Chain,
15263                      VAARG,
15264                      MachinePointerInfo(),
15265                      false, false, false, 0);
15266 }
15267
15268 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15269                            SelectionDAG &DAG) {
15270   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15271   // where a va_list is still an i8*.
15272   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15273   if (Subtarget->isCallingConvWin64(
15274         DAG.getMachineFunction().getFunction()->getCallingConv()))
15275     // Probably a Win64 va_copy.
15276     return DAG.expandVACopy(Op.getNode());
15277
15278   SDValue Chain = Op.getOperand(0);
15279   SDValue DstPtr = Op.getOperand(1);
15280   SDValue SrcPtr = Op.getOperand(2);
15281   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15282   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15283   SDLoc DL(Op);
15284
15285   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15286                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15287                        false, false,
15288                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15289 }
15290
15291 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15292 // amount is a constant. Takes immediate version of shift as input.
15293 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15294                                           SDValue SrcOp, uint64_t ShiftAmt,
15295                                           SelectionDAG &DAG) {
15296   MVT ElementType = VT.getVectorElementType();
15297
15298   // Fold this packed shift into its first operand if ShiftAmt is 0.
15299   if (ShiftAmt == 0)
15300     return SrcOp;
15301
15302   // Check for ShiftAmt >= element width
15303   if (ShiftAmt >= ElementType.getSizeInBits()) {
15304     if (Opc == X86ISD::VSRAI)
15305       ShiftAmt = ElementType.getSizeInBits() - 1;
15306     else
15307       return DAG.getConstant(0, dl, VT);
15308   }
15309
15310   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15311          && "Unknown target vector shift-by-constant node");
15312
15313   // Fold this packed vector shift into a build vector if SrcOp is a
15314   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15315   if (VT == SrcOp.getSimpleValueType() &&
15316       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15317     SmallVector<SDValue, 8> Elts;
15318     unsigned NumElts = SrcOp->getNumOperands();
15319     ConstantSDNode *ND;
15320
15321     switch(Opc) {
15322     default: llvm_unreachable(nullptr);
15323     case X86ISD::VSHLI:
15324       for (unsigned i=0; i!=NumElts; ++i) {
15325         SDValue CurrentOp = SrcOp->getOperand(i);
15326         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15327           Elts.push_back(CurrentOp);
15328           continue;
15329         }
15330         ND = cast<ConstantSDNode>(CurrentOp);
15331         const APInt &C = ND->getAPIntValue();
15332         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15333       }
15334       break;
15335     case X86ISD::VSRLI:
15336       for (unsigned i=0; i!=NumElts; ++i) {
15337         SDValue CurrentOp = SrcOp->getOperand(i);
15338         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15339           Elts.push_back(CurrentOp);
15340           continue;
15341         }
15342         ND = cast<ConstantSDNode>(CurrentOp);
15343         const APInt &C = ND->getAPIntValue();
15344         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15345       }
15346       break;
15347     case X86ISD::VSRAI:
15348       for (unsigned i=0; i!=NumElts; ++i) {
15349         SDValue CurrentOp = SrcOp->getOperand(i);
15350         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15351           Elts.push_back(CurrentOp);
15352           continue;
15353         }
15354         ND = cast<ConstantSDNode>(CurrentOp);
15355         const APInt &C = ND->getAPIntValue();
15356         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15357       }
15358       break;
15359     }
15360
15361     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15362   }
15363
15364   return DAG.getNode(Opc, dl, VT, SrcOp,
15365                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15366 }
15367
15368 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15369 // may or may not be a constant. Takes immediate version of shift as input.
15370 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15371                                    SDValue SrcOp, SDValue ShAmt,
15372                                    SelectionDAG &DAG) {
15373   MVT SVT = ShAmt.getSimpleValueType();
15374   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15375
15376   // Catch shift-by-constant.
15377   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15378     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15379                                       CShAmt->getZExtValue(), DAG);
15380
15381   // Change opcode to non-immediate version
15382   switch (Opc) {
15383     default: llvm_unreachable("Unknown target vector shift node");
15384     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15385     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15386     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15387   }
15388
15389   const X86Subtarget &Subtarget =
15390       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15391   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15392       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15393     // Let the shuffle legalizer expand this shift amount node.
15394     SDValue Op0 = ShAmt.getOperand(0);
15395     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15396     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15397   } else {
15398     // Need to build a vector containing shift amount.
15399     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15400     SmallVector<SDValue, 4> ShOps;
15401     ShOps.push_back(ShAmt);
15402     if (SVT == MVT::i32) {
15403       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15404       ShOps.push_back(DAG.getUNDEF(SVT));
15405     }
15406     ShOps.push_back(DAG.getUNDEF(SVT));
15407
15408     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15409     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15410   }
15411
15412   // The return type has to be a 128-bit type with the same element
15413   // type as the input type.
15414   MVT EltVT = VT.getVectorElementType();
15415   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15416
15417   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15418   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15419 }
15420
15421 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15422 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15423 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15424 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15425                                     SDValue PreservedSrc,
15426                                     const X86Subtarget *Subtarget,
15427                                     SelectionDAG &DAG) {
15428     EVT VT = Op.getValueType();
15429     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15430                                   MVT::i1, VT.getVectorNumElements());
15431     SDValue VMask = SDValue();
15432     unsigned OpcodeSelect = ISD::VSELECT;
15433     SDLoc dl(Op);
15434
15435     assert(MaskVT.isSimple() && "invalid mask type");
15436
15437     if (isAllOnes(Mask))
15438       return Op;
15439
15440     if (MaskVT.bitsGT(Mask.getValueType())) {
15441       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15442                                          MaskVT.getSizeInBits());
15443       VMask = DAG.getBitcast(MaskVT,
15444                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15445     } else {
15446       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15447                                        Mask.getValueType().getSizeInBits());
15448       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15449       // are extracted by EXTRACT_SUBVECTOR.
15450       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15451                           DAG.getBitcast(BitcastVT, Mask),
15452                           DAG.getIntPtrConstant(0, dl));
15453     }
15454
15455     switch (Op.getOpcode()) {
15456       default: break;
15457       case X86ISD::PCMPEQM:
15458       case X86ISD::PCMPGTM:
15459       case X86ISD::CMPM:
15460       case X86ISD::CMPMU:
15461         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15462       case X86ISD::VTRUNC:
15463       case X86ISD::VTRUNCS:
15464       case X86ISD::VTRUNCUS:
15465         // We can't use ISD::VSELECT here because it is not always "Legal"
15466         // for the destination type. For example vpmovqb require only AVX512
15467         // and vselect that can operate on byte element type require BWI
15468         OpcodeSelect = X86ISD::SELECT;
15469         break;
15470     }
15471     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15472       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15473     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15474 }
15475
15476 /// \brief Creates an SDNode for a predicated scalar operation.
15477 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15478 /// The mask is coming as MVT::i8 and it should be truncated
15479 /// to MVT::i1 while lowering masking intrinsics.
15480 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15481 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15482 /// for a scalar instruction.
15483 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15484                                     SDValue PreservedSrc,
15485                                     const X86Subtarget *Subtarget,
15486                                     SelectionDAG &DAG) {
15487     if (isAllOnes(Mask))
15488       return Op;
15489
15490     EVT VT = Op.getValueType();
15491     SDLoc dl(Op);
15492     // The mask should be of type MVT::i1
15493     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15494
15495     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15496       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15497     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15498 }
15499
15500 static int getSEHRegistrationNodeSize(const Function *Fn) {
15501   if (!Fn->hasPersonalityFn())
15502     report_fatal_error(
15503         "querying registration node size for function without personality");
15504   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15505   // WinEHStatePass for the full struct definition.
15506   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15507   case EHPersonality::MSVC_X86SEH: return 24;
15508   case EHPersonality::MSVC_CXX: return 16;
15509   default: break;
15510   }
15511   report_fatal_error("can only recover FP for MSVC EH personality functions");
15512 }
15513
15514 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15515 /// function or when returning to a parent frame after catching an exception, we
15516 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15517 /// Here's the math:
15518 ///   RegNodeBase = EntryEBP - RegNodeSize
15519 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15520 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15521 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15522 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15523                                    SDValue EntryEBP) {
15524   MachineFunction &MF = DAG.getMachineFunction();
15525   SDLoc dl;
15526
15527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15528   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15529
15530   // It's possible that the parent function no longer has a personality function
15531   // if the exceptional code was optimized away, in which case we just return
15532   // the incoming EBP.
15533   if (!Fn->hasPersonalityFn())
15534     return EntryEBP;
15535
15536   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15537
15538   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15539   // registration.
15540   MCSymbol *OffsetSym =
15541       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15542           GlobalValue::getRealLinkageName(Fn->getName()));
15543   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15544   SDValue RegNodeFrameOffset =
15545       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15546
15547   // RegNodeBase = EntryEBP - RegNodeSize
15548   // ParentFP = RegNodeBase - RegNodeFrameOffset
15549   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15550                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15551   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15552 }
15553
15554 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15555                                        SelectionDAG &DAG) {
15556   SDLoc dl(Op);
15557   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15558   EVT VT = Op.getValueType();
15559   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15560   if (IntrData) {
15561     switch(IntrData->Type) {
15562     case INTR_TYPE_1OP:
15563       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15564     case INTR_TYPE_2OP:
15565       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15566         Op.getOperand(2));
15567     case INTR_TYPE_3OP:
15568       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15569         Op.getOperand(2), Op.getOperand(3));
15570     case INTR_TYPE_4OP:
15571       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15572         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15573     case INTR_TYPE_1OP_MASK_RM: {
15574       SDValue Src = Op.getOperand(1);
15575       SDValue PassThru = Op.getOperand(2);
15576       SDValue Mask = Op.getOperand(3);
15577       SDValue RoundingMode;
15578       // We allways add rounding mode to the Node.
15579       // If the rounding mode is not specified, we add the
15580       // "current direction" mode.
15581       if (Op.getNumOperands() == 4)
15582         RoundingMode =
15583           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15584       else
15585         RoundingMode = Op.getOperand(4);
15586       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15587       if (IntrWithRoundingModeOpcode != 0)
15588         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15589             X86::STATIC_ROUNDING::CUR_DIRECTION)
15590           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15591                                       dl, Op.getValueType(), Src, RoundingMode),
15592                                       Mask, PassThru, Subtarget, DAG);
15593       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15594                                               RoundingMode),
15595                                   Mask, PassThru, Subtarget, DAG);
15596     }
15597     case INTR_TYPE_1OP_MASK: {
15598       SDValue Src = Op.getOperand(1);
15599       SDValue PassThru = Op.getOperand(2);
15600       SDValue Mask = Op.getOperand(3);
15601       // We add rounding mode to the Node when
15602       //   - RM Opcode is specified and
15603       //   - RM is not "current direction".
15604       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15605       if (IntrWithRoundingModeOpcode != 0) {
15606         SDValue Rnd = Op.getOperand(4);
15607         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15608         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15609           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15610                                       dl, Op.getValueType(),
15611                                       Src, Rnd),
15612                                       Mask, PassThru, Subtarget, DAG);
15613         }
15614       }
15615       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15616                                   Mask, PassThru, Subtarget, DAG);
15617     }
15618     case INTR_TYPE_SCALAR_MASK_RM: {
15619       SDValue Src1 = Op.getOperand(1);
15620       SDValue Src2 = Op.getOperand(2);
15621       SDValue Src0 = Op.getOperand(3);
15622       SDValue Mask = Op.getOperand(4);
15623       // There are 2 kinds of intrinsics in this group:
15624       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15625       // (2) With rounding mode and sae - 7 operands.
15626       if (Op.getNumOperands() == 6) {
15627         SDValue Sae  = Op.getOperand(5);
15628         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15629         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15630                                                 Sae),
15631                                     Mask, Src0, Subtarget, DAG);
15632       }
15633       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15634       SDValue RoundingMode  = Op.getOperand(5);
15635       SDValue Sae  = Op.getOperand(6);
15636       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15637                                               RoundingMode, Sae),
15638                                   Mask, Src0, Subtarget, DAG);
15639     }
15640     case INTR_TYPE_2OP_MASK: {
15641       SDValue Src1 = Op.getOperand(1);
15642       SDValue Src2 = Op.getOperand(2);
15643       SDValue PassThru = Op.getOperand(3);
15644       SDValue Mask = Op.getOperand(4);
15645       // We specify 2 possible opcodes for intrinsics with rounding modes.
15646       // First, we check if the intrinsic may have non-default rounding mode,
15647       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15648       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15649       if (IntrWithRoundingModeOpcode != 0) {
15650         SDValue Rnd = Op.getOperand(5);
15651         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15652         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15653           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15654                                       dl, Op.getValueType(),
15655                                       Src1, Src2, Rnd),
15656                                       Mask, PassThru, Subtarget, DAG);
15657         }
15658       }
15659       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15660                                               Src1,Src2),
15661                                   Mask, PassThru, Subtarget, DAG);
15662     }
15663     case INTR_TYPE_2OP_MASK_RM: {
15664       SDValue Src1 = Op.getOperand(1);
15665       SDValue Src2 = Op.getOperand(2);
15666       SDValue PassThru = Op.getOperand(3);
15667       SDValue Mask = Op.getOperand(4);
15668       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15669       // First, we check if the intrinsic have rounding mode (6 operands),
15670       // if not, we set rounding mode to "current".
15671       SDValue Rnd;
15672       if (Op.getNumOperands() == 6)
15673         Rnd = Op.getOperand(5);
15674       else
15675         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15676       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15677                                               Src1, Src2, Rnd),
15678                                   Mask, PassThru, Subtarget, DAG);
15679     }
15680     case INTR_TYPE_3OP_MASK_RM: {
15681       SDValue Src1 = Op.getOperand(1);
15682       SDValue Src2 = Op.getOperand(2);
15683       SDValue Imm = Op.getOperand(3);
15684       SDValue PassThru = Op.getOperand(4);
15685       SDValue Mask = Op.getOperand(5);
15686       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15687       // First, we check if the intrinsic have rounding mode (7 operands),
15688       // if not, we set rounding mode to "current".
15689       SDValue Rnd;
15690       if (Op.getNumOperands() == 7)
15691         Rnd = Op.getOperand(6);
15692       else
15693         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15694       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15695         Src1, Src2, Imm, Rnd),
15696         Mask, PassThru, Subtarget, DAG);
15697     }
15698     case INTR_TYPE_3OP_MASK: {
15699       SDValue Src1 = Op.getOperand(1);
15700       SDValue Src2 = Op.getOperand(2);
15701       SDValue Src3 = Op.getOperand(3);
15702       SDValue PassThru = Op.getOperand(4);
15703       SDValue Mask = Op.getOperand(5);
15704       // We specify 2 possible opcodes for intrinsics with rounding modes.
15705       // First, we check if the intrinsic may have non-default rounding mode,
15706       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15707       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15708       if (IntrWithRoundingModeOpcode != 0) {
15709         SDValue Rnd = Op.getOperand(6);
15710         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15711         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15712           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15713                                       dl, Op.getValueType(),
15714                                       Src1, Src2, Src3, Rnd),
15715                                       Mask, PassThru, Subtarget, DAG);
15716         }
15717       }
15718       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15719                                               Src1, Src2, Src3),
15720                                   Mask, PassThru, Subtarget, DAG);
15721     }
15722     case VPERM_3OP_MASKZ:
15723     case VPERM_3OP_MASK:
15724     case FMA_OP_MASK3:
15725     case FMA_OP_MASKZ:
15726     case FMA_OP_MASK: {
15727       SDValue Src1 = Op.getOperand(1);
15728       SDValue Src2 = Op.getOperand(2);
15729       SDValue Src3 = Op.getOperand(3);
15730       SDValue Mask = Op.getOperand(4);
15731       EVT VT = Op.getValueType();
15732       SDValue PassThru = SDValue();
15733
15734       // set PassThru element
15735       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15736         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15737       else if (IntrData->Type == FMA_OP_MASK3)
15738         PassThru = Src3;
15739       else
15740         PassThru = Src1;
15741
15742       // We specify 2 possible opcodes for intrinsics with rounding modes.
15743       // First, we check if the intrinsic may have non-default rounding mode,
15744       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15745       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15746       if (IntrWithRoundingModeOpcode != 0) {
15747         SDValue Rnd = Op.getOperand(5);
15748         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15749             X86::STATIC_ROUNDING::CUR_DIRECTION)
15750           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15751                                                   dl, Op.getValueType(),
15752                                                   Src1, Src2, Src3, Rnd),
15753                                       Mask, PassThru, Subtarget, DAG);
15754       }
15755       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15756                                               dl, Op.getValueType(),
15757                                               Src1, Src2, Src3),
15758                                   Mask, PassThru, Subtarget, DAG);
15759     }
15760     case CMP_MASK:
15761     case CMP_MASK_CC: {
15762       // Comparison intrinsics with masks.
15763       // Example of transformation:
15764       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15765       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15766       // (i8 (bitcast
15767       //   (v8i1 (insert_subvector undef,
15768       //           (v2i1 (and (PCMPEQM %a, %b),
15769       //                      (extract_subvector
15770       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15771       EVT VT = Op.getOperand(1).getValueType();
15772       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15773                                     VT.getVectorNumElements());
15774       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15775       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15776                                        Mask.getValueType().getSizeInBits());
15777       SDValue Cmp;
15778       if (IntrData->Type == CMP_MASK_CC) {
15779         SDValue CC = Op.getOperand(3);
15780         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15781         // We specify 2 possible opcodes for intrinsics with rounding modes.
15782         // First, we check if the intrinsic may have non-default rounding mode,
15783         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15784         if (IntrData->Opc1 != 0) {
15785           SDValue Rnd = Op.getOperand(5);
15786           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15787               X86::STATIC_ROUNDING::CUR_DIRECTION)
15788             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15789                               Op.getOperand(2), CC, Rnd);
15790         }
15791         //default rounding mode
15792         if(!Cmp.getNode())
15793             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15794                               Op.getOperand(2), CC);
15795
15796       } else {
15797         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15798         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15799                           Op.getOperand(2));
15800       }
15801       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15802                                              DAG.getTargetConstant(0, dl,
15803                                                                    MaskVT),
15804                                              Subtarget, DAG);
15805       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15806                                 DAG.getUNDEF(BitcastVT), CmpMask,
15807                                 DAG.getIntPtrConstant(0, dl));
15808       return DAG.getBitcast(Op.getValueType(), Res);
15809     }
15810     case COMI: { // Comparison intrinsics
15811       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15812       SDValue LHS = Op.getOperand(1);
15813       SDValue RHS = Op.getOperand(2);
15814       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15815       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15816       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15817       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15818                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15819       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15820     }
15821     case VSHIFT:
15822       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15823                                  Op.getOperand(1), Op.getOperand(2), DAG);
15824     case VSHIFT_MASK:
15825       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15826                                                       Op.getSimpleValueType(),
15827                                                       Op.getOperand(1),
15828                                                       Op.getOperand(2), DAG),
15829                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15830                                   DAG);
15831     case COMPRESS_EXPAND_IN_REG: {
15832       SDValue Mask = Op.getOperand(3);
15833       SDValue DataToCompress = Op.getOperand(1);
15834       SDValue PassThru = Op.getOperand(2);
15835       if (isAllOnes(Mask)) // return data as is
15836         return Op.getOperand(1);
15837
15838       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15839                                               DataToCompress),
15840                                   Mask, PassThru, Subtarget, DAG);
15841     }
15842     case BLEND: {
15843       SDValue Mask = Op.getOperand(3);
15844       EVT VT = Op.getValueType();
15845       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15846                                     VT.getVectorNumElements());
15847       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15848                                        Mask.getValueType().getSizeInBits());
15849       SDLoc dl(Op);
15850       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15851                                   DAG.getBitcast(BitcastVT, Mask),
15852                                   DAG.getIntPtrConstant(0, dl));
15853       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15854                          Op.getOperand(2));
15855     }
15856     default:
15857       break;
15858     }
15859   }
15860
15861   switch (IntNo) {
15862   default: return SDValue();    // Don't custom lower most intrinsics.
15863
15864   case Intrinsic::x86_avx2_permd:
15865   case Intrinsic::x86_avx2_permps:
15866     // Operands intentionally swapped. Mask is last operand to intrinsic,
15867     // but second operand for node/instruction.
15868     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15869                        Op.getOperand(2), Op.getOperand(1));
15870
15871   // ptest and testp intrinsics. The intrinsic these come from are designed to
15872   // return an integer value, not just an instruction so lower it to the ptest
15873   // or testp pattern and a setcc for the result.
15874   case Intrinsic::x86_sse41_ptestz:
15875   case Intrinsic::x86_sse41_ptestc:
15876   case Intrinsic::x86_sse41_ptestnzc:
15877   case Intrinsic::x86_avx_ptestz_256:
15878   case Intrinsic::x86_avx_ptestc_256:
15879   case Intrinsic::x86_avx_ptestnzc_256:
15880   case Intrinsic::x86_avx_vtestz_ps:
15881   case Intrinsic::x86_avx_vtestc_ps:
15882   case Intrinsic::x86_avx_vtestnzc_ps:
15883   case Intrinsic::x86_avx_vtestz_pd:
15884   case Intrinsic::x86_avx_vtestc_pd:
15885   case Intrinsic::x86_avx_vtestnzc_pd:
15886   case Intrinsic::x86_avx_vtestz_ps_256:
15887   case Intrinsic::x86_avx_vtestc_ps_256:
15888   case Intrinsic::x86_avx_vtestnzc_ps_256:
15889   case Intrinsic::x86_avx_vtestz_pd_256:
15890   case Intrinsic::x86_avx_vtestc_pd_256:
15891   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15892     bool IsTestPacked = false;
15893     unsigned X86CC;
15894     switch (IntNo) {
15895     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15896     case Intrinsic::x86_avx_vtestz_ps:
15897     case Intrinsic::x86_avx_vtestz_pd:
15898     case Intrinsic::x86_avx_vtestz_ps_256:
15899     case Intrinsic::x86_avx_vtestz_pd_256:
15900       IsTestPacked = true; // Fallthrough
15901     case Intrinsic::x86_sse41_ptestz:
15902     case Intrinsic::x86_avx_ptestz_256:
15903       // ZF = 1
15904       X86CC = X86::COND_E;
15905       break;
15906     case Intrinsic::x86_avx_vtestc_ps:
15907     case Intrinsic::x86_avx_vtestc_pd:
15908     case Intrinsic::x86_avx_vtestc_ps_256:
15909     case Intrinsic::x86_avx_vtestc_pd_256:
15910       IsTestPacked = true; // Fallthrough
15911     case Intrinsic::x86_sse41_ptestc:
15912     case Intrinsic::x86_avx_ptestc_256:
15913       // CF = 1
15914       X86CC = X86::COND_B;
15915       break;
15916     case Intrinsic::x86_avx_vtestnzc_ps:
15917     case Intrinsic::x86_avx_vtestnzc_pd:
15918     case Intrinsic::x86_avx_vtestnzc_ps_256:
15919     case Intrinsic::x86_avx_vtestnzc_pd_256:
15920       IsTestPacked = true; // Fallthrough
15921     case Intrinsic::x86_sse41_ptestnzc:
15922     case Intrinsic::x86_avx_ptestnzc_256:
15923       // ZF and CF = 0
15924       X86CC = X86::COND_A;
15925       break;
15926     }
15927
15928     SDValue LHS = Op.getOperand(1);
15929     SDValue RHS = Op.getOperand(2);
15930     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15931     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15932     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15933     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15934     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15935   }
15936   case Intrinsic::x86_avx512_kortestz_w:
15937   case Intrinsic::x86_avx512_kortestc_w: {
15938     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15939     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15940     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15941     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15942     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15943     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15944     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15945   }
15946
15947   case Intrinsic::x86_sse42_pcmpistria128:
15948   case Intrinsic::x86_sse42_pcmpestria128:
15949   case Intrinsic::x86_sse42_pcmpistric128:
15950   case Intrinsic::x86_sse42_pcmpestric128:
15951   case Intrinsic::x86_sse42_pcmpistrio128:
15952   case Intrinsic::x86_sse42_pcmpestrio128:
15953   case Intrinsic::x86_sse42_pcmpistris128:
15954   case Intrinsic::x86_sse42_pcmpestris128:
15955   case Intrinsic::x86_sse42_pcmpistriz128:
15956   case Intrinsic::x86_sse42_pcmpestriz128: {
15957     unsigned Opcode;
15958     unsigned X86CC;
15959     switch (IntNo) {
15960     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15961     case Intrinsic::x86_sse42_pcmpistria128:
15962       Opcode = X86ISD::PCMPISTRI;
15963       X86CC = X86::COND_A;
15964       break;
15965     case Intrinsic::x86_sse42_pcmpestria128:
15966       Opcode = X86ISD::PCMPESTRI;
15967       X86CC = X86::COND_A;
15968       break;
15969     case Intrinsic::x86_sse42_pcmpistric128:
15970       Opcode = X86ISD::PCMPISTRI;
15971       X86CC = X86::COND_B;
15972       break;
15973     case Intrinsic::x86_sse42_pcmpestric128:
15974       Opcode = X86ISD::PCMPESTRI;
15975       X86CC = X86::COND_B;
15976       break;
15977     case Intrinsic::x86_sse42_pcmpistrio128:
15978       Opcode = X86ISD::PCMPISTRI;
15979       X86CC = X86::COND_O;
15980       break;
15981     case Intrinsic::x86_sse42_pcmpestrio128:
15982       Opcode = X86ISD::PCMPESTRI;
15983       X86CC = X86::COND_O;
15984       break;
15985     case Intrinsic::x86_sse42_pcmpistris128:
15986       Opcode = X86ISD::PCMPISTRI;
15987       X86CC = X86::COND_S;
15988       break;
15989     case Intrinsic::x86_sse42_pcmpestris128:
15990       Opcode = X86ISD::PCMPESTRI;
15991       X86CC = X86::COND_S;
15992       break;
15993     case Intrinsic::x86_sse42_pcmpistriz128:
15994       Opcode = X86ISD::PCMPISTRI;
15995       X86CC = X86::COND_E;
15996       break;
15997     case Intrinsic::x86_sse42_pcmpestriz128:
15998       Opcode = X86ISD::PCMPESTRI;
15999       X86CC = X86::COND_E;
16000       break;
16001     }
16002     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16003     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16004     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16005     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16006                                 DAG.getConstant(X86CC, dl, MVT::i8),
16007                                 SDValue(PCMP.getNode(), 1));
16008     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16009   }
16010
16011   case Intrinsic::x86_sse42_pcmpistri128:
16012   case Intrinsic::x86_sse42_pcmpestri128: {
16013     unsigned Opcode;
16014     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16015       Opcode = X86ISD::PCMPISTRI;
16016     else
16017       Opcode = X86ISD::PCMPESTRI;
16018
16019     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16020     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16021     return DAG.getNode(Opcode, dl, VTs, NewOps);
16022   }
16023
16024   case Intrinsic::x86_seh_lsda: {
16025     // Compute the symbol for the LSDA. We know it'll get emitted later.
16026     MachineFunction &MF = DAG.getMachineFunction();
16027     SDValue Op1 = Op.getOperand(1);
16028     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16029     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16030         GlobalValue::getRealLinkageName(Fn->getName()));
16031
16032     // Generate a simple absolute symbol reference. This intrinsic is only
16033     // supported on 32-bit Windows, which isn't PIC.
16034     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16035     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16036   }
16037
16038   case Intrinsic::x86_seh_recoverfp: {
16039     SDValue FnOp = Op.getOperand(1);
16040     SDValue IncomingFPOp = Op.getOperand(2);
16041     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16042     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16043     if (!Fn)
16044       report_fatal_error(
16045           "llvm.x86.seh.recoverfp must take a function as the first argument");
16046     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16047   }
16048
16049   case Intrinsic::localaddress: {
16050     // Returns one of the stack, base, or frame pointer registers, depending on
16051     // which is used to reference local variables.
16052     MachineFunction &MF = DAG.getMachineFunction();
16053     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16054     unsigned Reg;
16055     if (RegInfo->hasBasePointer(MF))
16056       Reg = RegInfo->getBaseRegister();
16057     else // This function handles the SP or FP case.
16058       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16059     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16060   }
16061   }
16062 }
16063
16064 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16065                               SDValue Src, SDValue Mask, SDValue Base,
16066                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16067                               const X86Subtarget * Subtarget) {
16068   SDLoc dl(Op);
16069   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16070   if (!C)
16071     llvm_unreachable("Invalid scale type");
16072   unsigned ScaleVal = C->getZExtValue();
16073   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16074     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16075
16076   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16077   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16078                              Index.getSimpleValueType().getVectorNumElements());
16079   SDValue MaskInReg;
16080   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16081   if (MaskC)
16082     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16083   else {
16084     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16085                                      Mask.getValueType().getSizeInBits());
16086
16087     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16088     // are extracted by EXTRACT_SUBVECTOR.
16089     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16090                             DAG.getBitcast(BitcastVT, Mask),
16091                             DAG.getIntPtrConstant(0, dl));
16092   }
16093   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16094   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16095   SDValue Segment = DAG.getRegister(0, MVT::i32);
16096   if (Src.getOpcode() == ISD::UNDEF)
16097     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16098   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16099   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16100   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16101   return DAG.getMergeValues(RetOps, dl);
16102 }
16103
16104 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16105                                SDValue Src, SDValue Mask, SDValue Base,
16106                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16107   SDLoc dl(Op);
16108   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16109   if (!C)
16110     llvm_unreachable("Invalid scale type");
16111   unsigned ScaleVal = C->getZExtValue();
16112   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16113     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16114
16115   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16116   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16117   SDValue Segment = DAG.getRegister(0, MVT::i32);
16118   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16119                              Index.getSimpleValueType().getVectorNumElements());
16120   SDValue MaskInReg;
16121   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16122   if (MaskC)
16123     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16124   else {
16125     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16126                                      Mask.getValueType().getSizeInBits());
16127
16128     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16129     // are extracted by EXTRACT_SUBVECTOR.
16130     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16131                             DAG.getBitcast(BitcastVT, Mask),
16132                             DAG.getIntPtrConstant(0, dl));
16133   }
16134   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16135   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16136   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16137   return SDValue(Res, 1);
16138 }
16139
16140 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16141                                SDValue Mask, SDValue Base, SDValue Index,
16142                                SDValue ScaleOp, SDValue Chain) {
16143   SDLoc dl(Op);
16144   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16145   assert(C && "Invalid scale type");
16146   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16147   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16148   SDValue Segment = DAG.getRegister(0, MVT::i32);
16149   EVT MaskVT =
16150     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16151   SDValue MaskInReg;
16152   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16153   if (MaskC)
16154     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16155   else
16156     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16157   //SDVTList VTs = DAG.getVTList(MVT::Other);
16158   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16159   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16160   return SDValue(Res, 0);
16161 }
16162
16163 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16164 // read performance monitor counters (x86_rdpmc).
16165 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16166                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16167                               SmallVectorImpl<SDValue> &Results) {
16168   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16169   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16170   SDValue LO, HI;
16171
16172   // The ECX register is used to select the index of the performance counter
16173   // to read.
16174   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16175                                    N->getOperand(2));
16176   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16177
16178   // Reads the content of a 64-bit performance counter and returns it in the
16179   // registers EDX:EAX.
16180   if (Subtarget->is64Bit()) {
16181     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16182     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16183                             LO.getValue(2));
16184   } else {
16185     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16186     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16187                             LO.getValue(2));
16188   }
16189   Chain = HI.getValue(1);
16190
16191   if (Subtarget->is64Bit()) {
16192     // The EAX register is loaded with the low-order 32 bits. The EDX register
16193     // is loaded with the supported high-order bits of the counter.
16194     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16195                               DAG.getConstant(32, DL, MVT::i8));
16196     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16197     Results.push_back(Chain);
16198     return;
16199   }
16200
16201   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16202   SDValue Ops[] = { LO, HI };
16203   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16204   Results.push_back(Pair);
16205   Results.push_back(Chain);
16206 }
16207
16208 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16209 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16210 // also used to custom lower READCYCLECOUNTER nodes.
16211 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16212                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16213                               SmallVectorImpl<SDValue> &Results) {
16214   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16215   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16216   SDValue LO, HI;
16217
16218   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16219   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16220   // and the EAX register is loaded with the low-order 32 bits.
16221   if (Subtarget->is64Bit()) {
16222     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16223     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16224                             LO.getValue(2));
16225   } else {
16226     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16227     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16228                             LO.getValue(2));
16229   }
16230   SDValue Chain = HI.getValue(1);
16231
16232   if (Opcode == X86ISD::RDTSCP_DAG) {
16233     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16234
16235     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16236     // the ECX register. Add 'ecx' explicitly to the chain.
16237     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16238                                      HI.getValue(2));
16239     // Explicitly store the content of ECX at the location passed in input
16240     // to the 'rdtscp' intrinsic.
16241     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16242                          MachinePointerInfo(), false, false, 0);
16243   }
16244
16245   if (Subtarget->is64Bit()) {
16246     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16247     // the EAX register is loaded with the low-order 32 bits.
16248     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16249                               DAG.getConstant(32, DL, MVT::i8));
16250     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16251     Results.push_back(Chain);
16252     return;
16253   }
16254
16255   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16256   SDValue Ops[] = { LO, HI };
16257   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16258   Results.push_back(Pair);
16259   Results.push_back(Chain);
16260 }
16261
16262 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16263                                      SelectionDAG &DAG) {
16264   SmallVector<SDValue, 2> Results;
16265   SDLoc DL(Op);
16266   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16267                           Results);
16268   return DAG.getMergeValues(Results, DL);
16269 }
16270
16271 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16272                                     SelectionDAG &DAG) {
16273   MachineFunction &MF = DAG.getMachineFunction();
16274   const Function *Fn = MF.getFunction();
16275   SDLoc dl(Op);
16276   SDValue Chain = Op.getOperand(0);
16277
16278   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16279          "using llvm.x86.seh.restoreframe requires a frame pointer");
16280
16281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16282   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16283
16284   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16285   unsigned FrameReg =
16286       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16287   unsigned SPReg = RegInfo->getStackRegister();
16288   unsigned SlotSize = RegInfo->getSlotSize();
16289
16290   // Get incoming EBP.
16291   SDValue IncomingEBP =
16292       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16293
16294   // SP is saved in the first field of every registration node, so load
16295   // [EBP-RegNodeSize] into SP.
16296   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16297   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16298                                DAG.getConstant(-RegNodeSize, dl, VT));
16299   SDValue NewSP =
16300       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16301                   false, VT.getScalarSizeInBits() / 8);
16302   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16303
16304   if (!RegInfo->needsStackRealignment(MF)) {
16305     // Adjust EBP to point back to the original frame position.
16306     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16307     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16308   } else {
16309     assert(RegInfo->hasBasePointer(MF) &&
16310            "functions with Win32 EH must use frame or base pointer register");
16311
16312     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16313     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16314     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16315
16316     // Reload the spilled EBP value, now that the stack and base pointers are
16317     // set up.
16318     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16319     X86FI->setHasSEHFramePtrSave(true);
16320     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16321     X86FI->setSEHFramePtrSaveIndex(FI);
16322     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16323                                 MachinePointerInfo(), false, false, false,
16324                                 VT.getScalarSizeInBits() / 8);
16325     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16326   }
16327
16328   return Chain;
16329 }
16330
16331 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16332 /// return truncate Store/MaskedStore Node
16333 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16334                                                SelectionDAG &DAG,
16335                                                MVT ElementType) {
16336   SDLoc dl(Op);
16337   SDValue Mask = Op.getOperand(4);
16338   SDValue DataToTruncate = Op.getOperand(3);
16339   SDValue Addr = Op.getOperand(2);
16340   SDValue Chain = Op.getOperand(0);
16341
16342   EVT VT  = DataToTruncate.getValueType();
16343   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16344                              ElementType, VT.getVectorNumElements());
16345
16346   if (isAllOnes(Mask)) // return just a truncate store
16347     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16348                              MachinePointerInfo(), SVT, false, false,
16349                              SVT.getScalarSizeInBits()/8);
16350
16351   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16352                                 MVT::i1, VT.getVectorNumElements());
16353   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16354                                    Mask.getValueType().getSizeInBits());
16355   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16356   // are extracted by EXTRACT_SUBVECTOR.
16357   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16358                               DAG.getBitcast(BitcastVT, Mask),
16359                               DAG.getIntPtrConstant(0, dl));
16360
16361   MachineMemOperand *MMO = DAG.getMachineFunction().
16362     getMachineMemOperand(MachinePointerInfo(),
16363                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16364                          SVT.getScalarSizeInBits()/8);
16365
16366   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16367                             VMask, SVT, MMO, true);
16368 }
16369
16370 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16371                                       SelectionDAG &DAG) {
16372   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16373
16374   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16375   if (!IntrData) {
16376     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16377       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16378     return SDValue();
16379   }
16380
16381   SDLoc dl(Op);
16382   switch(IntrData->Type) {
16383   default:
16384     llvm_unreachable("Unknown Intrinsic Type");
16385     break;
16386   case RDSEED:
16387   case RDRAND: {
16388     // Emit the node with the right value type.
16389     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16390     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16391
16392     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16393     // Otherwise return the value from Rand, which is always 0, casted to i32.
16394     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16395                       DAG.getConstant(1, dl, Op->getValueType(1)),
16396                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16397                       SDValue(Result.getNode(), 1) };
16398     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16399                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16400                                   Ops);
16401
16402     // Return { result, isValid, chain }.
16403     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16404                        SDValue(Result.getNode(), 2));
16405   }
16406   case GATHER: {
16407   //gather(v1, mask, index, base, scale);
16408     SDValue Chain = Op.getOperand(0);
16409     SDValue Src   = Op.getOperand(2);
16410     SDValue Base  = Op.getOperand(3);
16411     SDValue Index = Op.getOperand(4);
16412     SDValue Mask  = Op.getOperand(5);
16413     SDValue Scale = Op.getOperand(6);
16414     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16415                          Chain, Subtarget);
16416   }
16417   case SCATTER: {
16418   //scatter(base, mask, index, v1, scale);
16419     SDValue Chain = Op.getOperand(0);
16420     SDValue Base  = Op.getOperand(2);
16421     SDValue Mask  = Op.getOperand(3);
16422     SDValue Index = Op.getOperand(4);
16423     SDValue Src   = Op.getOperand(5);
16424     SDValue Scale = Op.getOperand(6);
16425     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16426                           Scale, Chain);
16427   }
16428   case PREFETCH: {
16429     SDValue Hint = Op.getOperand(6);
16430     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16431     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16432     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16433     SDValue Chain = Op.getOperand(0);
16434     SDValue Mask  = Op.getOperand(2);
16435     SDValue Index = Op.getOperand(3);
16436     SDValue Base  = Op.getOperand(4);
16437     SDValue Scale = Op.getOperand(5);
16438     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16439   }
16440   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16441   case RDTSC: {
16442     SmallVector<SDValue, 2> Results;
16443     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16444                             Results);
16445     return DAG.getMergeValues(Results, dl);
16446   }
16447   // Read Performance Monitoring Counters.
16448   case RDPMC: {
16449     SmallVector<SDValue, 2> Results;
16450     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16451     return DAG.getMergeValues(Results, dl);
16452   }
16453   // XTEST intrinsics.
16454   case XTEST: {
16455     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16456     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16457     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16458                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16459                                 InTrans);
16460     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16461     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16462                        Ret, SDValue(InTrans.getNode(), 1));
16463   }
16464   // ADC/ADCX/SBB
16465   case ADX: {
16466     SmallVector<SDValue, 2> Results;
16467     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16468     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16469     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16470                                 DAG.getConstant(-1, dl, MVT::i8));
16471     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16472                               Op.getOperand(4), GenCF.getValue(1));
16473     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16474                                  Op.getOperand(5), MachinePointerInfo(),
16475                                  false, false, 0);
16476     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16477                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16478                                 Res.getValue(1));
16479     Results.push_back(SetCC);
16480     Results.push_back(Store);
16481     return DAG.getMergeValues(Results, dl);
16482   }
16483   case COMPRESS_TO_MEM: {
16484     SDLoc dl(Op);
16485     SDValue Mask = Op.getOperand(4);
16486     SDValue DataToCompress = Op.getOperand(3);
16487     SDValue Addr = Op.getOperand(2);
16488     SDValue Chain = Op.getOperand(0);
16489
16490     EVT VT = DataToCompress.getValueType();
16491     if (isAllOnes(Mask)) // return just a store
16492       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16493                           MachinePointerInfo(), false, false,
16494                           VT.getScalarSizeInBits()/8);
16495
16496     SDValue Compressed =
16497       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16498                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16499     return DAG.getStore(Chain, dl, Compressed, Addr,
16500                         MachinePointerInfo(), false, false,
16501                         VT.getScalarSizeInBits()/8);
16502   }
16503   case TRUNCATE_TO_MEM_VI8:
16504     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16505   case TRUNCATE_TO_MEM_VI16:
16506     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16507   case TRUNCATE_TO_MEM_VI32:
16508     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16509   case EXPAND_FROM_MEM: {
16510     SDLoc dl(Op);
16511     SDValue Mask = Op.getOperand(4);
16512     SDValue PassThru = Op.getOperand(3);
16513     SDValue Addr = Op.getOperand(2);
16514     SDValue Chain = Op.getOperand(0);
16515     EVT VT = Op.getValueType();
16516
16517     if (isAllOnes(Mask)) // return just a load
16518       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16519                          false, VT.getScalarSizeInBits()/8);
16520
16521     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16522                                        false, false, false,
16523                                        VT.getScalarSizeInBits()/8);
16524
16525     SDValue Results[] = {
16526       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16527                            Mask, PassThru, Subtarget, DAG), Chain};
16528     return DAG.getMergeValues(Results, dl);
16529   }
16530   }
16531 }
16532
16533 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16534                                            SelectionDAG &DAG) const {
16535   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16536   MFI->setReturnAddressIsTaken(true);
16537
16538   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16539     return SDValue();
16540
16541   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16542   SDLoc dl(Op);
16543   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16544
16545   if (Depth > 0) {
16546     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16547     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16548     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16549     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16550                        DAG.getNode(ISD::ADD, dl, PtrVT,
16551                                    FrameAddr, Offset),
16552                        MachinePointerInfo(), false, false, false, 0);
16553   }
16554
16555   // Just load the return address.
16556   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16557   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16558                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16559 }
16560
16561 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16562   MachineFunction &MF = DAG.getMachineFunction();
16563   MachineFrameInfo *MFI = MF.getFrameInfo();
16564   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16565   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16566   EVT VT = Op.getValueType();
16567
16568   MFI->setFrameAddressIsTaken(true);
16569
16570   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16571     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16572     // is not possible to crawl up the stack without looking at the unwind codes
16573     // simultaneously.
16574     int FrameAddrIndex = FuncInfo->getFAIndex();
16575     if (!FrameAddrIndex) {
16576       // Set up a frame object for the return address.
16577       unsigned SlotSize = RegInfo->getSlotSize();
16578       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16579           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16580       FuncInfo->setFAIndex(FrameAddrIndex);
16581     }
16582     return DAG.getFrameIndex(FrameAddrIndex, VT);
16583   }
16584
16585   unsigned FrameReg =
16586       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16587   SDLoc dl(Op);  // FIXME probably not meaningful
16588   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16589   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16590           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16591          "Invalid Frame Register!");
16592   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16593   while (Depth--)
16594     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16595                             MachinePointerInfo(),
16596                             false, false, false, 0);
16597   return FrameAddr;
16598 }
16599
16600 // FIXME? Maybe this could be a TableGen attribute on some registers and
16601 // this table could be generated automatically from RegInfo.
16602 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16603                                               SelectionDAG &DAG) const {
16604   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16605   const MachineFunction &MF = DAG.getMachineFunction();
16606
16607   unsigned Reg = StringSwitch<unsigned>(RegName)
16608                        .Case("esp", X86::ESP)
16609                        .Case("rsp", X86::RSP)
16610                        .Case("ebp", X86::EBP)
16611                        .Case("rbp", X86::RBP)
16612                        .Default(0);
16613
16614   if (Reg == X86::EBP || Reg == X86::RBP) {
16615     if (!TFI.hasFP(MF))
16616       report_fatal_error("register " + StringRef(RegName) +
16617                          " is allocatable: function has no frame pointer");
16618 #ifndef NDEBUG
16619     else {
16620       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16621       unsigned FrameReg =
16622           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16623       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16624              "Invalid Frame Register!");
16625     }
16626 #endif
16627   }
16628
16629   if (Reg)
16630     return Reg;
16631
16632   report_fatal_error("Invalid register name global variable");
16633 }
16634
16635 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16636                                                      SelectionDAG &DAG) const {
16637   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16638   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16639 }
16640
16641 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16642   SDValue Chain     = Op.getOperand(0);
16643   SDValue Offset    = Op.getOperand(1);
16644   SDValue Handler   = Op.getOperand(2);
16645   SDLoc dl      (Op);
16646
16647   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16648   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16649   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16650   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16651           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16652          "Invalid Frame Register!");
16653   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16654   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16655
16656   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16657                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16658                                                        dl));
16659   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16660   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16661                        false, false, 0);
16662   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16663
16664   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16665                      DAG.getRegister(StoreAddrReg, PtrVT));
16666 }
16667
16668 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16669   SDValue Chain = Op.getOperand(0);
16670   SDValue Dest = Op.getOperand(1);
16671   SDLoc DL(Op);
16672
16673   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16674   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16675
16676   // Load the address of the destination block.
16677   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16678   SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16679   unsigned WrapperKind =
16680       Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16681   SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16682   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16683   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16684                      DAG.getRegister(ReturnReg, PtrVT));
16685 }
16686
16687 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16688                                                SelectionDAG &DAG) const {
16689   SDLoc DL(Op);
16690   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16691                      DAG.getVTList(MVT::i32, MVT::Other),
16692                      Op.getOperand(0), Op.getOperand(1));
16693 }
16694
16695 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16696                                                 SelectionDAG &DAG) const {
16697   SDLoc DL(Op);
16698   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16699                      Op.getOperand(0), Op.getOperand(1));
16700 }
16701
16702 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16703   return Op.getOperand(0);
16704 }
16705
16706 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16707                                                 SelectionDAG &DAG) const {
16708   SDValue Root = Op.getOperand(0);
16709   SDValue Trmp = Op.getOperand(1); // trampoline
16710   SDValue FPtr = Op.getOperand(2); // nested function
16711   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16712   SDLoc dl (Op);
16713
16714   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16715   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16716
16717   if (Subtarget->is64Bit()) {
16718     SDValue OutChains[6];
16719
16720     // Large code-model.
16721     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16722     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16723
16724     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16725     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16726
16727     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16728
16729     // Load the pointer to the nested function into R11.
16730     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16731     SDValue Addr = Trmp;
16732     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16733                                 Addr, MachinePointerInfo(TrmpAddr),
16734                                 false, false, 0);
16735
16736     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16737                        DAG.getConstant(2, dl, MVT::i64));
16738     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16739                                 MachinePointerInfo(TrmpAddr, 2),
16740                                 false, false, 2);
16741
16742     // Load the 'nest' parameter value into R10.
16743     // R10 is specified in X86CallingConv.td
16744     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16745     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16746                        DAG.getConstant(10, dl, MVT::i64));
16747     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16748                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16749                                 false, false, 0);
16750
16751     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16752                        DAG.getConstant(12, dl, MVT::i64));
16753     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16754                                 MachinePointerInfo(TrmpAddr, 12),
16755                                 false, false, 2);
16756
16757     // Jump to the nested function.
16758     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16759     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16760                        DAG.getConstant(20, dl, MVT::i64));
16761     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16762                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16763                                 false, false, 0);
16764
16765     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16766     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16767                        DAG.getConstant(22, dl, MVT::i64));
16768     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16769                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16770                                 false, false, 0);
16771
16772     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16773   } else {
16774     const Function *Func =
16775       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16776     CallingConv::ID CC = Func->getCallingConv();
16777     unsigned NestReg;
16778
16779     switch (CC) {
16780     default:
16781       llvm_unreachable("Unsupported calling convention");
16782     case CallingConv::C:
16783     case CallingConv::X86_StdCall: {
16784       // Pass 'nest' parameter in ECX.
16785       // Must be kept in sync with X86CallingConv.td
16786       NestReg = X86::ECX;
16787
16788       // Check that ECX wasn't needed by an 'inreg' parameter.
16789       FunctionType *FTy = Func->getFunctionType();
16790       const AttributeSet &Attrs = Func->getAttributes();
16791
16792       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16793         unsigned InRegCount = 0;
16794         unsigned Idx = 1;
16795
16796         for (FunctionType::param_iterator I = FTy->param_begin(),
16797              E = FTy->param_end(); I != E; ++I, ++Idx)
16798           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16799             auto &DL = DAG.getDataLayout();
16800             // FIXME: should only count parameters that are lowered to integers.
16801             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16802           }
16803
16804         if (InRegCount > 2) {
16805           report_fatal_error("Nest register in use - reduce number of inreg"
16806                              " parameters!");
16807         }
16808       }
16809       break;
16810     }
16811     case CallingConv::X86_FastCall:
16812     case CallingConv::X86_ThisCall:
16813     case CallingConv::Fast:
16814       // Pass 'nest' parameter in EAX.
16815       // Must be kept in sync with X86CallingConv.td
16816       NestReg = X86::EAX;
16817       break;
16818     }
16819
16820     SDValue OutChains[4];
16821     SDValue Addr, Disp;
16822
16823     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16824                        DAG.getConstant(10, dl, MVT::i32));
16825     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16826
16827     // This is storing the opcode for MOV32ri.
16828     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16829     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16830     OutChains[0] = DAG.getStore(Root, dl,
16831                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16832                                 Trmp, MachinePointerInfo(TrmpAddr),
16833                                 false, false, 0);
16834
16835     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16836                        DAG.getConstant(1, dl, MVT::i32));
16837     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16838                                 MachinePointerInfo(TrmpAddr, 1),
16839                                 false, false, 1);
16840
16841     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16842     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16843                        DAG.getConstant(5, dl, MVT::i32));
16844     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16845                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16846                                 false, false, 1);
16847
16848     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16849                        DAG.getConstant(6, dl, MVT::i32));
16850     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16851                                 MachinePointerInfo(TrmpAddr, 6),
16852                                 false, false, 1);
16853
16854     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16855   }
16856 }
16857
16858 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16859                                             SelectionDAG &DAG) const {
16860   /*
16861    The rounding mode is in bits 11:10 of FPSR, and has the following
16862    settings:
16863      00 Round to nearest
16864      01 Round to -inf
16865      10 Round to +inf
16866      11 Round to 0
16867
16868   FLT_ROUNDS, on the other hand, expects the following:
16869     -1 Undefined
16870      0 Round to 0
16871      1 Round to nearest
16872      2 Round to +inf
16873      3 Round to -inf
16874
16875   To perform the conversion, we do:
16876     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16877   */
16878
16879   MachineFunction &MF = DAG.getMachineFunction();
16880   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16881   unsigned StackAlignment = TFI.getStackAlignment();
16882   MVT VT = Op.getSimpleValueType();
16883   SDLoc DL(Op);
16884
16885   // Save FP Control Word to stack slot
16886   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16887   SDValue StackSlot =
16888       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16889
16890   MachineMemOperand *MMO =
16891       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16892                               MachineMemOperand::MOStore, 2, 2);
16893
16894   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16895   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16896                                           DAG.getVTList(MVT::Other),
16897                                           Ops, MVT::i16, MMO);
16898
16899   // Load FP Control Word from stack slot
16900   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16901                             MachinePointerInfo(), false, false, false, 0);
16902
16903   // Transform as necessary
16904   SDValue CWD1 =
16905     DAG.getNode(ISD::SRL, DL, MVT::i16,
16906                 DAG.getNode(ISD::AND, DL, MVT::i16,
16907                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16908                 DAG.getConstant(11, DL, MVT::i8));
16909   SDValue CWD2 =
16910     DAG.getNode(ISD::SRL, DL, MVT::i16,
16911                 DAG.getNode(ISD::AND, DL, MVT::i16,
16912                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16913                 DAG.getConstant(9, DL, MVT::i8));
16914
16915   SDValue RetVal =
16916     DAG.getNode(ISD::AND, DL, MVT::i16,
16917                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16918                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16919                             DAG.getConstant(1, DL, MVT::i16)),
16920                 DAG.getConstant(3, DL, MVT::i16));
16921
16922   return DAG.getNode((VT.getSizeInBits() < 16 ?
16923                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16924 }
16925
16926 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16927   MVT VT = Op.getSimpleValueType();
16928   EVT OpVT = VT;
16929   unsigned NumBits = VT.getSizeInBits();
16930   SDLoc dl(Op);
16931
16932   Op = Op.getOperand(0);
16933   if (VT == MVT::i8) {
16934     // Zero extend to i32 since there is not an i8 bsr.
16935     OpVT = MVT::i32;
16936     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16937   }
16938
16939   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16940   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16941   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16942
16943   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16944   SDValue Ops[] = {
16945     Op,
16946     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16947     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16948     Op.getValue(1)
16949   };
16950   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16951
16952   // Finally xor with NumBits-1.
16953   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16954                    DAG.getConstant(NumBits - 1, dl, OpVT));
16955
16956   if (VT == MVT::i8)
16957     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16958   return Op;
16959 }
16960
16961 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16962   MVT VT = Op.getSimpleValueType();
16963   EVT OpVT = VT;
16964   unsigned NumBits = VT.getSizeInBits();
16965   SDLoc dl(Op);
16966
16967   Op = Op.getOperand(0);
16968   if (VT == MVT::i8) {
16969     // Zero extend to i32 since there is not an i8 bsr.
16970     OpVT = MVT::i32;
16971     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16972   }
16973
16974   // Issue a bsr (scan bits in reverse).
16975   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16976   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16977
16978   // And xor with NumBits-1.
16979   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16980                    DAG.getConstant(NumBits - 1, dl, OpVT));
16981
16982   if (VT == MVT::i8)
16983     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16984   return Op;
16985 }
16986
16987 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16988   MVT VT = Op.getSimpleValueType();
16989   unsigned NumBits = VT.getSizeInBits();
16990   SDLoc dl(Op);
16991   Op = Op.getOperand(0);
16992
16993   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16994   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16995   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16996
16997   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16998   SDValue Ops[] = {
16999     Op,
17000     DAG.getConstant(NumBits, dl, VT),
17001     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17002     Op.getValue(1)
17003   };
17004   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17005 }
17006
17007 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17008 // ones, and then concatenate the result back.
17009 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17010   MVT VT = Op.getSimpleValueType();
17011
17012   assert(VT.is256BitVector() && VT.isInteger() &&
17013          "Unsupported value type for operation");
17014
17015   unsigned NumElems = VT.getVectorNumElements();
17016   SDLoc dl(Op);
17017
17018   // Extract the LHS vectors
17019   SDValue LHS = Op.getOperand(0);
17020   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17021   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17022
17023   // Extract the RHS vectors
17024   SDValue RHS = Op.getOperand(1);
17025   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17026   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17027
17028   MVT EltVT = VT.getVectorElementType();
17029   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17030
17031   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17032                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17033                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17034 }
17035
17036 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17037   if (Op.getValueType() == MVT::i1)
17038     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17039                        Op.getOperand(0), Op.getOperand(1));
17040   assert(Op.getSimpleValueType().is256BitVector() &&
17041          Op.getSimpleValueType().isInteger() &&
17042          "Only handle AVX 256-bit vector integer operation");
17043   return Lower256IntArith(Op, DAG);
17044 }
17045
17046 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17047   if (Op.getValueType() == MVT::i1)
17048     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17049                        Op.getOperand(0), Op.getOperand(1));
17050   assert(Op.getSimpleValueType().is256BitVector() &&
17051          Op.getSimpleValueType().isInteger() &&
17052          "Only handle AVX 256-bit vector integer operation");
17053   return Lower256IntArith(Op, DAG);
17054 }
17055
17056 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17057   assert(Op.getSimpleValueType().is256BitVector() &&
17058          Op.getSimpleValueType().isInteger() &&
17059          "Only handle AVX 256-bit vector integer operation");
17060   return Lower256IntArith(Op, DAG);
17061 }
17062
17063 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17064                         SelectionDAG &DAG) {
17065   SDLoc dl(Op);
17066   MVT VT = Op.getSimpleValueType();
17067
17068   if (VT == MVT::i1)
17069     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17070
17071   // Decompose 256-bit ops into smaller 128-bit ops.
17072   if (VT.is256BitVector() && !Subtarget->hasInt256())
17073     return Lower256IntArith(Op, DAG);
17074
17075   SDValue A = Op.getOperand(0);
17076   SDValue B = Op.getOperand(1);
17077
17078   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17079   // pairs, multiply and truncate.
17080   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17081     if (Subtarget->hasInt256()) {
17082       if (VT == MVT::v32i8) {
17083         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17084         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17085         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17086         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17087         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17088         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17089         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17090         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17091                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17092                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17093       }
17094
17095       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17096       return DAG.getNode(
17097           ISD::TRUNCATE, dl, VT,
17098           DAG.getNode(ISD::MUL, dl, ExVT,
17099                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17100                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17101     }
17102
17103     assert(VT == MVT::v16i8 &&
17104            "Pre-AVX2 support only supports v16i8 multiplication");
17105     MVT ExVT = MVT::v8i16;
17106
17107     // Extract the lo parts and sign extend to i16
17108     SDValue ALo, BLo;
17109     if (Subtarget->hasSSE41()) {
17110       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17111       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17112     } else {
17113       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17114                               -1, 4, -1, 5, -1, 6, -1, 7};
17115       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17116       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17117       ALo = DAG.getBitcast(ExVT, ALo);
17118       BLo = DAG.getBitcast(ExVT, BLo);
17119       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17120       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17121     }
17122
17123     // Extract the hi parts and sign extend to i16
17124     SDValue AHi, BHi;
17125     if (Subtarget->hasSSE41()) {
17126       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17127                               -1, -1, -1, -1, -1, -1, -1, -1};
17128       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17129       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17130       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17131       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17132     } else {
17133       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17134                               -1, 12, -1, 13, -1, 14, -1, 15};
17135       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17136       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17137       AHi = DAG.getBitcast(ExVT, AHi);
17138       BHi = DAG.getBitcast(ExVT, BHi);
17139       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17140       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17141     }
17142
17143     // Multiply, mask the lower 8bits of the lo/hi results and pack
17144     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17145     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17146     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17147     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17148     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17149   }
17150
17151   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17152   if (VT == MVT::v4i32) {
17153     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17154            "Should not custom lower when pmuldq is available!");
17155
17156     // Extract the odd parts.
17157     static const int UnpackMask[] = { 1, -1, 3, -1 };
17158     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17159     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17160
17161     // Multiply the even parts.
17162     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17163     // Now multiply odd parts.
17164     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17165
17166     Evens = DAG.getBitcast(VT, Evens);
17167     Odds = DAG.getBitcast(VT, Odds);
17168
17169     // Merge the two vectors back together with a shuffle. This expands into 2
17170     // shuffles.
17171     static const int ShufMask[] = { 0, 4, 2, 6 };
17172     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17173   }
17174
17175   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17176          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17177
17178   //  Ahi = psrlqi(a, 32);
17179   //  Bhi = psrlqi(b, 32);
17180   //
17181   //  AloBlo = pmuludq(a, b);
17182   //  AloBhi = pmuludq(a, Bhi);
17183   //  AhiBlo = pmuludq(Ahi, b);
17184
17185   //  AloBhi = psllqi(AloBhi, 32);
17186   //  AhiBlo = psllqi(AhiBlo, 32);
17187   //  return AloBlo + AloBhi + AhiBlo;
17188
17189   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17190   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17191
17192   SDValue AhiBlo = Ahi;
17193   SDValue AloBhi = Bhi;
17194   // Bit cast to 32-bit vectors for MULUDQ
17195   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17196                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17197   A = DAG.getBitcast(MulVT, A);
17198   B = DAG.getBitcast(MulVT, B);
17199   Ahi = DAG.getBitcast(MulVT, Ahi);
17200   Bhi = DAG.getBitcast(MulVT, Bhi);
17201
17202   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17203   // After shifting right const values the result may be all-zero.
17204   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17205     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17206     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17207   }
17208   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17209     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17210     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17211   }
17212
17213   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17214   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17215 }
17216
17217 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17218   assert(Subtarget->isTargetWin64() && "Unexpected target");
17219   EVT VT = Op.getValueType();
17220   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17221          "Unexpected return type for lowering");
17222
17223   RTLIB::Libcall LC;
17224   bool isSigned;
17225   switch (Op->getOpcode()) {
17226   default: llvm_unreachable("Unexpected request for libcall!");
17227   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17228   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17229   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17230   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17231   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17232   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17233   }
17234
17235   SDLoc dl(Op);
17236   SDValue InChain = DAG.getEntryNode();
17237
17238   TargetLowering::ArgListTy Args;
17239   TargetLowering::ArgListEntry Entry;
17240   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17241     EVT ArgVT = Op->getOperand(i).getValueType();
17242     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17243            "Unexpected argument type for lowering");
17244     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17245     Entry.Node = StackPtr;
17246     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17247                            false, false, 16);
17248     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17249     Entry.Ty = PointerType::get(ArgTy,0);
17250     Entry.isSExt = false;
17251     Entry.isZExt = false;
17252     Args.push_back(Entry);
17253   }
17254
17255   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17256                                          getPointerTy(DAG.getDataLayout()));
17257
17258   TargetLowering::CallLoweringInfo CLI(DAG);
17259   CLI.setDebugLoc(dl).setChain(InChain)
17260     .setCallee(getLibcallCallingConv(LC),
17261                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17262                Callee, std::move(Args), 0)
17263     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17264
17265   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17266   return DAG.getBitcast(VT, CallInfo.first);
17267 }
17268
17269 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17270                              SelectionDAG &DAG) {
17271   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17272   EVT VT = Op0.getValueType();
17273   SDLoc dl(Op);
17274
17275   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17276          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17277
17278   // PMULxD operations multiply each even value (starting at 0) of LHS with
17279   // the related value of RHS and produce a widen result.
17280   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17281   // => <2 x i64> <ae|cg>
17282   //
17283   // In other word, to have all the results, we need to perform two PMULxD:
17284   // 1. one with the even values.
17285   // 2. one with the odd values.
17286   // To achieve #2, with need to place the odd values at an even position.
17287   //
17288   // Place the odd value at an even position (basically, shift all values 1
17289   // step to the left):
17290   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17291   // <a|b|c|d> => <b|undef|d|undef>
17292   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17293   // <e|f|g|h> => <f|undef|h|undef>
17294   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17295
17296   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17297   // ints.
17298   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17299   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17300   unsigned Opcode =
17301       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17302   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17303   // => <2 x i64> <ae|cg>
17304   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17305   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17306   // => <2 x i64> <bf|dh>
17307   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17308
17309   // Shuffle it back into the right order.
17310   SDValue Highs, Lows;
17311   if (VT == MVT::v8i32) {
17312     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17313     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17314     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17315     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17316   } else {
17317     const int HighMask[] = {1, 5, 3, 7};
17318     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17319     const int LowMask[] = {0, 4, 2, 6};
17320     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17321   }
17322
17323   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17324   // unsigned multiply.
17325   if (IsSigned && !Subtarget->hasSSE41()) {
17326     SDValue ShAmt = DAG.getConstant(
17327         31, dl,
17328         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17329     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17330                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17331     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17332                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17333
17334     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17335     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17336   }
17337
17338   // The first result of MUL_LOHI is actually the low value, followed by the
17339   // high value.
17340   SDValue Ops[] = {Lows, Highs};
17341   return DAG.getMergeValues(Ops, dl);
17342 }
17343
17344 // Return true if the required (according to Opcode) shift-imm form is natively
17345 // supported by the Subtarget
17346 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17347                                         unsigned Opcode) {
17348   if (VT.getScalarSizeInBits() < 16)
17349     return false;
17350
17351   if (VT.is512BitVector() &&
17352       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17353     return true;
17354
17355   bool LShift = VT.is128BitVector() ||
17356     (VT.is256BitVector() && Subtarget->hasInt256());
17357
17358   bool AShift = LShift && (Subtarget->hasVLX() ||
17359     (VT != MVT::v2i64 && VT != MVT::v4i64));
17360   return (Opcode == ISD::SRA) ? AShift : LShift;
17361 }
17362
17363 // The shift amount is a variable, but it is the same for all vector lanes.
17364 // These instructions are defined together with shift-immediate.
17365 static
17366 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17367                                       unsigned Opcode) {
17368   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17369 }
17370
17371 // Return true if the required (according to Opcode) variable-shift form is
17372 // natively supported by the Subtarget
17373 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17374                                     unsigned Opcode) {
17375
17376   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17377     return false;
17378
17379   // vXi16 supported only on AVX-512, BWI
17380   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17381     return false;
17382
17383   if (VT.is512BitVector() || Subtarget->hasVLX())
17384     return true;
17385
17386   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17387   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17388   return (Opcode == ISD::SRA) ? AShift : LShift;
17389 }
17390
17391 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17392                                          const X86Subtarget *Subtarget) {
17393   MVT VT = Op.getSimpleValueType();
17394   SDLoc dl(Op);
17395   SDValue R = Op.getOperand(0);
17396   SDValue Amt = Op.getOperand(1);
17397
17398   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17399     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17400
17401   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17402     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17403     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17404     SDValue Ex = DAG.getBitcast(ExVT, R);
17405
17406     if (ShiftAmt >= 32) {
17407       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17408       SDValue Upper =
17409           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17410       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17411                                                  ShiftAmt - 32, DAG);
17412       if (VT == MVT::v2i64)
17413         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17414       if (VT == MVT::v4i64)
17415         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17416                                   {9, 1, 11, 3, 13, 5, 15, 7});
17417     } else {
17418       // SRA upper i32, SHL whole i64 and select lower i32.
17419       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17420                                                  ShiftAmt, DAG);
17421       SDValue Lower =
17422           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17423       Lower = DAG.getBitcast(ExVT, Lower);
17424       if (VT == MVT::v2i64)
17425         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17426       if (VT == MVT::v4i64)
17427         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17428                                   {8, 1, 10, 3, 12, 5, 14, 7});
17429     }
17430     return DAG.getBitcast(VT, Ex);
17431   };
17432
17433   // Optimize shl/srl/sra with constant shift amount.
17434   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17435     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17436       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17437
17438       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17439         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17440
17441       // i64 SRA needs to be performed as partial shifts.
17442       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17443           Op.getOpcode() == ISD::SRA)
17444         return ArithmeticShiftRight64(ShiftAmt);
17445
17446       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17447         unsigned NumElts = VT.getVectorNumElements();
17448         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17449
17450         if (Op.getOpcode() == ISD::SHL) {
17451           // Simple i8 add case
17452           if (ShiftAmt == 1)
17453             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17454
17455           // Make a large shift.
17456           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17457                                                    R, ShiftAmt, DAG);
17458           SHL = DAG.getBitcast(VT, SHL);
17459           // Zero out the rightmost bits.
17460           SmallVector<SDValue, 32> V(
17461               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17462           return DAG.getNode(ISD::AND, dl, VT, SHL,
17463                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17464         }
17465         if (Op.getOpcode() == ISD::SRL) {
17466           // Make a large shift.
17467           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17468                                                    R, ShiftAmt, DAG);
17469           SRL = DAG.getBitcast(VT, SRL);
17470           // Zero out the leftmost bits.
17471           SmallVector<SDValue, 32> V(
17472               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17473           return DAG.getNode(ISD::AND, dl, VT, SRL,
17474                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17475         }
17476         if (Op.getOpcode() == ISD::SRA) {
17477           if (ShiftAmt == 7) {
17478             // ashr(R, 7)  === cmp_slt(R, 0)
17479             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17480             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17481           }
17482
17483           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17484           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17485           SmallVector<SDValue, 32> V(NumElts,
17486                                      DAG.getConstant(128 >> ShiftAmt, dl,
17487                                                      MVT::i8));
17488           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17489           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17490           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17491           return Res;
17492         }
17493         llvm_unreachable("Unknown shift opcode.");
17494       }
17495     }
17496   }
17497
17498   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17499   if (!Subtarget->is64Bit() &&
17500       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17501
17502     // Peek through any splat that was introduced for i64 shift vectorization.
17503     int SplatIndex = -1;
17504     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17505       if (SVN->isSplat()) {
17506         SplatIndex = SVN->getSplatIndex();
17507         Amt = Amt.getOperand(0);
17508         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17509                "Splat shuffle referencing second operand");
17510       }
17511
17512     if (Amt.getOpcode() != ISD::BITCAST ||
17513         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17514       return SDValue();
17515
17516     Amt = Amt.getOperand(0);
17517     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17518                      VT.getVectorNumElements();
17519     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17520     uint64_t ShiftAmt = 0;
17521     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17522     for (unsigned i = 0; i != Ratio; ++i) {
17523       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17524       if (!C)
17525         return SDValue();
17526       // 6 == Log2(64)
17527       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17528     }
17529
17530     // Check remaining shift amounts (if not a splat).
17531     if (SplatIndex < 0) {
17532       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17533         uint64_t ShAmt = 0;
17534         for (unsigned j = 0; j != Ratio; ++j) {
17535           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17536           if (!C)
17537             return SDValue();
17538           // 6 == Log2(64)
17539           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17540         }
17541         if (ShAmt != ShiftAmt)
17542           return SDValue();
17543       }
17544     }
17545
17546     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17547       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17548
17549     if (Op.getOpcode() == ISD::SRA)
17550       return ArithmeticShiftRight64(ShiftAmt);
17551   }
17552
17553   return SDValue();
17554 }
17555
17556 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17557                                         const X86Subtarget* Subtarget) {
17558   MVT VT = Op.getSimpleValueType();
17559   SDLoc dl(Op);
17560   SDValue R = Op.getOperand(0);
17561   SDValue Amt = Op.getOperand(1);
17562
17563   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17564     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17565
17566   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17567     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17568
17569   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17570     SDValue BaseShAmt;
17571     EVT EltVT = VT.getVectorElementType();
17572
17573     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17574       // Check if this build_vector node is doing a splat.
17575       // If so, then set BaseShAmt equal to the splat value.
17576       BaseShAmt = BV->getSplatValue();
17577       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17578         BaseShAmt = SDValue();
17579     } else {
17580       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17581         Amt = Amt.getOperand(0);
17582
17583       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17584       if (SVN && SVN->isSplat()) {
17585         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17586         SDValue InVec = Amt.getOperand(0);
17587         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17588           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17589                  "Unexpected shuffle index found!");
17590           BaseShAmt = InVec.getOperand(SplatIdx);
17591         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17592            if (ConstantSDNode *C =
17593                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17594              if (C->getZExtValue() == SplatIdx)
17595                BaseShAmt = InVec.getOperand(1);
17596            }
17597         }
17598
17599         if (!BaseShAmt)
17600           // Avoid introducing an extract element from a shuffle.
17601           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17602                                   DAG.getIntPtrConstant(SplatIdx, dl));
17603       }
17604     }
17605
17606     if (BaseShAmt.getNode()) {
17607       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17608       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17609         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17610       else if (EltVT.bitsLT(MVT::i32))
17611         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17612
17613       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17614     }
17615   }
17616
17617   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17618   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17619       Amt.getOpcode() == ISD::BITCAST &&
17620       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17621     Amt = Amt.getOperand(0);
17622     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17623                      VT.getVectorNumElements();
17624     std::vector<SDValue> Vals(Ratio);
17625     for (unsigned i = 0; i != Ratio; ++i)
17626       Vals[i] = Amt.getOperand(i);
17627     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17628       for (unsigned j = 0; j != Ratio; ++j)
17629         if (Vals[j] != Amt.getOperand(i + j))
17630           return SDValue();
17631     }
17632
17633     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17634       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17635   }
17636   return SDValue();
17637 }
17638
17639 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17640                           SelectionDAG &DAG) {
17641   MVT VT = Op.getSimpleValueType();
17642   SDLoc dl(Op);
17643   SDValue R = Op.getOperand(0);
17644   SDValue Amt = Op.getOperand(1);
17645
17646   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17647   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17648
17649   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17650     return V;
17651
17652   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17653       return V;
17654
17655   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17656     return Op;
17657
17658   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17659   // shifts per-lane and then shuffle the partial results back together.
17660   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17661     // Splat the shift amounts so the scalar shifts above will catch it.
17662     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17663     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17664     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17665     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17666     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17667   }
17668
17669   // i64 vector arithmetic shift can be emulated with the transform:
17670   // M = lshr(SIGN_BIT, Amt)
17671   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17672   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17673       Op.getOpcode() == ISD::SRA) {
17674     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17675     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17676     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17677     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17678     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17679     return R;
17680   }
17681
17682   // If possible, lower this packed shift into a vector multiply instead of
17683   // expanding it into a sequence of scalar shifts.
17684   // Do this only if the vector shift count is a constant build_vector.
17685   if (Op.getOpcode() == ISD::SHL &&
17686       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17687        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17688       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17689     SmallVector<SDValue, 8> Elts;
17690     EVT SVT = VT.getScalarType();
17691     unsigned SVTBits = SVT.getSizeInBits();
17692     const APInt &One = APInt(SVTBits, 1);
17693     unsigned NumElems = VT.getVectorNumElements();
17694
17695     for (unsigned i=0; i !=NumElems; ++i) {
17696       SDValue Op = Amt->getOperand(i);
17697       if (Op->getOpcode() == ISD::UNDEF) {
17698         Elts.push_back(Op);
17699         continue;
17700       }
17701
17702       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17703       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17704       uint64_t ShAmt = C.getZExtValue();
17705       if (ShAmt >= SVTBits) {
17706         Elts.push_back(DAG.getUNDEF(SVT));
17707         continue;
17708       }
17709       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17710     }
17711     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17712     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17713   }
17714
17715   // Lower SHL with variable shift amount.
17716   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17717     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17718
17719     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17720                      DAG.getConstant(0x3f800000U, dl, VT));
17721     Op = DAG.getBitcast(MVT::v4f32, Op);
17722     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17723     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17724   }
17725
17726   // If possible, lower this shift as a sequence of two shifts by
17727   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17728   // Example:
17729   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17730   //
17731   // Could be rewritten as:
17732   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17733   //
17734   // The advantage is that the two shifts from the example would be
17735   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17736   // the vector shift into four scalar shifts plus four pairs of vector
17737   // insert/extract.
17738   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17739       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17740     unsigned TargetOpcode = X86ISD::MOVSS;
17741     bool CanBeSimplified;
17742     // The splat value for the first packed shift (the 'X' from the example).
17743     SDValue Amt1 = Amt->getOperand(0);
17744     // The splat value for the second packed shift (the 'Y' from the example).
17745     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17746                                         Amt->getOperand(2);
17747
17748     // See if it is possible to replace this node with a sequence of
17749     // two shifts followed by a MOVSS/MOVSD
17750     if (VT == MVT::v4i32) {
17751       // Check if it is legal to use a MOVSS.
17752       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17753                         Amt2 == Amt->getOperand(3);
17754       if (!CanBeSimplified) {
17755         // Otherwise, check if we can still simplify this node using a MOVSD.
17756         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17757                           Amt->getOperand(2) == Amt->getOperand(3);
17758         TargetOpcode = X86ISD::MOVSD;
17759         Amt2 = Amt->getOperand(2);
17760       }
17761     } else {
17762       // Do similar checks for the case where the machine value type
17763       // is MVT::v8i16.
17764       CanBeSimplified = Amt1 == Amt->getOperand(1);
17765       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17766         CanBeSimplified = Amt2 == Amt->getOperand(i);
17767
17768       if (!CanBeSimplified) {
17769         TargetOpcode = X86ISD::MOVSD;
17770         CanBeSimplified = true;
17771         Amt2 = Amt->getOperand(4);
17772         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17773           CanBeSimplified = Amt1 == Amt->getOperand(i);
17774         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17775           CanBeSimplified = Amt2 == Amt->getOperand(j);
17776       }
17777     }
17778
17779     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17780         isa<ConstantSDNode>(Amt2)) {
17781       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17782       EVT CastVT = MVT::v4i32;
17783       SDValue Splat1 =
17784         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17785       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17786       SDValue Splat2 =
17787         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17788       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17789       if (TargetOpcode == X86ISD::MOVSD)
17790         CastVT = MVT::v2i64;
17791       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17792       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17793       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17794                                             BitCast1, DAG);
17795       return DAG.getBitcast(VT, Result);
17796     }
17797   }
17798
17799   // v4i32 Non Uniform Shifts.
17800   // If the shift amount is constant we can shift each lane using the SSE2
17801   // immediate shifts, else we need to zero-extend each lane to the lower i64
17802   // and shift using the SSE2 variable shifts.
17803   // The separate results can then be blended together.
17804   if (VT == MVT::v4i32) {
17805     unsigned Opc = Op.getOpcode();
17806     SDValue Amt0, Amt1, Amt2, Amt3;
17807     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17808       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17809       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17810       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17811       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17812     } else {
17813       // ISD::SHL is handled above but we include it here for completeness.
17814       switch (Opc) {
17815       default:
17816         llvm_unreachable("Unknown target vector shift node");
17817       case ISD::SHL:
17818         Opc = X86ISD::VSHL;
17819         break;
17820       case ISD::SRL:
17821         Opc = X86ISD::VSRL;
17822         break;
17823       case ISD::SRA:
17824         Opc = X86ISD::VSRA;
17825         break;
17826       }
17827       // The SSE2 shifts use the lower i64 as the same shift amount for
17828       // all lanes and the upper i64 is ignored. These shuffle masks
17829       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17830       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17831       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17832       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17833       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17834       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17835     }
17836
17837     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17838     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17839     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17840     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17841     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17842     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17843     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17844   }
17845
17846   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17847     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17848     unsigned ShiftOpcode = Op->getOpcode();
17849
17850     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17851       // On SSE41 targets we make use of the fact that VSELECT lowers
17852       // to PBLENDVB which selects bytes based just on the sign bit.
17853       if (Subtarget->hasSSE41()) {
17854         V0 = DAG.getBitcast(VT, V0);
17855         V1 = DAG.getBitcast(VT, V1);
17856         Sel = DAG.getBitcast(VT, Sel);
17857         return DAG.getBitcast(SelVT,
17858                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17859       }
17860       // On pre-SSE41 targets we test for the sign bit by comparing to
17861       // zero - a negative value will set all bits of the lanes to true
17862       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17863       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17864       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17865       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17866     };
17867
17868     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17869     // We can safely do this using i16 shifts as we're only interested in
17870     // the 3 lower bits of each byte.
17871     Amt = DAG.getBitcast(ExtVT, Amt);
17872     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17873     Amt = DAG.getBitcast(VT, Amt);
17874
17875     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17876       // r = VSELECT(r, shift(r, 4), a);
17877       SDValue M =
17878           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17879       R = SignBitSelect(VT, Amt, M, R);
17880
17881       // a += a
17882       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17883
17884       // r = VSELECT(r, shift(r, 2), a);
17885       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17886       R = SignBitSelect(VT, Amt, M, R);
17887
17888       // a += a
17889       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17890
17891       // return VSELECT(r, shift(r, 1), a);
17892       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17893       R = SignBitSelect(VT, Amt, M, R);
17894       return R;
17895     }
17896
17897     if (Op->getOpcode() == ISD::SRA) {
17898       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17899       // so we can correctly sign extend. We don't care what happens to the
17900       // lower byte.
17901       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17902       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17903       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17904       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17905       ALo = DAG.getBitcast(ExtVT, ALo);
17906       AHi = DAG.getBitcast(ExtVT, AHi);
17907       RLo = DAG.getBitcast(ExtVT, RLo);
17908       RHi = DAG.getBitcast(ExtVT, RHi);
17909
17910       // r = VSELECT(r, shift(r, 4), a);
17911       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17912                                 DAG.getConstant(4, dl, ExtVT));
17913       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17914                                 DAG.getConstant(4, dl, ExtVT));
17915       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17916       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17917
17918       // a += a
17919       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17920       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17921
17922       // r = VSELECT(r, shift(r, 2), a);
17923       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17924                         DAG.getConstant(2, dl, ExtVT));
17925       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17926                         DAG.getConstant(2, dl, ExtVT));
17927       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17928       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17929
17930       // a += a
17931       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17932       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17933
17934       // r = VSELECT(r, shift(r, 1), a);
17935       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17936                         DAG.getConstant(1, dl, ExtVT));
17937       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17938                         DAG.getConstant(1, dl, ExtVT));
17939       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17940       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17941
17942       // Logical shift the result back to the lower byte, leaving a zero upper
17943       // byte
17944       // meaning that we can safely pack with PACKUSWB.
17945       RLo =
17946           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17947       RHi =
17948           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17949       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17950     }
17951   }
17952
17953   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17954   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17955   // solution better.
17956   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17957     MVT ExtVT = MVT::v8i32;
17958     unsigned ExtOpc =
17959         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17960     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17961     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17962     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17963                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17964   }
17965
17966   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17967     MVT ExtVT = MVT::v8i32;
17968     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17969     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17970     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17971     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17972     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17973     ALo = DAG.getBitcast(ExtVT, ALo);
17974     AHi = DAG.getBitcast(ExtVT, AHi);
17975     RLo = DAG.getBitcast(ExtVT, RLo);
17976     RHi = DAG.getBitcast(ExtVT, RHi);
17977     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17978     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17979     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17980     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17981     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17982   }
17983
17984   if (VT == MVT::v8i16) {
17985     unsigned ShiftOpcode = Op->getOpcode();
17986
17987     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17988       // On SSE41 targets we make use of the fact that VSELECT lowers
17989       // to PBLENDVB which selects bytes based just on the sign bit.
17990       if (Subtarget->hasSSE41()) {
17991         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17992         V0 = DAG.getBitcast(ExtVT, V0);
17993         V1 = DAG.getBitcast(ExtVT, V1);
17994         Sel = DAG.getBitcast(ExtVT, Sel);
17995         return DAG.getBitcast(
17996             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17997       }
17998       // On pre-SSE41 targets we splat the sign bit - a negative value will
17999       // set all bits of the lanes to true and VSELECT uses that in
18000       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18001       SDValue C =
18002           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18003       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18004     };
18005
18006     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18007     if (Subtarget->hasSSE41()) {
18008       // On SSE41 targets we need to replicate the shift mask in both
18009       // bytes for PBLENDVB.
18010       Amt = DAG.getNode(
18011           ISD::OR, dl, VT,
18012           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18013           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18014     } else {
18015       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18016     }
18017
18018     // r = VSELECT(r, shift(r, 8), a);
18019     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18020     R = SignBitSelect(Amt, M, R);
18021
18022     // a += a
18023     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18024
18025     // r = VSELECT(r, shift(r, 4), a);
18026     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18027     R = SignBitSelect(Amt, M, R);
18028
18029     // a += a
18030     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18031
18032     // r = VSELECT(r, shift(r, 2), a);
18033     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18034     R = SignBitSelect(Amt, M, R);
18035
18036     // a += a
18037     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18038
18039     // return VSELECT(r, shift(r, 1), a);
18040     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18041     R = SignBitSelect(Amt, M, R);
18042     return R;
18043   }
18044
18045   // Decompose 256-bit shifts into smaller 128-bit shifts.
18046   if (VT.is256BitVector()) {
18047     unsigned NumElems = VT.getVectorNumElements();
18048     MVT EltVT = VT.getVectorElementType();
18049     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18050
18051     // Extract the two vectors
18052     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18053     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18054
18055     // Recreate the shift amount vectors
18056     SDValue Amt1, Amt2;
18057     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18058       // Constant shift amount
18059       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18060       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18061       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18062
18063       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18064       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18065     } else {
18066       // Variable shift amount
18067       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18068       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18069     }
18070
18071     // Issue new vector shifts for the smaller types
18072     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18073     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18074
18075     // Concatenate the result back
18076     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18077   }
18078
18079   return SDValue();
18080 }
18081
18082 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18083   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18084   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18085   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18086   // has only one use.
18087   SDNode *N = Op.getNode();
18088   SDValue LHS = N->getOperand(0);
18089   SDValue RHS = N->getOperand(1);
18090   unsigned BaseOp = 0;
18091   unsigned Cond = 0;
18092   SDLoc DL(Op);
18093   switch (Op.getOpcode()) {
18094   default: llvm_unreachable("Unknown ovf instruction!");
18095   case ISD::SADDO:
18096     // A subtract of one will be selected as a INC. Note that INC doesn't
18097     // set CF, so we can't do this for UADDO.
18098     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18099       if (C->isOne()) {
18100         BaseOp = X86ISD::INC;
18101         Cond = X86::COND_O;
18102         break;
18103       }
18104     BaseOp = X86ISD::ADD;
18105     Cond = X86::COND_O;
18106     break;
18107   case ISD::UADDO:
18108     BaseOp = X86ISD::ADD;
18109     Cond = X86::COND_B;
18110     break;
18111   case ISD::SSUBO:
18112     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18113     // set CF, so we can't do this for USUBO.
18114     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18115       if (C->isOne()) {
18116         BaseOp = X86ISD::DEC;
18117         Cond = X86::COND_O;
18118         break;
18119       }
18120     BaseOp = X86ISD::SUB;
18121     Cond = X86::COND_O;
18122     break;
18123   case ISD::USUBO:
18124     BaseOp = X86ISD::SUB;
18125     Cond = X86::COND_B;
18126     break;
18127   case ISD::SMULO:
18128     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18129     Cond = X86::COND_O;
18130     break;
18131   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18132     if (N->getValueType(0) == MVT::i8) {
18133       BaseOp = X86ISD::UMUL8;
18134       Cond = X86::COND_O;
18135       break;
18136     }
18137     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18138                                  MVT::i32);
18139     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18140
18141     SDValue SetCC =
18142       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18143                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18144                   SDValue(Sum.getNode(), 2));
18145
18146     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18147   }
18148   }
18149
18150   // Also sets EFLAGS.
18151   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18152   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18153
18154   SDValue SetCC =
18155     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18156                 DAG.getConstant(Cond, DL, MVT::i32),
18157                 SDValue(Sum.getNode(), 1));
18158
18159   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18160 }
18161
18162 /// Returns true if the operand type is exactly twice the native width, and
18163 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18164 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18165 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18166 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18167   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18168
18169   if (OpWidth == 64)
18170     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18171   else if (OpWidth == 128)
18172     return Subtarget->hasCmpxchg16b();
18173   else
18174     return false;
18175 }
18176
18177 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18178   return needsCmpXchgNb(SI->getValueOperand()->getType());
18179 }
18180
18181 // Note: this turns large loads into lock cmpxchg8b/16b.
18182 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18183 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18184   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18185   return needsCmpXchgNb(PTy->getElementType());
18186 }
18187
18188 TargetLoweringBase::AtomicRMWExpansionKind
18189 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18190   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18191   Type *MemType = AI->getType();
18192
18193   // If the operand is too big, we must see if cmpxchg8/16b is available
18194   // and default to library calls otherwise.
18195   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18196     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18197                                    : AtomicRMWExpansionKind::None;
18198   }
18199
18200   AtomicRMWInst::BinOp Op = AI->getOperation();
18201   switch (Op) {
18202   default:
18203     llvm_unreachable("Unknown atomic operation");
18204   case AtomicRMWInst::Xchg:
18205   case AtomicRMWInst::Add:
18206   case AtomicRMWInst::Sub:
18207     // It's better to use xadd, xsub or xchg for these in all cases.
18208     return AtomicRMWExpansionKind::None;
18209   case AtomicRMWInst::Or:
18210   case AtomicRMWInst::And:
18211   case AtomicRMWInst::Xor:
18212     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18213     // prefix to a normal instruction for these operations.
18214     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18215                             : AtomicRMWExpansionKind::None;
18216   case AtomicRMWInst::Nand:
18217   case AtomicRMWInst::Max:
18218   case AtomicRMWInst::Min:
18219   case AtomicRMWInst::UMax:
18220   case AtomicRMWInst::UMin:
18221     // These always require a non-trivial set of data operations on x86. We must
18222     // use a cmpxchg loop.
18223     return AtomicRMWExpansionKind::CmpXChg;
18224   }
18225 }
18226
18227 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18228   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18229   // no-sse2). There isn't any reason to disable it if the target processor
18230   // supports it.
18231   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18232 }
18233
18234 LoadInst *
18235 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18236   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18237   Type *MemType = AI->getType();
18238   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18239   // there is no benefit in turning such RMWs into loads, and it is actually
18240   // harmful as it introduces a mfence.
18241   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18242     return nullptr;
18243
18244   auto Builder = IRBuilder<>(AI);
18245   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18246   auto SynchScope = AI->getSynchScope();
18247   // We must restrict the ordering to avoid generating loads with Release or
18248   // ReleaseAcquire orderings.
18249   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18250   auto Ptr = AI->getPointerOperand();
18251
18252   // Before the load we need a fence. Here is an example lifted from
18253   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18254   // is required:
18255   // Thread 0:
18256   //   x.store(1, relaxed);
18257   //   r1 = y.fetch_add(0, release);
18258   // Thread 1:
18259   //   y.fetch_add(42, acquire);
18260   //   r2 = x.load(relaxed);
18261   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18262   // lowered to just a load without a fence. A mfence flushes the store buffer,
18263   // making the optimization clearly correct.
18264   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18265   // otherwise, we might be able to be more aggressive on relaxed idempotent
18266   // rmw. In practice, they do not look useful, so we don't try to be
18267   // especially clever.
18268   if (SynchScope == SingleThread)
18269     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18270     // the IR level, so we must wrap it in an intrinsic.
18271     return nullptr;
18272
18273   if (!hasMFENCE(*Subtarget))
18274     // FIXME: it might make sense to use a locked operation here but on a
18275     // different cache-line to prevent cache-line bouncing. In practice it
18276     // is probably a small win, and x86 processors without mfence are rare
18277     // enough that we do not bother.
18278     return nullptr;
18279
18280   Function *MFence =
18281       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18282   Builder.CreateCall(MFence, {});
18283
18284   // Finally we can emit the atomic load.
18285   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18286           AI->getType()->getPrimitiveSizeInBits());
18287   Loaded->setAtomic(Order, SynchScope);
18288   AI->replaceAllUsesWith(Loaded);
18289   AI->eraseFromParent();
18290   return Loaded;
18291 }
18292
18293 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18294                                  SelectionDAG &DAG) {
18295   SDLoc dl(Op);
18296   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18297     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18298   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18299     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18300
18301   // The only fence that needs an instruction is a sequentially-consistent
18302   // cross-thread fence.
18303   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18304     if (hasMFENCE(*Subtarget))
18305       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18306
18307     SDValue Chain = Op.getOperand(0);
18308     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18309     SDValue Ops[] = {
18310       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18311       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18312       DAG.getRegister(0, MVT::i32),            // Index
18313       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18314       DAG.getRegister(0, MVT::i32),            // Segment.
18315       Zero,
18316       Chain
18317     };
18318     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18319     return SDValue(Res, 0);
18320   }
18321
18322   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18323   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18324 }
18325
18326 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18327                              SelectionDAG &DAG) {
18328   MVT T = Op.getSimpleValueType();
18329   SDLoc DL(Op);
18330   unsigned Reg = 0;
18331   unsigned size = 0;
18332   switch(T.SimpleTy) {
18333   default: llvm_unreachable("Invalid value type!");
18334   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18335   case MVT::i16: Reg = X86::AX;  size = 2; break;
18336   case MVT::i32: Reg = X86::EAX; size = 4; break;
18337   case MVT::i64:
18338     assert(Subtarget->is64Bit() && "Node not type legal!");
18339     Reg = X86::RAX; size = 8;
18340     break;
18341   }
18342   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18343                                   Op.getOperand(2), SDValue());
18344   SDValue Ops[] = { cpIn.getValue(0),
18345                     Op.getOperand(1),
18346                     Op.getOperand(3),
18347                     DAG.getTargetConstant(size, DL, MVT::i8),
18348                     cpIn.getValue(1) };
18349   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18350   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18351   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18352                                            Ops, T, MMO);
18353
18354   SDValue cpOut =
18355     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18356   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18357                                       MVT::i32, cpOut.getValue(2));
18358   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18359                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18360                                 EFLAGS);
18361
18362   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18363   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18364   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18365   return SDValue();
18366 }
18367
18368 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18369                             SelectionDAG &DAG) {
18370   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18371   MVT DstVT = Op.getSimpleValueType();
18372
18373   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18374     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18375     if (DstVT != MVT::f64)
18376       // This conversion needs to be expanded.
18377       return SDValue();
18378
18379     SDValue InVec = Op->getOperand(0);
18380     SDLoc dl(Op);
18381     unsigned NumElts = SrcVT.getVectorNumElements();
18382     EVT SVT = SrcVT.getVectorElementType();
18383
18384     // Widen the vector in input in the case of MVT::v2i32.
18385     // Example: from MVT::v2i32 to MVT::v4i32.
18386     SmallVector<SDValue, 16> Elts;
18387     for (unsigned i = 0, e = NumElts; i != e; ++i)
18388       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18389                                  DAG.getIntPtrConstant(i, dl)));
18390
18391     // Explicitly mark the extra elements as Undef.
18392     Elts.append(NumElts, DAG.getUNDEF(SVT));
18393
18394     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18395     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18396     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18397     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18398                        DAG.getIntPtrConstant(0, dl));
18399   }
18400
18401   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18402          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18403   assert((DstVT == MVT::i64 ||
18404           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18405          "Unexpected custom BITCAST");
18406   // i64 <=> MMX conversions are Legal.
18407   if (SrcVT==MVT::i64 && DstVT.isVector())
18408     return Op;
18409   if (DstVT==MVT::i64 && SrcVT.isVector())
18410     return Op;
18411   // MMX <=> MMX conversions are Legal.
18412   if (SrcVT.isVector() && DstVT.isVector())
18413     return Op;
18414   // All other conversions need to be expanded.
18415   return SDValue();
18416 }
18417
18418 /// Compute the horizontal sum of bytes in V for the elements of VT.
18419 ///
18420 /// Requires V to be a byte vector and VT to be an integer vector type with
18421 /// wider elements than V's type. The width of the elements of VT determines
18422 /// how many bytes of V are summed horizontally to produce each element of the
18423 /// result.
18424 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18425                                       const X86Subtarget *Subtarget,
18426                                       SelectionDAG &DAG) {
18427   SDLoc DL(V);
18428   MVT ByteVecVT = V.getSimpleValueType();
18429   MVT EltVT = VT.getVectorElementType();
18430   int NumElts = VT.getVectorNumElements();
18431   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18432          "Expected value to have byte element type.");
18433   assert(EltVT != MVT::i8 &&
18434          "Horizontal byte sum only makes sense for wider elements!");
18435   unsigned VecSize = VT.getSizeInBits();
18436   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18437
18438   // PSADBW instruction horizontally add all bytes and leave the result in i64
18439   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18440   if (EltVT == MVT::i64) {
18441     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18442     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18443     return DAG.getBitcast(VT, V);
18444   }
18445
18446   if (EltVT == MVT::i32) {
18447     // We unpack the low half and high half into i32s interleaved with zeros so
18448     // that we can use PSADBW to horizontally sum them. The most useful part of
18449     // this is that it lines up the results of two PSADBW instructions to be
18450     // two v2i64 vectors which concatenated are the 4 population counts. We can
18451     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18452     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18453     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18454     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18455
18456     // Do the horizontal sums into two v2i64s.
18457     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18458     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18459                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18460     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18461                        DAG.getBitcast(ByteVecVT, High), Zeros);
18462
18463     // Merge them together.
18464     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18465     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18466                     DAG.getBitcast(ShortVecVT, Low),
18467                     DAG.getBitcast(ShortVecVT, High));
18468
18469     return DAG.getBitcast(VT, V);
18470   }
18471
18472   // The only element type left is i16.
18473   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18474
18475   // To obtain pop count for each i16 element starting from the pop count for
18476   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18477   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18478   // directly supported.
18479   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18480   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18481   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18482   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18483                   DAG.getBitcast(ByteVecVT, V));
18484   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18485 }
18486
18487 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18488                                         const X86Subtarget *Subtarget,
18489                                         SelectionDAG &DAG) {
18490   MVT VT = Op.getSimpleValueType();
18491   MVT EltVT = VT.getVectorElementType();
18492   unsigned VecSize = VT.getSizeInBits();
18493
18494   // Implement a lookup table in register by using an algorithm based on:
18495   // http://wm.ite.pl/articles/sse-popcount.html
18496   //
18497   // The general idea is that every lower byte nibble in the input vector is an
18498   // index into a in-register pre-computed pop count table. We then split up the
18499   // input vector in two new ones: (1) a vector with only the shifted-right
18500   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18501   // masked out higher ones) for each byte. PSHUB is used separately with both
18502   // to index the in-register table. Next, both are added and the result is a
18503   // i8 vector where each element contains the pop count for input byte.
18504   //
18505   // To obtain the pop count for elements != i8, we follow up with the same
18506   // approach and use additional tricks as described below.
18507   //
18508   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18509                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18510                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18511                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18512
18513   int NumByteElts = VecSize / 8;
18514   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18515   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18516   SmallVector<SDValue, 16> LUTVec;
18517   for (int i = 0; i < NumByteElts; ++i)
18518     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18519   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18520   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18521                                   DAG.getConstant(0x0F, DL, MVT::i8));
18522   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18523
18524   // High nibbles
18525   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18526   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18527   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18528
18529   // Low nibbles
18530   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18531
18532   // The input vector is used as the shuffle mask that index elements into the
18533   // LUT. After counting low and high nibbles, add the vector to obtain the
18534   // final pop count per i8 element.
18535   SDValue HighPopCnt =
18536       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18537   SDValue LowPopCnt =
18538       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18539   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18540
18541   if (EltVT == MVT::i8)
18542     return PopCnt;
18543
18544   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18545 }
18546
18547 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18548                                        const X86Subtarget *Subtarget,
18549                                        SelectionDAG &DAG) {
18550   MVT VT = Op.getSimpleValueType();
18551   assert(VT.is128BitVector() &&
18552          "Only 128-bit vector bitmath lowering supported.");
18553
18554   int VecSize = VT.getSizeInBits();
18555   MVT EltVT = VT.getVectorElementType();
18556   int Len = EltVT.getSizeInBits();
18557
18558   // This is the vectorized version of the "best" algorithm from
18559   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18560   // with a minor tweak to use a series of adds + shifts instead of vector
18561   // multiplications. Implemented for all integer vector types. We only use
18562   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18563   // much faster, even faster than using native popcnt instructions.
18564
18565   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18566     MVT VT = V.getSimpleValueType();
18567     SmallVector<SDValue, 32> Shifters(
18568         VT.getVectorNumElements(),
18569         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18570     return DAG.getNode(OpCode, DL, VT, V,
18571                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18572   };
18573   auto GetMask = [&](SDValue V, APInt Mask) {
18574     MVT VT = V.getSimpleValueType();
18575     SmallVector<SDValue, 32> Masks(
18576         VT.getVectorNumElements(),
18577         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18578     return DAG.getNode(ISD::AND, DL, VT, V,
18579                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18580   };
18581
18582   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18583   // x86, so set the SRL type to have elements at least i16 wide. This is
18584   // correct because all of our SRLs are followed immediately by a mask anyways
18585   // that handles any bits that sneak into the high bits of the byte elements.
18586   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18587
18588   SDValue V = Op;
18589
18590   // v = v - ((v >> 1) & 0x55555555...)
18591   SDValue Srl =
18592       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18593   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18594   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18595
18596   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18597   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18598   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18599   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18600   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18601
18602   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18603   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18604   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18605   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18606
18607   // At this point, V contains the byte-wise population count, and we are
18608   // merely doing a horizontal sum if necessary to get the wider element
18609   // counts.
18610   if (EltVT == MVT::i8)
18611     return V;
18612
18613   return LowerHorizontalByteSum(
18614       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18615       DAG);
18616 }
18617
18618 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18619                                 SelectionDAG &DAG) {
18620   MVT VT = Op.getSimpleValueType();
18621   // FIXME: Need to add AVX-512 support here!
18622   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18623          "Unknown CTPOP type to handle");
18624   SDLoc DL(Op.getNode());
18625   SDValue Op0 = Op.getOperand(0);
18626
18627   if (!Subtarget->hasSSSE3()) {
18628     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18629     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18630     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18631   }
18632
18633   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18634     unsigned NumElems = VT.getVectorNumElements();
18635
18636     // Extract each 128-bit vector, compute pop count and concat the result.
18637     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18638     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18639
18640     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18641                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18642                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18643   }
18644
18645   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18646 }
18647
18648 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18649                           SelectionDAG &DAG) {
18650   assert(Op.getValueType().isVector() &&
18651          "We only do custom lowering for vector population count.");
18652   return LowerVectorCTPOP(Op, Subtarget, DAG);
18653 }
18654
18655 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18656   SDNode *Node = Op.getNode();
18657   SDLoc dl(Node);
18658   EVT T = Node->getValueType(0);
18659   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18660                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18661   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18662                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18663                        Node->getOperand(0),
18664                        Node->getOperand(1), negOp,
18665                        cast<AtomicSDNode>(Node)->getMemOperand(),
18666                        cast<AtomicSDNode>(Node)->getOrdering(),
18667                        cast<AtomicSDNode>(Node)->getSynchScope());
18668 }
18669
18670 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18671   SDNode *Node = Op.getNode();
18672   SDLoc dl(Node);
18673   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18674
18675   // Convert seq_cst store -> xchg
18676   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18677   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18678   //        (The only way to get a 16-byte store is cmpxchg16b)
18679   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18680   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18681       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18682     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18683                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18684                                  Node->getOperand(0),
18685                                  Node->getOperand(1), Node->getOperand(2),
18686                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18687                                  cast<AtomicSDNode>(Node)->getOrdering(),
18688                                  cast<AtomicSDNode>(Node)->getSynchScope());
18689     return Swap.getValue(1);
18690   }
18691   // Other atomic stores have a simple pattern.
18692   return Op;
18693 }
18694
18695 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18696   EVT VT = Op.getNode()->getSimpleValueType(0);
18697
18698   // Let legalize expand this if it isn't a legal type yet.
18699   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18700     return SDValue();
18701
18702   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18703
18704   unsigned Opc;
18705   bool ExtraOp = false;
18706   switch (Op.getOpcode()) {
18707   default: llvm_unreachable("Invalid code");
18708   case ISD::ADDC: Opc = X86ISD::ADD; break;
18709   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18710   case ISD::SUBC: Opc = X86ISD::SUB; break;
18711   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18712   }
18713
18714   if (!ExtraOp)
18715     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18716                        Op.getOperand(1));
18717   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18718                      Op.getOperand(1), Op.getOperand(2));
18719 }
18720
18721 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18722                             SelectionDAG &DAG) {
18723   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18724
18725   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18726   // which returns the values as { float, float } (in XMM0) or
18727   // { double, double } (which is returned in XMM0, XMM1).
18728   SDLoc dl(Op);
18729   SDValue Arg = Op.getOperand(0);
18730   EVT ArgVT = Arg.getValueType();
18731   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18732
18733   TargetLowering::ArgListTy Args;
18734   TargetLowering::ArgListEntry Entry;
18735
18736   Entry.Node = Arg;
18737   Entry.Ty = ArgTy;
18738   Entry.isSExt = false;
18739   Entry.isZExt = false;
18740   Args.push_back(Entry);
18741
18742   bool isF64 = ArgVT == MVT::f64;
18743   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18744   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18745   // the results are returned via SRet in memory.
18746   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18748   SDValue Callee =
18749       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18750
18751   Type *RetTy = isF64
18752     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18753     : (Type*)VectorType::get(ArgTy, 4);
18754
18755   TargetLowering::CallLoweringInfo CLI(DAG);
18756   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18757     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18758
18759   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18760
18761   if (isF64)
18762     // Returned in xmm0 and xmm1.
18763     return CallResult.first;
18764
18765   // Returned in bits 0:31 and 32:64 xmm0.
18766   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18767                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18768   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18769                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18770   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18771   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18772 }
18773
18774 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18775                              SelectionDAG &DAG) {
18776   assert(Subtarget->hasAVX512() &&
18777          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18778
18779   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18780   EVT VT = N->getValue().getValueType();
18781   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18782   SDLoc dl(Op);
18783
18784   // X86 scatter kills mask register, so its type should be added to
18785   // the list of return values
18786   if (N->getNumValues() == 1) {
18787     SDValue Index = N->getIndex();
18788     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18789         !Index.getValueType().is512BitVector())
18790       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18791
18792     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18793     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18794                       N->getOperand(3), Index };
18795
18796     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18797     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18798     return SDValue(NewScatter.getNode(), 0);
18799   }
18800   return Op;
18801 }
18802
18803 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18804                             SelectionDAG &DAG) {
18805   assert(Subtarget->hasAVX512() &&
18806          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18807
18808   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18809   EVT VT = Op.getValueType();
18810   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18811   SDLoc dl(Op);
18812
18813   SDValue Index = N->getIndex();
18814   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18815       !Index.getValueType().is512BitVector()) {
18816     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18817     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18818                       N->getOperand(3), Index };
18819     DAG.UpdateNodeOperands(N, Ops);
18820   }
18821   return Op;
18822 }
18823
18824 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18825                                                     SelectionDAG &DAG) const {
18826   // TODO: Eventually, the lowering of these nodes should be informed by or
18827   // deferred to the GC strategy for the function in which they appear. For
18828   // now, however, they must be lowered to something. Since they are logically
18829   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18830   // require special handling for these nodes), lower them as literal NOOPs for
18831   // the time being.
18832   SmallVector<SDValue, 2> Ops;
18833
18834   Ops.push_back(Op.getOperand(0));
18835   if (Op->getGluedNode())
18836     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18837
18838   SDLoc OpDL(Op);
18839   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18840   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18841
18842   return NOOP;
18843 }
18844
18845 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18846                                                   SelectionDAG &DAG) const {
18847   // TODO: Eventually, the lowering of these nodes should be informed by or
18848   // deferred to the GC strategy for the function in which they appear. For
18849   // now, however, they must be lowered to something. Since they are logically
18850   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18851   // require special handling for these nodes), lower them as literal NOOPs for
18852   // the time being.
18853   SmallVector<SDValue, 2> Ops;
18854
18855   Ops.push_back(Op.getOperand(0));
18856   if (Op->getGluedNode())
18857     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18858
18859   SDLoc OpDL(Op);
18860   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18861   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18862
18863   return NOOP;
18864 }
18865
18866 /// LowerOperation - Provide custom lowering hooks for some operations.
18867 ///
18868 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18869   switch (Op.getOpcode()) {
18870   default: llvm_unreachable("Should not custom lower this!");
18871   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18872   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18873     return LowerCMP_SWAP(Op, Subtarget, DAG);
18874   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18875   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18876   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18877   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18878   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18879   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18880   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18881   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18882   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18883   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18884   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18885   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18886   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18887   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18888   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18889   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18890   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18891   case ISD::SHL_PARTS:
18892   case ISD::SRA_PARTS:
18893   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18894   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18895   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18896   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18897   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18898   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18899   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18900   case ISD::SIGN_EXTEND_VECTOR_INREG:
18901     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18902   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18903   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18904   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18905   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18906   case ISD::FABS:
18907   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18908   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18909   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18910   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18911   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18912   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18913   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18914   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18915   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18916   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18917   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18918   case ISD::INTRINSIC_VOID:
18919   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18920   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18921   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18922   case ISD::FRAME_TO_ARGS_OFFSET:
18923                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18924   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18925   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18926   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
18927   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18928   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18929   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18930   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18931   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18932   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18933   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18934   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18935   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18936   case ISD::UMUL_LOHI:
18937   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18938   case ISD::SRA:
18939   case ISD::SRL:
18940   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18941   case ISD::SADDO:
18942   case ISD::UADDO:
18943   case ISD::SSUBO:
18944   case ISD::USUBO:
18945   case ISD::SMULO:
18946   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18947   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18948   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18949   case ISD::ADDC:
18950   case ISD::ADDE:
18951   case ISD::SUBC:
18952   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18953   case ISD::ADD:                return LowerADD(Op, DAG);
18954   case ISD::SUB:                return LowerSUB(Op, DAG);
18955   case ISD::SMAX:
18956   case ISD::SMIN:
18957   case ISD::UMAX:
18958   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18959   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18960   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18961   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18962   case ISD::GC_TRANSITION_START:
18963                                 return LowerGC_TRANSITION_START(Op, DAG);
18964   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18965   }
18966 }
18967
18968 /// ReplaceNodeResults - Replace a node with an illegal result type
18969 /// with a new node built out of custom code.
18970 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18971                                            SmallVectorImpl<SDValue>&Results,
18972                                            SelectionDAG &DAG) const {
18973   SDLoc dl(N);
18974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18975   switch (N->getOpcode()) {
18976   default:
18977     llvm_unreachable("Do not know how to custom type legalize this operation!");
18978   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18979   case X86ISD::FMINC:
18980   case X86ISD::FMIN:
18981   case X86ISD::FMAXC:
18982   case X86ISD::FMAX: {
18983     EVT VT = N->getValueType(0);
18984     if (VT != MVT::v2f32)
18985       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18986     SDValue UNDEF = DAG.getUNDEF(VT);
18987     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18988                               N->getOperand(0), UNDEF);
18989     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18990                               N->getOperand(1), UNDEF);
18991     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18992     return;
18993   }
18994   case ISD::SIGN_EXTEND_INREG:
18995   case ISD::ADDC:
18996   case ISD::ADDE:
18997   case ISD::SUBC:
18998   case ISD::SUBE:
18999     // We don't want to expand or promote these.
19000     return;
19001   case ISD::SDIV:
19002   case ISD::UDIV:
19003   case ISD::SREM:
19004   case ISD::UREM:
19005   case ISD::SDIVREM:
19006   case ISD::UDIVREM: {
19007     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19008     Results.push_back(V);
19009     return;
19010   }
19011   case ISD::FP_TO_SINT:
19012   case ISD::FP_TO_UINT: {
19013     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19014
19015     std::pair<SDValue,SDValue> Vals =
19016         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19017     SDValue FIST = Vals.first, StackSlot = Vals.second;
19018     if (FIST.getNode()) {
19019       EVT VT = N->getValueType(0);
19020       // Return a load from the stack slot.
19021       if (StackSlot.getNode())
19022         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19023                                       MachinePointerInfo(),
19024                                       false, false, false, 0));
19025       else
19026         Results.push_back(FIST);
19027     }
19028     return;
19029   }
19030   case ISD::UINT_TO_FP: {
19031     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19032     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19033         N->getValueType(0) != MVT::v2f32)
19034       return;
19035     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19036                                  N->getOperand(0));
19037     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19038                                      MVT::f64);
19039     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19040     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19041                              DAG.getBitcast(MVT::v2i64, VBias));
19042     Or = DAG.getBitcast(MVT::v2f64, Or);
19043     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19044     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19045     return;
19046   }
19047   case ISD::FP_ROUND: {
19048     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19049         return;
19050     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19051     Results.push_back(V);
19052     return;
19053   }
19054   case ISD::FP_EXTEND: {
19055     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19056     // No other ValueType for FP_EXTEND should reach this point.
19057     assert(N->getValueType(0) == MVT::v2f32 &&
19058            "Do not know how to legalize this Node");
19059     return;
19060   }
19061   case ISD::INTRINSIC_W_CHAIN: {
19062     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19063     switch (IntNo) {
19064     default : llvm_unreachable("Do not know how to custom type "
19065                                "legalize this intrinsic operation!");
19066     case Intrinsic::x86_rdtsc:
19067       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19068                                      Results);
19069     case Intrinsic::x86_rdtscp:
19070       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19071                                      Results);
19072     case Intrinsic::x86_rdpmc:
19073       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19074     }
19075   }
19076   case ISD::READCYCLECOUNTER: {
19077     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19078                                    Results);
19079   }
19080   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19081     EVT T = N->getValueType(0);
19082     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19083     bool Regs64bit = T == MVT::i128;
19084     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19085     SDValue cpInL, cpInH;
19086     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19087                         DAG.getConstant(0, dl, HalfT));
19088     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19089                         DAG.getConstant(1, dl, HalfT));
19090     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19091                              Regs64bit ? X86::RAX : X86::EAX,
19092                              cpInL, SDValue());
19093     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19094                              Regs64bit ? X86::RDX : X86::EDX,
19095                              cpInH, cpInL.getValue(1));
19096     SDValue swapInL, swapInH;
19097     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19098                           DAG.getConstant(0, dl, HalfT));
19099     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19100                           DAG.getConstant(1, dl, HalfT));
19101     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19102                                Regs64bit ? X86::RBX : X86::EBX,
19103                                swapInL, cpInH.getValue(1));
19104     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19105                                Regs64bit ? X86::RCX : X86::ECX,
19106                                swapInH, swapInL.getValue(1));
19107     SDValue Ops[] = { swapInH.getValue(0),
19108                       N->getOperand(1),
19109                       swapInH.getValue(1) };
19110     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19111     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19112     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19113                                   X86ISD::LCMPXCHG8_DAG;
19114     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19115     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19116                                         Regs64bit ? X86::RAX : X86::EAX,
19117                                         HalfT, Result.getValue(1));
19118     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19119                                         Regs64bit ? X86::RDX : X86::EDX,
19120                                         HalfT, cpOutL.getValue(2));
19121     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19122
19123     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19124                                         MVT::i32, cpOutH.getValue(2));
19125     SDValue Success =
19126         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19127                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19128     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19129
19130     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19131     Results.push_back(Success);
19132     Results.push_back(EFLAGS.getValue(1));
19133     return;
19134   }
19135   case ISD::ATOMIC_SWAP:
19136   case ISD::ATOMIC_LOAD_ADD:
19137   case ISD::ATOMIC_LOAD_SUB:
19138   case ISD::ATOMIC_LOAD_AND:
19139   case ISD::ATOMIC_LOAD_OR:
19140   case ISD::ATOMIC_LOAD_XOR:
19141   case ISD::ATOMIC_LOAD_NAND:
19142   case ISD::ATOMIC_LOAD_MIN:
19143   case ISD::ATOMIC_LOAD_MAX:
19144   case ISD::ATOMIC_LOAD_UMIN:
19145   case ISD::ATOMIC_LOAD_UMAX:
19146   case ISD::ATOMIC_LOAD: {
19147     // Delegate to generic TypeLegalization. Situations we can really handle
19148     // should have already been dealt with by AtomicExpandPass.cpp.
19149     break;
19150   }
19151   case ISD::BITCAST: {
19152     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19153     EVT DstVT = N->getValueType(0);
19154     EVT SrcVT = N->getOperand(0)->getValueType(0);
19155
19156     if (SrcVT != MVT::f64 ||
19157         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19158       return;
19159
19160     unsigned NumElts = DstVT.getVectorNumElements();
19161     EVT SVT = DstVT.getVectorElementType();
19162     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19163     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19164                                    MVT::v2f64, N->getOperand(0));
19165     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19166
19167     if (ExperimentalVectorWideningLegalization) {
19168       // If we are legalizing vectors by widening, we already have the desired
19169       // legal vector type, just return it.
19170       Results.push_back(ToVecInt);
19171       return;
19172     }
19173
19174     SmallVector<SDValue, 8> Elts;
19175     for (unsigned i = 0, e = NumElts; i != e; ++i)
19176       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19177                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19178
19179     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19180   }
19181   }
19182 }
19183
19184 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19185   switch ((X86ISD::NodeType)Opcode) {
19186   case X86ISD::FIRST_NUMBER:       break;
19187   case X86ISD::BSF:                return "X86ISD::BSF";
19188   case X86ISD::BSR:                return "X86ISD::BSR";
19189   case X86ISD::SHLD:               return "X86ISD::SHLD";
19190   case X86ISD::SHRD:               return "X86ISD::SHRD";
19191   case X86ISD::FAND:               return "X86ISD::FAND";
19192   case X86ISD::FANDN:              return "X86ISD::FANDN";
19193   case X86ISD::FOR:                return "X86ISD::FOR";
19194   case X86ISD::FXOR:               return "X86ISD::FXOR";
19195   case X86ISD::FILD:               return "X86ISD::FILD";
19196   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19197   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19198   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19199   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19200   case X86ISD::FLD:                return "X86ISD::FLD";
19201   case X86ISD::FST:                return "X86ISD::FST";
19202   case X86ISD::CALL:               return "X86ISD::CALL";
19203   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19204   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19205   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19206   case X86ISD::BT:                 return "X86ISD::BT";
19207   case X86ISD::CMP:                return "X86ISD::CMP";
19208   case X86ISD::COMI:               return "X86ISD::COMI";
19209   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19210   case X86ISD::CMPM:               return "X86ISD::CMPM";
19211   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19212   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19213   case X86ISD::SETCC:              return "X86ISD::SETCC";
19214   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19215   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19216   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19217   case X86ISD::CMOV:               return "X86ISD::CMOV";
19218   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19219   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19220   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19221   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19222   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19223   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19224   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19225   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19226   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19227   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19228   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19229   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19230   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19231   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19232   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19233   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19234   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19235   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19236   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19237   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19238   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19239   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19240   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19241   case X86ISD::HADD:               return "X86ISD::HADD";
19242   case X86ISD::HSUB:               return "X86ISD::HSUB";
19243   case X86ISD::FHADD:              return "X86ISD::FHADD";
19244   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19245   case X86ISD::ABS:                return "X86ISD::ABS";
19246   case X86ISD::FMAX:               return "X86ISD::FMAX";
19247   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19248   case X86ISD::FMIN:               return "X86ISD::FMIN";
19249   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19250   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19251   case X86ISD::FMINC:              return "X86ISD::FMINC";
19252   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19253   case X86ISD::FRCP:               return "X86ISD::FRCP";
19254   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19255   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19256   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19257   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19258   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19259   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19260   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19261   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19262   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19263   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19264   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19265   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19266   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19267   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19268   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19269   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19270   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19271   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19272   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19273   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19274   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19275   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19276   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19277   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19278   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19279   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19280   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19281   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19282   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19283   case X86ISD::VSHL:               return "X86ISD::VSHL";
19284   case X86ISD::VSRL:               return "X86ISD::VSRL";
19285   case X86ISD::VSRA:               return "X86ISD::VSRA";
19286   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19287   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19288   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19289   case X86ISD::CMPP:               return "X86ISD::CMPP";
19290   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19291   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19292   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19293   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19294   case X86ISD::ADD:                return "X86ISD::ADD";
19295   case X86ISD::SUB:                return "X86ISD::SUB";
19296   case X86ISD::ADC:                return "X86ISD::ADC";
19297   case X86ISD::SBB:                return "X86ISD::SBB";
19298   case X86ISD::SMUL:               return "X86ISD::SMUL";
19299   case X86ISD::UMUL:               return "X86ISD::UMUL";
19300   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19301   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19302   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19303   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19304   case X86ISD::INC:                return "X86ISD::INC";
19305   case X86ISD::DEC:                return "X86ISD::DEC";
19306   case X86ISD::OR:                 return "X86ISD::OR";
19307   case X86ISD::XOR:                return "X86ISD::XOR";
19308   case X86ISD::AND:                return "X86ISD::AND";
19309   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19310   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19311   case X86ISD::PTEST:              return "X86ISD::PTEST";
19312   case X86ISD::TESTP:              return "X86ISD::TESTP";
19313   case X86ISD::TESTM:              return "X86ISD::TESTM";
19314   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19315   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19316   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19317   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19318   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19319   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19320   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19321   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19322   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19323   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19324   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19325   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19326   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19327   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19328   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19329   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19330   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19331   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19332   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19333   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19334   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19335   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19336   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19337   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19338   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19339   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19340   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19341   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19342   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19343   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19344   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19345   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19346   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19347   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19348   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19349   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19350   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19351   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19352   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19353   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19354   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19355   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19356   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19357   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19358   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19359   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19360   case X86ISD::SAHF:               return "X86ISD::SAHF";
19361   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19362   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19363   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19364   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19365   case X86ISD::FMADD:              return "X86ISD::FMADD";
19366   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19367   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19368   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19369   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19370   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19371   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19372   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19373   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19374   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19375   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19376   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19377   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19378   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19379   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19380   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19381   case X86ISD::XTEST:              return "X86ISD::XTEST";
19382   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19383   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19384   case X86ISD::SELECT:             return "X86ISD::SELECT";
19385   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19386   case X86ISD::RCP28:              return "X86ISD::RCP28";
19387   case X86ISD::EXP2:               return "X86ISD::EXP2";
19388   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19389   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19390   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19391   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19392   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19393   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19394   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19395   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19396   case X86ISD::ADDS:               return "X86ISD::ADDS";
19397   case X86ISD::SUBS:               return "X86ISD::SUBS";
19398   case X86ISD::AVG:                return "X86ISD::AVG";
19399   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19400   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19401   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19402   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19403   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19404   }
19405   return nullptr;
19406 }
19407
19408 // isLegalAddressingMode - Return true if the addressing mode represented
19409 // by AM is legal for this target, for a load/store of the specified type.
19410 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19411                                               const AddrMode &AM, Type *Ty,
19412                                               unsigned AS) const {
19413   // X86 supports extremely general addressing modes.
19414   CodeModel::Model M = getTargetMachine().getCodeModel();
19415   Reloc::Model R = getTargetMachine().getRelocationModel();
19416
19417   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19418   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19419     return false;
19420
19421   if (AM.BaseGV) {
19422     unsigned GVFlags =
19423       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19424
19425     // If a reference to this global requires an extra load, we can't fold it.
19426     if (isGlobalStubReference(GVFlags))
19427       return false;
19428
19429     // If BaseGV requires a register for the PIC base, we cannot also have a
19430     // BaseReg specified.
19431     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19432       return false;
19433
19434     // If lower 4G is not available, then we must use rip-relative addressing.
19435     if ((M != CodeModel::Small || R != Reloc::Static) &&
19436         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19437       return false;
19438   }
19439
19440   switch (AM.Scale) {
19441   case 0:
19442   case 1:
19443   case 2:
19444   case 4:
19445   case 8:
19446     // These scales always work.
19447     break;
19448   case 3:
19449   case 5:
19450   case 9:
19451     // These scales are formed with basereg+scalereg.  Only accept if there is
19452     // no basereg yet.
19453     if (AM.HasBaseReg)
19454       return false;
19455     break;
19456   default:  // Other stuff never works.
19457     return false;
19458   }
19459
19460   return true;
19461 }
19462
19463 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19464   unsigned Bits = Ty->getScalarSizeInBits();
19465
19466   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19467   // particularly cheaper than those without.
19468   if (Bits == 8)
19469     return false;
19470
19471   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19472   // variable shifts just as cheap as scalar ones.
19473   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19474     return false;
19475
19476   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19477   // fully general vector.
19478   return true;
19479 }
19480
19481 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19482   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19483     return false;
19484   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19485   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19486   return NumBits1 > NumBits2;
19487 }
19488
19489 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19490   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19491     return false;
19492
19493   if (!isTypeLegal(EVT::getEVT(Ty1)))
19494     return false;
19495
19496   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19497
19498   // Assuming the caller doesn't have a zeroext or signext return parameter,
19499   // truncation all the way down to i1 is valid.
19500   return true;
19501 }
19502
19503 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19504   return isInt<32>(Imm);
19505 }
19506
19507 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19508   // Can also use sub to handle negated immediates.
19509   return isInt<32>(Imm);
19510 }
19511
19512 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19513   if (!VT1.isInteger() || !VT2.isInteger())
19514     return false;
19515   unsigned NumBits1 = VT1.getSizeInBits();
19516   unsigned NumBits2 = VT2.getSizeInBits();
19517   return NumBits1 > NumBits2;
19518 }
19519
19520 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19521   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19522   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19523 }
19524
19525 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19526   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19527   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19528 }
19529
19530 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19531   EVT VT1 = Val.getValueType();
19532   if (isZExtFree(VT1, VT2))
19533     return true;
19534
19535   if (Val.getOpcode() != ISD::LOAD)
19536     return false;
19537
19538   if (!VT1.isSimple() || !VT1.isInteger() ||
19539       !VT2.isSimple() || !VT2.isInteger())
19540     return false;
19541
19542   switch (VT1.getSimpleVT().SimpleTy) {
19543   default: break;
19544   case MVT::i8:
19545   case MVT::i16:
19546   case MVT::i32:
19547     // X86 has 8, 16, and 32-bit zero-extending loads.
19548     return true;
19549   }
19550
19551   return false;
19552 }
19553
19554 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19555
19556 bool
19557 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19558   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19559     return false;
19560
19561   VT = VT.getScalarType();
19562
19563   if (!VT.isSimple())
19564     return false;
19565
19566   switch (VT.getSimpleVT().SimpleTy) {
19567   case MVT::f32:
19568   case MVT::f64:
19569     return true;
19570   default:
19571     break;
19572   }
19573
19574   return false;
19575 }
19576
19577 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19578   // i16 instructions are longer (0x66 prefix) and potentially slower.
19579   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19580 }
19581
19582 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19583 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19584 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19585 /// are assumed to be legal.
19586 bool
19587 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19588                                       EVT VT) const {
19589   if (!VT.isSimple())
19590     return false;
19591
19592   // Not for i1 vectors
19593   if (VT.getScalarType() == MVT::i1)
19594     return false;
19595
19596   // Very little shuffling can be done for 64-bit vectors right now.
19597   if (VT.getSizeInBits() == 64)
19598     return false;
19599
19600   // We only care that the types being shuffled are legal. The lowering can
19601   // handle any possible shuffle mask that results.
19602   return isTypeLegal(VT.getSimpleVT());
19603 }
19604
19605 bool
19606 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19607                                           EVT VT) const {
19608   // Just delegate to the generic legality, clear masks aren't special.
19609   return isShuffleMaskLegal(Mask, VT);
19610 }
19611
19612 //===----------------------------------------------------------------------===//
19613 //                           X86 Scheduler Hooks
19614 //===----------------------------------------------------------------------===//
19615
19616 /// Utility function to emit xbegin specifying the start of an RTM region.
19617 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19618                                      const TargetInstrInfo *TII) {
19619   DebugLoc DL = MI->getDebugLoc();
19620
19621   const BasicBlock *BB = MBB->getBasicBlock();
19622   MachineFunction::iterator I = MBB;
19623   ++I;
19624
19625   // For the v = xbegin(), we generate
19626   //
19627   // thisMBB:
19628   //  xbegin sinkMBB
19629   //
19630   // mainMBB:
19631   //  eax = -1
19632   //
19633   // sinkMBB:
19634   //  v = eax
19635
19636   MachineBasicBlock *thisMBB = MBB;
19637   MachineFunction *MF = MBB->getParent();
19638   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19639   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19640   MF->insert(I, mainMBB);
19641   MF->insert(I, sinkMBB);
19642
19643   // Transfer the remainder of BB and its successor edges to sinkMBB.
19644   sinkMBB->splice(sinkMBB->begin(), MBB,
19645                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19646   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19647
19648   // thisMBB:
19649   //  xbegin sinkMBB
19650   //  # fallthrough to mainMBB
19651   //  # abortion to sinkMBB
19652   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19653   thisMBB->addSuccessor(mainMBB);
19654   thisMBB->addSuccessor(sinkMBB);
19655
19656   // mainMBB:
19657   //  EAX = -1
19658   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19659   mainMBB->addSuccessor(sinkMBB);
19660
19661   // sinkMBB:
19662   // EAX is live into the sinkMBB
19663   sinkMBB->addLiveIn(X86::EAX);
19664   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19665           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19666     .addReg(X86::EAX);
19667
19668   MI->eraseFromParent();
19669   return sinkMBB;
19670 }
19671
19672 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19673 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19674 // in the .td file.
19675 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19676                                        const TargetInstrInfo *TII) {
19677   unsigned Opc;
19678   switch (MI->getOpcode()) {
19679   default: llvm_unreachable("illegal opcode!");
19680   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19681   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19682   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19683   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19684   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19685   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19686   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19687   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19688   }
19689
19690   DebugLoc dl = MI->getDebugLoc();
19691   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19692
19693   unsigned NumArgs = MI->getNumOperands();
19694   for (unsigned i = 1; i < NumArgs; ++i) {
19695     MachineOperand &Op = MI->getOperand(i);
19696     if (!(Op.isReg() && Op.isImplicit()))
19697       MIB.addOperand(Op);
19698   }
19699   if (MI->hasOneMemOperand())
19700     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19701
19702   BuildMI(*BB, MI, dl,
19703     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19704     .addReg(X86::XMM0);
19705
19706   MI->eraseFromParent();
19707   return BB;
19708 }
19709
19710 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19711 // defs in an instruction pattern
19712 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19713                                        const TargetInstrInfo *TII) {
19714   unsigned Opc;
19715   switch (MI->getOpcode()) {
19716   default: llvm_unreachable("illegal opcode!");
19717   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19718   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19719   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19720   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19721   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19722   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19723   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19724   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19725   }
19726
19727   DebugLoc dl = MI->getDebugLoc();
19728   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19729
19730   unsigned NumArgs = MI->getNumOperands(); // remove the results
19731   for (unsigned i = 1; i < NumArgs; ++i) {
19732     MachineOperand &Op = MI->getOperand(i);
19733     if (!(Op.isReg() && Op.isImplicit()))
19734       MIB.addOperand(Op);
19735   }
19736   if (MI->hasOneMemOperand())
19737     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19738
19739   BuildMI(*BB, MI, dl,
19740     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19741     .addReg(X86::ECX);
19742
19743   MI->eraseFromParent();
19744   return BB;
19745 }
19746
19747 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19748                                       const X86Subtarget *Subtarget) {
19749   DebugLoc dl = MI->getDebugLoc();
19750   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19751   // Address into RAX/EAX, other two args into ECX, EDX.
19752   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19753   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19754   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19755   for (int i = 0; i < X86::AddrNumOperands; ++i)
19756     MIB.addOperand(MI->getOperand(i));
19757
19758   unsigned ValOps = X86::AddrNumOperands;
19759   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19760     .addReg(MI->getOperand(ValOps).getReg());
19761   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19762     .addReg(MI->getOperand(ValOps+1).getReg());
19763
19764   // The instruction doesn't actually take any operands though.
19765   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19766
19767   MI->eraseFromParent(); // The pseudo is gone now.
19768   return BB;
19769 }
19770
19771 MachineBasicBlock *
19772 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19773                                                  MachineBasicBlock *MBB) const {
19774   // Emit va_arg instruction on X86-64.
19775
19776   // Operands to this pseudo-instruction:
19777   // 0  ) Output        : destination address (reg)
19778   // 1-5) Input         : va_list address (addr, i64mem)
19779   // 6  ) ArgSize       : Size (in bytes) of vararg type
19780   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19781   // 8  ) Align         : Alignment of type
19782   // 9  ) EFLAGS (implicit-def)
19783
19784   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19785   static_assert(X86::AddrNumOperands == 5,
19786                 "VAARG_64 assumes 5 address operands");
19787
19788   unsigned DestReg = MI->getOperand(0).getReg();
19789   MachineOperand &Base = MI->getOperand(1);
19790   MachineOperand &Scale = MI->getOperand(2);
19791   MachineOperand &Index = MI->getOperand(3);
19792   MachineOperand &Disp = MI->getOperand(4);
19793   MachineOperand &Segment = MI->getOperand(5);
19794   unsigned ArgSize = MI->getOperand(6).getImm();
19795   unsigned ArgMode = MI->getOperand(7).getImm();
19796   unsigned Align = MI->getOperand(8).getImm();
19797
19798   // Memory Reference
19799   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19800   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19801   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19802
19803   // Machine Information
19804   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19805   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19806   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19807   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19808   DebugLoc DL = MI->getDebugLoc();
19809
19810   // struct va_list {
19811   //   i32   gp_offset
19812   //   i32   fp_offset
19813   //   i64   overflow_area (address)
19814   //   i64   reg_save_area (address)
19815   // }
19816   // sizeof(va_list) = 24
19817   // alignment(va_list) = 8
19818
19819   unsigned TotalNumIntRegs = 6;
19820   unsigned TotalNumXMMRegs = 8;
19821   bool UseGPOffset = (ArgMode == 1);
19822   bool UseFPOffset = (ArgMode == 2);
19823   unsigned MaxOffset = TotalNumIntRegs * 8 +
19824                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19825
19826   /* Align ArgSize to a multiple of 8 */
19827   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19828   bool NeedsAlign = (Align > 8);
19829
19830   MachineBasicBlock *thisMBB = MBB;
19831   MachineBasicBlock *overflowMBB;
19832   MachineBasicBlock *offsetMBB;
19833   MachineBasicBlock *endMBB;
19834
19835   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19836   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19837   unsigned OffsetReg = 0;
19838
19839   if (!UseGPOffset && !UseFPOffset) {
19840     // If we only pull from the overflow region, we don't create a branch.
19841     // We don't need to alter control flow.
19842     OffsetDestReg = 0; // unused
19843     OverflowDestReg = DestReg;
19844
19845     offsetMBB = nullptr;
19846     overflowMBB = thisMBB;
19847     endMBB = thisMBB;
19848   } else {
19849     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19850     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19851     // If not, pull from overflow_area. (branch to overflowMBB)
19852     //
19853     //       thisMBB
19854     //         |     .
19855     //         |        .
19856     //     offsetMBB   overflowMBB
19857     //         |        .
19858     //         |     .
19859     //        endMBB
19860
19861     // Registers for the PHI in endMBB
19862     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19863     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19864
19865     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19866     MachineFunction *MF = MBB->getParent();
19867     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19868     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19869     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19870
19871     MachineFunction::iterator MBBIter = MBB;
19872     ++MBBIter;
19873
19874     // Insert the new basic blocks
19875     MF->insert(MBBIter, offsetMBB);
19876     MF->insert(MBBIter, overflowMBB);
19877     MF->insert(MBBIter, endMBB);
19878
19879     // Transfer the remainder of MBB and its successor edges to endMBB.
19880     endMBB->splice(endMBB->begin(), thisMBB,
19881                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19882     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19883
19884     // Make offsetMBB and overflowMBB successors of thisMBB
19885     thisMBB->addSuccessor(offsetMBB);
19886     thisMBB->addSuccessor(overflowMBB);
19887
19888     // endMBB is a successor of both offsetMBB and overflowMBB
19889     offsetMBB->addSuccessor(endMBB);
19890     overflowMBB->addSuccessor(endMBB);
19891
19892     // Load the offset value into a register
19893     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19894     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19895       .addOperand(Base)
19896       .addOperand(Scale)
19897       .addOperand(Index)
19898       .addDisp(Disp, UseFPOffset ? 4 : 0)
19899       .addOperand(Segment)
19900       .setMemRefs(MMOBegin, MMOEnd);
19901
19902     // Check if there is enough room left to pull this argument.
19903     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19904       .addReg(OffsetReg)
19905       .addImm(MaxOffset + 8 - ArgSizeA8);
19906
19907     // Branch to "overflowMBB" if offset >= max
19908     // Fall through to "offsetMBB" otherwise
19909     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19910       .addMBB(overflowMBB);
19911   }
19912
19913   // In offsetMBB, emit code to use the reg_save_area.
19914   if (offsetMBB) {
19915     assert(OffsetReg != 0);
19916
19917     // Read the reg_save_area address.
19918     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19919     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19920       .addOperand(Base)
19921       .addOperand(Scale)
19922       .addOperand(Index)
19923       .addDisp(Disp, 16)
19924       .addOperand(Segment)
19925       .setMemRefs(MMOBegin, MMOEnd);
19926
19927     // Zero-extend the offset
19928     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19929       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19930         .addImm(0)
19931         .addReg(OffsetReg)
19932         .addImm(X86::sub_32bit);
19933
19934     // Add the offset to the reg_save_area to get the final address.
19935     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19936       .addReg(OffsetReg64)
19937       .addReg(RegSaveReg);
19938
19939     // Compute the offset for the next argument
19940     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19941     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19942       .addReg(OffsetReg)
19943       .addImm(UseFPOffset ? 16 : 8);
19944
19945     // Store it back into the va_list.
19946     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19947       .addOperand(Base)
19948       .addOperand(Scale)
19949       .addOperand(Index)
19950       .addDisp(Disp, UseFPOffset ? 4 : 0)
19951       .addOperand(Segment)
19952       .addReg(NextOffsetReg)
19953       .setMemRefs(MMOBegin, MMOEnd);
19954
19955     // Jump to endMBB
19956     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19957       .addMBB(endMBB);
19958   }
19959
19960   //
19961   // Emit code to use overflow area
19962   //
19963
19964   // Load the overflow_area address into a register.
19965   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19966   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19967     .addOperand(Base)
19968     .addOperand(Scale)
19969     .addOperand(Index)
19970     .addDisp(Disp, 8)
19971     .addOperand(Segment)
19972     .setMemRefs(MMOBegin, MMOEnd);
19973
19974   // If we need to align it, do so. Otherwise, just copy the address
19975   // to OverflowDestReg.
19976   if (NeedsAlign) {
19977     // Align the overflow address
19978     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19979     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19980
19981     // aligned_addr = (addr + (align-1)) & ~(align-1)
19982     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19983       .addReg(OverflowAddrReg)
19984       .addImm(Align-1);
19985
19986     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19987       .addReg(TmpReg)
19988       .addImm(~(uint64_t)(Align-1));
19989   } else {
19990     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19991       .addReg(OverflowAddrReg);
19992   }
19993
19994   // Compute the next overflow address after this argument.
19995   // (the overflow address should be kept 8-byte aligned)
19996   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19997   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19998     .addReg(OverflowDestReg)
19999     .addImm(ArgSizeA8);
20000
20001   // Store the new overflow address.
20002   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20003     .addOperand(Base)
20004     .addOperand(Scale)
20005     .addOperand(Index)
20006     .addDisp(Disp, 8)
20007     .addOperand(Segment)
20008     .addReg(NextAddrReg)
20009     .setMemRefs(MMOBegin, MMOEnd);
20010
20011   // If we branched, emit the PHI to the front of endMBB.
20012   if (offsetMBB) {
20013     BuildMI(*endMBB, endMBB->begin(), DL,
20014             TII->get(X86::PHI), DestReg)
20015       .addReg(OffsetDestReg).addMBB(offsetMBB)
20016       .addReg(OverflowDestReg).addMBB(overflowMBB);
20017   }
20018
20019   // Erase the pseudo instruction
20020   MI->eraseFromParent();
20021
20022   return endMBB;
20023 }
20024
20025 MachineBasicBlock *
20026 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20027                                                  MachineInstr *MI,
20028                                                  MachineBasicBlock *MBB) const {
20029   // Emit code to save XMM registers to the stack. The ABI says that the
20030   // number of registers to save is given in %al, so it's theoretically
20031   // possible to do an indirect jump trick to avoid saving all of them,
20032   // however this code takes a simpler approach and just executes all
20033   // of the stores if %al is non-zero. It's less code, and it's probably
20034   // easier on the hardware branch predictor, and stores aren't all that
20035   // expensive anyway.
20036
20037   // Create the new basic blocks. One block contains all the XMM stores,
20038   // and one block is the final destination regardless of whether any
20039   // stores were performed.
20040   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20041   MachineFunction *F = MBB->getParent();
20042   MachineFunction::iterator MBBIter = MBB;
20043   ++MBBIter;
20044   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20045   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20046   F->insert(MBBIter, XMMSaveMBB);
20047   F->insert(MBBIter, EndMBB);
20048
20049   // Transfer the remainder of MBB and its successor edges to EndMBB.
20050   EndMBB->splice(EndMBB->begin(), MBB,
20051                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20052   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20053
20054   // The original block will now fall through to the XMM save block.
20055   MBB->addSuccessor(XMMSaveMBB);
20056   // The XMMSaveMBB will fall through to the end block.
20057   XMMSaveMBB->addSuccessor(EndMBB);
20058
20059   // Now add the instructions.
20060   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20061   DebugLoc DL = MI->getDebugLoc();
20062
20063   unsigned CountReg = MI->getOperand(0).getReg();
20064   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20065   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20066
20067   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20068     // If %al is 0, branch around the XMM save block.
20069     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20070     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20071     MBB->addSuccessor(EndMBB);
20072   }
20073
20074   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20075   // that was just emitted, but clearly shouldn't be "saved".
20076   assert((MI->getNumOperands() <= 3 ||
20077           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20078           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20079          && "Expected last argument to be EFLAGS");
20080   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20081   // In the XMM save block, save all the XMM argument registers.
20082   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20083     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20084     MachineMemOperand *MMO = F->getMachineMemOperand(
20085         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20086         MachineMemOperand::MOStore,
20087         /*Size=*/16, /*Align=*/16);
20088     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20089       .addFrameIndex(RegSaveFrameIndex)
20090       .addImm(/*Scale=*/1)
20091       .addReg(/*IndexReg=*/0)
20092       .addImm(/*Disp=*/Offset)
20093       .addReg(/*Segment=*/0)
20094       .addReg(MI->getOperand(i).getReg())
20095       .addMemOperand(MMO);
20096   }
20097
20098   MI->eraseFromParent();   // The pseudo instruction is gone now.
20099
20100   return EndMBB;
20101 }
20102
20103 // The EFLAGS operand of SelectItr might be missing a kill marker
20104 // because there were multiple uses of EFLAGS, and ISel didn't know
20105 // which to mark. Figure out whether SelectItr should have had a
20106 // kill marker, and set it if it should. Returns the correct kill
20107 // marker value.
20108 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20109                                      MachineBasicBlock* BB,
20110                                      const TargetRegisterInfo* TRI) {
20111   // Scan forward through BB for a use/def of EFLAGS.
20112   MachineBasicBlock::iterator miI(std::next(SelectItr));
20113   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20114     const MachineInstr& mi = *miI;
20115     if (mi.readsRegister(X86::EFLAGS))
20116       return false;
20117     if (mi.definesRegister(X86::EFLAGS))
20118       break; // Should have kill-flag - update below.
20119   }
20120
20121   // If we hit the end of the block, check whether EFLAGS is live into a
20122   // successor.
20123   if (miI == BB->end()) {
20124     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20125                                           sEnd = BB->succ_end();
20126          sItr != sEnd; ++sItr) {
20127       MachineBasicBlock* succ = *sItr;
20128       if (succ->isLiveIn(X86::EFLAGS))
20129         return false;
20130     }
20131   }
20132
20133   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20134   // out. SelectMI should have a kill flag on EFLAGS.
20135   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20136   return true;
20137 }
20138
20139 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20140 // together with other CMOV pseudo-opcodes into a single basic-block with
20141 // conditional jump around it.
20142 static bool isCMOVPseudo(MachineInstr *MI) {
20143   switch (MI->getOpcode()) {
20144   case X86::CMOV_FR32:
20145   case X86::CMOV_FR64:
20146   case X86::CMOV_GR8:
20147   case X86::CMOV_GR16:
20148   case X86::CMOV_GR32:
20149   case X86::CMOV_RFP32:
20150   case X86::CMOV_RFP64:
20151   case X86::CMOV_RFP80:
20152   case X86::CMOV_V2F64:
20153   case X86::CMOV_V2I64:
20154   case X86::CMOV_V4F32:
20155   case X86::CMOV_V4F64:
20156   case X86::CMOV_V4I64:
20157   case X86::CMOV_V16F32:
20158   case X86::CMOV_V8F32:
20159   case X86::CMOV_V8F64:
20160   case X86::CMOV_V8I64:
20161   case X86::CMOV_V8I1:
20162   case X86::CMOV_V16I1:
20163   case X86::CMOV_V32I1:
20164   case X86::CMOV_V64I1:
20165     return true;
20166
20167   default:
20168     return false;
20169   }
20170 }
20171
20172 MachineBasicBlock *
20173 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20174                                      MachineBasicBlock *BB) const {
20175   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20176   DebugLoc DL = MI->getDebugLoc();
20177
20178   // To "insert" a SELECT_CC instruction, we actually have to insert the
20179   // diamond control-flow pattern.  The incoming instruction knows the
20180   // destination vreg to set, the condition code register to branch on, the
20181   // true/false values to select between, and a branch opcode to use.
20182   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20183   MachineFunction::iterator It = BB;
20184   ++It;
20185
20186   //  thisMBB:
20187   //  ...
20188   //   TrueVal = ...
20189   //   cmpTY ccX, r1, r2
20190   //   bCC copy1MBB
20191   //   fallthrough --> copy0MBB
20192   MachineBasicBlock *thisMBB = BB;
20193   MachineFunction *F = BB->getParent();
20194
20195   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20196   // as described above, by inserting a BB, and then making a PHI at the join
20197   // point to select the true and false operands of the CMOV in the PHI.
20198   //
20199   // The code also handles two different cases of multiple CMOV opcodes
20200   // in a row.
20201   //
20202   // Case 1:
20203   // In this case, there are multiple CMOVs in a row, all which are based on
20204   // the same condition setting (or the exact opposite condition setting).
20205   // In this case we can lower all the CMOVs using a single inserted BB, and
20206   // then make a number of PHIs at the join point to model the CMOVs. The only
20207   // trickiness here, is that in a case like:
20208   //
20209   // t2 = CMOV cond1 t1, f1
20210   // t3 = CMOV cond1 t2, f2
20211   //
20212   // when rewriting this into PHIs, we have to perform some renaming on the
20213   // temps since you cannot have a PHI operand refer to a PHI result earlier
20214   // in the same block.  The "simple" but wrong lowering would be:
20215   //
20216   // t2 = PHI t1(BB1), f1(BB2)
20217   // t3 = PHI t2(BB1), f2(BB2)
20218   //
20219   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20220   // renaming is to note that on the path through BB1, t2 is really just a
20221   // copy of t1, and do that renaming, properly generating:
20222   //
20223   // t2 = PHI t1(BB1), f1(BB2)
20224   // t3 = PHI t1(BB1), f2(BB2)
20225   //
20226   // Case 2, we lower cascaded CMOVs such as
20227   //
20228   //   (CMOV (CMOV F, T, cc1), T, cc2)
20229   //
20230   // to two successives branches.  For that, we look for another CMOV as the
20231   // following instruction.
20232   //
20233   // Without this, we would add a PHI between the two jumps, which ends up
20234   // creating a few copies all around. For instance, for
20235   //
20236   //    (sitofp (zext (fcmp une)))
20237   //
20238   // we would generate:
20239   //
20240   //         ucomiss %xmm1, %xmm0
20241   //         movss  <1.0f>, %xmm0
20242   //         movaps  %xmm0, %xmm1
20243   //         jne     .LBB5_2
20244   //         xorps   %xmm1, %xmm1
20245   // .LBB5_2:
20246   //         jp      .LBB5_4
20247   //         movaps  %xmm1, %xmm0
20248   // .LBB5_4:
20249   //         retq
20250   //
20251   // because this custom-inserter would have generated:
20252   //
20253   //   A
20254   //   | \
20255   //   |  B
20256   //   | /
20257   //   C
20258   //   | \
20259   //   |  D
20260   //   | /
20261   //   E
20262   //
20263   // A: X = ...; Y = ...
20264   // B: empty
20265   // C: Z = PHI [X, A], [Y, B]
20266   // D: empty
20267   // E: PHI [X, C], [Z, D]
20268   //
20269   // If we lower both CMOVs in a single step, we can instead generate:
20270   //
20271   //   A
20272   //   | \
20273   //   |  C
20274   //   | /|
20275   //   |/ |
20276   //   |  |
20277   //   |  D
20278   //   | /
20279   //   E
20280   //
20281   // A: X = ...; Y = ...
20282   // D: empty
20283   // E: PHI [X, A], [X, C], [Y, D]
20284   //
20285   // Which, in our sitofp/fcmp example, gives us something like:
20286   //
20287   //         ucomiss %xmm1, %xmm0
20288   //         movss  <1.0f>, %xmm0
20289   //         jne     .LBB5_4
20290   //         jp      .LBB5_4
20291   //         xorps   %xmm0, %xmm0
20292   // .LBB5_4:
20293   //         retq
20294   //
20295   MachineInstr *CascadedCMOV = nullptr;
20296   MachineInstr *LastCMOV = MI;
20297   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20298   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20299   MachineBasicBlock::iterator NextMIIt =
20300       std::next(MachineBasicBlock::iterator(MI));
20301
20302   // Check for case 1, where there are multiple CMOVs with the same condition
20303   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20304   // number of jumps the most.
20305
20306   if (isCMOVPseudo(MI)) {
20307     // See if we have a string of CMOVS with the same condition.
20308     while (NextMIIt != BB->end() &&
20309            isCMOVPseudo(NextMIIt) &&
20310            (NextMIIt->getOperand(3).getImm() == CC ||
20311             NextMIIt->getOperand(3).getImm() == OppCC)) {
20312       LastCMOV = &*NextMIIt;
20313       ++NextMIIt;
20314     }
20315   }
20316
20317   // This checks for case 2, but only do this if we didn't already find
20318   // case 1, as indicated by LastCMOV == MI.
20319   if (LastCMOV == MI &&
20320       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20321       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20322       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20323     CascadedCMOV = &*NextMIIt;
20324   }
20325
20326   MachineBasicBlock *jcc1MBB = nullptr;
20327
20328   // If we have a cascaded CMOV, we lower it to two successive branches to
20329   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20330   if (CascadedCMOV) {
20331     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20332     F->insert(It, jcc1MBB);
20333     jcc1MBB->addLiveIn(X86::EFLAGS);
20334   }
20335
20336   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20337   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20338   F->insert(It, copy0MBB);
20339   F->insert(It, sinkMBB);
20340
20341   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20342   // live into the sink and copy blocks.
20343   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20344
20345   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20346   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20347       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20348     copy0MBB->addLiveIn(X86::EFLAGS);
20349     sinkMBB->addLiveIn(X86::EFLAGS);
20350   }
20351
20352   // Transfer the remainder of BB and its successor edges to sinkMBB.
20353   sinkMBB->splice(sinkMBB->begin(), BB,
20354                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20355   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20356
20357   // Add the true and fallthrough blocks as its successors.
20358   if (CascadedCMOV) {
20359     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20360     BB->addSuccessor(jcc1MBB);
20361
20362     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20363     // jump to the sinkMBB.
20364     jcc1MBB->addSuccessor(copy0MBB);
20365     jcc1MBB->addSuccessor(sinkMBB);
20366   } else {
20367     BB->addSuccessor(copy0MBB);
20368   }
20369
20370   // The true block target of the first (or only) branch is always sinkMBB.
20371   BB->addSuccessor(sinkMBB);
20372
20373   // Create the conditional branch instruction.
20374   unsigned Opc = X86::GetCondBranchFromCond(CC);
20375   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20376
20377   if (CascadedCMOV) {
20378     unsigned Opc2 = X86::GetCondBranchFromCond(
20379         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20380     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20381   }
20382
20383   //  copy0MBB:
20384   //   %FalseValue = ...
20385   //   # fallthrough to sinkMBB
20386   copy0MBB->addSuccessor(sinkMBB);
20387
20388   //  sinkMBB:
20389   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20390   //  ...
20391   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20392   MachineBasicBlock::iterator MIItEnd =
20393     std::next(MachineBasicBlock::iterator(LastCMOV));
20394   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20395   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20396   MachineInstrBuilder MIB;
20397
20398   // As we are creating the PHIs, we have to be careful if there is more than
20399   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20400   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20401   // That also means that PHI construction must work forward from earlier to
20402   // later, and that the code must maintain a mapping from earlier PHI's
20403   // destination registers, and the registers that went into the PHI.
20404
20405   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20406     unsigned DestReg = MIIt->getOperand(0).getReg();
20407     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20408     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20409
20410     // If this CMOV we are generating is the opposite condition from
20411     // the jump we generated, then we have to swap the operands for the
20412     // PHI that is going to be generated.
20413     if (MIIt->getOperand(3).getImm() == OppCC)
20414         std::swap(Op1Reg, Op2Reg);
20415
20416     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20417       Op1Reg = RegRewriteTable[Op1Reg].first;
20418
20419     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20420       Op2Reg = RegRewriteTable[Op2Reg].second;
20421
20422     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20423                   TII->get(X86::PHI), DestReg)
20424           .addReg(Op1Reg).addMBB(copy0MBB)
20425           .addReg(Op2Reg).addMBB(thisMBB);
20426
20427     // Add this PHI to the rewrite table.
20428     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20429   }
20430
20431   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20432   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20433   if (CascadedCMOV) {
20434     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20435     // Copy the PHI result to the register defined by the second CMOV.
20436     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20437             DL, TII->get(TargetOpcode::COPY),
20438             CascadedCMOV->getOperand(0).getReg())
20439         .addReg(MI->getOperand(0).getReg());
20440     CascadedCMOV->eraseFromParent();
20441   }
20442
20443   // Now remove the CMOV(s).
20444   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20445     (MIIt++)->eraseFromParent();
20446
20447   return sinkMBB;
20448 }
20449
20450 MachineBasicBlock *
20451 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20452                                        MachineBasicBlock *BB) const {
20453   // Combine the following atomic floating-point modification pattern:
20454   //   a.store(reg OP a.load(acquire), release)
20455   // Transform them into:
20456   //   OPss (%gpr), %xmm
20457   //   movss %xmm, (%gpr)
20458   // Or sd equivalent for 64-bit operations.
20459   unsigned MOp, FOp;
20460   switch (MI->getOpcode()) {
20461   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20462   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20463   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20464   }
20465   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20466   DebugLoc DL = MI->getDebugLoc();
20467   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20468   unsigned MSrc = MI->getOperand(0).getReg();
20469   unsigned VSrc = MI->getOperand(5).getReg();
20470   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20471                                 .addReg(/*Base=*/MSrc)
20472                                 .addImm(/*Scale=*/1)
20473                                 .addReg(/*Index=*/0)
20474                                 .addImm(0)
20475                                 .addReg(0);
20476   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20477                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20478                           .addReg(VSrc)
20479                           .addReg(/*Base=*/MSrc)
20480                           .addImm(/*Scale=*/1)
20481                           .addReg(/*Index=*/0)
20482                           .addImm(/*Disp=*/0)
20483                           .addReg(/*Segment=*/0);
20484   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20485   MI->eraseFromParent(); // The pseudo instruction is gone now.
20486   return BB;
20487 }
20488
20489 MachineBasicBlock *
20490 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20491                                         MachineBasicBlock *BB) const {
20492   MachineFunction *MF = BB->getParent();
20493   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20494   DebugLoc DL = MI->getDebugLoc();
20495   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20496
20497   assert(MF->shouldSplitStack());
20498
20499   const bool Is64Bit = Subtarget->is64Bit();
20500   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20501
20502   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20503   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20504
20505   // BB:
20506   //  ... [Till the alloca]
20507   // If stacklet is not large enough, jump to mallocMBB
20508   //
20509   // bumpMBB:
20510   //  Allocate by subtracting from RSP
20511   //  Jump to continueMBB
20512   //
20513   // mallocMBB:
20514   //  Allocate by call to runtime
20515   //
20516   // continueMBB:
20517   //  ...
20518   //  [rest of original BB]
20519   //
20520
20521   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20522   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20523   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20524
20525   MachineRegisterInfo &MRI = MF->getRegInfo();
20526   const TargetRegisterClass *AddrRegClass =
20527       getRegClassFor(getPointerTy(MF->getDataLayout()));
20528
20529   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20530     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20531     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20532     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20533     sizeVReg = MI->getOperand(1).getReg(),
20534     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20535
20536   MachineFunction::iterator MBBIter = BB;
20537   ++MBBIter;
20538
20539   MF->insert(MBBIter, bumpMBB);
20540   MF->insert(MBBIter, mallocMBB);
20541   MF->insert(MBBIter, continueMBB);
20542
20543   continueMBB->splice(continueMBB->begin(), BB,
20544                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20545   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20546
20547   // Add code to the main basic block to check if the stack limit has been hit,
20548   // and if so, jump to mallocMBB otherwise to bumpMBB.
20549   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20550   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20551     .addReg(tmpSPVReg).addReg(sizeVReg);
20552   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20553     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20554     .addReg(SPLimitVReg);
20555   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20556
20557   // bumpMBB simply decreases the stack pointer, since we know the current
20558   // stacklet has enough space.
20559   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20560     .addReg(SPLimitVReg);
20561   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20562     .addReg(SPLimitVReg);
20563   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20564
20565   // Calls into a routine in libgcc to allocate more space from the heap.
20566   const uint32_t *RegMask =
20567       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20568   if (IsLP64) {
20569     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20570       .addReg(sizeVReg);
20571     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20572       .addExternalSymbol("__morestack_allocate_stack_space")
20573       .addRegMask(RegMask)
20574       .addReg(X86::RDI, RegState::Implicit)
20575       .addReg(X86::RAX, RegState::ImplicitDefine);
20576   } else if (Is64Bit) {
20577     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20578       .addReg(sizeVReg);
20579     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20580       .addExternalSymbol("__morestack_allocate_stack_space")
20581       .addRegMask(RegMask)
20582       .addReg(X86::EDI, RegState::Implicit)
20583       .addReg(X86::EAX, RegState::ImplicitDefine);
20584   } else {
20585     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20586       .addImm(12);
20587     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20588     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20589       .addExternalSymbol("__morestack_allocate_stack_space")
20590       .addRegMask(RegMask)
20591       .addReg(X86::EAX, RegState::ImplicitDefine);
20592   }
20593
20594   if (!Is64Bit)
20595     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20596       .addImm(16);
20597
20598   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20599     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20600   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20601
20602   // Set up the CFG correctly.
20603   BB->addSuccessor(bumpMBB);
20604   BB->addSuccessor(mallocMBB);
20605   mallocMBB->addSuccessor(continueMBB);
20606   bumpMBB->addSuccessor(continueMBB);
20607
20608   // Take care of the PHI nodes.
20609   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20610           MI->getOperand(0).getReg())
20611     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20612     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20613
20614   // Delete the original pseudo instruction.
20615   MI->eraseFromParent();
20616
20617   // And we're done.
20618   return continueMBB;
20619 }
20620
20621 MachineBasicBlock *
20622 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20623                                         MachineBasicBlock *BB) const {
20624   DebugLoc DL = MI->getDebugLoc();
20625
20626   assert(!Subtarget->isTargetMachO());
20627
20628   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20629                                                     DL);
20630
20631   MI->eraseFromParent();   // The pseudo instruction is gone now.
20632   return BB;
20633 }
20634
20635 MachineBasicBlock *
20636 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20637                                       MachineBasicBlock *BB) const {
20638   // This is pretty easy.  We're taking the value that we received from
20639   // our load from the relocation, sticking it in either RDI (x86-64)
20640   // or EAX and doing an indirect call.  The return value will then
20641   // be in the normal return register.
20642   MachineFunction *F = BB->getParent();
20643   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20644   DebugLoc DL = MI->getDebugLoc();
20645
20646   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20647   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20648
20649   // Get a register mask for the lowered call.
20650   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20651   // proper register mask.
20652   const uint32_t *RegMask =
20653       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20654   if (Subtarget->is64Bit()) {
20655     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20656                                       TII->get(X86::MOV64rm), X86::RDI)
20657     .addReg(X86::RIP)
20658     .addImm(0).addReg(0)
20659     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20660                       MI->getOperand(3).getTargetFlags())
20661     .addReg(0);
20662     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20663     addDirectMem(MIB, X86::RDI);
20664     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20665   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20666     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20667                                       TII->get(X86::MOV32rm), X86::EAX)
20668     .addReg(0)
20669     .addImm(0).addReg(0)
20670     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20671                       MI->getOperand(3).getTargetFlags())
20672     .addReg(0);
20673     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20674     addDirectMem(MIB, X86::EAX);
20675     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20676   } else {
20677     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20678                                       TII->get(X86::MOV32rm), X86::EAX)
20679     .addReg(TII->getGlobalBaseReg(F))
20680     .addImm(0).addReg(0)
20681     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20682                       MI->getOperand(3).getTargetFlags())
20683     .addReg(0);
20684     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20685     addDirectMem(MIB, X86::EAX);
20686     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20687   }
20688
20689   MI->eraseFromParent(); // The pseudo instruction is gone now.
20690   return BB;
20691 }
20692
20693 MachineBasicBlock *
20694 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20695                                     MachineBasicBlock *MBB) const {
20696   DebugLoc DL = MI->getDebugLoc();
20697   MachineFunction *MF = MBB->getParent();
20698   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20699   MachineRegisterInfo &MRI = MF->getRegInfo();
20700
20701   const BasicBlock *BB = MBB->getBasicBlock();
20702   MachineFunction::iterator I = MBB;
20703   ++I;
20704
20705   // Memory Reference
20706   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20707   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20708
20709   unsigned DstReg;
20710   unsigned MemOpndSlot = 0;
20711
20712   unsigned CurOp = 0;
20713
20714   DstReg = MI->getOperand(CurOp++).getReg();
20715   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20716   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20717   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20718   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20719
20720   MemOpndSlot = CurOp;
20721
20722   MVT PVT = getPointerTy(MF->getDataLayout());
20723   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20724          "Invalid Pointer Size!");
20725
20726   // For v = setjmp(buf), we generate
20727   //
20728   // thisMBB:
20729   //  buf[LabelOffset] = restoreMBB
20730   //  SjLjSetup restoreMBB
20731   //
20732   // mainMBB:
20733   //  v_main = 0
20734   //
20735   // sinkMBB:
20736   //  v = phi(main, restore)
20737   //
20738   // restoreMBB:
20739   //  if base pointer being used, load it from frame
20740   //  v_restore = 1
20741
20742   MachineBasicBlock *thisMBB = MBB;
20743   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20744   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20745   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20746   MF->insert(I, mainMBB);
20747   MF->insert(I, sinkMBB);
20748   MF->push_back(restoreMBB);
20749
20750   MachineInstrBuilder MIB;
20751
20752   // Transfer the remainder of BB and its successor edges to sinkMBB.
20753   sinkMBB->splice(sinkMBB->begin(), MBB,
20754                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20755   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20756
20757   // thisMBB:
20758   unsigned PtrStoreOpc = 0;
20759   unsigned LabelReg = 0;
20760   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20761   Reloc::Model RM = MF->getTarget().getRelocationModel();
20762   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20763                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20764
20765   // Prepare IP either in reg or imm.
20766   if (!UseImmLabel) {
20767     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20768     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20769     LabelReg = MRI.createVirtualRegister(PtrRC);
20770     if (Subtarget->is64Bit()) {
20771       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20772               .addReg(X86::RIP)
20773               .addImm(0)
20774               .addReg(0)
20775               .addMBB(restoreMBB)
20776               .addReg(0);
20777     } else {
20778       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20779       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20780               .addReg(XII->getGlobalBaseReg(MF))
20781               .addImm(0)
20782               .addReg(0)
20783               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20784               .addReg(0);
20785     }
20786   } else
20787     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20788   // Store IP
20789   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20790   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20791     if (i == X86::AddrDisp)
20792       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20793     else
20794       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20795   }
20796   if (!UseImmLabel)
20797     MIB.addReg(LabelReg);
20798   else
20799     MIB.addMBB(restoreMBB);
20800   MIB.setMemRefs(MMOBegin, MMOEnd);
20801   // Setup
20802   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20803           .addMBB(restoreMBB);
20804
20805   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20806   MIB.addRegMask(RegInfo->getNoPreservedMask());
20807   thisMBB->addSuccessor(mainMBB);
20808   thisMBB->addSuccessor(restoreMBB);
20809
20810   // mainMBB:
20811   //  EAX = 0
20812   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20813   mainMBB->addSuccessor(sinkMBB);
20814
20815   // sinkMBB:
20816   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20817           TII->get(X86::PHI), DstReg)
20818     .addReg(mainDstReg).addMBB(mainMBB)
20819     .addReg(restoreDstReg).addMBB(restoreMBB);
20820
20821   // restoreMBB:
20822   if (RegInfo->hasBasePointer(*MF)) {
20823     const bool Uses64BitFramePtr =
20824         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20825     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20826     X86FI->setRestoreBasePointer(MF);
20827     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20828     unsigned BasePtr = RegInfo->getBaseRegister();
20829     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20830     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20831                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20832       .setMIFlag(MachineInstr::FrameSetup);
20833   }
20834   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20835   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20836   restoreMBB->addSuccessor(sinkMBB);
20837
20838   MI->eraseFromParent();
20839   return sinkMBB;
20840 }
20841
20842 MachineBasicBlock *
20843 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20844                                      MachineBasicBlock *MBB) const {
20845   DebugLoc DL = MI->getDebugLoc();
20846   MachineFunction *MF = MBB->getParent();
20847   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20848   MachineRegisterInfo &MRI = MF->getRegInfo();
20849
20850   // Memory Reference
20851   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20852   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20853
20854   MVT PVT = getPointerTy(MF->getDataLayout());
20855   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20856          "Invalid Pointer Size!");
20857
20858   const TargetRegisterClass *RC =
20859     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20860   unsigned Tmp = MRI.createVirtualRegister(RC);
20861   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20862   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20863   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20864   unsigned SP = RegInfo->getStackRegister();
20865
20866   MachineInstrBuilder MIB;
20867
20868   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20869   const int64_t SPOffset = 2 * PVT.getStoreSize();
20870
20871   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20872   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20873
20874   // Reload FP
20875   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20876   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20877     MIB.addOperand(MI->getOperand(i));
20878   MIB.setMemRefs(MMOBegin, MMOEnd);
20879   // Reload IP
20880   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20881   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20882     if (i == X86::AddrDisp)
20883       MIB.addDisp(MI->getOperand(i), LabelOffset);
20884     else
20885       MIB.addOperand(MI->getOperand(i));
20886   }
20887   MIB.setMemRefs(MMOBegin, MMOEnd);
20888   // Reload SP
20889   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20890   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20891     if (i == X86::AddrDisp)
20892       MIB.addDisp(MI->getOperand(i), SPOffset);
20893     else
20894       MIB.addOperand(MI->getOperand(i));
20895   }
20896   MIB.setMemRefs(MMOBegin, MMOEnd);
20897   // Jump
20898   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20899
20900   MI->eraseFromParent();
20901   return MBB;
20902 }
20903
20904 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20905 // accumulator loops. Writing back to the accumulator allows the coalescer
20906 // to remove extra copies in the loop.
20907 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20908 MachineBasicBlock *
20909 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20910                                  MachineBasicBlock *MBB) const {
20911   MachineOperand &AddendOp = MI->getOperand(3);
20912
20913   // Bail out early if the addend isn't a register - we can't switch these.
20914   if (!AddendOp.isReg())
20915     return MBB;
20916
20917   MachineFunction &MF = *MBB->getParent();
20918   MachineRegisterInfo &MRI = MF.getRegInfo();
20919
20920   // Check whether the addend is defined by a PHI:
20921   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20922   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20923   if (!AddendDef.isPHI())
20924     return MBB;
20925
20926   // Look for the following pattern:
20927   // loop:
20928   //   %addend = phi [%entry, 0], [%loop, %result]
20929   //   ...
20930   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20931
20932   // Replace with:
20933   //   loop:
20934   //   %addend = phi [%entry, 0], [%loop, %result]
20935   //   ...
20936   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20937
20938   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20939     assert(AddendDef.getOperand(i).isReg());
20940     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20941     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20942     if (&PHISrcInst == MI) {
20943       // Found a matching instruction.
20944       unsigned NewFMAOpc = 0;
20945       switch (MI->getOpcode()) {
20946         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20947         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20948         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20949         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20950         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20951         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20952         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20953         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20954         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20955         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20956         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20957         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20958         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20959         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20960         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20961         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20962         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20963         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20964         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20965         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20966
20967         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20968         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20969         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20970         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20971         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20972         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20973         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20974         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20975         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20976         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20977         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20978         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20979         default: llvm_unreachable("Unrecognized FMA variant.");
20980       }
20981
20982       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20983       MachineInstrBuilder MIB =
20984         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20985         .addOperand(MI->getOperand(0))
20986         .addOperand(MI->getOperand(3))
20987         .addOperand(MI->getOperand(2))
20988         .addOperand(MI->getOperand(1));
20989       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20990       MI->eraseFromParent();
20991     }
20992   }
20993
20994   return MBB;
20995 }
20996
20997 MachineBasicBlock *
20998 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20999                                                MachineBasicBlock *BB) const {
21000   switch (MI->getOpcode()) {
21001   default: llvm_unreachable("Unexpected instr type to insert");
21002   case X86::TAILJMPd64:
21003   case X86::TAILJMPr64:
21004   case X86::TAILJMPm64:
21005   case X86::TAILJMPd64_REX:
21006   case X86::TAILJMPr64_REX:
21007   case X86::TAILJMPm64_REX:
21008     llvm_unreachable("TAILJMP64 would not be touched here.");
21009   case X86::TCRETURNdi64:
21010   case X86::TCRETURNri64:
21011   case X86::TCRETURNmi64:
21012     return BB;
21013   case X86::WIN_ALLOCA:
21014     return EmitLoweredWinAlloca(MI, BB);
21015   case X86::SEG_ALLOCA_32:
21016   case X86::SEG_ALLOCA_64:
21017     return EmitLoweredSegAlloca(MI, BB);
21018   case X86::TLSCall_32:
21019   case X86::TLSCall_64:
21020     return EmitLoweredTLSCall(MI, BB);
21021   case X86::CMOV_FR32:
21022   case X86::CMOV_FR64:
21023   case X86::CMOV_GR8:
21024   case X86::CMOV_GR16:
21025   case X86::CMOV_GR32:
21026   case X86::CMOV_RFP32:
21027   case X86::CMOV_RFP64:
21028   case X86::CMOV_RFP80:
21029   case X86::CMOV_V2F64:
21030   case X86::CMOV_V2I64:
21031   case X86::CMOV_V4F32:
21032   case X86::CMOV_V4F64:
21033   case X86::CMOV_V4I64:
21034   case X86::CMOV_V16F32:
21035   case X86::CMOV_V8F32:
21036   case X86::CMOV_V8F64:
21037   case X86::CMOV_V8I64:
21038   case X86::CMOV_V8I1:
21039   case X86::CMOV_V16I1:
21040   case X86::CMOV_V32I1:
21041   case X86::CMOV_V64I1:
21042     return EmitLoweredSelect(MI, BB);
21043
21044   case X86::RELEASE_FADD32mr:
21045   case X86::RELEASE_FADD64mr:
21046     return EmitLoweredAtomicFP(MI, BB);
21047
21048   case X86::FP32_TO_INT16_IN_MEM:
21049   case X86::FP32_TO_INT32_IN_MEM:
21050   case X86::FP32_TO_INT64_IN_MEM:
21051   case X86::FP64_TO_INT16_IN_MEM:
21052   case X86::FP64_TO_INT32_IN_MEM:
21053   case X86::FP64_TO_INT64_IN_MEM:
21054   case X86::FP80_TO_INT16_IN_MEM:
21055   case X86::FP80_TO_INT32_IN_MEM:
21056   case X86::FP80_TO_INT64_IN_MEM: {
21057     MachineFunction *F = BB->getParent();
21058     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21059     DebugLoc DL = MI->getDebugLoc();
21060
21061     // Change the floating point control register to use "round towards zero"
21062     // mode when truncating to an integer value.
21063     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21064     addFrameReference(BuildMI(*BB, MI, DL,
21065                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21066
21067     // Load the old value of the high byte of the control word...
21068     unsigned OldCW =
21069       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21070     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21071                       CWFrameIdx);
21072
21073     // Set the high part to be round to zero...
21074     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21075       .addImm(0xC7F);
21076
21077     // Reload the modified control word now...
21078     addFrameReference(BuildMI(*BB, MI, DL,
21079                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21080
21081     // Restore the memory image of control word to original value
21082     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21083       .addReg(OldCW);
21084
21085     // Get the X86 opcode to use.
21086     unsigned Opc;
21087     switch (MI->getOpcode()) {
21088     default: llvm_unreachable("illegal opcode!");
21089     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21090     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21091     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21092     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21093     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21094     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21095     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21096     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21097     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21098     }
21099
21100     X86AddressMode AM;
21101     MachineOperand &Op = MI->getOperand(0);
21102     if (Op.isReg()) {
21103       AM.BaseType = X86AddressMode::RegBase;
21104       AM.Base.Reg = Op.getReg();
21105     } else {
21106       AM.BaseType = X86AddressMode::FrameIndexBase;
21107       AM.Base.FrameIndex = Op.getIndex();
21108     }
21109     Op = MI->getOperand(1);
21110     if (Op.isImm())
21111       AM.Scale = Op.getImm();
21112     Op = MI->getOperand(2);
21113     if (Op.isImm())
21114       AM.IndexReg = Op.getImm();
21115     Op = MI->getOperand(3);
21116     if (Op.isGlobal()) {
21117       AM.GV = Op.getGlobal();
21118     } else {
21119       AM.Disp = Op.getImm();
21120     }
21121     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21122                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21123
21124     // Reload the original control word now.
21125     addFrameReference(BuildMI(*BB, MI, DL,
21126                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21127
21128     MI->eraseFromParent();   // The pseudo instruction is gone now.
21129     return BB;
21130   }
21131     // String/text processing lowering.
21132   case X86::PCMPISTRM128REG:
21133   case X86::VPCMPISTRM128REG:
21134   case X86::PCMPISTRM128MEM:
21135   case X86::VPCMPISTRM128MEM:
21136   case X86::PCMPESTRM128REG:
21137   case X86::VPCMPESTRM128REG:
21138   case X86::PCMPESTRM128MEM:
21139   case X86::VPCMPESTRM128MEM:
21140     assert(Subtarget->hasSSE42() &&
21141            "Target must have SSE4.2 or AVX features enabled");
21142     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21143
21144   // String/text processing lowering.
21145   case X86::PCMPISTRIREG:
21146   case X86::VPCMPISTRIREG:
21147   case X86::PCMPISTRIMEM:
21148   case X86::VPCMPISTRIMEM:
21149   case X86::PCMPESTRIREG:
21150   case X86::VPCMPESTRIREG:
21151   case X86::PCMPESTRIMEM:
21152   case X86::VPCMPESTRIMEM:
21153     assert(Subtarget->hasSSE42() &&
21154            "Target must have SSE4.2 or AVX features enabled");
21155     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21156
21157   // Thread synchronization.
21158   case X86::MONITOR:
21159     return EmitMonitor(MI, BB, Subtarget);
21160
21161   // xbegin
21162   case X86::XBEGIN:
21163     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21164
21165   case X86::VASTART_SAVE_XMM_REGS:
21166     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21167
21168   case X86::VAARG_64:
21169     return EmitVAARG64WithCustomInserter(MI, BB);
21170
21171   case X86::EH_SjLj_SetJmp32:
21172   case X86::EH_SjLj_SetJmp64:
21173     return emitEHSjLjSetJmp(MI, BB);
21174
21175   case X86::EH_SjLj_LongJmp32:
21176   case X86::EH_SjLj_LongJmp64:
21177     return emitEHSjLjLongJmp(MI, BB);
21178
21179   case TargetOpcode::STATEPOINT:
21180     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21181     // this point in the process.  We diverge later.
21182     return emitPatchPoint(MI, BB);
21183
21184   case TargetOpcode::STACKMAP:
21185   case TargetOpcode::PATCHPOINT:
21186     return emitPatchPoint(MI, BB);
21187
21188   case X86::VFMADDPDr213r:
21189   case X86::VFMADDPSr213r:
21190   case X86::VFMADDSDr213r:
21191   case X86::VFMADDSSr213r:
21192   case X86::VFMSUBPDr213r:
21193   case X86::VFMSUBPSr213r:
21194   case X86::VFMSUBSDr213r:
21195   case X86::VFMSUBSSr213r:
21196   case X86::VFNMADDPDr213r:
21197   case X86::VFNMADDPSr213r:
21198   case X86::VFNMADDSDr213r:
21199   case X86::VFNMADDSSr213r:
21200   case X86::VFNMSUBPDr213r:
21201   case X86::VFNMSUBPSr213r:
21202   case X86::VFNMSUBSDr213r:
21203   case X86::VFNMSUBSSr213r:
21204   case X86::VFMADDSUBPDr213r:
21205   case X86::VFMADDSUBPSr213r:
21206   case X86::VFMSUBADDPDr213r:
21207   case X86::VFMSUBADDPSr213r:
21208   case X86::VFMADDPDr213rY:
21209   case X86::VFMADDPSr213rY:
21210   case X86::VFMSUBPDr213rY:
21211   case X86::VFMSUBPSr213rY:
21212   case X86::VFNMADDPDr213rY:
21213   case X86::VFNMADDPSr213rY:
21214   case X86::VFNMSUBPDr213rY:
21215   case X86::VFNMSUBPSr213rY:
21216   case X86::VFMADDSUBPDr213rY:
21217   case X86::VFMADDSUBPSr213rY:
21218   case X86::VFMSUBADDPDr213rY:
21219   case X86::VFMSUBADDPSr213rY:
21220     return emitFMA3Instr(MI, BB);
21221   }
21222 }
21223
21224 //===----------------------------------------------------------------------===//
21225 //                           X86 Optimization Hooks
21226 //===----------------------------------------------------------------------===//
21227
21228 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21229                                                       APInt &KnownZero,
21230                                                       APInt &KnownOne,
21231                                                       const SelectionDAG &DAG,
21232                                                       unsigned Depth) const {
21233   unsigned BitWidth = KnownZero.getBitWidth();
21234   unsigned Opc = Op.getOpcode();
21235   assert((Opc >= ISD::BUILTIN_OP_END ||
21236           Opc == ISD::INTRINSIC_WO_CHAIN ||
21237           Opc == ISD::INTRINSIC_W_CHAIN ||
21238           Opc == ISD::INTRINSIC_VOID) &&
21239          "Should use MaskedValueIsZero if you don't know whether Op"
21240          " is a target node!");
21241
21242   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21243   switch (Opc) {
21244   default: break;
21245   case X86ISD::ADD:
21246   case X86ISD::SUB:
21247   case X86ISD::ADC:
21248   case X86ISD::SBB:
21249   case X86ISD::SMUL:
21250   case X86ISD::UMUL:
21251   case X86ISD::INC:
21252   case X86ISD::DEC:
21253   case X86ISD::OR:
21254   case X86ISD::XOR:
21255   case X86ISD::AND:
21256     // These nodes' second result is a boolean.
21257     if (Op.getResNo() == 0)
21258       break;
21259     // Fallthrough
21260   case X86ISD::SETCC:
21261     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21262     break;
21263   case ISD::INTRINSIC_WO_CHAIN: {
21264     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21265     unsigned NumLoBits = 0;
21266     switch (IntId) {
21267     default: break;
21268     case Intrinsic::x86_sse_movmsk_ps:
21269     case Intrinsic::x86_avx_movmsk_ps_256:
21270     case Intrinsic::x86_sse2_movmsk_pd:
21271     case Intrinsic::x86_avx_movmsk_pd_256:
21272     case Intrinsic::x86_mmx_pmovmskb:
21273     case Intrinsic::x86_sse2_pmovmskb_128:
21274     case Intrinsic::x86_avx2_pmovmskb: {
21275       // High bits of movmskp{s|d}, pmovmskb are known zero.
21276       switch (IntId) {
21277         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21278         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21279         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21280         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21281         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21282         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21283         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21284         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21285       }
21286       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21287       break;
21288     }
21289     }
21290     break;
21291   }
21292   }
21293 }
21294
21295 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21296   SDValue Op,
21297   const SelectionDAG &,
21298   unsigned Depth) const {
21299   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21300   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21301     return Op.getValueType().getScalarType().getSizeInBits();
21302
21303   // Fallback case.
21304   return 1;
21305 }
21306
21307 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21308 /// node is a GlobalAddress + offset.
21309 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21310                                        const GlobalValue* &GA,
21311                                        int64_t &Offset) const {
21312   if (N->getOpcode() == X86ISD::Wrapper) {
21313     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21314       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21315       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21316       return true;
21317     }
21318   }
21319   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21320 }
21321
21322 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21323 /// same as extracting the high 128-bit part of 256-bit vector and then
21324 /// inserting the result into the low part of a new 256-bit vector
21325 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21326   EVT VT = SVOp->getValueType(0);
21327   unsigned NumElems = VT.getVectorNumElements();
21328
21329   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21330   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21331     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21332         SVOp->getMaskElt(j) >= 0)
21333       return false;
21334
21335   return true;
21336 }
21337
21338 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21339 /// same as extracting the low 128-bit part of 256-bit vector and then
21340 /// inserting the result into the high part of a new 256-bit vector
21341 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21342   EVT VT = SVOp->getValueType(0);
21343   unsigned NumElems = VT.getVectorNumElements();
21344
21345   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21346   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21347     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21348         SVOp->getMaskElt(j) >= 0)
21349       return false;
21350
21351   return true;
21352 }
21353
21354 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21355 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21356                                         TargetLowering::DAGCombinerInfo &DCI,
21357                                         const X86Subtarget* Subtarget) {
21358   SDLoc dl(N);
21359   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21360   SDValue V1 = SVOp->getOperand(0);
21361   SDValue V2 = SVOp->getOperand(1);
21362   EVT VT = SVOp->getValueType(0);
21363   unsigned NumElems = VT.getVectorNumElements();
21364
21365   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21366       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21367     //
21368     //                   0,0,0,...
21369     //                      |
21370     //    V      UNDEF    BUILD_VECTOR    UNDEF
21371     //     \      /           \           /
21372     //  CONCAT_VECTOR         CONCAT_VECTOR
21373     //         \                  /
21374     //          \                /
21375     //          RESULT: V + zero extended
21376     //
21377     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21378         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21379         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21380       return SDValue();
21381
21382     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21383       return SDValue();
21384
21385     // To match the shuffle mask, the first half of the mask should
21386     // be exactly the first vector, and all the rest a splat with the
21387     // first element of the second one.
21388     for (unsigned i = 0; i != NumElems/2; ++i)
21389       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21390           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21391         return SDValue();
21392
21393     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21394     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21395       if (Ld->hasNUsesOfValue(1, 0)) {
21396         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21397         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21398         SDValue ResNode =
21399           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21400                                   Ld->getMemoryVT(),
21401                                   Ld->getPointerInfo(),
21402                                   Ld->getAlignment(),
21403                                   false/*isVolatile*/, true/*ReadMem*/,
21404                                   false/*WriteMem*/);
21405
21406         // Make sure the newly-created LOAD is in the same position as Ld in
21407         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21408         // and update uses of Ld's output chain to use the TokenFactor.
21409         if (Ld->hasAnyUseOfValue(1)) {
21410           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21411                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21412           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21413           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21414                                  SDValue(ResNode.getNode(), 1));
21415         }
21416
21417         return DAG.getBitcast(VT, ResNode);
21418       }
21419     }
21420
21421     // Emit a zeroed vector and insert the desired subvector on its
21422     // first half.
21423     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21424     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21425     return DCI.CombineTo(N, InsV);
21426   }
21427
21428   //===--------------------------------------------------------------------===//
21429   // Combine some shuffles into subvector extracts and inserts:
21430   //
21431
21432   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21433   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21434     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21435     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21436     return DCI.CombineTo(N, InsV);
21437   }
21438
21439   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21440   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21441     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21442     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21443     return DCI.CombineTo(N, InsV);
21444   }
21445
21446   return SDValue();
21447 }
21448
21449 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21450 /// possible.
21451 ///
21452 /// This is the leaf of the recursive combinine below. When we have found some
21453 /// chain of single-use x86 shuffle instructions and accumulated the combined
21454 /// shuffle mask represented by them, this will try to pattern match that mask
21455 /// into either a single instruction if there is a special purpose instruction
21456 /// for this operation, or into a PSHUFB instruction which is a fully general
21457 /// instruction but should only be used to replace chains over a certain depth.
21458 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21459                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21460                                    TargetLowering::DAGCombinerInfo &DCI,
21461                                    const X86Subtarget *Subtarget) {
21462   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21463
21464   // Find the operand that enters the chain. Note that multiple uses are OK
21465   // here, we're not going to remove the operand we find.
21466   SDValue Input = Op.getOperand(0);
21467   while (Input.getOpcode() == ISD::BITCAST)
21468     Input = Input.getOperand(0);
21469
21470   MVT VT = Input.getSimpleValueType();
21471   MVT RootVT = Root.getSimpleValueType();
21472   SDLoc DL(Root);
21473
21474   // Just remove no-op shuffle masks.
21475   if (Mask.size() == 1) {
21476     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21477                   /*AddTo*/ true);
21478     return true;
21479   }
21480
21481   // Use the float domain if the operand type is a floating point type.
21482   bool FloatDomain = VT.isFloatingPoint();
21483
21484   // For floating point shuffles, we don't have free copies in the shuffle
21485   // instructions or the ability to load as part of the instruction, so
21486   // canonicalize their shuffles to UNPCK or MOV variants.
21487   //
21488   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21489   // vectors because it can have a load folded into it that UNPCK cannot. This
21490   // doesn't preclude something switching to the shorter encoding post-RA.
21491   //
21492   // FIXME: Should teach these routines about AVX vector widths.
21493   if (FloatDomain && VT.getSizeInBits() == 128) {
21494     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21495       bool Lo = Mask.equals({0, 0});
21496       unsigned Shuffle;
21497       MVT ShuffleVT;
21498       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21499       // is no slower than UNPCKLPD but has the option to fold the input operand
21500       // into even an unaligned memory load.
21501       if (Lo && Subtarget->hasSSE3()) {
21502         Shuffle = X86ISD::MOVDDUP;
21503         ShuffleVT = MVT::v2f64;
21504       } else {
21505         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21506         // than the UNPCK variants.
21507         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21508         ShuffleVT = MVT::v4f32;
21509       }
21510       if (Depth == 1 && Root->getOpcode() == Shuffle)
21511         return false; // Nothing to do!
21512       Op = DAG.getBitcast(ShuffleVT, Input);
21513       DCI.AddToWorklist(Op.getNode());
21514       if (Shuffle == X86ISD::MOVDDUP)
21515         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21516       else
21517         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21518       DCI.AddToWorklist(Op.getNode());
21519       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21520                     /*AddTo*/ true);
21521       return true;
21522     }
21523     if (Subtarget->hasSSE3() &&
21524         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21525       bool Lo = Mask.equals({0, 0, 2, 2});
21526       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21527       MVT ShuffleVT = MVT::v4f32;
21528       if (Depth == 1 && Root->getOpcode() == Shuffle)
21529         return false; // Nothing to do!
21530       Op = DAG.getBitcast(ShuffleVT, Input);
21531       DCI.AddToWorklist(Op.getNode());
21532       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21533       DCI.AddToWorklist(Op.getNode());
21534       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21535                     /*AddTo*/ true);
21536       return true;
21537     }
21538     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21539       bool Lo = Mask.equals({0, 0, 1, 1});
21540       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21541       MVT ShuffleVT = MVT::v4f32;
21542       if (Depth == 1 && Root->getOpcode() == Shuffle)
21543         return false; // Nothing to do!
21544       Op = DAG.getBitcast(ShuffleVT, Input);
21545       DCI.AddToWorklist(Op.getNode());
21546       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21547       DCI.AddToWorklist(Op.getNode());
21548       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21549                     /*AddTo*/ true);
21550       return true;
21551     }
21552   }
21553
21554   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21555   // variants as none of these have single-instruction variants that are
21556   // superior to the UNPCK formulation.
21557   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21558       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21559        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21560        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21561        Mask.equals(
21562            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21563     bool Lo = Mask[0] == 0;
21564     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21565     if (Depth == 1 && Root->getOpcode() == Shuffle)
21566       return false; // Nothing to do!
21567     MVT ShuffleVT;
21568     switch (Mask.size()) {
21569     case 8:
21570       ShuffleVT = MVT::v8i16;
21571       break;
21572     case 16:
21573       ShuffleVT = MVT::v16i8;
21574       break;
21575     default:
21576       llvm_unreachable("Impossible mask size!");
21577     };
21578     Op = DAG.getBitcast(ShuffleVT, Input);
21579     DCI.AddToWorklist(Op.getNode());
21580     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21581     DCI.AddToWorklist(Op.getNode());
21582     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21583                   /*AddTo*/ true);
21584     return true;
21585   }
21586
21587   // Don't try to re-form single instruction chains under any circumstances now
21588   // that we've done encoding canonicalization for them.
21589   if (Depth < 2)
21590     return false;
21591
21592   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21593   // can replace them with a single PSHUFB instruction profitably. Intel's
21594   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21595   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21596   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21597     SmallVector<SDValue, 16> PSHUFBMask;
21598     int NumBytes = VT.getSizeInBits() / 8;
21599     int Ratio = NumBytes / Mask.size();
21600     for (int i = 0; i < NumBytes; ++i) {
21601       if (Mask[i / Ratio] == SM_SentinelUndef) {
21602         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21603         continue;
21604       }
21605       int M = Mask[i / Ratio] != SM_SentinelZero
21606                   ? Ratio * Mask[i / Ratio] + i % Ratio
21607                   : 255;
21608       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21609     }
21610     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21611     Op = DAG.getBitcast(ByteVT, Input);
21612     DCI.AddToWorklist(Op.getNode());
21613     SDValue PSHUFBMaskOp =
21614         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21615     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21616     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21617     DCI.AddToWorklist(Op.getNode());
21618     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21619                   /*AddTo*/ true);
21620     return true;
21621   }
21622
21623   // Failed to find any combines.
21624   return false;
21625 }
21626
21627 /// \brief Fully generic combining of x86 shuffle instructions.
21628 ///
21629 /// This should be the last combine run over the x86 shuffle instructions. Once
21630 /// they have been fully optimized, this will recursively consider all chains
21631 /// of single-use shuffle instructions, build a generic model of the cumulative
21632 /// shuffle operation, and check for simpler instructions which implement this
21633 /// operation. We use this primarily for two purposes:
21634 ///
21635 /// 1) Collapse generic shuffles to specialized single instructions when
21636 ///    equivalent. In most cases, this is just an encoding size win, but
21637 ///    sometimes we will collapse multiple generic shuffles into a single
21638 ///    special-purpose shuffle.
21639 /// 2) Look for sequences of shuffle instructions with 3 or more total
21640 ///    instructions, and replace them with the slightly more expensive SSSE3
21641 ///    PSHUFB instruction if available. We do this as the last combining step
21642 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21643 ///    a suitable short sequence of other instructions. The PHUFB will either
21644 ///    use a register or have to read from memory and so is slightly (but only
21645 ///    slightly) more expensive than the other shuffle instructions.
21646 ///
21647 /// Because this is inherently a quadratic operation (for each shuffle in
21648 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21649 /// This should never be an issue in practice as the shuffle lowering doesn't
21650 /// produce sequences of more than 8 instructions.
21651 ///
21652 /// FIXME: We will currently miss some cases where the redundant shuffling
21653 /// would simplify under the threshold for PSHUFB formation because of
21654 /// combine-ordering. To fix this, we should do the redundant instruction
21655 /// combining in this recursive walk.
21656 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21657                                           ArrayRef<int> RootMask,
21658                                           int Depth, bool HasPSHUFB,
21659                                           SelectionDAG &DAG,
21660                                           TargetLowering::DAGCombinerInfo &DCI,
21661                                           const X86Subtarget *Subtarget) {
21662   // Bound the depth of our recursive combine because this is ultimately
21663   // quadratic in nature.
21664   if (Depth > 8)
21665     return false;
21666
21667   // Directly rip through bitcasts to find the underlying operand.
21668   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21669     Op = Op.getOperand(0);
21670
21671   MVT VT = Op.getSimpleValueType();
21672   if (!VT.isVector())
21673     return false; // Bail if we hit a non-vector.
21674
21675   assert(Root.getSimpleValueType().isVector() &&
21676          "Shuffles operate on vector types!");
21677   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21678          "Can only combine shuffles of the same vector register size.");
21679
21680   if (!isTargetShuffle(Op.getOpcode()))
21681     return false;
21682   SmallVector<int, 16> OpMask;
21683   bool IsUnary;
21684   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21685   // We only can combine unary shuffles which we can decode the mask for.
21686   if (!HaveMask || !IsUnary)
21687     return false;
21688
21689   assert(VT.getVectorNumElements() == OpMask.size() &&
21690          "Different mask size from vector size!");
21691   assert(((RootMask.size() > OpMask.size() &&
21692            RootMask.size() % OpMask.size() == 0) ||
21693           (OpMask.size() > RootMask.size() &&
21694            OpMask.size() % RootMask.size() == 0) ||
21695           OpMask.size() == RootMask.size()) &&
21696          "The smaller number of elements must divide the larger.");
21697   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21698   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21699   assert(((RootRatio == 1 && OpRatio == 1) ||
21700           (RootRatio == 1) != (OpRatio == 1)) &&
21701          "Must not have a ratio for both incoming and op masks!");
21702
21703   SmallVector<int, 16> Mask;
21704   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21705
21706   // Merge this shuffle operation's mask into our accumulated mask. Note that
21707   // this shuffle's mask will be the first applied to the input, followed by the
21708   // root mask to get us all the way to the root value arrangement. The reason
21709   // for this order is that we are recursing up the operation chain.
21710   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21711     int RootIdx = i / RootRatio;
21712     if (RootMask[RootIdx] < 0) {
21713       // This is a zero or undef lane, we're done.
21714       Mask.push_back(RootMask[RootIdx]);
21715       continue;
21716     }
21717
21718     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21719     int OpIdx = RootMaskedIdx / OpRatio;
21720     if (OpMask[OpIdx] < 0) {
21721       // The incoming lanes are zero or undef, it doesn't matter which ones we
21722       // are using.
21723       Mask.push_back(OpMask[OpIdx]);
21724       continue;
21725     }
21726
21727     // Ok, we have non-zero lanes, map them through.
21728     Mask.push_back(OpMask[OpIdx] * OpRatio +
21729                    RootMaskedIdx % OpRatio);
21730   }
21731
21732   // See if we can recurse into the operand to combine more things.
21733   switch (Op.getOpcode()) {
21734     case X86ISD::PSHUFB:
21735       HasPSHUFB = true;
21736     case X86ISD::PSHUFD:
21737     case X86ISD::PSHUFHW:
21738     case X86ISD::PSHUFLW:
21739       if (Op.getOperand(0).hasOneUse() &&
21740           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21741                                         HasPSHUFB, DAG, DCI, Subtarget))
21742         return true;
21743       break;
21744
21745     case X86ISD::UNPCKL:
21746     case X86ISD::UNPCKH:
21747       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21748       // We can't check for single use, we have to check that this shuffle is the only user.
21749       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21750           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21751                                         HasPSHUFB, DAG, DCI, Subtarget))
21752           return true;
21753       break;
21754   }
21755
21756   // Minor canonicalization of the accumulated shuffle mask to make it easier
21757   // to match below. All this does is detect masks with squential pairs of
21758   // elements, and shrink them to the half-width mask. It does this in a loop
21759   // so it will reduce the size of the mask to the minimal width mask which
21760   // performs an equivalent shuffle.
21761   SmallVector<int, 16> WidenedMask;
21762   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21763     Mask = std::move(WidenedMask);
21764     WidenedMask.clear();
21765   }
21766
21767   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21768                                 Subtarget);
21769 }
21770
21771 /// \brief Get the PSHUF-style mask from PSHUF node.
21772 ///
21773 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21774 /// PSHUF-style masks that can be reused with such instructions.
21775 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21776   MVT VT = N.getSimpleValueType();
21777   SmallVector<int, 4> Mask;
21778   bool IsUnary;
21779   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21780   (void)HaveMask;
21781   assert(HaveMask);
21782
21783   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21784   // matter. Check that the upper masks are repeats and remove them.
21785   if (VT.getSizeInBits() > 128) {
21786     int LaneElts = 128 / VT.getScalarSizeInBits();
21787 #ifndef NDEBUG
21788     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21789       for (int j = 0; j < LaneElts; ++j)
21790         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21791                "Mask doesn't repeat in high 128-bit lanes!");
21792 #endif
21793     Mask.resize(LaneElts);
21794   }
21795
21796   switch (N.getOpcode()) {
21797   case X86ISD::PSHUFD:
21798     return Mask;
21799   case X86ISD::PSHUFLW:
21800     Mask.resize(4);
21801     return Mask;
21802   case X86ISD::PSHUFHW:
21803     Mask.erase(Mask.begin(), Mask.begin() + 4);
21804     for (int &M : Mask)
21805       M -= 4;
21806     return Mask;
21807   default:
21808     llvm_unreachable("No valid shuffle instruction found!");
21809   }
21810 }
21811
21812 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21813 ///
21814 /// We walk up the chain and look for a combinable shuffle, skipping over
21815 /// shuffles that we could hoist this shuffle's transformation past without
21816 /// altering anything.
21817 static SDValue
21818 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21819                              SelectionDAG &DAG,
21820                              TargetLowering::DAGCombinerInfo &DCI) {
21821   assert(N.getOpcode() == X86ISD::PSHUFD &&
21822          "Called with something other than an x86 128-bit half shuffle!");
21823   SDLoc DL(N);
21824
21825   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21826   // of the shuffles in the chain so that we can form a fresh chain to replace
21827   // this one.
21828   SmallVector<SDValue, 8> Chain;
21829   SDValue V = N.getOperand(0);
21830   for (; V.hasOneUse(); V = V.getOperand(0)) {
21831     switch (V.getOpcode()) {
21832     default:
21833       return SDValue(); // Nothing combined!
21834
21835     case ISD::BITCAST:
21836       // Skip bitcasts as we always know the type for the target specific
21837       // instructions.
21838       continue;
21839
21840     case X86ISD::PSHUFD:
21841       // Found another dword shuffle.
21842       break;
21843
21844     case X86ISD::PSHUFLW:
21845       // Check that the low words (being shuffled) are the identity in the
21846       // dword shuffle, and the high words are self-contained.
21847       if (Mask[0] != 0 || Mask[1] != 1 ||
21848           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21849         return SDValue();
21850
21851       Chain.push_back(V);
21852       continue;
21853
21854     case X86ISD::PSHUFHW:
21855       // Check that the high words (being shuffled) are the identity in the
21856       // dword shuffle, and the low words are self-contained.
21857       if (Mask[2] != 2 || Mask[3] != 3 ||
21858           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21859         return SDValue();
21860
21861       Chain.push_back(V);
21862       continue;
21863
21864     case X86ISD::UNPCKL:
21865     case X86ISD::UNPCKH:
21866       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21867       // shuffle into a preceding word shuffle.
21868       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21869           V.getSimpleValueType().getScalarType() != MVT::i16)
21870         return SDValue();
21871
21872       // Search for a half-shuffle which we can combine with.
21873       unsigned CombineOp =
21874           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21875       if (V.getOperand(0) != V.getOperand(1) ||
21876           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21877         return SDValue();
21878       Chain.push_back(V);
21879       V = V.getOperand(0);
21880       do {
21881         switch (V.getOpcode()) {
21882         default:
21883           return SDValue(); // Nothing to combine.
21884
21885         case X86ISD::PSHUFLW:
21886         case X86ISD::PSHUFHW:
21887           if (V.getOpcode() == CombineOp)
21888             break;
21889
21890           Chain.push_back(V);
21891
21892           // Fallthrough!
21893         case ISD::BITCAST:
21894           V = V.getOperand(0);
21895           continue;
21896         }
21897         break;
21898       } while (V.hasOneUse());
21899       break;
21900     }
21901     // Break out of the loop if we break out of the switch.
21902     break;
21903   }
21904
21905   if (!V.hasOneUse())
21906     // We fell out of the loop without finding a viable combining instruction.
21907     return SDValue();
21908
21909   // Merge this node's mask and our incoming mask.
21910   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21911   for (int &M : Mask)
21912     M = VMask[M];
21913   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21914                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21915
21916   // Rebuild the chain around this new shuffle.
21917   while (!Chain.empty()) {
21918     SDValue W = Chain.pop_back_val();
21919
21920     if (V.getValueType() != W.getOperand(0).getValueType())
21921       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21922
21923     switch (W.getOpcode()) {
21924     default:
21925       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21926
21927     case X86ISD::UNPCKL:
21928     case X86ISD::UNPCKH:
21929       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21930       break;
21931
21932     case X86ISD::PSHUFD:
21933     case X86ISD::PSHUFLW:
21934     case X86ISD::PSHUFHW:
21935       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21936       break;
21937     }
21938   }
21939   if (V.getValueType() != N.getValueType())
21940     V = DAG.getBitcast(N.getValueType(), V);
21941
21942   // Return the new chain to replace N.
21943   return V;
21944 }
21945
21946 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21947 ///
21948 /// We walk up the chain, skipping shuffles of the other half and looking
21949 /// through shuffles which switch halves trying to find a shuffle of the same
21950 /// pair of dwords.
21951 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21952                                         SelectionDAG &DAG,
21953                                         TargetLowering::DAGCombinerInfo &DCI) {
21954   assert(
21955       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21956       "Called with something other than an x86 128-bit half shuffle!");
21957   SDLoc DL(N);
21958   unsigned CombineOpcode = N.getOpcode();
21959
21960   // Walk up a single-use chain looking for a combinable shuffle.
21961   SDValue V = N.getOperand(0);
21962   for (; V.hasOneUse(); V = V.getOperand(0)) {
21963     switch (V.getOpcode()) {
21964     default:
21965       return false; // Nothing combined!
21966
21967     case ISD::BITCAST:
21968       // Skip bitcasts as we always know the type for the target specific
21969       // instructions.
21970       continue;
21971
21972     case X86ISD::PSHUFLW:
21973     case X86ISD::PSHUFHW:
21974       if (V.getOpcode() == CombineOpcode)
21975         break;
21976
21977       // Other-half shuffles are no-ops.
21978       continue;
21979     }
21980     // Break out of the loop if we break out of the switch.
21981     break;
21982   }
21983
21984   if (!V.hasOneUse())
21985     // We fell out of the loop without finding a viable combining instruction.
21986     return false;
21987
21988   // Combine away the bottom node as its shuffle will be accumulated into
21989   // a preceding shuffle.
21990   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21991
21992   // Record the old value.
21993   SDValue Old = V;
21994
21995   // Merge this node's mask and our incoming mask (adjusted to account for all
21996   // the pshufd instructions encountered).
21997   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21998   for (int &M : Mask)
21999     M = VMask[M];
22000   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22001                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22002
22003   // Check that the shuffles didn't cancel each other out. If not, we need to
22004   // combine to the new one.
22005   if (Old != V)
22006     // Replace the combinable shuffle with the combined one, updating all users
22007     // so that we re-evaluate the chain here.
22008     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22009
22010   return true;
22011 }
22012
22013 /// \brief Try to combine x86 target specific shuffles.
22014 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22015                                            TargetLowering::DAGCombinerInfo &DCI,
22016                                            const X86Subtarget *Subtarget) {
22017   SDLoc DL(N);
22018   MVT VT = N.getSimpleValueType();
22019   SmallVector<int, 4> Mask;
22020
22021   switch (N.getOpcode()) {
22022   case X86ISD::PSHUFD:
22023   case X86ISD::PSHUFLW:
22024   case X86ISD::PSHUFHW:
22025     Mask = getPSHUFShuffleMask(N);
22026     assert(Mask.size() == 4);
22027     break;
22028   default:
22029     return SDValue();
22030   }
22031
22032   // Nuke no-op shuffles that show up after combining.
22033   if (isNoopShuffleMask(Mask))
22034     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22035
22036   // Look for simplifications involving one or two shuffle instructions.
22037   SDValue V = N.getOperand(0);
22038   switch (N.getOpcode()) {
22039   default:
22040     break;
22041   case X86ISD::PSHUFLW:
22042   case X86ISD::PSHUFHW:
22043     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22044
22045     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22046       return SDValue(); // We combined away this shuffle, so we're done.
22047
22048     // See if this reduces to a PSHUFD which is no more expensive and can
22049     // combine with more operations. Note that it has to at least flip the
22050     // dwords as otherwise it would have been removed as a no-op.
22051     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22052       int DMask[] = {0, 1, 2, 3};
22053       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22054       DMask[DOffset + 0] = DOffset + 1;
22055       DMask[DOffset + 1] = DOffset + 0;
22056       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22057       V = DAG.getBitcast(DVT, V);
22058       DCI.AddToWorklist(V.getNode());
22059       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22060                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22061       DCI.AddToWorklist(V.getNode());
22062       return DAG.getBitcast(VT, V);
22063     }
22064
22065     // Look for shuffle patterns which can be implemented as a single unpack.
22066     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22067     // only works when we have a PSHUFD followed by two half-shuffles.
22068     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22069         (V.getOpcode() == X86ISD::PSHUFLW ||
22070          V.getOpcode() == X86ISD::PSHUFHW) &&
22071         V.getOpcode() != N.getOpcode() &&
22072         V.hasOneUse()) {
22073       SDValue D = V.getOperand(0);
22074       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22075         D = D.getOperand(0);
22076       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22077         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22078         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22079         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22080         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22081         int WordMask[8];
22082         for (int i = 0; i < 4; ++i) {
22083           WordMask[i + NOffset] = Mask[i] + NOffset;
22084           WordMask[i + VOffset] = VMask[i] + VOffset;
22085         }
22086         // Map the word mask through the DWord mask.
22087         int MappedMask[8];
22088         for (int i = 0; i < 8; ++i)
22089           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22090         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22091             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22092           // We can replace all three shuffles with an unpack.
22093           V = DAG.getBitcast(VT, D.getOperand(0));
22094           DCI.AddToWorklist(V.getNode());
22095           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22096                                                 : X86ISD::UNPCKH,
22097                              DL, VT, V, V);
22098         }
22099       }
22100     }
22101
22102     break;
22103
22104   case X86ISD::PSHUFD:
22105     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22106       return NewN;
22107
22108     break;
22109   }
22110
22111   return SDValue();
22112 }
22113
22114 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22115 ///
22116 /// We combine this directly on the abstract vector shuffle nodes so it is
22117 /// easier to generically match. We also insert dummy vector shuffle nodes for
22118 /// the operands which explicitly discard the lanes which are unused by this
22119 /// operation to try to flow through the rest of the combiner the fact that
22120 /// they're unused.
22121 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22122   SDLoc DL(N);
22123   EVT VT = N->getValueType(0);
22124
22125   // We only handle target-independent shuffles.
22126   // FIXME: It would be easy and harmless to use the target shuffle mask
22127   // extraction tool to support more.
22128   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22129     return SDValue();
22130
22131   auto *SVN = cast<ShuffleVectorSDNode>(N);
22132   ArrayRef<int> Mask = SVN->getMask();
22133   SDValue V1 = N->getOperand(0);
22134   SDValue V2 = N->getOperand(1);
22135
22136   // We require the first shuffle operand to be the SUB node, and the second to
22137   // be the ADD node.
22138   // FIXME: We should support the commuted patterns.
22139   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22140     return SDValue();
22141
22142   // If there are other uses of these operations we can't fold them.
22143   if (!V1->hasOneUse() || !V2->hasOneUse())
22144     return SDValue();
22145
22146   // Ensure that both operations have the same operands. Note that we can
22147   // commute the FADD operands.
22148   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22149   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22150       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22151     return SDValue();
22152
22153   // We're looking for blends between FADD and FSUB nodes. We insist on these
22154   // nodes being lined up in a specific expected pattern.
22155   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22156         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22157         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22158     return SDValue();
22159
22160   // Only specific types are legal at this point, assert so we notice if and
22161   // when these change.
22162   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22163           VT == MVT::v4f64) &&
22164          "Unknown vector type encountered!");
22165
22166   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22167 }
22168
22169 /// PerformShuffleCombine - Performs several different shuffle combines.
22170 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22171                                      TargetLowering::DAGCombinerInfo &DCI,
22172                                      const X86Subtarget *Subtarget) {
22173   SDLoc dl(N);
22174   SDValue N0 = N->getOperand(0);
22175   SDValue N1 = N->getOperand(1);
22176   EVT VT = N->getValueType(0);
22177
22178   // Don't create instructions with illegal types after legalize types has run.
22179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22180   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22181     return SDValue();
22182
22183   // If we have legalized the vector types, look for blends of FADD and FSUB
22184   // nodes that we can fuse into an ADDSUB node.
22185   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22186     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22187       return AddSub;
22188
22189   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22190   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22191       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22192     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22193
22194   // During Type Legalization, when promoting illegal vector types,
22195   // the backend might introduce new shuffle dag nodes and bitcasts.
22196   //
22197   // This code performs the following transformation:
22198   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22199   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22200   //
22201   // We do this only if both the bitcast and the BINOP dag nodes have
22202   // one use. Also, perform this transformation only if the new binary
22203   // operation is legal. This is to avoid introducing dag nodes that
22204   // potentially need to be further expanded (or custom lowered) into a
22205   // less optimal sequence of dag nodes.
22206   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22207       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22208       N0.getOpcode() == ISD::BITCAST) {
22209     SDValue BC0 = N0.getOperand(0);
22210     EVT SVT = BC0.getValueType();
22211     unsigned Opcode = BC0.getOpcode();
22212     unsigned NumElts = VT.getVectorNumElements();
22213
22214     if (BC0.hasOneUse() && SVT.isVector() &&
22215         SVT.getVectorNumElements() * 2 == NumElts &&
22216         TLI.isOperationLegal(Opcode, VT)) {
22217       bool CanFold = false;
22218       switch (Opcode) {
22219       default : break;
22220       case ISD::ADD :
22221       case ISD::FADD :
22222       case ISD::SUB :
22223       case ISD::FSUB :
22224       case ISD::MUL :
22225       case ISD::FMUL :
22226         CanFold = true;
22227       }
22228
22229       unsigned SVTNumElts = SVT.getVectorNumElements();
22230       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22231       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22232         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22233       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22234         CanFold = SVOp->getMaskElt(i) < 0;
22235
22236       if (CanFold) {
22237         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22238         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22239         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22240         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22241       }
22242     }
22243   }
22244
22245   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22246   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22247   // consecutive, non-overlapping, and in the right order.
22248   SmallVector<SDValue, 16> Elts;
22249   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22250     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22251
22252   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22253     return LD;
22254
22255   if (isTargetShuffle(N->getOpcode())) {
22256     SDValue Shuffle =
22257         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22258     if (Shuffle.getNode())
22259       return Shuffle;
22260
22261     // Try recursively combining arbitrary sequences of x86 shuffle
22262     // instructions into higher-order shuffles. We do this after combining
22263     // specific PSHUF instruction sequences into their minimal form so that we
22264     // can evaluate how many specialized shuffle instructions are involved in
22265     // a particular chain.
22266     SmallVector<int, 1> NonceMask; // Just a placeholder.
22267     NonceMask.push_back(0);
22268     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22269                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22270                                       DCI, Subtarget))
22271       return SDValue(); // This routine will use CombineTo to replace N.
22272   }
22273
22274   return SDValue();
22275 }
22276
22277 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22278 /// specific shuffle of a load can be folded into a single element load.
22279 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22280 /// shuffles have been custom lowered so we need to handle those here.
22281 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22282                                          TargetLowering::DAGCombinerInfo &DCI) {
22283   if (DCI.isBeforeLegalizeOps())
22284     return SDValue();
22285
22286   SDValue InVec = N->getOperand(0);
22287   SDValue EltNo = N->getOperand(1);
22288
22289   if (!isa<ConstantSDNode>(EltNo))
22290     return SDValue();
22291
22292   EVT OriginalVT = InVec.getValueType();
22293
22294   if (InVec.getOpcode() == ISD::BITCAST) {
22295     // Don't duplicate a load with other uses.
22296     if (!InVec.hasOneUse())
22297       return SDValue();
22298     EVT BCVT = InVec.getOperand(0).getValueType();
22299     if (!BCVT.isVector() ||
22300         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22301       return SDValue();
22302     InVec = InVec.getOperand(0);
22303   }
22304
22305   EVT CurrentVT = InVec.getValueType();
22306
22307   if (!isTargetShuffle(InVec.getOpcode()))
22308     return SDValue();
22309
22310   // Don't duplicate a load with other uses.
22311   if (!InVec.hasOneUse())
22312     return SDValue();
22313
22314   SmallVector<int, 16> ShuffleMask;
22315   bool UnaryShuffle;
22316   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22317                             ShuffleMask, UnaryShuffle))
22318     return SDValue();
22319
22320   // Select the input vector, guarding against out of range extract vector.
22321   unsigned NumElems = CurrentVT.getVectorNumElements();
22322   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22323   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22324   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22325                                          : InVec.getOperand(1);
22326
22327   // If inputs to shuffle are the same for both ops, then allow 2 uses
22328   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22329                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22330
22331   if (LdNode.getOpcode() == ISD::BITCAST) {
22332     // Don't duplicate a load with other uses.
22333     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22334       return SDValue();
22335
22336     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22337     LdNode = LdNode.getOperand(0);
22338   }
22339
22340   if (!ISD::isNormalLoad(LdNode.getNode()))
22341     return SDValue();
22342
22343   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22344
22345   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22346     return SDValue();
22347
22348   EVT EltVT = N->getValueType(0);
22349   // If there's a bitcast before the shuffle, check if the load type and
22350   // alignment is valid.
22351   unsigned Align = LN0->getAlignment();
22352   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22353   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22354       EltVT.getTypeForEVT(*DAG.getContext()));
22355
22356   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22357     return SDValue();
22358
22359   // All checks match so transform back to vector_shuffle so that DAG combiner
22360   // can finish the job
22361   SDLoc dl(N);
22362
22363   // Create shuffle node taking into account the case that its a unary shuffle
22364   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22365                                    : InVec.getOperand(1);
22366   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22367                                  InVec.getOperand(0), Shuffle,
22368                                  &ShuffleMask[0]);
22369   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22370   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22371                      EltNo);
22372 }
22373
22374 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22375 /// special and don't usually play with other vector types, it's better to
22376 /// handle them early to be sure we emit efficient code by avoiding
22377 /// store-load conversions.
22378 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22379   if (N->getValueType(0) != MVT::x86mmx ||
22380       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22381       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22382     return SDValue();
22383
22384   SDValue V = N->getOperand(0);
22385   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22386   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22387     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22388                        N->getValueType(0), V.getOperand(0));
22389
22390   return SDValue();
22391 }
22392
22393 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22394 /// generation and convert it from being a bunch of shuffles and extracts
22395 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22396 /// storing the value and loading scalars back, while for x64 we should
22397 /// use 64-bit extracts and shifts.
22398 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22399                                          TargetLowering::DAGCombinerInfo &DCI) {
22400   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22401     return NewOp;
22402
22403   SDValue InputVector = N->getOperand(0);
22404   SDLoc dl(InputVector);
22405   // Detect mmx to i32 conversion through a v2i32 elt extract.
22406   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22407       N->getValueType(0) == MVT::i32 &&
22408       InputVector.getValueType() == MVT::v2i32) {
22409
22410     // The bitcast source is a direct mmx result.
22411     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22412     if (MMXSrc.getValueType() == MVT::x86mmx)
22413       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22414                          N->getValueType(0),
22415                          InputVector.getNode()->getOperand(0));
22416
22417     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22418     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22419     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22420         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22421         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22422         MMXSrcOp.getValueType() == MVT::v1i64 &&
22423         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22424       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22425                          N->getValueType(0),
22426                          MMXSrcOp.getOperand(0));
22427   }
22428
22429   EVT VT = N->getValueType(0);
22430
22431   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22432       InputVector.getOpcode() == ISD::BITCAST &&
22433       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22434     uint64_t ExtractedElt =
22435           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22436     uint64_t InputValue =
22437           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22438     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22439     return DAG.getConstant(Res, dl, MVT::i1);
22440   }
22441   // Only operate on vectors of 4 elements, where the alternative shuffling
22442   // gets to be more expensive.
22443   if (InputVector.getValueType() != MVT::v4i32)
22444     return SDValue();
22445
22446   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22447   // single use which is a sign-extend or zero-extend, and all elements are
22448   // used.
22449   SmallVector<SDNode *, 4> Uses;
22450   unsigned ExtractedElements = 0;
22451   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22452        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22453     if (UI.getUse().getResNo() != InputVector.getResNo())
22454       return SDValue();
22455
22456     SDNode *Extract = *UI;
22457     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22458       return SDValue();
22459
22460     if (Extract->getValueType(0) != MVT::i32)
22461       return SDValue();
22462     if (!Extract->hasOneUse())
22463       return SDValue();
22464     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22465         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22466       return SDValue();
22467     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22468       return SDValue();
22469
22470     // Record which element was extracted.
22471     ExtractedElements |=
22472       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22473
22474     Uses.push_back(Extract);
22475   }
22476
22477   // If not all the elements were used, this may not be worthwhile.
22478   if (ExtractedElements != 15)
22479     return SDValue();
22480
22481   // Ok, we've now decided to do the transformation.
22482   // If 64-bit shifts are legal, use the extract-shift sequence,
22483   // otherwise bounce the vector off the cache.
22484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22485   SDValue Vals[4];
22486
22487   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22488     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22489     auto &DL = DAG.getDataLayout();
22490     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22491     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22492       DAG.getConstant(0, dl, VecIdxTy));
22493     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22494       DAG.getConstant(1, dl, VecIdxTy));
22495
22496     SDValue ShAmt = DAG.getConstant(
22497         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22498     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22499     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22500       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22501     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22502     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22503       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22504   } else {
22505     // Store the value to a temporary stack slot.
22506     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22507     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22508       MachinePointerInfo(), false, false, 0);
22509
22510     EVT ElementType = InputVector.getValueType().getVectorElementType();
22511     unsigned EltSize = ElementType.getSizeInBits() / 8;
22512
22513     // Replace each use (extract) with a load of the appropriate element.
22514     for (unsigned i = 0; i < 4; ++i) {
22515       uint64_t Offset = EltSize * i;
22516       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22517       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22518
22519       SDValue ScalarAddr =
22520           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22521
22522       // Load the scalar.
22523       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22524                             ScalarAddr, MachinePointerInfo(),
22525                             false, false, false, 0);
22526
22527     }
22528   }
22529
22530   // Replace the extracts
22531   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22532     UE = Uses.end(); UI != UE; ++UI) {
22533     SDNode *Extract = *UI;
22534
22535     SDValue Idx = Extract->getOperand(1);
22536     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22537     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22538   }
22539
22540   // The replacement was made in place; don't return anything.
22541   return SDValue();
22542 }
22543
22544 static SDValue
22545 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22546                                       const X86Subtarget *Subtarget) {
22547   SDLoc dl(N);
22548   SDValue Cond = N->getOperand(0);
22549   SDValue LHS = N->getOperand(1);
22550   SDValue RHS = N->getOperand(2);
22551
22552   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22553     SDValue CondSrc = Cond->getOperand(0);
22554     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22555       Cond = CondSrc->getOperand(0);
22556   }
22557
22558   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22559     return SDValue();
22560
22561   // A vselect where all conditions and data are constants can be optimized into
22562   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22563   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22564       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22565     return SDValue();
22566
22567   unsigned MaskValue = 0;
22568   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22569     return SDValue();
22570
22571   MVT VT = N->getSimpleValueType(0);
22572   unsigned NumElems = VT.getVectorNumElements();
22573   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22574   for (unsigned i = 0; i < NumElems; ++i) {
22575     // Be sure we emit undef where we can.
22576     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22577       ShuffleMask[i] = -1;
22578     else
22579       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22580   }
22581
22582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22583   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22584     return SDValue();
22585   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22586 }
22587
22588 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22589 /// nodes.
22590 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22591                                     TargetLowering::DAGCombinerInfo &DCI,
22592                                     const X86Subtarget *Subtarget) {
22593   SDLoc DL(N);
22594   SDValue Cond = N->getOperand(0);
22595   // Get the LHS/RHS of the select.
22596   SDValue LHS = N->getOperand(1);
22597   SDValue RHS = N->getOperand(2);
22598   EVT VT = LHS.getValueType();
22599   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22600
22601   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22602   // instructions match the semantics of the common C idiom x<y?x:y but not
22603   // x<=y?x:y, because of how they handle negative zero (which can be
22604   // ignored in unsafe-math mode).
22605   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22606   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22607       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22608       (Subtarget->hasSSE2() ||
22609        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22610     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22611
22612     unsigned Opcode = 0;
22613     // Check for x CC y ? x : y.
22614     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22615         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22616       switch (CC) {
22617       default: break;
22618       case ISD::SETULT:
22619         // Converting this to a min would handle NaNs incorrectly, and swapping
22620         // the operands would cause it to handle comparisons between positive
22621         // and negative zero incorrectly.
22622         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22623           if (!DAG.getTarget().Options.UnsafeFPMath &&
22624               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22625             break;
22626           std::swap(LHS, RHS);
22627         }
22628         Opcode = X86ISD::FMIN;
22629         break;
22630       case ISD::SETOLE:
22631         // Converting this to a min would handle comparisons between positive
22632         // and negative zero incorrectly.
22633         if (!DAG.getTarget().Options.UnsafeFPMath &&
22634             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22635           break;
22636         Opcode = X86ISD::FMIN;
22637         break;
22638       case ISD::SETULE:
22639         // Converting this to a min would handle both negative zeros and NaNs
22640         // incorrectly, but we can swap the operands to fix both.
22641         std::swap(LHS, RHS);
22642       case ISD::SETOLT:
22643       case ISD::SETLT:
22644       case ISD::SETLE:
22645         Opcode = X86ISD::FMIN;
22646         break;
22647
22648       case ISD::SETOGE:
22649         // Converting this to a max would handle comparisons between positive
22650         // and negative zero incorrectly.
22651         if (!DAG.getTarget().Options.UnsafeFPMath &&
22652             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22653           break;
22654         Opcode = X86ISD::FMAX;
22655         break;
22656       case ISD::SETUGT:
22657         // Converting this to a max would handle NaNs incorrectly, and swapping
22658         // the operands would cause it to handle comparisons between positive
22659         // and negative zero incorrectly.
22660         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22661           if (!DAG.getTarget().Options.UnsafeFPMath &&
22662               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22663             break;
22664           std::swap(LHS, RHS);
22665         }
22666         Opcode = X86ISD::FMAX;
22667         break;
22668       case ISD::SETUGE:
22669         // Converting this to a max would handle both negative zeros and NaNs
22670         // incorrectly, but we can swap the operands to fix both.
22671         std::swap(LHS, RHS);
22672       case ISD::SETOGT:
22673       case ISD::SETGT:
22674       case ISD::SETGE:
22675         Opcode = X86ISD::FMAX;
22676         break;
22677       }
22678     // Check for x CC y ? y : x -- a min/max with reversed arms.
22679     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22680                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22681       switch (CC) {
22682       default: break;
22683       case ISD::SETOGE:
22684         // Converting this to a min would handle comparisons between positive
22685         // and negative zero incorrectly, and swapping the operands would
22686         // cause it to handle NaNs incorrectly.
22687         if (!DAG.getTarget().Options.UnsafeFPMath &&
22688             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22689           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22690             break;
22691           std::swap(LHS, RHS);
22692         }
22693         Opcode = X86ISD::FMIN;
22694         break;
22695       case ISD::SETUGT:
22696         // Converting this to a min would handle NaNs incorrectly.
22697         if (!DAG.getTarget().Options.UnsafeFPMath &&
22698             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22699           break;
22700         Opcode = X86ISD::FMIN;
22701         break;
22702       case ISD::SETUGE:
22703         // Converting this to a min would handle both negative zeros and NaNs
22704         // incorrectly, but we can swap the operands to fix both.
22705         std::swap(LHS, RHS);
22706       case ISD::SETOGT:
22707       case ISD::SETGT:
22708       case ISD::SETGE:
22709         Opcode = X86ISD::FMIN;
22710         break;
22711
22712       case ISD::SETULT:
22713         // Converting this to a max would handle NaNs incorrectly.
22714         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22715           break;
22716         Opcode = X86ISD::FMAX;
22717         break;
22718       case ISD::SETOLE:
22719         // Converting this to a max would handle comparisons between positive
22720         // and negative zero incorrectly, and swapping the operands would
22721         // cause it to handle NaNs incorrectly.
22722         if (!DAG.getTarget().Options.UnsafeFPMath &&
22723             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22724           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22725             break;
22726           std::swap(LHS, RHS);
22727         }
22728         Opcode = X86ISD::FMAX;
22729         break;
22730       case ISD::SETULE:
22731         // Converting this to a max would handle both negative zeros and NaNs
22732         // incorrectly, but we can swap the operands to fix both.
22733         std::swap(LHS, RHS);
22734       case ISD::SETOLT:
22735       case ISD::SETLT:
22736       case ISD::SETLE:
22737         Opcode = X86ISD::FMAX;
22738         break;
22739       }
22740     }
22741
22742     if (Opcode)
22743       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22744   }
22745
22746   EVT CondVT = Cond.getValueType();
22747   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22748       CondVT.getVectorElementType() == MVT::i1) {
22749     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22750     // lowering on KNL. In this case we convert it to
22751     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22752     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22753     // Since SKX these selects have a proper lowering.
22754     EVT OpVT = LHS.getValueType();
22755     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22756         (OpVT.getVectorElementType() == MVT::i8 ||
22757          OpVT.getVectorElementType() == MVT::i16) &&
22758         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22759       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22760       DCI.AddToWorklist(Cond.getNode());
22761       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22762     }
22763   }
22764   // If this is a select between two integer constants, try to do some
22765   // optimizations.
22766   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22767     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22768       // Don't do this for crazy integer types.
22769       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22770         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22771         // so that TrueC (the true value) is larger than FalseC.
22772         bool NeedsCondInvert = false;
22773
22774         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22775             // Efficiently invertible.
22776             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22777              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22778               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22779           NeedsCondInvert = true;
22780           std::swap(TrueC, FalseC);
22781         }
22782
22783         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22784         if (FalseC->getAPIntValue() == 0 &&
22785             TrueC->getAPIntValue().isPowerOf2()) {
22786           if (NeedsCondInvert) // Invert the condition if needed.
22787             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22788                                DAG.getConstant(1, DL, Cond.getValueType()));
22789
22790           // Zero extend the condition if needed.
22791           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22792
22793           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22794           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22795                              DAG.getConstant(ShAmt, DL, MVT::i8));
22796         }
22797
22798         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22799         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22800           if (NeedsCondInvert) // Invert the condition if needed.
22801             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22802                                DAG.getConstant(1, DL, Cond.getValueType()));
22803
22804           // Zero extend the condition if needed.
22805           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22806                              FalseC->getValueType(0), Cond);
22807           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22808                              SDValue(FalseC, 0));
22809         }
22810
22811         // Optimize cases that will turn into an LEA instruction.  This requires
22812         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22813         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22814           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22815           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22816
22817           bool isFastMultiplier = false;
22818           if (Diff < 10) {
22819             switch ((unsigned char)Diff) {
22820               default: break;
22821               case 1:  // result = add base, cond
22822               case 2:  // result = lea base(    , cond*2)
22823               case 3:  // result = lea base(cond, cond*2)
22824               case 4:  // result = lea base(    , cond*4)
22825               case 5:  // result = lea base(cond, cond*4)
22826               case 8:  // result = lea base(    , cond*8)
22827               case 9:  // result = lea base(cond, cond*8)
22828                 isFastMultiplier = true;
22829                 break;
22830             }
22831           }
22832
22833           if (isFastMultiplier) {
22834             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22835             if (NeedsCondInvert) // Invert the condition if needed.
22836               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22837                                  DAG.getConstant(1, DL, Cond.getValueType()));
22838
22839             // Zero extend the condition if needed.
22840             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22841                                Cond);
22842             // Scale the condition by the difference.
22843             if (Diff != 1)
22844               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22845                                  DAG.getConstant(Diff, DL,
22846                                                  Cond.getValueType()));
22847
22848             // Add the base if non-zero.
22849             if (FalseC->getAPIntValue() != 0)
22850               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22851                                  SDValue(FalseC, 0));
22852             return Cond;
22853           }
22854         }
22855       }
22856   }
22857
22858   // Canonicalize max and min:
22859   // (x > y) ? x : y -> (x >= y) ? x : y
22860   // (x < y) ? x : y -> (x <= y) ? x : y
22861   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22862   // the need for an extra compare
22863   // against zero. e.g.
22864   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22865   // subl   %esi, %edi
22866   // testl  %edi, %edi
22867   // movl   $0, %eax
22868   // cmovgl %edi, %eax
22869   // =>
22870   // xorl   %eax, %eax
22871   // subl   %esi, $edi
22872   // cmovsl %eax, %edi
22873   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22874       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22875       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22876     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22877     switch (CC) {
22878     default: break;
22879     case ISD::SETLT:
22880     case ISD::SETGT: {
22881       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22882       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22883                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22884       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22885     }
22886     }
22887   }
22888
22889   // Early exit check
22890   if (!TLI.isTypeLegal(VT))
22891     return SDValue();
22892
22893   // Match VSELECTs into subs with unsigned saturation.
22894   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22895       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22896       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22897        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22898     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22899
22900     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22901     // left side invert the predicate to simplify logic below.
22902     SDValue Other;
22903     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22904       Other = RHS;
22905       CC = ISD::getSetCCInverse(CC, true);
22906     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22907       Other = LHS;
22908     }
22909
22910     if (Other.getNode() && Other->getNumOperands() == 2 &&
22911         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22912       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22913       SDValue CondRHS = Cond->getOperand(1);
22914
22915       // Look for a general sub with unsigned saturation first.
22916       // x >= y ? x-y : 0 --> subus x, y
22917       // x >  y ? x-y : 0 --> subus x, y
22918       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22919           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22920         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22921
22922       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22923         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22924           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22925             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22926               // If the RHS is a constant we have to reverse the const
22927               // canonicalization.
22928               // x > C-1 ? x+-C : 0 --> subus x, C
22929               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22930                   CondRHSConst->getAPIntValue() ==
22931                       (-OpRHSConst->getAPIntValue() - 1))
22932                 return DAG.getNode(
22933                     X86ISD::SUBUS, DL, VT, OpLHS,
22934                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22935
22936           // Another special case: If C was a sign bit, the sub has been
22937           // canonicalized into a xor.
22938           // FIXME: Would it be better to use computeKnownBits to determine
22939           //        whether it's safe to decanonicalize the xor?
22940           // x s< 0 ? x^C : 0 --> subus x, C
22941           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22942               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22943               OpRHSConst->getAPIntValue().isSignBit())
22944             // Note that we have to rebuild the RHS constant here to ensure we
22945             // don't rely on particular values of undef lanes.
22946             return DAG.getNode(
22947                 X86ISD::SUBUS, DL, VT, OpLHS,
22948                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22949         }
22950     }
22951   }
22952
22953   // Simplify vector selection if condition value type matches vselect
22954   // operand type
22955   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22956     assert(Cond.getValueType().isVector() &&
22957            "vector select expects a vector selector!");
22958
22959     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22960     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22961
22962     // Try invert the condition if true value is not all 1s and false value
22963     // is not all 0s.
22964     if (!TValIsAllOnes && !FValIsAllZeros &&
22965         // Check if the selector will be produced by CMPP*/PCMP*
22966         Cond.getOpcode() == ISD::SETCC &&
22967         // Check if SETCC has already been promoted
22968         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22969             CondVT) {
22970       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22971       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22972
22973       if (TValIsAllZeros || FValIsAllOnes) {
22974         SDValue CC = Cond.getOperand(2);
22975         ISD::CondCode NewCC =
22976           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22977                                Cond.getOperand(0).getValueType().isInteger());
22978         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22979         std::swap(LHS, RHS);
22980         TValIsAllOnes = FValIsAllOnes;
22981         FValIsAllZeros = TValIsAllZeros;
22982       }
22983     }
22984
22985     if (TValIsAllOnes || FValIsAllZeros) {
22986       SDValue Ret;
22987
22988       if (TValIsAllOnes && FValIsAllZeros)
22989         Ret = Cond;
22990       else if (TValIsAllOnes)
22991         Ret =
22992             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22993       else if (FValIsAllZeros)
22994         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22995                           DAG.getBitcast(CondVT, LHS));
22996
22997       return DAG.getBitcast(VT, Ret);
22998     }
22999   }
23000
23001   // We should generate an X86ISD::BLENDI from a vselect if its argument
23002   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23003   // constants. This specific pattern gets generated when we split a
23004   // selector for a 512 bit vector in a machine without AVX512 (but with
23005   // 256-bit vectors), during legalization:
23006   //
23007   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23008   //
23009   // Iff we find this pattern and the build_vectors are built from
23010   // constants, we translate the vselect into a shuffle_vector that we
23011   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23012   if ((N->getOpcode() == ISD::VSELECT ||
23013        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23014       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23015     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23016     if (Shuffle.getNode())
23017       return Shuffle;
23018   }
23019
23020   // If this is a *dynamic* select (non-constant condition) and we can match
23021   // this node with one of the variable blend instructions, restructure the
23022   // condition so that the blends can use the high bit of each element and use
23023   // SimplifyDemandedBits to simplify the condition operand.
23024   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23025       !DCI.isBeforeLegalize() &&
23026       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23027     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23028
23029     // Don't optimize vector selects that map to mask-registers.
23030     if (BitWidth == 1)
23031       return SDValue();
23032
23033     // We can only handle the cases where VSELECT is directly legal on the
23034     // subtarget. We custom lower VSELECT nodes with constant conditions and
23035     // this makes it hard to see whether a dynamic VSELECT will correctly
23036     // lower, so we both check the operation's status and explicitly handle the
23037     // cases where a *dynamic* blend will fail even though a constant-condition
23038     // blend could be custom lowered.
23039     // FIXME: We should find a better way to handle this class of problems.
23040     // Potentially, we should combine constant-condition vselect nodes
23041     // pre-legalization into shuffles and not mark as many types as custom
23042     // lowered.
23043     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23044       return SDValue();
23045     // FIXME: We don't support i16-element blends currently. We could and
23046     // should support them by making *all* the bits in the condition be set
23047     // rather than just the high bit and using an i8-element blend.
23048     if (VT.getScalarType() == MVT::i16)
23049       return SDValue();
23050     // Dynamic blending was only available from SSE4.1 onward.
23051     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23052       return SDValue();
23053     // Byte blends are only available in AVX2
23054     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23055         !Subtarget->hasAVX2())
23056       return SDValue();
23057
23058     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23059     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23060
23061     APInt KnownZero, KnownOne;
23062     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23063                                           DCI.isBeforeLegalizeOps());
23064     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23065         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23066                                  TLO)) {
23067       // If we changed the computation somewhere in the DAG, this change
23068       // will affect all users of Cond.
23069       // Make sure it is fine and update all the nodes so that we do not
23070       // use the generic VSELECT anymore. Otherwise, we may perform
23071       // wrong optimizations as we messed up with the actual expectation
23072       // for the vector boolean values.
23073       if (Cond != TLO.Old) {
23074         // Check all uses of that condition operand to check whether it will be
23075         // consumed by non-BLEND instructions, which may depend on all bits are
23076         // set properly.
23077         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23078              I != E; ++I)
23079           if (I->getOpcode() != ISD::VSELECT)
23080             // TODO: Add other opcodes eventually lowered into BLEND.
23081             return SDValue();
23082
23083         // Update all the users of the condition, before committing the change,
23084         // so that the VSELECT optimizations that expect the correct vector
23085         // boolean value will not be triggered.
23086         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23087              I != E; ++I)
23088           DAG.ReplaceAllUsesOfValueWith(
23089               SDValue(*I, 0),
23090               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23091                           Cond, I->getOperand(1), I->getOperand(2)));
23092         DCI.CommitTargetLoweringOpt(TLO);
23093         return SDValue();
23094       }
23095       // At this point, only Cond is changed. Change the condition
23096       // just for N to keep the opportunity to optimize all other
23097       // users their own way.
23098       DAG.ReplaceAllUsesOfValueWith(
23099           SDValue(N, 0),
23100           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23101                       TLO.New, N->getOperand(1), N->getOperand(2)));
23102       return SDValue();
23103     }
23104   }
23105
23106   return SDValue();
23107 }
23108
23109 // Check whether a boolean test is testing a boolean value generated by
23110 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23111 // code.
23112 //
23113 // Simplify the following patterns:
23114 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23115 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23116 // to (Op EFLAGS Cond)
23117 //
23118 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23119 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23120 // to (Op EFLAGS !Cond)
23121 //
23122 // where Op could be BRCOND or CMOV.
23123 //
23124 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23125   // Quit if not CMP and SUB with its value result used.
23126   if (Cmp.getOpcode() != X86ISD::CMP &&
23127       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23128       return SDValue();
23129
23130   // Quit if not used as a boolean value.
23131   if (CC != X86::COND_E && CC != X86::COND_NE)
23132     return SDValue();
23133
23134   // Check CMP operands. One of them should be 0 or 1 and the other should be
23135   // an SetCC or extended from it.
23136   SDValue Op1 = Cmp.getOperand(0);
23137   SDValue Op2 = Cmp.getOperand(1);
23138
23139   SDValue SetCC;
23140   const ConstantSDNode* C = nullptr;
23141   bool needOppositeCond = (CC == X86::COND_E);
23142   bool checkAgainstTrue = false; // Is it a comparison against 1?
23143
23144   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23145     SetCC = Op2;
23146   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23147     SetCC = Op1;
23148   else // Quit if all operands are not constants.
23149     return SDValue();
23150
23151   if (C->getZExtValue() == 1) {
23152     needOppositeCond = !needOppositeCond;
23153     checkAgainstTrue = true;
23154   } else if (C->getZExtValue() != 0)
23155     // Quit if the constant is neither 0 or 1.
23156     return SDValue();
23157
23158   bool truncatedToBoolWithAnd = false;
23159   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23160   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23161          SetCC.getOpcode() == ISD::TRUNCATE ||
23162          SetCC.getOpcode() == ISD::AND) {
23163     if (SetCC.getOpcode() == ISD::AND) {
23164       int OpIdx = -1;
23165       ConstantSDNode *CS;
23166       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23167           CS->getZExtValue() == 1)
23168         OpIdx = 1;
23169       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23170           CS->getZExtValue() == 1)
23171         OpIdx = 0;
23172       if (OpIdx == -1)
23173         break;
23174       SetCC = SetCC.getOperand(OpIdx);
23175       truncatedToBoolWithAnd = true;
23176     } else
23177       SetCC = SetCC.getOperand(0);
23178   }
23179
23180   switch (SetCC.getOpcode()) {
23181   case X86ISD::SETCC_CARRY:
23182     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23183     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23184     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23185     // truncated to i1 using 'and'.
23186     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23187       break;
23188     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23189            "Invalid use of SETCC_CARRY!");
23190     // FALL THROUGH
23191   case X86ISD::SETCC:
23192     // Set the condition code or opposite one if necessary.
23193     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23194     if (needOppositeCond)
23195       CC = X86::GetOppositeBranchCondition(CC);
23196     return SetCC.getOperand(1);
23197   case X86ISD::CMOV: {
23198     // Check whether false/true value has canonical one, i.e. 0 or 1.
23199     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23200     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23201     // Quit if true value is not a constant.
23202     if (!TVal)
23203       return SDValue();
23204     // Quit if false value is not a constant.
23205     if (!FVal) {
23206       SDValue Op = SetCC.getOperand(0);
23207       // Skip 'zext' or 'trunc' node.
23208       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23209           Op.getOpcode() == ISD::TRUNCATE)
23210         Op = Op.getOperand(0);
23211       // A special case for rdrand/rdseed, where 0 is set if false cond is
23212       // found.
23213       if ((Op.getOpcode() != X86ISD::RDRAND &&
23214            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23215         return SDValue();
23216     }
23217     // Quit if false value is not the constant 0 or 1.
23218     bool FValIsFalse = true;
23219     if (FVal && FVal->getZExtValue() != 0) {
23220       if (FVal->getZExtValue() != 1)
23221         return SDValue();
23222       // If FVal is 1, opposite cond is needed.
23223       needOppositeCond = !needOppositeCond;
23224       FValIsFalse = false;
23225     }
23226     // Quit if TVal is not the constant opposite of FVal.
23227     if (FValIsFalse && TVal->getZExtValue() != 1)
23228       return SDValue();
23229     if (!FValIsFalse && TVal->getZExtValue() != 0)
23230       return SDValue();
23231     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23232     if (needOppositeCond)
23233       CC = X86::GetOppositeBranchCondition(CC);
23234     return SetCC.getOperand(3);
23235   }
23236   }
23237
23238   return SDValue();
23239 }
23240
23241 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23242 /// Match:
23243 ///   (X86or (X86setcc) (X86setcc))
23244 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23245 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23246                                            X86::CondCode &CC1, SDValue &Flags,
23247                                            bool &isAnd) {
23248   if (Cond->getOpcode() == X86ISD::CMP) {
23249     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23250     if (!CondOp1C || !CondOp1C->isNullValue())
23251       return false;
23252
23253     Cond = Cond->getOperand(0);
23254   }
23255
23256   isAnd = false;
23257
23258   SDValue SetCC0, SetCC1;
23259   switch (Cond->getOpcode()) {
23260   default: return false;
23261   case ISD::AND:
23262   case X86ISD::AND:
23263     isAnd = true;
23264     // fallthru
23265   case ISD::OR:
23266   case X86ISD::OR:
23267     SetCC0 = Cond->getOperand(0);
23268     SetCC1 = Cond->getOperand(1);
23269     break;
23270   };
23271
23272   // Make sure we have SETCC nodes, using the same flags value.
23273   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23274       SetCC1.getOpcode() != X86ISD::SETCC ||
23275       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23276     return false;
23277
23278   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23279   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23280   Flags = SetCC0->getOperand(1);
23281   return true;
23282 }
23283
23284 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23285 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23286                                   TargetLowering::DAGCombinerInfo &DCI,
23287                                   const X86Subtarget *Subtarget) {
23288   SDLoc DL(N);
23289
23290   // If the flag operand isn't dead, don't touch this CMOV.
23291   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23292     return SDValue();
23293
23294   SDValue FalseOp = N->getOperand(0);
23295   SDValue TrueOp = N->getOperand(1);
23296   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23297   SDValue Cond = N->getOperand(3);
23298
23299   if (CC == X86::COND_E || CC == X86::COND_NE) {
23300     switch (Cond.getOpcode()) {
23301     default: break;
23302     case X86ISD::BSR:
23303     case X86ISD::BSF:
23304       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23305       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23306         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23307     }
23308   }
23309
23310   SDValue Flags;
23311
23312   Flags = checkBoolTestSetCCCombine(Cond, CC);
23313   if (Flags.getNode() &&
23314       // Extra check as FCMOV only supports a subset of X86 cond.
23315       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23316     SDValue Ops[] = { FalseOp, TrueOp,
23317                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23318     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23319   }
23320
23321   // If this is a select between two integer constants, try to do some
23322   // optimizations.  Note that the operands are ordered the opposite of SELECT
23323   // operands.
23324   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23325     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23326       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23327       // larger than FalseC (the false value).
23328       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23329         CC = X86::GetOppositeBranchCondition(CC);
23330         std::swap(TrueC, FalseC);
23331         std::swap(TrueOp, FalseOp);
23332       }
23333
23334       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23335       // This is efficient for any integer data type (including i8/i16) and
23336       // shift amount.
23337       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23338         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23339                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23340
23341         // Zero extend the condition if needed.
23342         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23343
23344         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23345         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23346                            DAG.getConstant(ShAmt, DL, MVT::i8));
23347         if (N->getNumValues() == 2)  // Dead flag value?
23348           return DCI.CombineTo(N, Cond, SDValue());
23349         return Cond;
23350       }
23351
23352       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23353       // for any integer data type, including i8/i16.
23354       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23355         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23356                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23357
23358         // Zero extend the condition if needed.
23359         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23360                            FalseC->getValueType(0), Cond);
23361         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23362                            SDValue(FalseC, 0));
23363
23364         if (N->getNumValues() == 2)  // Dead flag value?
23365           return DCI.CombineTo(N, Cond, SDValue());
23366         return Cond;
23367       }
23368
23369       // Optimize cases that will turn into an LEA instruction.  This requires
23370       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23371       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23372         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23373         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23374
23375         bool isFastMultiplier = false;
23376         if (Diff < 10) {
23377           switch ((unsigned char)Diff) {
23378           default: break;
23379           case 1:  // result = add base, cond
23380           case 2:  // result = lea base(    , cond*2)
23381           case 3:  // result = lea base(cond, cond*2)
23382           case 4:  // result = lea base(    , cond*4)
23383           case 5:  // result = lea base(cond, cond*4)
23384           case 8:  // result = lea base(    , cond*8)
23385           case 9:  // result = lea base(cond, cond*8)
23386             isFastMultiplier = true;
23387             break;
23388           }
23389         }
23390
23391         if (isFastMultiplier) {
23392           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23393           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23394                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23395           // Zero extend the condition if needed.
23396           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23397                              Cond);
23398           // Scale the condition by the difference.
23399           if (Diff != 1)
23400             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23401                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23402
23403           // Add the base if non-zero.
23404           if (FalseC->getAPIntValue() != 0)
23405             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23406                                SDValue(FalseC, 0));
23407           if (N->getNumValues() == 2)  // Dead flag value?
23408             return DCI.CombineTo(N, Cond, SDValue());
23409           return Cond;
23410         }
23411       }
23412     }
23413   }
23414
23415   // Handle these cases:
23416   //   (select (x != c), e, c) -> select (x != c), e, x),
23417   //   (select (x == c), c, e) -> select (x == c), x, e)
23418   // where the c is an integer constant, and the "select" is the combination
23419   // of CMOV and CMP.
23420   //
23421   // The rationale for this change is that the conditional-move from a constant
23422   // needs two instructions, however, conditional-move from a register needs
23423   // only one instruction.
23424   //
23425   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23426   //  some instruction-combining opportunities. This opt needs to be
23427   //  postponed as late as possible.
23428   //
23429   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23430     // the DCI.xxxx conditions are provided to postpone the optimization as
23431     // late as possible.
23432
23433     ConstantSDNode *CmpAgainst = nullptr;
23434     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23435         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23436         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23437
23438       if (CC == X86::COND_NE &&
23439           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23440         CC = X86::GetOppositeBranchCondition(CC);
23441         std::swap(TrueOp, FalseOp);
23442       }
23443
23444       if (CC == X86::COND_E &&
23445           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23446         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23447                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23448         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23449       }
23450     }
23451   }
23452
23453   // Fold and/or of setcc's to double CMOV:
23454   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23455   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23456   //
23457   // This combine lets us generate:
23458   //   cmovcc1 (jcc1 if we don't have CMOV)
23459   //   cmovcc2 (same)
23460   // instead of:
23461   //   setcc1
23462   //   setcc2
23463   //   and/or
23464   //   cmovne (jne if we don't have CMOV)
23465   // When we can't use the CMOV instruction, it might increase branch
23466   // mispredicts.
23467   // When we can use CMOV, or when there is no mispredict, this improves
23468   // throughput and reduces register pressure.
23469   //
23470   if (CC == X86::COND_NE) {
23471     SDValue Flags;
23472     X86::CondCode CC0, CC1;
23473     bool isAndSetCC;
23474     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23475       if (isAndSetCC) {
23476         std::swap(FalseOp, TrueOp);
23477         CC0 = X86::GetOppositeBranchCondition(CC0);
23478         CC1 = X86::GetOppositeBranchCondition(CC1);
23479       }
23480
23481       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23482         Flags};
23483       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23484       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23485       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23486       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23487       return CMOV;
23488     }
23489   }
23490
23491   return SDValue();
23492 }
23493
23494 /// PerformMulCombine - Optimize a single multiply with constant into two
23495 /// in order to implement it with two cheaper instructions, e.g.
23496 /// LEA + SHL, LEA + LEA.
23497 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23498                                  TargetLowering::DAGCombinerInfo &DCI) {
23499   // An imul is usually smaller than the alternative sequence.
23500   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23501     return SDValue();
23502
23503   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23504     return SDValue();
23505
23506   EVT VT = N->getValueType(0);
23507   if (VT != MVT::i64 && VT != MVT::i32)
23508     return SDValue();
23509
23510   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23511   if (!C)
23512     return SDValue();
23513   uint64_t MulAmt = C->getZExtValue();
23514   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23515     return SDValue();
23516
23517   uint64_t MulAmt1 = 0;
23518   uint64_t MulAmt2 = 0;
23519   if ((MulAmt % 9) == 0) {
23520     MulAmt1 = 9;
23521     MulAmt2 = MulAmt / 9;
23522   } else if ((MulAmt % 5) == 0) {
23523     MulAmt1 = 5;
23524     MulAmt2 = MulAmt / 5;
23525   } else if ((MulAmt % 3) == 0) {
23526     MulAmt1 = 3;
23527     MulAmt2 = MulAmt / 3;
23528   }
23529   if (MulAmt2 &&
23530       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23531     SDLoc DL(N);
23532
23533     if (isPowerOf2_64(MulAmt2) &&
23534         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23535       // If second multiplifer is pow2, issue it first. We want the multiply by
23536       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23537       // is an add.
23538       std::swap(MulAmt1, MulAmt2);
23539
23540     SDValue NewMul;
23541     if (isPowerOf2_64(MulAmt1))
23542       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23543                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23544     else
23545       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23546                            DAG.getConstant(MulAmt1, DL, VT));
23547
23548     if (isPowerOf2_64(MulAmt2))
23549       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23550                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23551     else
23552       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23553                            DAG.getConstant(MulAmt2, DL, VT));
23554
23555     // Do not add new nodes to DAG combiner worklist.
23556     DCI.CombineTo(N, NewMul, false);
23557   }
23558   return SDValue();
23559 }
23560
23561 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23562   SDValue N0 = N->getOperand(0);
23563   SDValue N1 = N->getOperand(1);
23564   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23565   EVT VT = N0.getValueType();
23566
23567   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23568   // since the result of setcc_c is all zero's or all ones.
23569   if (VT.isInteger() && !VT.isVector() &&
23570       N1C && N0.getOpcode() == ISD::AND &&
23571       N0.getOperand(1).getOpcode() == ISD::Constant) {
23572     SDValue N00 = N0.getOperand(0);
23573     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23574     APInt ShAmt = N1C->getAPIntValue();
23575     Mask = Mask.shl(ShAmt);
23576     bool MaskOK = false;
23577     // We can handle cases concerning bit-widening nodes containing setcc_c if
23578     // we carefully interrogate the mask to make sure we are semantics
23579     // preserving.
23580     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23581     // of the underlying setcc_c operation if the setcc_c was zero extended.
23582     // Consider the following example:
23583     //   zext(setcc_c)                 -> i32 0x0000FFFF
23584     //   c1                            -> i32 0x0000FFFF
23585     //   c2                            -> i32 0x00000001
23586     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23587     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23588     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23589       MaskOK = true;
23590     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23591                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23592       MaskOK = true;
23593     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23594                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23595                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23596       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23597     }
23598     if (MaskOK && Mask != 0) {
23599       SDLoc DL(N);
23600       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23601     }
23602   }
23603
23604   // Hardware support for vector shifts is sparse which makes us scalarize the
23605   // vector operations in many cases. Also, on sandybridge ADD is faster than
23606   // shl.
23607   // (shl V, 1) -> add V,V
23608   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23609     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23610       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23611       // We shift all of the values by one. In many cases we do not have
23612       // hardware support for this operation. This is better expressed as an ADD
23613       // of two values.
23614       if (N1SplatC->getAPIntValue() == 1)
23615         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23616     }
23617
23618   return SDValue();
23619 }
23620
23621 /// \brief Returns a vector of 0s if the node in input is a vector logical
23622 /// shift by a constant amount which is known to be bigger than or equal
23623 /// to the vector element size in bits.
23624 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23625                                       const X86Subtarget *Subtarget) {
23626   EVT VT = N->getValueType(0);
23627
23628   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23629       (!Subtarget->hasInt256() ||
23630        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23631     return SDValue();
23632
23633   SDValue Amt = N->getOperand(1);
23634   SDLoc DL(N);
23635   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23636     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23637       APInt ShiftAmt = AmtSplat->getAPIntValue();
23638       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23639
23640       // SSE2/AVX2 logical shifts always return a vector of 0s
23641       // if the shift amount is bigger than or equal to
23642       // the element size. The constant shift amount will be
23643       // encoded as a 8-bit immediate.
23644       if (ShiftAmt.trunc(8).uge(MaxAmount))
23645         return getZeroVector(VT, Subtarget, DAG, DL);
23646     }
23647
23648   return SDValue();
23649 }
23650
23651 /// PerformShiftCombine - Combine shifts.
23652 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23653                                    TargetLowering::DAGCombinerInfo &DCI,
23654                                    const X86Subtarget *Subtarget) {
23655   if (N->getOpcode() == ISD::SHL)
23656     if (SDValue V = PerformSHLCombine(N, DAG))
23657       return V;
23658
23659   // Try to fold this logical shift into a zero vector.
23660   if (N->getOpcode() != ISD::SRA)
23661     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23662       return V;
23663
23664   return SDValue();
23665 }
23666
23667 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23668 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23669 // and friends.  Likewise for OR -> CMPNEQSS.
23670 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23671                             TargetLowering::DAGCombinerInfo &DCI,
23672                             const X86Subtarget *Subtarget) {
23673   unsigned opcode;
23674
23675   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23676   // we're requiring SSE2 for both.
23677   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23678     SDValue N0 = N->getOperand(0);
23679     SDValue N1 = N->getOperand(1);
23680     SDValue CMP0 = N0->getOperand(1);
23681     SDValue CMP1 = N1->getOperand(1);
23682     SDLoc DL(N);
23683
23684     // The SETCCs should both refer to the same CMP.
23685     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23686       return SDValue();
23687
23688     SDValue CMP00 = CMP0->getOperand(0);
23689     SDValue CMP01 = CMP0->getOperand(1);
23690     EVT     VT    = CMP00.getValueType();
23691
23692     if (VT == MVT::f32 || VT == MVT::f64) {
23693       bool ExpectingFlags = false;
23694       // Check for any users that want flags:
23695       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23696            !ExpectingFlags && UI != UE; ++UI)
23697         switch (UI->getOpcode()) {
23698         default:
23699         case ISD::BR_CC:
23700         case ISD::BRCOND:
23701         case ISD::SELECT:
23702           ExpectingFlags = true;
23703           break;
23704         case ISD::CopyToReg:
23705         case ISD::SIGN_EXTEND:
23706         case ISD::ZERO_EXTEND:
23707         case ISD::ANY_EXTEND:
23708           break;
23709         }
23710
23711       if (!ExpectingFlags) {
23712         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23713         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23714
23715         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23716           X86::CondCode tmp = cc0;
23717           cc0 = cc1;
23718           cc1 = tmp;
23719         }
23720
23721         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23722             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23723           // FIXME: need symbolic constants for these magic numbers.
23724           // See X86ATTInstPrinter.cpp:printSSECC().
23725           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23726           if (Subtarget->hasAVX512()) {
23727             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23728                                          CMP01,
23729                                          DAG.getConstant(x86cc, DL, MVT::i8));
23730             if (N->getValueType(0) != MVT::i1)
23731               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23732                                  FSetCC);
23733             return FSetCC;
23734           }
23735           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23736                                               CMP00.getValueType(), CMP00, CMP01,
23737                                               DAG.getConstant(x86cc, DL,
23738                                                               MVT::i8));
23739
23740           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23741           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23742
23743           if (is64BitFP && !Subtarget->is64Bit()) {
23744             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23745             // 64-bit integer, since that's not a legal type. Since
23746             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23747             // bits, but can do this little dance to extract the lowest 32 bits
23748             // and work with those going forward.
23749             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23750                                            OnesOrZeroesF);
23751             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23752             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23753                                         Vector32, DAG.getIntPtrConstant(0, DL));
23754             IntVT = MVT::i32;
23755           }
23756
23757           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23758           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23759                                       DAG.getConstant(1, DL, IntVT));
23760           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23761                                               ANDed);
23762           return OneBitOfTruth;
23763         }
23764       }
23765     }
23766   }
23767   return SDValue();
23768 }
23769
23770 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23771 /// so it can be folded inside ANDNP.
23772 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23773   EVT VT = N->getValueType(0);
23774
23775   // Match direct AllOnes for 128 and 256-bit vectors
23776   if (ISD::isBuildVectorAllOnes(N))
23777     return true;
23778
23779   // Look through a bit convert.
23780   if (N->getOpcode() == ISD::BITCAST)
23781     N = N->getOperand(0).getNode();
23782
23783   // Sometimes the operand may come from a insert_subvector building a 256-bit
23784   // allones vector
23785   if (VT.is256BitVector() &&
23786       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23787     SDValue V1 = N->getOperand(0);
23788     SDValue V2 = N->getOperand(1);
23789
23790     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23791         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23792         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23793         ISD::isBuildVectorAllOnes(V2.getNode()))
23794       return true;
23795   }
23796
23797   return false;
23798 }
23799
23800 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23801 // register. In most cases we actually compare or select YMM-sized registers
23802 // and mixing the two types creates horrible code. This method optimizes
23803 // some of the transition sequences.
23804 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23805                                  TargetLowering::DAGCombinerInfo &DCI,
23806                                  const X86Subtarget *Subtarget) {
23807   EVT VT = N->getValueType(0);
23808   if (!VT.is256BitVector())
23809     return SDValue();
23810
23811   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23812           N->getOpcode() == ISD::ZERO_EXTEND ||
23813           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23814
23815   SDValue Narrow = N->getOperand(0);
23816   EVT NarrowVT = Narrow->getValueType(0);
23817   if (!NarrowVT.is128BitVector())
23818     return SDValue();
23819
23820   if (Narrow->getOpcode() != ISD::XOR &&
23821       Narrow->getOpcode() != ISD::AND &&
23822       Narrow->getOpcode() != ISD::OR)
23823     return SDValue();
23824
23825   SDValue N0  = Narrow->getOperand(0);
23826   SDValue N1  = Narrow->getOperand(1);
23827   SDLoc DL(Narrow);
23828
23829   // The Left side has to be a trunc.
23830   if (N0.getOpcode() != ISD::TRUNCATE)
23831     return SDValue();
23832
23833   // The type of the truncated inputs.
23834   EVT WideVT = N0->getOperand(0)->getValueType(0);
23835   if (WideVT != VT)
23836     return SDValue();
23837
23838   // The right side has to be a 'trunc' or a constant vector.
23839   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23840   ConstantSDNode *RHSConstSplat = nullptr;
23841   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23842     RHSConstSplat = RHSBV->getConstantSplatNode();
23843   if (!RHSTrunc && !RHSConstSplat)
23844     return SDValue();
23845
23846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23847
23848   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23849     return SDValue();
23850
23851   // Set N0 and N1 to hold the inputs to the new wide operation.
23852   N0 = N0->getOperand(0);
23853   if (RHSConstSplat) {
23854     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23855                      SDValue(RHSConstSplat, 0));
23856     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23857     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23858   } else if (RHSTrunc) {
23859     N1 = N1->getOperand(0);
23860   }
23861
23862   // Generate the wide operation.
23863   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23864   unsigned Opcode = N->getOpcode();
23865   switch (Opcode) {
23866   case ISD::ANY_EXTEND:
23867     return Op;
23868   case ISD::ZERO_EXTEND: {
23869     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23870     APInt Mask = APInt::getAllOnesValue(InBits);
23871     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23872     return DAG.getNode(ISD::AND, DL, VT,
23873                        Op, DAG.getConstant(Mask, DL, VT));
23874   }
23875   case ISD::SIGN_EXTEND:
23876     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23877                        Op, DAG.getValueType(NarrowVT));
23878   default:
23879     llvm_unreachable("Unexpected opcode");
23880   }
23881 }
23882
23883 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23884                                  TargetLowering::DAGCombinerInfo &DCI,
23885                                  const X86Subtarget *Subtarget) {
23886   SDValue N0 = N->getOperand(0);
23887   SDValue N1 = N->getOperand(1);
23888   SDLoc DL(N);
23889
23890   // A vector zext_in_reg may be represented as a shuffle,
23891   // feeding into a bitcast (this represents anyext) feeding into
23892   // an and with a mask.
23893   // We'd like to try to combine that into a shuffle with zero
23894   // plus a bitcast, removing the and.
23895   if (N0.getOpcode() != ISD::BITCAST ||
23896       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23897     return SDValue();
23898
23899   // The other side of the AND should be a splat of 2^C, where C
23900   // is the number of bits in the source type.
23901   if (N1.getOpcode() == ISD::BITCAST)
23902     N1 = N1.getOperand(0);
23903   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23904     return SDValue();
23905   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23906
23907   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23908   EVT SrcType = Shuffle->getValueType(0);
23909
23910   // We expect a single-source shuffle
23911   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23912     return SDValue();
23913
23914   unsigned SrcSize = SrcType.getScalarSizeInBits();
23915
23916   APInt SplatValue, SplatUndef;
23917   unsigned SplatBitSize;
23918   bool HasAnyUndefs;
23919   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23920                                 SplatBitSize, HasAnyUndefs))
23921     return SDValue();
23922
23923   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23924   // Make sure the splat matches the mask we expect
23925   if (SplatBitSize > ResSize ||
23926       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23927     return SDValue();
23928
23929   // Make sure the input and output size make sense
23930   if (SrcSize >= ResSize || ResSize % SrcSize)
23931     return SDValue();
23932
23933   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23934   // The number of u's between each two values depends on the ratio between
23935   // the source and dest type.
23936   unsigned ZextRatio = ResSize / SrcSize;
23937   bool IsZext = true;
23938   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23939     if (i % ZextRatio) {
23940       if (Shuffle->getMaskElt(i) > 0) {
23941         // Expected undef
23942         IsZext = false;
23943         break;
23944       }
23945     } else {
23946       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23947         // Expected element number
23948         IsZext = false;
23949         break;
23950       }
23951     }
23952   }
23953
23954   if (!IsZext)
23955     return SDValue();
23956
23957   // Ok, perform the transformation - replace the shuffle with
23958   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23959   // (instead of undef) where the k elements come from the zero vector.
23960   SmallVector<int, 8> Mask;
23961   unsigned NumElems = SrcType.getVectorNumElements();
23962   for (unsigned i = 0; i < NumElems; ++i)
23963     if (i % ZextRatio)
23964       Mask.push_back(NumElems);
23965     else
23966       Mask.push_back(i / ZextRatio);
23967
23968   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23969     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23970   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23971 }
23972
23973 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23974                                  TargetLowering::DAGCombinerInfo &DCI,
23975                                  const X86Subtarget *Subtarget) {
23976   if (DCI.isBeforeLegalizeOps())
23977     return SDValue();
23978
23979   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23980     return Zext;
23981
23982   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23983     return R;
23984
23985   EVT VT = N->getValueType(0);
23986   SDValue N0 = N->getOperand(0);
23987   SDValue N1 = N->getOperand(1);
23988   SDLoc DL(N);
23989
23990   // Create BEXTR instructions
23991   // BEXTR is ((X >> imm) & (2**size-1))
23992   if (VT == MVT::i32 || VT == MVT::i64) {
23993     // Check for BEXTR.
23994     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23995         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23996       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23997       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23998       if (MaskNode && ShiftNode) {
23999         uint64_t Mask = MaskNode->getZExtValue();
24000         uint64_t Shift = ShiftNode->getZExtValue();
24001         if (isMask_64(Mask)) {
24002           uint64_t MaskSize = countPopulation(Mask);
24003           if (Shift + MaskSize <= VT.getSizeInBits())
24004             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24005                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24006                                                VT));
24007         }
24008       }
24009     } // BEXTR
24010
24011     return SDValue();
24012   }
24013
24014   // Want to form ANDNP nodes:
24015   // 1) In the hopes of then easily combining them with OR and AND nodes
24016   //    to form PBLEND/PSIGN.
24017   // 2) To match ANDN packed intrinsics
24018   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24019     return SDValue();
24020
24021   // Check LHS for vnot
24022   if (N0.getOpcode() == ISD::XOR &&
24023       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24024       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24025     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24026
24027   // Check RHS for vnot
24028   if (N1.getOpcode() == ISD::XOR &&
24029       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24030       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24031     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24032
24033   return SDValue();
24034 }
24035
24036 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24037                                 TargetLowering::DAGCombinerInfo &DCI,
24038                                 const X86Subtarget *Subtarget) {
24039   if (DCI.isBeforeLegalizeOps())
24040     return SDValue();
24041
24042   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24043     return R;
24044
24045   SDValue N0 = N->getOperand(0);
24046   SDValue N1 = N->getOperand(1);
24047   EVT VT = N->getValueType(0);
24048
24049   // look for psign/blend
24050   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24051     if (!Subtarget->hasSSSE3() ||
24052         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24053       return SDValue();
24054
24055     // Canonicalize pandn to RHS
24056     if (N0.getOpcode() == X86ISD::ANDNP)
24057       std::swap(N0, N1);
24058     // or (and (m, y), (pandn m, x))
24059     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24060       SDValue Mask = N1.getOperand(0);
24061       SDValue X    = N1.getOperand(1);
24062       SDValue Y;
24063       if (N0.getOperand(0) == Mask)
24064         Y = N0.getOperand(1);
24065       if (N0.getOperand(1) == Mask)
24066         Y = N0.getOperand(0);
24067
24068       // Check to see if the mask appeared in both the AND and ANDNP and
24069       if (!Y.getNode())
24070         return SDValue();
24071
24072       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24073       // Look through mask bitcast.
24074       if (Mask.getOpcode() == ISD::BITCAST)
24075         Mask = Mask.getOperand(0);
24076       if (X.getOpcode() == ISD::BITCAST)
24077         X = X.getOperand(0);
24078       if (Y.getOpcode() == ISD::BITCAST)
24079         Y = Y.getOperand(0);
24080
24081       EVT MaskVT = Mask.getValueType();
24082
24083       // Validate that the Mask operand is a vector sra node.
24084       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24085       // there is no psrai.b
24086       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24087       unsigned SraAmt = ~0;
24088       if (Mask.getOpcode() == ISD::SRA) {
24089         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24090           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24091             SraAmt = AmtConst->getZExtValue();
24092       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24093         SDValue SraC = Mask.getOperand(1);
24094         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24095       }
24096       if ((SraAmt + 1) != EltBits)
24097         return SDValue();
24098
24099       SDLoc DL(N);
24100
24101       // Now we know we at least have a plendvb with the mask val.  See if
24102       // we can form a psignb/w/d.
24103       // psign = x.type == y.type == mask.type && y = sub(0, x);
24104       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24105           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24106           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24107         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24108                "Unsupported VT for PSIGN");
24109         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24110         return DAG.getBitcast(VT, Mask);
24111       }
24112       // PBLENDVB only available on SSE 4.1
24113       if (!Subtarget->hasSSE41())
24114         return SDValue();
24115
24116       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24117
24118       X = DAG.getBitcast(BlendVT, X);
24119       Y = DAG.getBitcast(BlendVT, Y);
24120       Mask = DAG.getBitcast(BlendVT, Mask);
24121       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24122       return DAG.getBitcast(VT, Mask);
24123     }
24124   }
24125
24126   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24127     return SDValue();
24128
24129   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24130   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24131
24132   // SHLD/SHRD instructions have lower register pressure, but on some
24133   // platforms they have higher latency than the equivalent
24134   // series of shifts/or that would otherwise be generated.
24135   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24136   // have higher latencies and we are not optimizing for size.
24137   if (!OptForSize && Subtarget->isSHLDSlow())
24138     return SDValue();
24139
24140   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24141     std::swap(N0, N1);
24142   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24143     return SDValue();
24144   if (!N0.hasOneUse() || !N1.hasOneUse())
24145     return SDValue();
24146
24147   SDValue ShAmt0 = N0.getOperand(1);
24148   if (ShAmt0.getValueType() != MVT::i8)
24149     return SDValue();
24150   SDValue ShAmt1 = N1.getOperand(1);
24151   if (ShAmt1.getValueType() != MVT::i8)
24152     return SDValue();
24153   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24154     ShAmt0 = ShAmt0.getOperand(0);
24155   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24156     ShAmt1 = ShAmt1.getOperand(0);
24157
24158   SDLoc DL(N);
24159   unsigned Opc = X86ISD::SHLD;
24160   SDValue Op0 = N0.getOperand(0);
24161   SDValue Op1 = N1.getOperand(0);
24162   if (ShAmt0.getOpcode() == ISD::SUB) {
24163     Opc = X86ISD::SHRD;
24164     std::swap(Op0, Op1);
24165     std::swap(ShAmt0, ShAmt1);
24166   }
24167
24168   unsigned Bits = VT.getSizeInBits();
24169   if (ShAmt1.getOpcode() == ISD::SUB) {
24170     SDValue Sum = ShAmt1.getOperand(0);
24171     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24172       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24173       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24174         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24175       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24176         return DAG.getNode(Opc, DL, VT,
24177                            Op0, Op1,
24178                            DAG.getNode(ISD::TRUNCATE, DL,
24179                                        MVT::i8, ShAmt0));
24180     }
24181   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24182     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24183     if (ShAmt0C &&
24184         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24185       return DAG.getNode(Opc, DL, VT,
24186                          N0.getOperand(0), N1.getOperand(0),
24187                          DAG.getNode(ISD::TRUNCATE, DL,
24188                                        MVT::i8, ShAmt0));
24189   }
24190
24191   return SDValue();
24192 }
24193
24194 // Generate NEG and CMOV for integer abs.
24195 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24196   EVT VT = N->getValueType(0);
24197
24198   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24199   // 8-bit integer abs to NEG and CMOV.
24200   if (VT.isInteger() && VT.getSizeInBits() == 8)
24201     return SDValue();
24202
24203   SDValue N0 = N->getOperand(0);
24204   SDValue N1 = N->getOperand(1);
24205   SDLoc DL(N);
24206
24207   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24208   // and change it to SUB and CMOV.
24209   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24210       N0.getOpcode() == ISD::ADD &&
24211       N0.getOperand(1) == N1 &&
24212       N1.getOpcode() == ISD::SRA &&
24213       N1.getOperand(0) == N0.getOperand(0))
24214     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24215       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24216         // Generate SUB & CMOV.
24217         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24218                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24219
24220         SDValue Ops[] = { N0.getOperand(0), Neg,
24221                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24222                           SDValue(Neg.getNode(), 1) };
24223         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24224       }
24225   return SDValue();
24226 }
24227
24228 // Try to turn tests against the signbit in the form of:
24229 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24230 // into:
24231 //   SETGT(X, -1)
24232 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24233   // This is only worth doing if the output type is i8.
24234   if (N->getValueType(0) != MVT::i8)
24235     return SDValue();
24236
24237   SDValue N0 = N->getOperand(0);
24238   SDValue N1 = N->getOperand(1);
24239
24240   // We should be performing an xor against a truncated shift.
24241   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24242     return SDValue();
24243
24244   // Make sure we are performing an xor against one.
24245   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24246     return SDValue();
24247
24248   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24249   SDValue Shift = N0.getOperand(0);
24250   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24251     return SDValue();
24252
24253   // Make sure we are truncating from one of i16, i32 or i64.
24254   EVT ShiftTy = Shift.getValueType();
24255   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24256     return SDValue();
24257
24258   // Make sure the shift amount extracts the sign bit.
24259   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24260       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24261     return SDValue();
24262
24263   // Create a greater-than comparison against -1.
24264   // N.B. Using SETGE against 0 works but we want a canonical looking
24265   // comparison, using SETGT matches up with what TranslateX86CC.
24266   SDLoc DL(N);
24267   SDValue ShiftOp = Shift.getOperand(0);
24268   EVT ShiftOpTy = ShiftOp.getValueType();
24269   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24270                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24271   return Cond;
24272 }
24273
24274 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24275                                  TargetLowering::DAGCombinerInfo &DCI,
24276                                  const X86Subtarget *Subtarget) {
24277   if (DCI.isBeforeLegalizeOps())
24278     return SDValue();
24279
24280   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24281     return RV;
24282
24283   if (Subtarget->hasCMov())
24284     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24285       return RV;
24286
24287   return SDValue();
24288 }
24289
24290 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24291 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24292                                   TargetLowering::DAGCombinerInfo &DCI,
24293                                   const X86Subtarget *Subtarget) {
24294   LoadSDNode *Ld = cast<LoadSDNode>(N);
24295   EVT RegVT = Ld->getValueType(0);
24296   EVT MemVT = Ld->getMemoryVT();
24297   SDLoc dl(Ld);
24298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24299
24300   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24301   // into two 16-byte operations.
24302   ISD::LoadExtType Ext = Ld->getExtensionType();
24303   bool Fast;
24304   unsigned AddressSpace = Ld->getAddressSpace();
24305   unsigned Alignment = Ld->getAlignment();
24306   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24307       Ext == ISD::NON_EXTLOAD &&
24308       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24309                              AddressSpace, Alignment, &Fast) && !Fast) {
24310     unsigned NumElems = RegVT.getVectorNumElements();
24311     if (NumElems < 2)
24312       return SDValue();
24313
24314     SDValue Ptr = Ld->getBasePtr();
24315     SDValue Increment =
24316         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24317
24318     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24319                                   NumElems/2);
24320     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24321                                 Ld->getPointerInfo(), Ld->isVolatile(),
24322                                 Ld->isNonTemporal(), Ld->isInvariant(),
24323                                 Alignment);
24324     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24325     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24326                                 Ld->getPointerInfo(), Ld->isVolatile(),
24327                                 Ld->isNonTemporal(), Ld->isInvariant(),
24328                                 std::min(16U, Alignment));
24329     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24330                              Load1.getValue(1),
24331                              Load2.getValue(1));
24332
24333     SDValue NewVec = DAG.getUNDEF(RegVT);
24334     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24335     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24336     return DCI.CombineTo(N, NewVec, TF, true);
24337   }
24338
24339   return SDValue();
24340 }
24341
24342 /// PerformMLOADCombine - Resolve extending loads
24343 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24344                                    TargetLowering::DAGCombinerInfo &DCI,
24345                                    const X86Subtarget *Subtarget) {
24346   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24347   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24348     return SDValue();
24349
24350   EVT VT = Mld->getValueType(0);
24351   unsigned NumElems = VT.getVectorNumElements();
24352   EVT LdVT = Mld->getMemoryVT();
24353   SDLoc dl(Mld);
24354
24355   assert(LdVT != VT && "Cannot extend to the same type");
24356   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24357   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24358   // From, To sizes and ElemCount must be pow of two
24359   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24360     "Unexpected size for extending masked load");
24361
24362   unsigned SizeRatio  = ToSz / FromSz;
24363   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24364
24365   // Create a type on which we perform the shuffle
24366   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24367           LdVT.getScalarType(), NumElems*SizeRatio);
24368   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24369
24370   // Convert Src0 value
24371   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24372   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24373     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24374     for (unsigned i = 0; i != NumElems; ++i)
24375       ShuffleVec[i] = i * SizeRatio;
24376
24377     // Can't shuffle using an illegal type.
24378     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24379             && "WideVecVT should be legal");
24380     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24381                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24382   }
24383   // Prepare the new mask
24384   SDValue NewMask;
24385   SDValue Mask = Mld->getMask();
24386   if (Mask.getValueType() == VT) {
24387     // Mask and original value have the same type
24388     NewMask = DAG.getBitcast(WideVecVT, Mask);
24389     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24390     for (unsigned i = 0; i != NumElems; ++i)
24391       ShuffleVec[i] = i * SizeRatio;
24392     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24393       ShuffleVec[i] = NumElems*SizeRatio;
24394     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24395                                    DAG.getConstant(0, dl, WideVecVT),
24396                                    &ShuffleVec[0]);
24397   }
24398   else {
24399     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24400     unsigned WidenNumElts = NumElems*SizeRatio;
24401     unsigned MaskNumElts = VT.getVectorNumElements();
24402     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24403                                      WidenNumElts);
24404
24405     unsigned NumConcat = WidenNumElts / MaskNumElts;
24406     SmallVector<SDValue, 16> Ops(NumConcat);
24407     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24408     Ops[0] = Mask;
24409     for (unsigned i = 1; i != NumConcat; ++i)
24410       Ops[i] = ZeroVal;
24411
24412     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24413   }
24414
24415   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24416                                      Mld->getBasePtr(), NewMask, WideSrc0,
24417                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24418                                      ISD::NON_EXTLOAD);
24419   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24420   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24421
24422 }
24423 /// PerformMSTORECombine - Resolve truncating stores
24424 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24425                                     const X86Subtarget *Subtarget) {
24426   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24427   if (!Mst->isTruncatingStore())
24428     return SDValue();
24429
24430   EVT VT = Mst->getValue().getValueType();
24431   unsigned NumElems = VT.getVectorNumElements();
24432   EVT StVT = Mst->getMemoryVT();
24433   SDLoc dl(Mst);
24434
24435   assert(StVT != VT && "Cannot truncate to the same type");
24436   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24437   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24438
24439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24440
24441   // The truncating store is legal in some cases. For example
24442   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24443   // are designated for truncate store.
24444   // In this case we don't need any further transformations.
24445   if (TLI.isTruncStoreLegal(VT, StVT))
24446     return SDValue();
24447
24448   // From, To sizes and ElemCount must be pow of two
24449   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24450     "Unexpected size for truncating masked store");
24451   // We are going to use the original vector elt for storing.
24452   // Accumulated smaller vector elements must be a multiple of the store size.
24453   assert (((NumElems * FromSz) % ToSz) == 0 &&
24454           "Unexpected ratio for truncating masked store");
24455
24456   unsigned SizeRatio  = FromSz / ToSz;
24457   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24458
24459   // Create a type on which we perform the shuffle
24460   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24461           StVT.getScalarType(), NumElems*SizeRatio);
24462
24463   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24464
24465   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24466   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24467   for (unsigned i = 0; i != NumElems; ++i)
24468     ShuffleVec[i] = i * SizeRatio;
24469
24470   // Can't shuffle using an illegal type.
24471   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24472           && "WideVecVT should be legal");
24473
24474   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24475                                         DAG.getUNDEF(WideVecVT),
24476                                         &ShuffleVec[0]);
24477
24478   SDValue NewMask;
24479   SDValue Mask = Mst->getMask();
24480   if (Mask.getValueType() == VT) {
24481     // Mask and original value have the same type
24482     NewMask = DAG.getBitcast(WideVecVT, Mask);
24483     for (unsigned i = 0; i != NumElems; ++i)
24484       ShuffleVec[i] = i * SizeRatio;
24485     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24486       ShuffleVec[i] = NumElems*SizeRatio;
24487     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24488                                    DAG.getConstant(0, dl, WideVecVT),
24489                                    &ShuffleVec[0]);
24490   }
24491   else {
24492     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24493     unsigned WidenNumElts = NumElems*SizeRatio;
24494     unsigned MaskNumElts = VT.getVectorNumElements();
24495     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24496                                      WidenNumElts);
24497
24498     unsigned NumConcat = WidenNumElts / MaskNumElts;
24499     SmallVector<SDValue, 16> Ops(NumConcat);
24500     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24501     Ops[0] = Mask;
24502     for (unsigned i = 1; i != NumConcat; ++i)
24503       Ops[i] = ZeroVal;
24504
24505     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24506   }
24507
24508   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24509                             NewMask, StVT, Mst->getMemOperand(), false);
24510 }
24511 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24512 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24513                                    const X86Subtarget *Subtarget) {
24514   StoreSDNode *St = cast<StoreSDNode>(N);
24515   EVT VT = St->getValue().getValueType();
24516   EVT StVT = St->getMemoryVT();
24517   SDLoc dl(St);
24518   SDValue StoredVal = St->getOperand(1);
24519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24520
24521   // If we are saving a concatenation of two XMM registers and 32-byte stores
24522   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24523   bool Fast;
24524   unsigned AddressSpace = St->getAddressSpace();
24525   unsigned Alignment = St->getAlignment();
24526   if (VT.is256BitVector() && StVT == VT &&
24527       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24528                              AddressSpace, Alignment, &Fast) && !Fast) {
24529     unsigned NumElems = VT.getVectorNumElements();
24530     if (NumElems < 2)
24531       return SDValue();
24532
24533     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24534     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24535
24536     SDValue Stride =
24537         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24538     SDValue Ptr0 = St->getBasePtr();
24539     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24540
24541     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24542                                 St->getPointerInfo(), St->isVolatile(),
24543                                 St->isNonTemporal(), Alignment);
24544     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24545                                 St->getPointerInfo(), St->isVolatile(),
24546                                 St->isNonTemporal(),
24547                                 std::min(16U, Alignment));
24548     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24549   }
24550
24551   // Optimize trunc store (of multiple scalars) to shuffle and store.
24552   // First, pack all of the elements in one place. Next, store to memory
24553   // in fewer chunks.
24554   if (St->isTruncatingStore() && VT.isVector()) {
24555     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24556     unsigned NumElems = VT.getVectorNumElements();
24557     assert(StVT != VT && "Cannot truncate to the same type");
24558     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24559     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24560
24561     // The truncating store is legal in some cases. For example
24562     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24563     // are designated for truncate store.
24564     // In this case we don't need any further transformations.
24565     if (TLI.isTruncStoreLegal(VT, StVT))
24566       return SDValue();
24567
24568     // From, To sizes and ElemCount must be pow of two
24569     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24570     // We are going to use the original vector elt for storing.
24571     // Accumulated smaller vector elements must be a multiple of the store size.
24572     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24573
24574     unsigned SizeRatio  = FromSz / ToSz;
24575
24576     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24577
24578     // Create a type on which we perform the shuffle
24579     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24580             StVT.getScalarType(), NumElems*SizeRatio);
24581
24582     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24583
24584     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24585     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24586     for (unsigned i = 0; i != NumElems; ++i)
24587       ShuffleVec[i] = i * SizeRatio;
24588
24589     // Can't shuffle using an illegal type.
24590     if (!TLI.isTypeLegal(WideVecVT))
24591       return SDValue();
24592
24593     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24594                                          DAG.getUNDEF(WideVecVT),
24595                                          &ShuffleVec[0]);
24596     // At this point all of the data is stored at the bottom of the
24597     // register. We now need to save it to mem.
24598
24599     // Find the largest store unit
24600     MVT StoreType = MVT::i8;
24601     for (MVT Tp : MVT::integer_valuetypes()) {
24602       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24603         StoreType = Tp;
24604     }
24605
24606     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24607     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24608         (64 <= NumElems * ToSz))
24609       StoreType = MVT::f64;
24610
24611     // Bitcast the original vector into a vector of store-size units
24612     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24613             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24614     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24615     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24616     SmallVector<SDValue, 8> Chains;
24617     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24618                                         TLI.getPointerTy(DAG.getDataLayout()));
24619     SDValue Ptr = St->getBasePtr();
24620
24621     // Perform one or more big stores into memory.
24622     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24623       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24624                                    StoreType, ShuffWide,
24625                                    DAG.getIntPtrConstant(i, dl));
24626       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24627                                 St->getPointerInfo(), St->isVolatile(),
24628                                 St->isNonTemporal(), St->getAlignment());
24629       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24630       Chains.push_back(Ch);
24631     }
24632
24633     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24634   }
24635
24636   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24637   // the FP state in cases where an emms may be missing.
24638   // A preferable solution to the general problem is to figure out the right
24639   // places to insert EMMS.  This qualifies as a quick hack.
24640
24641   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24642   if (VT.getSizeInBits() != 64)
24643     return SDValue();
24644
24645   const Function *F = DAG.getMachineFunction().getFunction();
24646   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24647   bool F64IsLegal =
24648       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24649   if ((VT.isVector() ||
24650        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24651       isa<LoadSDNode>(St->getValue()) &&
24652       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24653       St->getChain().hasOneUse() && !St->isVolatile()) {
24654     SDNode* LdVal = St->getValue().getNode();
24655     LoadSDNode *Ld = nullptr;
24656     int TokenFactorIndex = -1;
24657     SmallVector<SDValue, 8> Ops;
24658     SDNode* ChainVal = St->getChain().getNode();
24659     // Must be a store of a load.  We currently handle two cases:  the load
24660     // is a direct child, and it's under an intervening TokenFactor.  It is
24661     // possible to dig deeper under nested TokenFactors.
24662     if (ChainVal == LdVal)
24663       Ld = cast<LoadSDNode>(St->getChain());
24664     else if (St->getValue().hasOneUse() &&
24665              ChainVal->getOpcode() == ISD::TokenFactor) {
24666       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24667         if (ChainVal->getOperand(i).getNode() == LdVal) {
24668           TokenFactorIndex = i;
24669           Ld = cast<LoadSDNode>(St->getValue());
24670         } else
24671           Ops.push_back(ChainVal->getOperand(i));
24672       }
24673     }
24674
24675     if (!Ld || !ISD::isNormalLoad(Ld))
24676       return SDValue();
24677
24678     // If this is not the MMX case, i.e. we are just turning i64 load/store
24679     // into f64 load/store, avoid the transformation if there are multiple
24680     // uses of the loaded value.
24681     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24682       return SDValue();
24683
24684     SDLoc LdDL(Ld);
24685     SDLoc StDL(N);
24686     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24687     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24688     // pair instead.
24689     if (Subtarget->is64Bit() || F64IsLegal) {
24690       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24691       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24692                                   Ld->getPointerInfo(), Ld->isVolatile(),
24693                                   Ld->isNonTemporal(), Ld->isInvariant(),
24694                                   Ld->getAlignment());
24695       SDValue NewChain = NewLd.getValue(1);
24696       if (TokenFactorIndex != -1) {
24697         Ops.push_back(NewChain);
24698         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24699       }
24700       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24701                           St->getPointerInfo(),
24702                           St->isVolatile(), St->isNonTemporal(),
24703                           St->getAlignment());
24704     }
24705
24706     // Otherwise, lower to two pairs of 32-bit loads / stores.
24707     SDValue LoAddr = Ld->getBasePtr();
24708     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24709                                  DAG.getConstant(4, LdDL, MVT::i32));
24710
24711     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24712                                Ld->getPointerInfo(),
24713                                Ld->isVolatile(), Ld->isNonTemporal(),
24714                                Ld->isInvariant(), Ld->getAlignment());
24715     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24716                                Ld->getPointerInfo().getWithOffset(4),
24717                                Ld->isVolatile(), Ld->isNonTemporal(),
24718                                Ld->isInvariant(),
24719                                MinAlign(Ld->getAlignment(), 4));
24720
24721     SDValue NewChain = LoLd.getValue(1);
24722     if (TokenFactorIndex != -1) {
24723       Ops.push_back(LoLd);
24724       Ops.push_back(HiLd);
24725       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24726     }
24727
24728     LoAddr = St->getBasePtr();
24729     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24730                          DAG.getConstant(4, StDL, MVT::i32));
24731
24732     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24733                                 St->getPointerInfo(),
24734                                 St->isVolatile(), St->isNonTemporal(),
24735                                 St->getAlignment());
24736     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24737                                 St->getPointerInfo().getWithOffset(4),
24738                                 St->isVolatile(),
24739                                 St->isNonTemporal(),
24740                                 MinAlign(St->getAlignment(), 4));
24741     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24742   }
24743
24744   // This is similar to the above case, but here we handle a scalar 64-bit
24745   // integer store that is extracted from a vector on a 32-bit target.
24746   // If we have SSE2, then we can treat it like a floating-point double
24747   // to get past legalization. The execution dependencies fixup pass will
24748   // choose the optimal machine instruction for the store if this really is
24749   // an integer or v2f32 rather than an f64.
24750   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24751       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24752     SDValue OldExtract = St->getOperand(1);
24753     SDValue ExtOp0 = OldExtract.getOperand(0);
24754     unsigned VecSize = ExtOp0.getValueSizeInBits();
24755     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24756     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24757     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24758                                      BitCast, OldExtract.getOperand(1));
24759     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24760                         St->getPointerInfo(), St->isVolatile(),
24761                         St->isNonTemporal(), St->getAlignment());
24762   }
24763
24764   return SDValue();
24765 }
24766
24767 /// Return 'true' if this vector operation is "horizontal"
24768 /// and return the operands for the horizontal operation in LHS and RHS.  A
24769 /// horizontal operation performs the binary operation on successive elements
24770 /// of its first operand, then on successive elements of its second operand,
24771 /// returning the resulting values in a vector.  For example, if
24772 ///   A = < float a0, float a1, float a2, float a3 >
24773 /// and
24774 ///   B = < float b0, float b1, float b2, float b3 >
24775 /// then the result of doing a horizontal operation on A and B is
24776 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24777 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24778 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24779 /// set to A, RHS to B, and the routine returns 'true'.
24780 /// Note that the binary operation should have the property that if one of the
24781 /// operands is UNDEF then the result is UNDEF.
24782 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24783   // Look for the following pattern: if
24784   //   A = < float a0, float a1, float a2, float a3 >
24785   //   B = < float b0, float b1, float b2, float b3 >
24786   // and
24787   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24788   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24789   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24790   // which is A horizontal-op B.
24791
24792   // At least one of the operands should be a vector shuffle.
24793   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24794       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24795     return false;
24796
24797   MVT VT = LHS.getSimpleValueType();
24798
24799   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24800          "Unsupported vector type for horizontal add/sub");
24801
24802   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24803   // operate independently on 128-bit lanes.
24804   unsigned NumElts = VT.getVectorNumElements();
24805   unsigned NumLanes = VT.getSizeInBits()/128;
24806   unsigned NumLaneElts = NumElts / NumLanes;
24807   assert((NumLaneElts % 2 == 0) &&
24808          "Vector type should have an even number of elements in each lane");
24809   unsigned HalfLaneElts = NumLaneElts/2;
24810
24811   // View LHS in the form
24812   //   LHS = VECTOR_SHUFFLE A, B, LMask
24813   // If LHS is not a shuffle then pretend it is the shuffle
24814   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24815   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24816   // type VT.
24817   SDValue A, B;
24818   SmallVector<int, 16> LMask(NumElts);
24819   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24820     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24821       A = LHS.getOperand(0);
24822     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24823       B = LHS.getOperand(1);
24824     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24825     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24826   } else {
24827     if (LHS.getOpcode() != ISD::UNDEF)
24828       A = LHS;
24829     for (unsigned i = 0; i != NumElts; ++i)
24830       LMask[i] = i;
24831   }
24832
24833   // Likewise, view RHS in the form
24834   //   RHS = VECTOR_SHUFFLE C, D, RMask
24835   SDValue C, D;
24836   SmallVector<int, 16> RMask(NumElts);
24837   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24838     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24839       C = RHS.getOperand(0);
24840     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24841       D = RHS.getOperand(1);
24842     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24843     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24844   } else {
24845     if (RHS.getOpcode() != ISD::UNDEF)
24846       C = RHS;
24847     for (unsigned i = 0; i != NumElts; ++i)
24848       RMask[i] = i;
24849   }
24850
24851   // Check that the shuffles are both shuffling the same vectors.
24852   if (!(A == C && B == D) && !(A == D && B == C))
24853     return false;
24854
24855   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24856   if (!A.getNode() && !B.getNode())
24857     return false;
24858
24859   // If A and B occur in reverse order in RHS, then "swap" them (which means
24860   // rewriting the mask).
24861   if (A != C)
24862     ShuffleVectorSDNode::commuteMask(RMask);
24863
24864   // At this point LHS and RHS are equivalent to
24865   //   LHS = VECTOR_SHUFFLE A, B, LMask
24866   //   RHS = VECTOR_SHUFFLE A, B, RMask
24867   // Check that the masks correspond to performing a horizontal operation.
24868   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24869     for (unsigned i = 0; i != NumLaneElts; ++i) {
24870       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24871
24872       // Ignore any UNDEF components.
24873       if (LIdx < 0 || RIdx < 0 ||
24874           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24875           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24876         continue;
24877
24878       // Check that successive elements are being operated on.  If not, this is
24879       // not a horizontal operation.
24880       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24881       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24882       if (!(LIdx == Index && RIdx == Index + 1) &&
24883           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24884         return false;
24885     }
24886   }
24887
24888   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24889   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24890   return true;
24891 }
24892
24893 /// Do target-specific dag combines on floating point adds.
24894 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24895                                   const X86Subtarget *Subtarget) {
24896   EVT VT = N->getValueType(0);
24897   SDValue LHS = N->getOperand(0);
24898   SDValue RHS = N->getOperand(1);
24899
24900   // Try to synthesize horizontal adds from adds of shuffles.
24901   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24902        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24903       isHorizontalBinOp(LHS, RHS, true))
24904     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24905   return SDValue();
24906 }
24907
24908 /// Do target-specific dag combines on floating point subs.
24909 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24910                                   const X86Subtarget *Subtarget) {
24911   EVT VT = N->getValueType(0);
24912   SDValue LHS = N->getOperand(0);
24913   SDValue RHS = N->getOperand(1);
24914
24915   // Try to synthesize horizontal subs from subs of shuffles.
24916   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24917        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24918       isHorizontalBinOp(LHS, RHS, false))
24919     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24920   return SDValue();
24921 }
24922
24923 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24924 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24925   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24926
24927   // F[X]OR(0.0, x) -> x
24928   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24929     if (C->getValueAPF().isPosZero())
24930       return N->getOperand(1);
24931
24932   // F[X]OR(x, 0.0) -> x
24933   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24934     if (C->getValueAPF().isPosZero())
24935       return N->getOperand(0);
24936   return SDValue();
24937 }
24938
24939 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24940 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24941   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24942
24943   // Only perform optimizations if UnsafeMath is used.
24944   if (!DAG.getTarget().Options.UnsafeFPMath)
24945     return SDValue();
24946
24947   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24948   // into FMINC and FMAXC, which are Commutative operations.
24949   unsigned NewOp = 0;
24950   switch (N->getOpcode()) {
24951     default: llvm_unreachable("unknown opcode");
24952     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24953     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24954   }
24955
24956   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24957                      N->getOperand(0), N->getOperand(1));
24958 }
24959
24960 /// Do target-specific dag combines on X86ISD::FAND nodes.
24961 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24962   // FAND(0.0, x) -> 0.0
24963   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24964     if (C->getValueAPF().isPosZero())
24965       return N->getOperand(0);
24966
24967   // FAND(x, 0.0) -> 0.0
24968   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24969     if (C->getValueAPF().isPosZero())
24970       return N->getOperand(1);
24971
24972   return SDValue();
24973 }
24974
24975 /// Do target-specific dag combines on X86ISD::FANDN nodes
24976 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24977   // FANDN(0.0, x) -> x
24978   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24979     if (C->getValueAPF().isPosZero())
24980       return N->getOperand(1);
24981
24982   // FANDN(x, 0.0) -> 0.0
24983   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24984     if (C->getValueAPF().isPosZero())
24985       return N->getOperand(1);
24986
24987   return SDValue();
24988 }
24989
24990 static SDValue PerformBTCombine(SDNode *N,
24991                                 SelectionDAG &DAG,
24992                                 TargetLowering::DAGCombinerInfo &DCI) {
24993   // BT ignores high bits in the bit index operand.
24994   SDValue Op1 = N->getOperand(1);
24995   if (Op1.hasOneUse()) {
24996     unsigned BitWidth = Op1.getValueSizeInBits();
24997     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24998     APInt KnownZero, KnownOne;
24999     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25000                                           !DCI.isBeforeLegalizeOps());
25001     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25002     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25003         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25004       DCI.CommitTargetLoweringOpt(TLO);
25005   }
25006   return SDValue();
25007 }
25008
25009 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25010   SDValue Op = N->getOperand(0);
25011   if (Op.getOpcode() == ISD::BITCAST)
25012     Op = Op.getOperand(0);
25013   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25014   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25015       VT.getVectorElementType().getSizeInBits() ==
25016       OpVT.getVectorElementType().getSizeInBits()) {
25017     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25018   }
25019   return SDValue();
25020 }
25021
25022 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25023                                                const X86Subtarget *Subtarget) {
25024   EVT VT = N->getValueType(0);
25025   if (!VT.isVector())
25026     return SDValue();
25027
25028   SDValue N0 = N->getOperand(0);
25029   SDValue N1 = N->getOperand(1);
25030   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25031   SDLoc dl(N);
25032
25033   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25034   // both SSE and AVX2 since there is no sign-extended shift right
25035   // operation on a vector with 64-bit elements.
25036   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25037   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25038   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25039       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25040     SDValue N00 = N0.getOperand(0);
25041
25042     // EXTLOAD has a better solution on AVX2,
25043     // it may be replaced with X86ISD::VSEXT node.
25044     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25045       if (!ISD::isNormalLoad(N00.getNode()))
25046         return SDValue();
25047
25048     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25049         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25050                                   N00, N1);
25051       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25052     }
25053   }
25054   return SDValue();
25055 }
25056
25057 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25058                                   TargetLowering::DAGCombinerInfo &DCI,
25059                                   const X86Subtarget *Subtarget) {
25060   SDValue N0 = N->getOperand(0);
25061   EVT VT = N->getValueType(0);
25062   EVT SVT = VT.getScalarType();
25063   EVT InVT = N0.getValueType();
25064   EVT InSVT = InVT.getScalarType();
25065   SDLoc DL(N);
25066
25067   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25068   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25069   // This exposes the sext to the sdivrem lowering, so that it directly extends
25070   // from AH (which we otherwise need to do contortions to access).
25071   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25072       InVT == MVT::i8 && VT == MVT::i32) {
25073     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25074     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25075                             N0.getOperand(0), N0.getOperand(1));
25076     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25077     return R.getValue(1);
25078   }
25079
25080   if (!DCI.isBeforeLegalizeOps()) {
25081     if (InVT == MVT::i1) {
25082       SDValue Zero = DAG.getConstant(0, DL, VT);
25083       SDValue AllOnes =
25084         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25085       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25086     }
25087     return SDValue();
25088   }
25089
25090   if (VT.isVector() && Subtarget->hasSSE2()) {
25091     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25092       EVT InVT = N.getValueType();
25093       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25094                                    Size / InVT.getScalarSizeInBits());
25095       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25096                                     DAG.getUNDEF(InVT));
25097       Opnds[0] = N;
25098       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25099     };
25100
25101     // If target-size is less than 128-bits, extend to a type that would extend
25102     // to 128 bits, extend that and extract the original target vector.
25103     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25104         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25105         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25106       unsigned Scale = 128 / VT.getSizeInBits();
25107       EVT ExVT =
25108           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25109       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25110       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25111       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25112                          DAG.getIntPtrConstant(0, DL));
25113     }
25114
25115     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25116     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25117     if (VT.getSizeInBits() == 128 &&
25118         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25119         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25120       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25121       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25122     }
25123
25124     // On pre-AVX2 targets, split into 128-bit nodes of
25125     // ISD::SIGN_EXTEND_VECTOR_INREG.
25126     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25127         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25128         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25129       unsigned NumVecs = VT.getSizeInBits() / 128;
25130       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25131       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25132       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25133
25134       SmallVector<SDValue, 8> Opnds;
25135       for (unsigned i = 0, Offset = 0; i != NumVecs;
25136            ++i, Offset += NumSubElts) {
25137         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25138                                      DAG.getIntPtrConstant(Offset, DL));
25139         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25140         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25141         Opnds.push_back(SrcVec);
25142       }
25143       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25144     }
25145   }
25146
25147   if (!Subtarget->hasFp256())
25148     return SDValue();
25149
25150   if (VT.isVector() && VT.getSizeInBits() == 256)
25151     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25152       return R;
25153
25154   return SDValue();
25155 }
25156
25157 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25158                                  const X86Subtarget* Subtarget) {
25159   SDLoc dl(N);
25160   EVT VT = N->getValueType(0);
25161
25162   // Let legalize expand this if it isn't a legal type yet.
25163   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25164     return SDValue();
25165
25166   EVT ScalarVT = VT.getScalarType();
25167   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25168       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25169        !Subtarget->hasAVX512()))
25170     return SDValue();
25171
25172   SDValue A = N->getOperand(0);
25173   SDValue B = N->getOperand(1);
25174   SDValue C = N->getOperand(2);
25175
25176   bool NegA = (A.getOpcode() == ISD::FNEG);
25177   bool NegB = (B.getOpcode() == ISD::FNEG);
25178   bool NegC = (C.getOpcode() == ISD::FNEG);
25179
25180   // Negative multiplication when NegA xor NegB
25181   bool NegMul = (NegA != NegB);
25182   if (NegA)
25183     A = A.getOperand(0);
25184   if (NegB)
25185     B = B.getOperand(0);
25186   if (NegC)
25187     C = C.getOperand(0);
25188
25189   unsigned Opcode;
25190   if (!NegMul)
25191     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25192   else
25193     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25194
25195   return DAG.getNode(Opcode, dl, VT, A, B, C);
25196 }
25197
25198 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25199                                   TargetLowering::DAGCombinerInfo &DCI,
25200                                   const X86Subtarget *Subtarget) {
25201   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25202   //           (and (i32 x86isd::setcc_carry), 1)
25203   // This eliminates the zext. This transformation is necessary because
25204   // ISD::SETCC is always legalized to i8.
25205   SDLoc dl(N);
25206   SDValue N0 = N->getOperand(0);
25207   EVT VT = N->getValueType(0);
25208
25209   if (N0.getOpcode() == ISD::AND &&
25210       N0.hasOneUse() &&
25211       N0.getOperand(0).hasOneUse()) {
25212     SDValue N00 = N0.getOperand(0);
25213     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25214       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25215       if (!C || C->getZExtValue() != 1)
25216         return SDValue();
25217       return DAG.getNode(ISD::AND, dl, VT,
25218                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25219                                      N00.getOperand(0), N00.getOperand(1)),
25220                          DAG.getConstant(1, dl, VT));
25221     }
25222   }
25223
25224   if (N0.getOpcode() == ISD::TRUNCATE &&
25225       N0.hasOneUse() &&
25226       N0.getOperand(0).hasOneUse()) {
25227     SDValue N00 = N0.getOperand(0);
25228     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25229       return DAG.getNode(ISD::AND, dl, VT,
25230                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25231                                      N00.getOperand(0), N00.getOperand(1)),
25232                          DAG.getConstant(1, dl, VT));
25233     }
25234   }
25235
25236   if (VT.is256BitVector())
25237     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25238       return R;
25239
25240   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25241   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25242   // This exposes the zext to the udivrem lowering, so that it directly extends
25243   // from AH (which we otherwise need to do contortions to access).
25244   if (N0.getOpcode() == ISD::UDIVREM &&
25245       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25246       (VT == MVT::i32 || VT == MVT::i64)) {
25247     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25248     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25249                             N0.getOperand(0), N0.getOperand(1));
25250     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25251     return R.getValue(1);
25252   }
25253
25254   return SDValue();
25255 }
25256
25257 // Optimize x == -y --> x+y == 0
25258 //          x != -y --> x+y != 0
25259 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25260                                       const X86Subtarget* Subtarget) {
25261   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25262   SDValue LHS = N->getOperand(0);
25263   SDValue RHS = N->getOperand(1);
25264   EVT VT = N->getValueType(0);
25265   SDLoc DL(N);
25266
25267   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25268     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25269       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25270         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25271                                    LHS.getOperand(1));
25272         return DAG.getSetCC(DL, N->getValueType(0), addV,
25273                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25274       }
25275   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25276     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25277       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25278         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25279                                    RHS.getOperand(1));
25280         return DAG.getSetCC(DL, N->getValueType(0), addV,
25281                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25282       }
25283
25284   if (VT.getScalarType() == MVT::i1 &&
25285       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25286     bool IsSEXT0 =
25287         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25288         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25289     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25290
25291     if (!IsSEXT0 || !IsVZero1) {
25292       // Swap the operands and update the condition code.
25293       std::swap(LHS, RHS);
25294       CC = ISD::getSetCCSwappedOperands(CC);
25295
25296       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25297                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25298       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25299     }
25300
25301     if (IsSEXT0 && IsVZero1) {
25302       assert(VT == LHS.getOperand(0).getValueType() &&
25303              "Uexpected operand type");
25304       if (CC == ISD::SETGT)
25305         return DAG.getConstant(0, DL, VT);
25306       if (CC == ISD::SETLE)
25307         return DAG.getConstant(1, DL, VT);
25308       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25309         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25310
25311       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25312              "Unexpected condition code!");
25313       return LHS.getOperand(0);
25314     }
25315   }
25316
25317   return SDValue();
25318 }
25319
25320 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25321                                          SelectionDAG &DAG) {
25322   SDLoc dl(Load);
25323   MVT VT = Load->getSimpleValueType(0);
25324   MVT EVT = VT.getVectorElementType();
25325   SDValue Addr = Load->getOperand(1);
25326   SDValue NewAddr = DAG.getNode(
25327       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25328       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25329                       Addr.getSimpleValueType()));
25330
25331   SDValue NewLoad =
25332       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25333                   DAG.getMachineFunction().getMachineMemOperand(
25334                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25335   return NewLoad;
25336 }
25337
25338 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25339                                       const X86Subtarget *Subtarget) {
25340   SDLoc dl(N);
25341   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25342   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25343          "X86insertps is only defined for v4x32");
25344
25345   SDValue Ld = N->getOperand(1);
25346   if (MayFoldLoad(Ld)) {
25347     // Extract the countS bits from the immediate so we can get the proper
25348     // address when narrowing the vector load to a specific element.
25349     // When the second source op is a memory address, insertps doesn't use
25350     // countS and just gets an f32 from that address.
25351     unsigned DestIndex =
25352         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25353
25354     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25355
25356     // Create this as a scalar to vector to match the instruction pattern.
25357     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25358     // countS bits are ignored when loading from memory on insertps, which
25359     // means we don't need to explicitly set them to 0.
25360     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25361                        LoadScalarToVector, N->getOperand(2));
25362   }
25363   return SDValue();
25364 }
25365
25366 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25367   SDValue V0 = N->getOperand(0);
25368   SDValue V1 = N->getOperand(1);
25369   SDLoc DL(N);
25370   EVT VT = N->getValueType(0);
25371
25372   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25373   // operands and changing the mask to 1. This saves us a bunch of
25374   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25375   // x86InstrInfo knows how to commute this back after instruction selection
25376   // if it would help register allocation.
25377
25378   // TODO: If optimizing for size or a processor that doesn't suffer from
25379   // partial register update stalls, this should be transformed into a MOVSD
25380   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25381
25382   if (VT == MVT::v2f64)
25383     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25384       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25385         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25386         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25387       }
25388
25389   return SDValue();
25390 }
25391
25392 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25393 // as "sbb reg,reg", since it can be extended without zext and produces
25394 // an all-ones bit which is more useful than 0/1 in some cases.
25395 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25396                                MVT VT) {
25397   if (VT == MVT::i8)
25398     return DAG.getNode(ISD::AND, DL, VT,
25399                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25400                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25401                                    EFLAGS),
25402                        DAG.getConstant(1, DL, VT));
25403   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25404   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25405                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25406                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25407                                  EFLAGS));
25408 }
25409
25410 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25411 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25412                                    TargetLowering::DAGCombinerInfo &DCI,
25413                                    const X86Subtarget *Subtarget) {
25414   SDLoc DL(N);
25415   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25416   SDValue EFLAGS = N->getOperand(1);
25417
25418   if (CC == X86::COND_A) {
25419     // Try to convert COND_A into COND_B in an attempt to facilitate
25420     // materializing "setb reg".
25421     //
25422     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25423     // cannot take an immediate as its first operand.
25424     //
25425     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25426         EFLAGS.getValueType().isInteger() &&
25427         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25428       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25429                                    EFLAGS.getNode()->getVTList(),
25430                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25431       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25432       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25433     }
25434   }
25435
25436   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25437   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25438   // cases.
25439   if (CC == X86::COND_B)
25440     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25441
25442   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25443     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25444     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25445   }
25446
25447   return SDValue();
25448 }
25449
25450 // Optimize branch condition evaluation.
25451 //
25452 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25453                                     TargetLowering::DAGCombinerInfo &DCI,
25454                                     const X86Subtarget *Subtarget) {
25455   SDLoc DL(N);
25456   SDValue Chain = N->getOperand(0);
25457   SDValue Dest = N->getOperand(1);
25458   SDValue EFLAGS = N->getOperand(3);
25459   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25460
25461   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25462     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25463     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25464                        Flags);
25465   }
25466
25467   return SDValue();
25468 }
25469
25470 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25471                                                          SelectionDAG &DAG) {
25472   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25473   // optimize away operation when it's from a constant.
25474   //
25475   // The general transformation is:
25476   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25477   //       AND(VECTOR_CMP(x,y), constant2)
25478   //    constant2 = UNARYOP(constant)
25479
25480   // Early exit if this isn't a vector operation, the operand of the
25481   // unary operation isn't a bitwise AND, or if the sizes of the operations
25482   // aren't the same.
25483   EVT VT = N->getValueType(0);
25484   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25485       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25486       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25487     return SDValue();
25488
25489   // Now check that the other operand of the AND is a constant. We could
25490   // make the transformation for non-constant splats as well, but it's unclear
25491   // that would be a benefit as it would not eliminate any operations, just
25492   // perform one more step in scalar code before moving to the vector unit.
25493   if (BuildVectorSDNode *BV =
25494           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25495     // Bail out if the vector isn't a constant.
25496     if (!BV->isConstant())
25497       return SDValue();
25498
25499     // Everything checks out. Build up the new and improved node.
25500     SDLoc DL(N);
25501     EVT IntVT = BV->getValueType(0);
25502     // Create a new constant of the appropriate type for the transformed
25503     // DAG.
25504     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25505     // The AND node needs bitcasts to/from an integer vector type around it.
25506     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25507     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25508                                  N->getOperand(0)->getOperand(0), MaskConst);
25509     SDValue Res = DAG.getBitcast(VT, NewAnd);
25510     return Res;
25511   }
25512
25513   return SDValue();
25514 }
25515
25516 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25517                                         const X86Subtarget *Subtarget) {
25518   SDValue Op0 = N->getOperand(0);
25519   EVT VT = N->getValueType(0);
25520   EVT InVT = Op0.getValueType();
25521   EVT InSVT = InVT.getScalarType();
25522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25523
25524   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25525   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25526   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25527     SDLoc dl(N);
25528     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25529                                  InVT.getVectorNumElements());
25530     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25531
25532     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25533       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25534
25535     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25536   }
25537
25538   return SDValue();
25539 }
25540
25541 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25542                                         const X86Subtarget *Subtarget) {
25543   // First try to optimize away the conversion entirely when it's
25544   // conditionally from a constant. Vectors only.
25545   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25546     return Res;
25547
25548   // Now move on to more general possibilities.
25549   SDValue Op0 = N->getOperand(0);
25550   EVT VT = N->getValueType(0);
25551   EVT InVT = Op0.getValueType();
25552   EVT InSVT = InVT.getScalarType();
25553
25554   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25555   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25556   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25557     SDLoc dl(N);
25558     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25559                                  InVT.getVectorNumElements());
25560     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25561     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25562   }
25563
25564   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25565   // a 32-bit target where SSE doesn't support i64->FP operations.
25566   if (Op0.getOpcode() == ISD::LOAD) {
25567     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25568     EVT LdVT = Ld->getValueType(0);
25569
25570     // This transformation is not supported if the result type is f16
25571     if (VT == MVT::f16)
25572       return SDValue();
25573
25574     if (!Ld->isVolatile() && !VT.isVector() &&
25575         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25576         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25577       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25578           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25579       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25580       return FILDChain;
25581     }
25582   }
25583   return SDValue();
25584 }
25585
25586 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25587 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25588                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25589   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25590   // the result is either zero or one (depending on the input carry bit).
25591   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25592   if (X86::isZeroNode(N->getOperand(0)) &&
25593       X86::isZeroNode(N->getOperand(1)) &&
25594       // We don't have a good way to replace an EFLAGS use, so only do this when
25595       // dead right now.
25596       SDValue(N, 1).use_empty()) {
25597     SDLoc DL(N);
25598     EVT VT = N->getValueType(0);
25599     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25600     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25601                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25602                                            DAG.getConstant(X86::COND_B, DL,
25603                                                            MVT::i8),
25604                                            N->getOperand(2)),
25605                                DAG.getConstant(1, DL, VT));
25606     return DCI.CombineTo(N, Res1, CarryOut);
25607   }
25608
25609   return SDValue();
25610 }
25611
25612 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25613 //      (add Y, (setne X, 0)) -> sbb -1, Y
25614 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25615 //      (sub (setne X, 0), Y) -> adc -1, Y
25616 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25617   SDLoc DL(N);
25618
25619   // Look through ZExts.
25620   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25621   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25622     return SDValue();
25623
25624   SDValue SetCC = Ext.getOperand(0);
25625   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25626     return SDValue();
25627
25628   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25629   if (CC != X86::COND_E && CC != X86::COND_NE)
25630     return SDValue();
25631
25632   SDValue Cmp = SetCC.getOperand(1);
25633   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25634       !X86::isZeroNode(Cmp.getOperand(1)) ||
25635       !Cmp.getOperand(0).getValueType().isInteger())
25636     return SDValue();
25637
25638   SDValue CmpOp0 = Cmp.getOperand(0);
25639   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25640                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25641
25642   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25643   if (CC == X86::COND_NE)
25644     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25645                        DL, OtherVal.getValueType(), OtherVal,
25646                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25647                        NewCmp);
25648   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25649                      DL, OtherVal.getValueType(), OtherVal,
25650                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25651 }
25652
25653 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25654 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25655                                  const X86Subtarget *Subtarget) {
25656   EVT VT = N->getValueType(0);
25657   SDValue Op0 = N->getOperand(0);
25658   SDValue Op1 = N->getOperand(1);
25659
25660   // Try to synthesize horizontal adds from adds of shuffles.
25661   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25662        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25663       isHorizontalBinOp(Op0, Op1, true))
25664     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25665
25666   return OptimizeConditionalInDecrement(N, DAG);
25667 }
25668
25669 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25670                                  const X86Subtarget *Subtarget) {
25671   SDValue Op0 = N->getOperand(0);
25672   SDValue Op1 = N->getOperand(1);
25673
25674   // X86 can't encode an immediate LHS of a sub. See if we can push the
25675   // negation into a preceding instruction.
25676   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25677     // If the RHS of the sub is a XOR with one use and a constant, invert the
25678     // immediate. Then add one to the LHS of the sub so we can turn
25679     // X-Y -> X+~Y+1, saving one register.
25680     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25681         isa<ConstantSDNode>(Op1.getOperand(1))) {
25682       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25683       EVT VT = Op0.getValueType();
25684       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25685                                    Op1.getOperand(0),
25686                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25687       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25688                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25689     }
25690   }
25691
25692   // Try to synthesize horizontal adds from adds of shuffles.
25693   EVT VT = N->getValueType(0);
25694   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25695        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25696       isHorizontalBinOp(Op0, Op1, true))
25697     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25698
25699   return OptimizeConditionalInDecrement(N, DAG);
25700 }
25701
25702 /// performVZEXTCombine - Performs build vector combines
25703 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25704                                    TargetLowering::DAGCombinerInfo &DCI,
25705                                    const X86Subtarget *Subtarget) {
25706   SDLoc DL(N);
25707   MVT VT = N->getSimpleValueType(0);
25708   SDValue Op = N->getOperand(0);
25709   MVT OpVT = Op.getSimpleValueType();
25710   MVT OpEltVT = OpVT.getVectorElementType();
25711   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25712
25713   // (vzext (bitcast (vzext (x)) -> (vzext x)
25714   SDValue V = Op;
25715   while (V.getOpcode() == ISD::BITCAST)
25716     V = V.getOperand(0);
25717
25718   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25719     MVT InnerVT = V.getSimpleValueType();
25720     MVT InnerEltVT = InnerVT.getVectorElementType();
25721
25722     // If the element sizes match exactly, we can just do one larger vzext. This
25723     // is always an exact type match as vzext operates on integer types.
25724     if (OpEltVT == InnerEltVT) {
25725       assert(OpVT == InnerVT && "Types must match for vzext!");
25726       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25727     }
25728
25729     // The only other way we can combine them is if only a single element of the
25730     // inner vzext is used in the input to the outer vzext.
25731     if (InnerEltVT.getSizeInBits() < InputBits)
25732       return SDValue();
25733
25734     // In this case, the inner vzext is completely dead because we're going to
25735     // only look at bits inside of the low element. Just do the outer vzext on
25736     // a bitcast of the input to the inner.
25737     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25738   }
25739
25740   // Check if we can bypass extracting and re-inserting an element of an input
25741   // vector. Essentially:
25742   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25743   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25744       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25745       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25746     SDValue ExtractedV = V.getOperand(0);
25747     SDValue OrigV = ExtractedV.getOperand(0);
25748     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25749       if (ExtractIdx->getZExtValue() == 0) {
25750         MVT OrigVT = OrigV.getSimpleValueType();
25751         // Extract a subvector if necessary...
25752         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25753           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25754           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25755                                     OrigVT.getVectorNumElements() / Ratio);
25756           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25757                               DAG.getIntPtrConstant(0, DL));
25758         }
25759         Op = DAG.getBitcast(OpVT, OrigV);
25760         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25761       }
25762   }
25763
25764   return SDValue();
25765 }
25766
25767 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25768                                              DAGCombinerInfo &DCI) const {
25769   SelectionDAG &DAG = DCI.DAG;
25770   switch (N->getOpcode()) {
25771   default: break;
25772   case ISD::EXTRACT_VECTOR_ELT:
25773     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25774   case ISD::VSELECT:
25775   case ISD::SELECT:
25776   case X86ISD::SHRUNKBLEND:
25777     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25778   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25779   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25780   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25781   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25782   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25783   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25784   case ISD::SHL:
25785   case ISD::SRA:
25786   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25787   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25788   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25789   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25790   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25791   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25792   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25793   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25794   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25795   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25796   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25797   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25798   case X86ISD::FXOR:
25799   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25800   case X86ISD::FMIN:
25801   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25802   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25803   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25804   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25805   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25806   case ISD::ANY_EXTEND:
25807   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25808   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25809   case ISD::SIGN_EXTEND_INREG:
25810     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25811   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25812   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25813   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25814   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25815   case X86ISD::SHUFP:       // Handle all target specific shuffles
25816   case X86ISD::PALIGNR:
25817   case X86ISD::UNPCKH:
25818   case X86ISD::UNPCKL:
25819   case X86ISD::MOVHLPS:
25820   case X86ISD::MOVLHPS:
25821   case X86ISD::PSHUFB:
25822   case X86ISD::PSHUFD:
25823   case X86ISD::PSHUFHW:
25824   case X86ISD::PSHUFLW:
25825   case X86ISD::MOVSS:
25826   case X86ISD::MOVSD:
25827   case X86ISD::VPERMILPI:
25828   case X86ISD::VPERM2X128:
25829   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25830   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25831   case X86ISD::INSERTPS: {
25832     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25833       return PerformINSERTPSCombine(N, DAG, Subtarget);
25834     break;
25835   }
25836   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25837   }
25838
25839   return SDValue();
25840 }
25841
25842 /// isTypeDesirableForOp - Return true if the target has native support for
25843 /// the specified value type and it is 'desirable' to use the type for the
25844 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25845 /// instruction encodings are longer and some i16 instructions are slow.
25846 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25847   if (!isTypeLegal(VT))
25848     return false;
25849   if (VT != MVT::i16)
25850     return true;
25851
25852   switch (Opc) {
25853   default:
25854     return true;
25855   case ISD::LOAD:
25856   case ISD::SIGN_EXTEND:
25857   case ISD::ZERO_EXTEND:
25858   case ISD::ANY_EXTEND:
25859   case ISD::SHL:
25860   case ISD::SRL:
25861   case ISD::SUB:
25862   case ISD::ADD:
25863   case ISD::MUL:
25864   case ISD::AND:
25865   case ISD::OR:
25866   case ISD::XOR:
25867     return false;
25868   }
25869 }
25870
25871 /// IsDesirableToPromoteOp - This method query the target whether it is
25872 /// beneficial for dag combiner to promote the specified node. If true, it
25873 /// should return the desired promotion type by reference.
25874 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25875   EVT VT = Op.getValueType();
25876   if (VT != MVT::i16)
25877     return false;
25878
25879   bool Promote = false;
25880   bool Commute = false;
25881   switch (Op.getOpcode()) {
25882   default: break;
25883   case ISD::LOAD: {
25884     LoadSDNode *LD = cast<LoadSDNode>(Op);
25885     // If the non-extending load has a single use and it's not live out, then it
25886     // might be folded.
25887     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25888                                                      Op.hasOneUse()*/) {
25889       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25890              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25891         // The only case where we'd want to promote LOAD (rather then it being
25892         // promoted as an operand is when it's only use is liveout.
25893         if (UI->getOpcode() != ISD::CopyToReg)
25894           return false;
25895       }
25896     }
25897     Promote = true;
25898     break;
25899   }
25900   case ISD::SIGN_EXTEND:
25901   case ISD::ZERO_EXTEND:
25902   case ISD::ANY_EXTEND:
25903     Promote = true;
25904     break;
25905   case ISD::SHL:
25906   case ISD::SRL: {
25907     SDValue N0 = Op.getOperand(0);
25908     // Look out for (store (shl (load), x)).
25909     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25910       return false;
25911     Promote = true;
25912     break;
25913   }
25914   case ISD::ADD:
25915   case ISD::MUL:
25916   case ISD::AND:
25917   case ISD::OR:
25918   case ISD::XOR:
25919     Commute = true;
25920     // fallthrough
25921   case ISD::SUB: {
25922     SDValue N0 = Op.getOperand(0);
25923     SDValue N1 = Op.getOperand(1);
25924     if (!Commute && MayFoldLoad(N1))
25925       return false;
25926     // Avoid disabling potential load folding opportunities.
25927     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25928       return false;
25929     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25930       return false;
25931     Promote = true;
25932   }
25933   }
25934
25935   PVT = MVT::i32;
25936   return Promote;
25937 }
25938
25939 //===----------------------------------------------------------------------===//
25940 //                           X86 Inline Assembly Support
25941 //===----------------------------------------------------------------------===//
25942
25943 // Helper to match a string separated by whitespace.
25944 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25945   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25946
25947   for (StringRef Piece : Pieces) {
25948     if (!S.startswith(Piece)) // Check if the piece matches.
25949       return false;
25950
25951     S = S.substr(Piece.size());
25952     StringRef::size_type Pos = S.find_first_not_of(" \t");
25953     if (Pos == 0) // We matched a prefix.
25954       return false;
25955
25956     S = S.substr(Pos);
25957   }
25958
25959   return S.empty();
25960 }
25961
25962 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25963
25964   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25965     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25966         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25967         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25968
25969       if (AsmPieces.size() == 3)
25970         return true;
25971       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25972         return true;
25973     }
25974   }
25975   return false;
25976 }
25977
25978 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25979   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25980
25981   std::string AsmStr = IA->getAsmString();
25982
25983   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25984   if (!Ty || Ty->getBitWidth() % 16 != 0)
25985     return false;
25986
25987   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25988   SmallVector<StringRef, 4> AsmPieces;
25989   SplitString(AsmStr, AsmPieces, ";\n");
25990
25991   switch (AsmPieces.size()) {
25992   default: return false;
25993   case 1:
25994     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25995     // we will turn this bswap into something that will be lowered to logical
25996     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25997     // lower so don't worry about this.
25998     // bswap $0
25999     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26000         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26001         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26002         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26003         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26004         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26005       // No need to check constraints, nothing other than the equivalent of
26006       // "=r,0" would be valid here.
26007       return IntrinsicLowering::LowerToByteSwap(CI);
26008     }
26009
26010     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26011     if (CI->getType()->isIntegerTy(16) &&
26012         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26013         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26014          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26015       AsmPieces.clear();
26016       StringRef ConstraintsStr = IA->getConstraintString();
26017       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26018       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26019       if (clobbersFlagRegisters(AsmPieces))
26020         return IntrinsicLowering::LowerToByteSwap(CI);
26021     }
26022     break;
26023   case 3:
26024     if (CI->getType()->isIntegerTy(32) &&
26025         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26026         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26027         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26028         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26029       AsmPieces.clear();
26030       StringRef ConstraintsStr = IA->getConstraintString();
26031       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26032       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26033       if (clobbersFlagRegisters(AsmPieces))
26034         return IntrinsicLowering::LowerToByteSwap(CI);
26035     }
26036
26037     if (CI->getType()->isIntegerTy(64)) {
26038       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26039       if (Constraints.size() >= 2 &&
26040           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26041           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26042         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26043         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26044             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26045             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26046           return IntrinsicLowering::LowerToByteSwap(CI);
26047       }
26048     }
26049     break;
26050   }
26051   return false;
26052 }
26053
26054 /// getConstraintType - Given a constraint letter, return the type of
26055 /// constraint it is for this target.
26056 X86TargetLowering::ConstraintType
26057 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26058   if (Constraint.size() == 1) {
26059     switch (Constraint[0]) {
26060     case 'R':
26061     case 'q':
26062     case 'Q':
26063     case 'f':
26064     case 't':
26065     case 'u':
26066     case 'y':
26067     case 'x':
26068     case 'Y':
26069     case 'l':
26070       return C_RegisterClass;
26071     case 'a':
26072     case 'b':
26073     case 'c':
26074     case 'd':
26075     case 'S':
26076     case 'D':
26077     case 'A':
26078       return C_Register;
26079     case 'I':
26080     case 'J':
26081     case 'K':
26082     case 'L':
26083     case 'M':
26084     case 'N':
26085     case 'G':
26086     case 'C':
26087     case 'e':
26088     case 'Z':
26089       return C_Other;
26090     default:
26091       break;
26092     }
26093   }
26094   return TargetLowering::getConstraintType(Constraint);
26095 }
26096
26097 /// Examine constraint type and operand type and determine a weight value.
26098 /// This object must already have been set up with the operand type
26099 /// and the current alternative constraint selected.
26100 TargetLowering::ConstraintWeight
26101   X86TargetLowering::getSingleConstraintMatchWeight(
26102     AsmOperandInfo &info, const char *constraint) const {
26103   ConstraintWeight weight = CW_Invalid;
26104   Value *CallOperandVal = info.CallOperandVal;
26105     // If we don't have a value, we can't do a match,
26106     // but allow it at the lowest weight.
26107   if (!CallOperandVal)
26108     return CW_Default;
26109   Type *type = CallOperandVal->getType();
26110   // Look at the constraint type.
26111   switch (*constraint) {
26112   default:
26113     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26114   case 'R':
26115   case 'q':
26116   case 'Q':
26117   case 'a':
26118   case 'b':
26119   case 'c':
26120   case 'd':
26121   case 'S':
26122   case 'D':
26123   case 'A':
26124     if (CallOperandVal->getType()->isIntegerTy())
26125       weight = CW_SpecificReg;
26126     break;
26127   case 'f':
26128   case 't':
26129   case 'u':
26130     if (type->isFloatingPointTy())
26131       weight = CW_SpecificReg;
26132     break;
26133   case 'y':
26134     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26135       weight = CW_SpecificReg;
26136     break;
26137   case 'x':
26138   case 'Y':
26139     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26140         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26141       weight = CW_Register;
26142     break;
26143   case 'I':
26144     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26145       if (C->getZExtValue() <= 31)
26146         weight = CW_Constant;
26147     }
26148     break;
26149   case 'J':
26150     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26151       if (C->getZExtValue() <= 63)
26152         weight = CW_Constant;
26153     }
26154     break;
26155   case 'K':
26156     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26157       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26158         weight = CW_Constant;
26159     }
26160     break;
26161   case 'L':
26162     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26163       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26164         weight = CW_Constant;
26165     }
26166     break;
26167   case 'M':
26168     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26169       if (C->getZExtValue() <= 3)
26170         weight = CW_Constant;
26171     }
26172     break;
26173   case 'N':
26174     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26175       if (C->getZExtValue() <= 0xff)
26176         weight = CW_Constant;
26177     }
26178     break;
26179   case 'G':
26180   case 'C':
26181     if (isa<ConstantFP>(CallOperandVal)) {
26182       weight = CW_Constant;
26183     }
26184     break;
26185   case 'e':
26186     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26187       if ((C->getSExtValue() >= -0x80000000LL) &&
26188           (C->getSExtValue() <= 0x7fffffffLL))
26189         weight = CW_Constant;
26190     }
26191     break;
26192   case 'Z':
26193     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26194       if (C->getZExtValue() <= 0xffffffff)
26195         weight = CW_Constant;
26196     }
26197     break;
26198   }
26199   return weight;
26200 }
26201
26202 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26203 /// with another that has more specific requirements based on the type of the
26204 /// corresponding operand.
26205 const char *X86TargetLowering::
26206 LowerXConstraint(EVT ConstraintVT) const {
26207   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26208   // 'f' like normal targets.
26209   if (ConstraintVT.isFloatingPoint()) {
26210     if (Subtarget->hasSSE2())
26211       return "Y";
26212     if (Subtarget->hasSSE1())
26213       return "x";
26214   }
26215
26216   return TargetLowering::LowerXConstraint(ConstraintVT);
26217 }
26218
26219 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26220 /// vector.  If it is invalid, don't add anything to Ops.
26221 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26222                                                      std::string &Constraint,
26223                                                      std::vector<SDValue>&Ops,
26224                                                      SelectionDAG &DAG) const {
26225   SDValue Result;
26226
26227   // Only support length 1 constraints for now.
26228   if (Constraint.length() > 1) return;
26229
26230   char ConstraintLetter = Constraint[0];
26231   switch (ConstraintLetter) {
26232   default: break;
26233   case 'I':
26234     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26235       if (C->getZExtValue() <= 31) {
26236         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26237                                        Op.getValueType());
26238         break;
26239       }
26240     }
26241     return;
26242   case 'J':
26243     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26244       if (C->getZExtValue() <= 63) {
26245         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26246                                        Op.getValueType());
26247         break;
26248       }
26249     }
26250     return;
26251   case 'K':
26252     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26253       if (isInt<8>(C->getSExtValue())) {
26254         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26255                                        Op.getValueType());
26256         break;
26257       }
26258     }
26259     return;
26260   case 'L':
26261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26262       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26263           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26264         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26265                                        Op.getValueType());
26266         break;
26267       }
26268     }
26269     return;
26270   case 'M':
26271     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26272       if (C->getZExtValue() <= 3) {
26273         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26274                                        Op.getValueType());
26275         break;
26276       }
26277     }
26278     return;
26279   case 'N':
26280     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26281       if (C->getZExtValue() <= 255) {
26282         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26283                                        Op.getValueType());
26284         break;
26285       }
26286     }
26287     return;
26288   case 'O':
26289     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26290       if (C->getZExtValue() <= 127) {
26291         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26292                                        Op.getValueType());
26293         break;
26294       }
26295     }
26296     return;
26297   case 'e': {
26298     // 32-bit signed value
26299     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26300       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26301                                            C->getSExtValue())) {
26302         // Widen to 64 bits here to get it sign extended.
26303         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26304         break;
26305       }
26306     // FIXME gcc accepts some relocatable values here too, but only in certain
26307     // memory models; it's complicated.
26308     }
26309     return;
26310   }
26311   case 'Z': {
26312     // 32-bit unsigned value
26313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26314       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26315                                            C->getZExtValue())) {
26316         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26317                                        Op.getValueType());
26318         break;
26319       }
26320     }
26321     // FIXME gcc accepts some relocatable values here too, but only in certain
26322     // memory models; it's complicated.
26323     return;
26324   }
26325   case 'i': {
26326     // Literal immediates are always ok.
26327     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26328       // Widen to 64 bits here to get it sign extended.
26329       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26330       break;
26331     }
26332
26333     // In any sort of PIC mode addresses need to be computed at runtime by
26334     // adding in a register or some sort of table lookup.  These can't
26335     // be used as immediates.
26336     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26337       return;
26338
26339     // If we are in non-pic codegen mode, we allow the address of a global (with
26340     // an optional displacement) to be used with 'i'.
26341     GlobalAddressSDNode *GA = nullptr;
26342     int64_t Offset = 0;
26343
26344     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26345     while (1) {
26346       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26347         Offset += GA->getOffset();
26348         break;
26349       } else if (Op.getOpcode() == ISD::ADD) {
26350         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26351           Offset += C->getZExtValue();
26352           Op = Op.getOperand(0);
26353           continue;
26354         }
26355       } else if (Op.getOpcode() == ISD::SUB) {
26356         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26357           Offset += -C->getZExtValue();
26358           Op = Op.getOperand(0);
26359           continue;
26360         }
26361       }
26362
26363       // Otherwise, this isn't something we can handle, reject it.
26364       return;
26365     }
26366
26367     const GlobalValue *GV = GA->getGlobal();
26368     // If we require an extra load to get this address, as in PIC mode, we
26369     // can't accept it.
26370     if (isGlobalStubReference(
26371             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26372       return;
26373
26374     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26375                                         GA->getValueType(0), Offset);
26376     break;
26377   }
26378   }
26379
26380   if (Result.getNode()) {
26381     Ops.push_back(Result);
26382     return;
26383   }
26384   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26385 }
26386
26387 std::pair<unsigned, const TargetRegisterClass *>
26388 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26389                                                 StringRef Constraint,
26390                                                 MVT VT) const {
26391   // First, see if this is a constraint that directly corresponds to an LLVM
26392   // register class.
26393   if (Constraint.size() == 1) {
26394     // GCC Constraint Letters
26395     switch (Constraint[0]) {
26396     default: break;
26397       // TODO: Slight differences here in allocation order and leaving
26398       // RIP in the class. Do they matter any more here than they do
26399       // in the normal allocation?
26400     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26401       if (Subtarget->is64Bit()) {
26402         if (VT == MVT::i32 || VT == MVT::f32)
26403           return std::make_pair(0U, &X86::GR32RegClass);
26404         if (VT == MVT::i16)
26405           return std::make_pair(0U, &X86::GR16RegClass);
26406         if (VT == MVT::i8 || VT == MVT::i1)
26407           return std::make_pair(0U, &X86::GR8RegClass);
26408         if (VT == MVT::i64 || VT == MVT::f64)
26409           return std::make_pair(0U, &X86::GR64RegClass);
26410         break;
26411       }
26412       // 32-bit fallthrough
26413     case 'Q':   // Q_REGS
26414       if (VT == MVT::i32 || VT == MVT::f32)
26415         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26416       if (VT == MVT::i16)
26417         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26418       if (VT == MVT::i8 || VT == MVT::i1)
26419         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26420       if (VT == MVT::i64)
26421         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26422       break;
26423     case 'r':   // GENERAL_REGS
26424     case 'l':   // INDEX_REGS
26425       if (VT == MVT::i8 || VT == MVT::i1)
26426         return std::make_pair(0U, &X86::GR8RegClass);
26427       if (VT == MVT::i16)
26428         return std::make_pair(0U, &X86::GR16RegClass);
26429       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26430         return std::make_pair(0U, &X86::GR32RegClass);
26431       return std::make_pair(0U, &X86::GR64RegClass);
26432     case 'R':   // LEGACY_REGS
26433       if (VT == MVT::i8 || VT == MVT::i1)
26434         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26435       if (VT == MVT::i16)
26436         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26437       if (VT == MVT::i32 || !Subtarget->is64Bit())
26438         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26439       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26440     case 'f':  // FP Stack registers.
26441       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26442       // value to the correct fpstack register class.
26443       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26444         return std::make_pair(0U, &X86::RFP32RegClass);
26445       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26446         return std::make_pair(0U, &X86::RFP64RegClass);
26447       return std::make_pair(0U, &X86::RFP80RegClass);
26448     case 'y':   // MMX_REGS if MMX allowed.
26449       if (!Subtarget->hasMMX()) break;
26450       return std::make_pair(0U, &X86::VR64RegClass);
26451     case 'Y':   // SSE_REGS if SSE2 allowed
26452       if (!Subtarget->hasSSE2()) break;
26453       // FALL THROUGH.
26454     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26455       if (!Subtarget->hasSSE1()) break;
26456
26457       switch (VT.SimpleTy) {
26458       default: break;
26459       // Scalar SSE types.
26460       case MVT::f32:
26461       case MVT::i32:
26462         return std::make_pair(0U, &X86::FR32RegClass);
26463       case MVT::f64:
26464       case MVT::i64:
26465         return std::make_pair(0U, &X86::FR64RegClass);
26466       // Vector types.
26467       case MVT::v16i8:
26468       case MVT::v8i16:
26469       case MVT::v4i32:
26470       case MVT::v2i64:
26471       case MVT::v4f32:
26472       case MVT::v2f64:
26473         return std::make_pair(0U, &X86::VR128RegClass);
26474       // AVX types.
26475       case MVT::v32i8:
26476       case MVT::v16i16:
26477       case MVT::v8i32:
26478       case MVT::v4i64:
26479       case MVT::v8f32:
26480       case MVT::v4f64:
26481         return std::make_pair(0U, &X86::VR256RegClass);
26482       case MVT::v8f64:
26483       case MVT::v16f32:
26484       case MVT::v16i32:
26485       case MVT::v8i64:
26486         return std::make_pair(0U, &X86::VR512RegClass);
26487       }
26488       break;
26489     }
26490   }
26491
26492   // Use the default implementation in TargetLowering to convert the register
26493   // constraint into a member of a register class.
26494   std::pair<unsigned, const TargetRegisterClass*> Res;
26495   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26496
26497   // Not found as a standard register?
26498   if (!Res.second) {
26499     // Map st(0) -> st(7) -> ST0
26500     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26501         tolower(Constraint[1]) == 's' &&
26502         tolower(Constraint[2]) == 't' &&
26503         Constraint[3] == '(' &&
26504         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26505         Constraint[5] == ')' &&
26506         Constraint[6] == '}') {
26507
26508       Res.first = X86::FP0+Constraint[4]-'0';
26509       Res.second = &X86::RFP80RegClass;
26510       return Res;
26511     }
26512
26513     // GCC allows "st(0)" to be called just plain "st".
26514     if (StringRef("{st}").equals_lower(Constraint)) {
26515       Res.first = X86::FP0;
26516       Res.second = &X86::RFP80RegClass;
26517       return Res;
26518     }
26519
26520     // flags -> EFLAGS
26521     if (StringRef("{flags}").equals_lower(Constraint)) {
26522       Res.first = X86::EFLAGS;
26523       Res.second = &X86::CCRRegClass;
26524       return Res;
26525     }
26526
26527     // 'A' means EAX + EDX.
26528     if (Constraint == "A") {
26529       Res.first = X86::EAX;
26530       Res.second = &X86::GR32_ADRegClass;
26531       return Res;
26532     }
26533     return Res;
26534   }
26535
26536   // Otherwise, check to see if this is a register class of the wrong value
26537   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26538   // turn into {ax},{dx}.
26539   // MVT::Other is used to specify clobber names.
26540   if (Res.second->hasType(VT) || VT == MVT::Other)
26541     return Res;   // Correct type already, nothing to do.
26542
26543   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26544   // return "eax". This should even work for things like getting 64bit integer
26545   // registers when given an f64 type.
26546   const TargetRegisterClass *Class = Res.second;
26547   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26548       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26549     unsigned Size = VT.getSizeInBits();
26550     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26551                                   : Size == 16 ? MVT::i16
26552                                   : Size == 32 ? MVT::i32
26553                                   : Size == 64 ? MVT::i64
26554                                   : MVT::Other;
26555     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26556     if (DestReg > 0) {
26557       Res.first = DestReg;
26558       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26559                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26560                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26561                  : &X86::GR64RegClass;
26562       assert(Res.second->contains(Res.first) && "Register in register class");
26563     } else {
26564       // No register found/type mismatch.
26565       Res.first = 0;
26566       Res.second = nullptr;
26567     }
26568   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26569              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26570              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26571              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26572              Class == &X86::VR512RegClass) {
26573     // Handle references to XMM physical registers that got mapped into the
26574     // wrong class.  This can happen with constraints like {xmm0} where the
26575     // target independent register mapper will just pick the first match it can
26576     // find, ignoring the required type.
26577
26578     if (VT == MVT::f32 || VT == MVT::i32)
26579       Res.second = &X86::FR32RegClass;
26580     else if (VT == MVT::f64 || VT == MVT::i64)
26581       Res.second = &X86::FR64RegClass;
26582     else if (X86::VR128RegClass.hasType(VT))
26583       Res.second = &X86::VR128RegClass;
26584     else if (X86::VR256RegClass.hasType(VT))
26585       Res.second = &X86::VR256RegClass;
26586     else if (X86::VR512RegClass.hasType(VT))
26587       Res.second = &X86::VR512RegClass;
26588     else {
26589       // Type mismatch and not a clobber: Return an error;
26590       Res.first = 0;
26591       Res.second = nullptr;
26592     }
26593   }
26594
26595   return Res;
26596 }
26597
26598 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26599                                             const AddrMode &AM, Type *Ty,
26600                                             unsigned AS) const {
26601   // Scaling factors are not free at all.
26602   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26603   // will take 2 allocations in the out of order engine instead of 1
26604   // for plain addressing mode, i.e. inst (reg1).
26605   // E.g.,
26606   // vaddps (%rsi,%drx), %ymm0, %ymm1
26607   // Requires two allocations (one for the load, one for the computation)
26608   // whereas:
26609   // vaddps (%rsi), %ymm0, %ymm1
26610   // Requires just 1 allocation, i.e., freeing allocations for other operations
26611   // and having less micro operations to execute.
26612   //
26613   // For some X86 architectures, this is even worse because for instance for
26614   // stores, the complex addressing mode forces the instruction to use the
26615   // "load" ports instead of the dedicated "store" port.
26616   // E.g., on Haswell:
26617   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26618   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26619   if (isLegalAddressingMode(DL, AM, Ty, AS))
26620     // Scale represents reg2 * scale, thus account for 1
26621     // as soon as we use a second register.
26622     return AM.Scale != 0;
26623   return -1;
26624 }
26625
26626 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26627   // Integer division on x86 is expensive. However, when aggressively optimizing
26628   // for code size, we prefer to use a div instruction, as it is usually smaller
26629   // than the alternative sequence.
26630   // The exception to this is vector division. Since x86 doesn't have vector
26631   // integer division, leaving the division as-is is a loss even in terms of
26632   // size, because it will have to be scalarized, while the alternative code
26633   // sequence can be performed in vector form.
26634   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26635                                    Attribute::MinSize);
26636   return OptSize && !VT.isVector();
26637 }