AVX512: Implement instructions encoding, lowering and intrinsics
[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
308   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
309     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
310     // is. We should promote the value to 64-bits to solve this.
311     // This is what the CRT headers do - `fmodf` is an inline header
312     // function casting to f64 and calling `fmod`.
313     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
314   } else {
315     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
316   }
317
318   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
319   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
320   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
321
322   // Promote the i8 variants and force them on up to i32 which has a shorter
323   // encoding.
324   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
326   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
327   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
328   if (Subtarget->hasBMI()) {
329     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
330     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
331     if (Subtarget->is64Bit())
332       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
333   } else {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
335     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
336     if (Subtarget->is64Bit())
337       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
338   }
339
340   if (Subtarget->hasLZCNT()) {
341     // When promoting the i8 variants, force them to i32 for a shorter
342     // encoding.
343     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
346     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
348     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
351   } else {
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
353     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
354     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
358     if (Subtarget->is64Bit()) {
359       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
360       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
361     }
362   }
363
364   // Special handling for half-precision floating point conversions.
365   // If we don't have F16C support, then lower half float conversions
366   // into library calls.
367   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
368     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
369     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370   }
371
372   // There's never any support for operations beyond MVT::f32.
373   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
374   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
375   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
376   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
377
378   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
382   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
384
385   if (Subtarget->hasPOPCNT()) {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
387   } else {
388     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
389     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
390     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
391     if (Subtarget->is64Bit())
392       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
393   }
394
395   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
396
397   if (!Subtarget->hasMOVBE())
398     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
399
400   // These should be promoted to a larger select which is supported.
401   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
402   // X86 wants to expand cmov itself.
403   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
404   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
410   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
417     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
418   }
419   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
420   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
421   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
422   // support continuation, user-level threading, and etc.. As a result, no
423   // other SjLj exception interfaces are implemented and please don't build
424   // your own exception handling based on them.
425   // LLVM/Clang supports zero-cost DWARF exception handling.
426   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
427   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
428
429   // Darwin ABI issue.
430   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
431   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
432   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
433   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
434   if (Subtarget->is64Bit())
435     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
436   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
437   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
438   if (Subtarget->is64Bit()) {
439     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
440     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
441     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
442     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
443     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
444   }
445   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
446   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
447   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
448   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
449   if (Subtarget->is64Bit()) {
450     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
451     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
452     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
453   }
454
455   if (Subtarget->hasSSE1())
456     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
457
458   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
459
460   // Expand certain atomics
461   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
462     MVT VT = IntVTs[i];
463     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
464     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
465     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
466   }
467
468   if (Subtarget->hasCmpxchg16b()) {
469     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
470   }
471
472   // FIXME - use subtarget debug flags
473   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
474       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
475     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
476   }
477
478   if (Subtarget->isTarget64BitLP64()) {
479     setExceptionPointerRegister(X86::RAX);
480     setExceptionSelectorRegister(X86::RDX);
481   } else {
482     setExceptionPointerRegister(X86::EAX);
483     setExceptionSelectorRegister(X86::EDX);
484   }
485   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
486   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
487
488   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
489   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
490
491   setOperationAction(ISD::TRAP, MVT::Other, Legal);
492   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
493
494   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
495   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
496   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
497   if (Subtarget->is64Bit()) {
498     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
499     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
500   } else {
501     // TargetInfo::CharPtrBuiltinVaList
502     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
503     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
504   }
505
506   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
507   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
508
509   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
510
511   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
512   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
513   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
514
515   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
516     // f32 and f64 use SSE.
517     // Set up the FP register classes.
518     addRegisterClass(MVT::f32, &X86::FR32RegClass);
519     addRegisterClass(MVT::f64, &X86::FR64RegClass);
520
521     // Use ANDPD to simulate FABS.
522     setOperationAction(ISD::FABS , MVT::f64, Custom);
523     setOperationAction(ISD::FABS , MVT::f32, Custom);
524
525     // Use XORP to simulate FNEG.
526     setOperationAction(ISD::FNEG , MVT::f64, Custom);
527     setOperationAction(ISD::FNEG , MVT::f32, Custom);
528
529     // Use ANDPD and ORPD to simulate FCOPYSIGN.
530     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
531     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
532
533     // Lower this to FGETSIGNx86 plus an AND.
534     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
535     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
536
537     // We don't support sin/cos/fmod
538     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
539     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
540     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
541     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
542     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
543     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
544
545     // Expand FP immediates into loads from the stack, except for the special
546     // cases we handle.
547     addLegalFPImmediate(APFloat(+0.0)); // xorpd
548     addLegalFPImmediate(APFloat(+0.0f)); // xorps
549   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
550     // Use SSE for f32, x87 for f64.
551     // Set up the FP register classes.
552     addRegisterClass(MVT::f32, &X86::FR32RegClass);
553     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554
555     // Use ANDPS to simulate FABS.
556     setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558     // Use XORP to simulate FNEG.
559     setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
562
563     // Use ANDPS and ORPS to simulate FCOPYSIGN.
564     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
565     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566
567     // We don't support sin/cos/fmod
568     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
569     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
570     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571
572     // Special cases we handle for FP constants.
573     addLegalFPImmediate(APFloat(+0.0f)); // xorps
574     addLegalFPImmediate(APFloat(+0.0)); // FLD0
575     addLegalFPImmediate(APFloat(+1.0)); // FLD1
576     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
577     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578
579     if (!TM.Options.UnsafeFPMath) {
580       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
581       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
582       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
583     }
584   } else if (!Subtarget->useSoftFloat()) {
585     // f32 and f64 in x87.
586     // Set up the FP register classes.
587     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
588     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589
590     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
591     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
594
595     if (!TM.Options.UnsafeFPMath) {
596       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
597       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
602     }
603     addLegalFPImmediate(APFloat(+0.0)); // FLD0
604     addLegalFPImmediate(APFloat(+1.0)); // FLD1
605     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
611   }
612
613   // We don't support FMA.
614   setOperationAction(ISD::FMA, MVT::f64, Expand);
615   setOperationAction(ISD::FMA, MVT::f32, Expand);
616
617   // Long double always uses X87.
618   if (!Subtarget->useSoftFloat()) {
619     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
620     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
622     {
623       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
624       addLegalFPImmediate(TmpFlt);  // FLD0
625       TmpFlt.changeSign();
626       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
627
628       bool ignored;
629       APFloat TmpFlt2(+1.0);
630       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
631                       &ignored);
632       addLegalFPImmediate(TmpFlt2);  // FLD1
633       TmpFlt2.changeSign();
634       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
635     }
636
637     if (!TM.Options.UnsafeFPMath) {
638       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
639       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
640       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
641     }
642
643     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
644     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
645     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
646     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
647     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
648     setOperationAction(ISD::FMA, MVT::f80, Expand);
649   }
650
651   // Always use a library call for pow.
652   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
655
656   setOperationAction(ISD::FLOG, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
661   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
662   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
663
664   // First set operation action for all vector types to either promote
665   // (for widening) or expand (for scalarization). Then we will selectively
666   // turn on ones that can be effectively codegen'd.
667   for (MVT VT : MVT::vector_valuetypes()) {
668     setOperationAction(ISD::ADD , VT, Expand);
669     setOperationAction(ISD::SUB , VT, Expand);
670     setOperationAction(ISD::FADD, VT, Expand);
671     setOperationAction(ISD::FNEG, VT, Expand);
672     setOperationAction(ISD::FSUB, VT, Expand);
673     setOperationAction(ISD::MUL , VT, Expand);
674     setOperationAction(ISD::FMUL, VT, Expand);
675     setOperationAction(ISD::SDIV, VT, Expand);
676     setOperationAction(ISD::UDIV, VT, Expand);
677     setOperationAction(ISD::FDIV, VT, Expand);
678     setOperationAction(ISD::SREM, VT, Expand);
679     setOperationAction(ISD::UREM, VT, Expand);
680     setOperationAction(ISD::LOAD, VT, Expand);
681     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
682     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
683     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
684     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::FABS, VT, Expand);
687     setOperationAction(ISD::FSIN, VT, Expand);
688     setOperationAction(ISD::FSINCOS, VT, Expand);
689     setOperationAction(ISD::FCOS, VT, Expand);
690     setOperationAction(ISD::FSINCOS, VT, Expand);
691     setOperationAction(ISD::FREM, VT, Expand);
692     setOperationAction(ISD::FMA,  VT, Expand);
693     setOperationAction(ISD::FPOWI, VT, Expand);
694     setOperationAction(ISD::FSQRT, VT, Expand);
695     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
696     setOperationAction(ISD::FFLOOR, VT, Expand);
697     setOperationAction(ISD::FCEIL, VT, Expand);
698     setOperationAction(ISD::FTRUNC, VT, Expand);
699     setOperationAction(ISD::FRINT, VT, Expand);
700     setOperationAction(ISD::FNEARBYINT, VT, Expand);
701     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
702     setOperationAction(ISD::MULHS, VT, Expand);
703     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704     setOperationAction(ISD::MULHU, VT, Expand);
705     setOperationAction(ISD::SDIVREM, VT, Expand);
706     setOperationAction(ISD::UDIVREM, VT, Expand);
707     setOperationAction(ISD::FPOW, VT, Expand);
708     setOperationAction(ISD::CTPOP, VT, Expand);
709     setOperationAction(ISD::CTTZ, VT, Expand);
710     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
711     setOperationAction(ISD::CTLZ, VT, Expand);
712     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
713     setOperationAction(ISD::SHL, VT, Expand);
714     setOperationAction(ISD::SRA, VT, Expand);
715     setOperationAction(ISD::SRL, VT, Expand);
716     setOperationAction(ISD::ROTL, VT, Expand);
717     setOperationAction(ISD::ROTR, VT, Expand);
718     setOperationAction(ISD::BSWAP, VT, Expand);
719     setOperationAction(ISD::SETCC, VT, Expand);
720     setOperationAction(ISD::FLOG, VT, Expand);
721     setOperationAction(ISD::FLOG2, VT, Expand);
722     setOperationAction(ISD::FLOG10, VT, Expand);
723     setOperationAction(ISD::FEXP, VT, Expand);
724     setOperationAction(ISD::FEXP2, VT, Expand);
725     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
726     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
727     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
730     setOperationAction(ISD::TRUNCATE, VT, Expand);
731     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
732     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
733     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
734     setOperationAction(ISD::VSELECT, VT, Expand);
735     setOperationAction(ISD::SELECT_CC, VT, Expand);
736     for (MVT InnerVT : MVT::vector_valuetypes()) {
737       setTruncStoreAction(InnerVT, VT, Expand);
738
739       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
740       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
741
742       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
743       // types, we have to deal with them whether we ask for Expansion or not.
744       // Setting Expand causes its own optimisation problems though, so leave
745       // them legal.
746       if (VT.getVectorElementType() == MVT::i1)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748
749       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
750       // split/scalarized right now.
751       if (VT.getVectorElementType() == MVT::f16)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753     }
754   }
755
756   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
757   // with -msoft-float, disable use of MMX as well.
758   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
759     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
760     // No operations on x86mmx supported, everything uses intrinsics.
761   }
762
763   // MMX-sized vectors (other than x86mmx) are expected to be expanded
764   // into smaller operations.
765   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
766     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
767     setOperationAction(ISD::AND,                MMXTy,      Expand);
768     setOperationAction(ISD::OR,                 MMXTy,      Expand);
769     setOperationAction(ISD::XOR,                MMXTy,      Expand);
770     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
771     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
772     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
773   }
774   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
775
776   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
777     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
778
779     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
784     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
785     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
786     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
787     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
788     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
789     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
790     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
791     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
792     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
793   }
794
795   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
796     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
797
798     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
799     // registers cannot be used even for integer operations.
800     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
801     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
802     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
803     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
804
805     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
806     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
807     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
808     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
809     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
810     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
811     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
812     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
815     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
816     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
817     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
818     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
819     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
821     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
827     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
828
829     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
830     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
831     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
832     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
849
850     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
851     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
852     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
853     // ISD::CTTZ v2i64 - scalarization is faster.
854     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
855     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
856     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
857     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
858
859     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
860     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
861       MVT VT = (MVT::SimpleValueType)i;
862       // Do not attempt to custom lower non-power-of-2 vectors
863       if (!isPowerOf2_32(VT.getVectorNumElements()))
864         continue;
865       // Do not attempt to custom lower non-128-bit vectors
866       if (!VT.is128BitVector())
867         continue;
868       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
869       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
870       setOperationAction(ISD::VSELECT,            VT, Custom);
871       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
872     }
873
874     // We support custom legalizing of sext and anyext loads for specific
875     // memory vector types which we can load as a scalar (or sequence of
876     // scalars) and extend in-register to a legal 128-bit vector type. For sext
877     // loads these must work with a single scalar load.
878     for (MVT VT : MVT::integer_vector_valuetypes()) {
879       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
882       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
883       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
884       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
885       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
886       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
887       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
888     }
889
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
891     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
893     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
894     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
895     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
897     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
898
899     if (Subtarget->is64Bit()) {
900       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
901       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
902     }
903
904     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
905     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
906       MVT VT = (MVT::SimpleValueType)i;
907
908       // Do not attempt to promote non-128-bit vectors
909       if (!VT.is128BitVector())
910         continue;
911
912       setOperationAction(ISD::AND,    VT, Promote);
913       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
914       setOperationAction(ISD::OR,     VT, Promote);
915       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
916       setOperationAction(ISD::XOR,    VT, Promote);
917       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
918       setOperationAction(ISD::LOAD,   VT, Promote);
919       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
920       setOperationAction(ISD::SELECT, VT, Promote);
921       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
922     }
923
924     // Custom lower v2i64 and v2f64 selects.
925     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
926     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
927     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
929
930     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
931     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
932
933     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
934
935     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
936     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
937     // As there is no 64-bit GPR available, we need build a special custom
938     // sequence to convert from v2i32 to v2f32.
939     if (!Subtarget->is64Bit())
940       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
941
942     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
943     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
944
945     for (MVT VT : MVT::fp_vector_valuetypes())
946       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
947
948     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
949     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
950     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
951   }
952
953   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
954     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
955       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
956       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
957       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
958       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
959       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
960     }
961
962     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
963     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
964     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
965     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
966     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
967     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
968     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
969     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
970
971     // FIXME: Do we need to handle scalar-to-vector here?
972     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
973
974     // We directly match byte blends in the backend as they match the VSELECT
975     // condition form.
976     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
977
978     // SSE41 brings specific instructions for doing vector sign extend even in
979     // cases where we don't have SRA.
980     for (MVT VT : MVT::integer_vector_valuetypes()) {
981       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
982       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
983       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
984     }
985
986     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
987     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
988     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
989     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
990     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
993
994     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
995     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
996     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
997     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1000
1001     // i8 and i16 vectors are custom because the source register and source
1002     // source memory operand types are not the same width.  f32 vectors are
1003     // custom since the immediate controlling the insert encodes additional
1004     // information.
1005     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1009
1010     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014
1015     // FIXME: these should be Legal, but that's only for the case where
1016     // the index is constant.  For now custom expand to deal with that.
1017     if (Subtarget->is64Bit()) {
1018       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1019       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020     }
1021   }
1022
1023   if (Subtarget->hasSSE2()) {
1024     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1025     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1026     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1027
1028     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1029     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1030
1031     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1032     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1033
1034     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1035     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1036
1037     // In the customized shift lowering, the legal cases in AVX2 will be
1038     // recognized.
1039     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1040     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1041
1042     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1043     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1044
1045     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1046     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1047   }
1048
1049   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1050     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1051     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1052     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1053     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1055     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1056
1057     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1058     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1060
1061     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1063     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1064     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1065     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1066     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1067     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1068     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1069     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1070     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1071     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1072     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1073
1074     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1077     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1079     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1080     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1081     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1082     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1083     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1084     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1085     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1086
1087     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1088     // even though v8i16 is a legal type.
1089     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1090     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1091     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1092
1093     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1094     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1095     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1096
1097     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1098     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1099
1100     for (MVT VT : MVT::fp_vector_valuetypes())
1101       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1102
1103     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1110     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1111
1112     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1113     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1114     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1115     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1116
1117     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1118     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1119     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1120
1121     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1122     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1123     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1124     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1125     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1126     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1127     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1128     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1129     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1130     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1131     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1132     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1133
1134     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1135     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1136     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1137     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1138
1139     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1140     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1141     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1142     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1143     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1144     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1145     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1146     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1147
1148     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1149       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1150       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1151       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1152       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1153       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1154       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1155     }
1156
1157     if (Subtarget->hasInt256()) {
1158       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1159       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1160       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1161       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1162
1163       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1164       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1165       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1166       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1167
1168       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1169       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1170       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1171       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1172
1173       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1174       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1175       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1176       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1177
1178       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1179       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1180       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1181       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1182       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1183       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1184       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1185       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1186       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1187       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1188       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1189       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1190
1191       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1192       // when we have a 256bit-wide blend with immediate.
1193       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1194
1195       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1196       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1197       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1198       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1199       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1201       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1202
1203       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1204       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1205       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1206       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1208       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1209     } else {
1210       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1211       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1212       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1213       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1214
1215       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1216       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1217       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1218       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1219
1220       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1221       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1223       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1224
1225       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1226       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1227       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1228       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1229       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1230       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1231       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1232       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1233       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1234       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1235       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1236       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1237     }
1238
1239     // In the customized shift lowering, the legal cases in AVX2 will be
1240     // recognized.
1241     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1242     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1243
1244     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1245     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1246
1247     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1248     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1249
1250     // Custom lower several nodes for 256-bit types.
1251     for (MVT VT : MVT::vector_valuetypes()) {
1252       if (VT.getScalarSizeInBits() >= 32) {
1253         setOperationAction(ISD::MLOAD,  VT, Legal);
1254         setOperationAction(ISD::MSTORE, VT, Legal);
1255       }
1256       // Extract subvector is special because the value type
1257       // (result) is 128-bit but the source is 256-bit wide.
1258       if (VT.is128BitVector()) {
1259         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1260       }
1261       // Do not attempt to custom lower other non-256-bit vectors
1262       if (!VT.is256BitVector())
1263         continue;
1264
1265       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1266       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1267       setOperationAction(ISD::VSELECT,            VT, Custom);
1268       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1269       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1270       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1271       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1272       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1273     }
1274
1275     if (Subtarget->hasInt256())
1276       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1277
1278
1279     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Do not attempt to promote non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::AND,    VT, Promote);
1288       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1289       setOperationAction(ISD::OR,     VT, Promote);
1290       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1291       setOperationAction(ISD::XOR,    VT, Promote);
1292       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1293       setOperationAction(ISD::LOAD,   VT, Promote);
1294       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1295       setOperationAction(ISD::SELECT, VT, Promote);
1296       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1297     }
1298   }
1299
1300   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1301     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1305
1306     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1307     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1308     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1309
1310     for (MVT VT : MVT::fp_vector_valuetypes())
1311       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1312
1313     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1314     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1315     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1316     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1317     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1318     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1319     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1320     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1321     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1322     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1323     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1324     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1325
1326     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1327     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1328     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1329     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1330     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1331     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1332     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1333     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1334     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1337     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1338     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1339
1340     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1341     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1342     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1343     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1344     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1345     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1346
1347     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1349     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1350     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1352     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1353     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1354     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1355
1356     // FIXME:  [US]INT_TO_FP are not legal for f80.
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1359     if (Subtarget->is64Bit()) {
1360       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1361       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1362     }
1363     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1365     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1366     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1367     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1368     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1369     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1370     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1371     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1372     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1374     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1375     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1376     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1377     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1378     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1379
1380     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1381     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1382     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1383     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1384     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1385     if (Subtarget->hasVLX()){
1386       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1387       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1388       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1389       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1390       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1391
1392       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1393       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1394       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1395       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1396       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1397     }
1398     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1399     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1400     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1401     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1402     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1403     if (Subtarget->hasDQI()) {
1404       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1405       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1406
1407       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1408       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1410       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1411       if (Subtarget->hasVLX()) {
1412         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1413         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1414         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1415         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1416         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1417         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1418         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1419         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1420       }
1421     }
1422     if (Subtarget->hasVLX()) {
1423       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1424       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1425       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1426       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1427       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1428       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1429       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1430       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1431     }
1432     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1433     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1434     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1435     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1436     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1437     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1438     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1440     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1441     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1442     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1443     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1444     if (Subtarget->hasDQI()) {
1445       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1446       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1447     }
1448     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1449     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1450     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1451     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1452     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1453     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1454     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1455     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1456     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1457     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1458
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1460     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1461     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1462     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1463     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1464
1465     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1466     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1467
1468     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1469
1470     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1471     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1472     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1473     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1474     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1475     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1477     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1478     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1479     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1480     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1481
1482     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1483     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1484     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1485     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1486     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1487     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1488     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1489     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1490
1491     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1492     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1493
1494     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1496
1497     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1498
1499     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1500     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1501
1502     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1503     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1504
1505     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1506     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1507
1508     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1509     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1510     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1511     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1512     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1513     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1514
1515     if (Subtarget->hasCDI()) {
1516       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1517       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1518       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1519       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1520
1521       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64, Custom);
1522       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1523     }
1524     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1525       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1526       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1527       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1528       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1529       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1531       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1532       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1533
1534       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1535       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1536       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1537       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1538     }
1539     if (Subtarget->hasDQI()) {
1540       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1541       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1542       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1543     }
1544     // Custom lower several nodes.
1545     for (MVT VT : MVT::vector_valuetypes()) {
1546       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1547       if (EltSize == 1) {
1548         setOperationAction(ISD::AND, VT, Legal);
1549         setOperationAction(ISD::OR,  VT, Legal);
1550         setOperationAction(ISD::XOR,  VT, Legal);
1551       }
1552       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1553         setOperationAction(ISD::MGATHER,  VT, Custom);
1554         setOperationAction(ISD::MSCATTER, VT, Custom);
1555       }
1556       // Extract subvector is special because the value type
1557       // (result) is 256/128-bit but the source is 512-bit wide.
1558       if (VT.is128BitVector() || VT.is256BitVector()) {
1559         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1560       }
1561       if (VT.getVectorElementType() == MVT::i1)
1562         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1563
1564       // Do not attempt to custom lower other non-512-bit vectors
1565       if (!VT.is512BitVector())
1566         continue;
1567
1568       if (EltSize >= 32) {
1569         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1570         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1571         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1572         setOperationAction(ISD::VSELECT,             VT, Legal);
1573         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1574         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1575         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1576         setOperationAction(ISD::MLOAD,               VT, Legal);
1577         setOperationAction(ISD::MSTORE,              VT, Legal);
1578       }
1579     }
1580     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1581       MVT VT = (MVT::SimpleValueType)i;
1582
1583       // Do not attempt to promote non-512-bit vectors.
1584       if (!VT.is512BitVector())
1585         continue;
1586
1587       setOperationAction(ISD::SELECT, VT, Promote);
1588       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1589     }
1590   }// has  AVX-512
1591
1592   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1593     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1594     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1595
1596     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1597     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1598
1599     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1600     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1601     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1602     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1603     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1605     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1606     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1607     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1608     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1609     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1610     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1612     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1613     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1614     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1615     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1616     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1617     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1618     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1619     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1620     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1621     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1622     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1623     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1624     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1625     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1626     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1627     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1628     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1629     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1630     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1631     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1632
1633     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1634     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1635     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1636     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1637     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1638     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1639     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1640     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1641
1642     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1643     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1644     if (Subtarget->hasVLX())
1645       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1646
1647     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1648       const MVT VT = (MVT::SimpleValueType)i;
1649
1650       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1651
1652       // Do not attempt to promote non-512-bit vectors.
1653       if (!VT.is512BitVector())
1654         continue;
1655
1656       if (EltSize < 32) {
1657         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1658         setOperationAction(ISD::VSELECT,             VT, Legal);
1659       }
1660     }
1661   }
1662
1663   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1664     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1665     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1666
1667     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1668     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1669     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1670     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1671     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1672     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1673     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1674     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1675     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1676     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1677     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1679
1680     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1681     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1682     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1683     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1684     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1685     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1686     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1687     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1688
1689     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1690     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1691     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1692     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1693     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1694     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1695     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1696     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1697   }
1698
1699   // We want to custom lower some of our intrinsics.
1700   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1701   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1702   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1703   if (!Subtarget->is64Bit())
1704     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1705
1706   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1707   // handle type legalization for these operations here.
1708   //
1709   // FIXME: We really should do custom legalization for addition and
1710   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1711   // than generic legalization for 64-bit multiplication-with-overflow, though.
1712   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1713     // Add/Sub/Mul with overflow operations are custom lowered.
1714     MVT VT = IntVTs[i];
1715     setOperationAction(ISD::SADDO, VT, Custom);
1716     setOperationAction(ISD::UADDO, VT, Custom);
1717     setOperationAction(ISD::SSUBO, VT, Custom);
1718     setOperationAction(ISD::USUBO, VT, Custom);
1719     setOperationAction(ISD::SMULO, VT, Custom);
1720     setOperationAction(ISD::UMULO, VT, Custom);
1721   }
1722
1723
1724   if (!Subtarget->is64Bit()) {
1725     // These libcalls are not available in 32-bit.
1726     setLibcallName(RTLIB::SHL_I128, nullptr);
1727     setLibcallName(RTLIB::SRL_I128, nullptr);
1728     setLibcallName(RTLIB::SRA_I128, nullptr);
1729   }
1730
1731   // Combine sin / cos into one node or libcall if possible.
1732   if (Subtarget->hasSinCos()) {
1733     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1734     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1735     if (Subtarget->isTargetDarwin()) {
1736       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1737       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1738       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1739       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1740     }
1741   }
1742
1743   if (Subtarget->isTargetWin64()) {
1744     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1745     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1746     setOperationAction(ISD::SREM, MVT::i128, Custom);
1747     setOperationAction(ISD::UREM, MVT::i128, Custom);
1748     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1749     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1750   }
1751
1752   // We have target-specific dag combine patterns for the following nodes:
1753   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1754   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1755   setTargetDAGCombine(ISD::BITCAST);
1756   setTargetDAGCombine(ISD::VSELECT);
1757   setTargetDAGCombine(ISD::SELECT);
1758   setTargetDAGCombine(ISD::SHL);
1759   setTargetDAGCombine(ISD::SRA);
1760   setTargetDAGCombine(ISD::SRL);
1761   setTargetDAGCombine(ISD::OR);
1762   setTargetDAGCombine(ISD::AND);
1763   setTargetDAGCombine(ISD::ADD);
1764   setTargetDAGCombine(ISD::FADD);
1765   setTargetDAGCombine(ISD::FSUB);
1766   setTargetDAGCombine(ISD::FMA);
1767   setTargetDAGCombine(ISD::SUB);
1768   setTargetDAGCombine(ISD::LOAD);
1769   setTargetDAGCombine(ISD::MLOAD);
1770   setTargetDAGCombine(ISD::STORE);
1771   setTargetDAGCombine(ISD::MSTORE);
1772   setTargetDAGCombine(ISD::ZERO_EXTEND);
1773   setTargetDAGCombine(ISD::ANY_EXTEND);
1774   setTargetDAGCombine(ISD::SIGN_EXTEND);
1775   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1776   setTargetDAGCombine(ISD::SINT_TO_FP);
1777   setTargetDAGCombine(ISD::UINT_TO_FP);
1778   setTargetDAGCombine(ISD::SETCC);
1779   setTargetDAGCombine(ISD::BUILD_VECTOR);
1780   setTargetDAGCombine(ISD::MUL);
1781   setTargetDAGCombine(ISD::XOR);
1782
1783   computeRegisterProperties(Subtarget->getRegisterInfo());
1784
1785   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1786   MaxStoresPerMemsetOptSize = 8;
1787   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1788   MaxStoresPerMemcpyOptSize = 4;
1789   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1790   MaxStoresPerMemmoveOptSize = 4;
1791   setPrefLoopAlignment(4); // 2^4 bytes.
1792
1793   // Predictable cmov don't hurt on atom because it's in-order.
1794   PredictableSelectIsExpensive = !Subtarget->isAtom();
1795   EnableExtLdPromotion = true;
1796   setPrefFunctionAlignment(4); // 2^4 bytes.
1797
1798   verifyIntrinsicTables();
1799 }
1800
1801 // This has so far only been implemented for 64-bit MachO.
1802 bool X86TargetLowering::useLoadStackGuardNode() const {
1803   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1804 }
1805
1806 TargetLoweringBase::LegalizeTypeAction
1807 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1808   if (ExperimentalVectorWideningLegalization &&
1809       VT.getVectorNumElements() != 1 &&
1810       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1811     return TypeWidenVector;
1812
1813   return TargetLoweringBase::getPreferredVectorAction(VT);
1814 }
1815
1816 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1817                                           EVT VT) const {
1818   if (!VT.isVector())
1819     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1820
1821   const unsigned NumElts = VT.getVectorNumElements();
1822   const EVT EltVT = VT.getVectorElementType();
1823   if (VT.is512BitVector()) {
1824     if (Subtarget->hasAVX512())
1825       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1826           EltVT == MVT::f32 || EltVT == MVT::f64)
1827         switch(NumElts) {
1828         case  8: return MVT::v8i1;
1829         case 16: return MVT::v16i1;
1830       }
1831     if (Subtarget->hasBWI())
1832       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1833         switch(NumElts) {
1834         case 32: return MVT::v32i1;
1835         case 64: return MVT::v64i1;
1836       }
1837   }
1838
1839   if (VT.is256BitVector() || VT.is128BitVector()) {
1840     if (Subtarget->hasVLX())
1841       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1842           EltVT == MVT::f32 || EltVT == MVT::f64)
1843         switch(NumElts) {
1844         case 2: return MVT::v2i1;
1845         case 4: return MVT::v4i1;
1846         case 8: return MVT::v8i1;
1847       }
1848     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1849       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1850         switch(NumElts) {
1851         case  8: return MVT::v8i1;
1852         case 16: return MVT::v16i1;
1853         case 32: return MVT::v32i1;
1854       }
1855   }
1856
1857   return VT.changeVectorElementTypeToInteger();
1858 }
1859
1860 /// Helper for getByValTypeAlignment to determine
1861 /// the desired ByVal argument alignment.
1862 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1863   if (MaxAlign == 16)
1864     return;
1865   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1866     if (VTy->getBitWidth() == 128)
1867       MaxAlign = 16;
1868   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1869     unsigned EltAlign = 0;
1870     getMaxByValAlign(ATy->getElementType(), EltAlign);
1871     if (EltAlign > MaxAlign)
1872       MaxAlign = EltAlign;
1873   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1874     for (auto *EltTy : STy->elements()) {
1875       unsigned EltAlign = 0;
1876       getMaxByValAlign(EltTy, EltAlign);
1877       if (EltAlign > MaxAlign)
1878         MaxAlign = EltAlign;
1879       if (MaxAlign == 16)
1880         break;
1881     }
1882   }
1883 }
1884
1885 /// Return the desired alignment for ByVal aggregate
1886 /// function arguments in the caller parameter area. For X86, aggregates
1887 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1888 /// are at 4-byte boundaries.
1889 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1890                                                   const DataLayout &DL) const {
1891   if (Subtarget->is64Bit()) {
1892     // Max of 8 and alignment of type.
1893     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1894     if (TyAlign > 8)
1895       return TyAlign;
1896     return 8;
1897   }
1898
1899   unsigned Align = 4;
1900   if (Subtarget->hasSSE1())
1901     getMaxByValAlign(Ty, Align);
1902   return Align;
1903 }
1904
1905 /// Returns the target specific optimal type for load
1906 /// and store operations as a result of memset, memcpy, and memmove
1907 /// lowering. If DstAlign is zero that means it's safe to destination
1908 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1909 /// means there isn't a need to check it against alignment requirement,
1910 /// probably because the source does not need to be loaded. If 'IsMemset' is
1911 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1912 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1913 /// source is constant so it does not need to be loaded.
1914 /// It returns EVT::Other if the type should be determined using generic
1915 /// target-independent logic.
1916 EVT
1917 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1918                                        unsigned DstAlign, unsigned SrcAlign,
1919                                        bool IsMemset, bool ZeroMemset,
1920                                        bool MemcpyStrSrc,
1921                                        MachineFunction &MF) const {
1922   const Function *F = MF.getFunction();
1923   if ((!IsMemset || ZeroMemset) &&
1924       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1925     if (Size >= 16 &&
1926         (!Subtarget->isUnalignedMem16Slow() ||
1927          ((DstAlign == 0 || DstAlign >= 16) &&
1928           (SrcAlign == 0 || SrcAlign >= 16)))) {
1929       if (Size >= 32) {
1930         // FIXME: Check if unaligned 32-byte accesses are slow.
1931         if (Subtarget->hasInt256())
1932           return MVT::v8i32;
1933         if (Subtarget->hasFp256())
1934           return MVT::v8f32;
1935       }
1936       if (Subtarget->hasSSE2())
1937         return MVT::v4i32;
1938       if (Subtarget->hasSSE1())
1939         return MVT::v4f32;
1940     } else if (!MemcpyStrSrc && Size >= 8 &&
1941                !Subtarget->is64Bit() &&
1942                Subtarget->hasSSE2()) {
1943       // Do not use f64 to lower memcpy if source is string constant. It's
1944       // better to use i32 to avoid the loads.
1945       return MVT::f64;
1946     }
1947   }
1948   // This is a compromise. If we reach here, unaligned accesses may be slow on
1949   // this target. However, creating smaller, aligned accesses could be even
1950   // slower and would certainly be a lot more code.
1951   if (Subtarget->is64Bit() && Size >= 8)
1952     return MVT::i64;
1953   return MVT::i32;
1954 }
1955
1956 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1957   if (VT == MVT::f32)
1958     return X86ScalarSSEf32;
1959   else if (VT == MVT::f64)
1960     return X86ScalarSSEf64;
1961   return true;
1962 }
1963
1964 bool
1965 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1966                                                   unsigned,
1967                                                   unsigned,
1968                                                   bool *Fast) const {
1969   if (Fast) {
1970     switch (VT.getSizeInBits()) {
1971     default:
1972       // 8-byte and under are always assumed to be fast.
1973       *Fast = true;
1974       break;
1975     case 128:
1976       *Fast = !Subtarget->isUnalignedMem16Slow();
1977       break;
1978     case 256:
1979       *Fast = !Subtarget->isUnalignedMem32Slow();
1980       break;
1981     // TODO: What about AVX-512 (512-bit) accesses?
1982     }
1983   }
1984   // Misaligned accesses of any size are always allowed.
1985   return true;
1986 }
1987
1988 /// Return the entry encoding for a jump table in the
1989 /// current function.  The returned value is a member of the
1990 /// MachineJumpTableInfo::JTEntryKind enum.
1991 unsigned X86TargetLowering::getJumpTableEncoding() const {
1992   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1993   // symbol.
1994   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1995       Subtarget->isPICStyleGOT())
1996     return MachineJumpTableInfo::EK_Custom32;
1997
1998   // Otherwise, use the normal jump table encoding heuristics.
1999   return TargetLowering::getJumpTableEncoding();
2000 }
2001
2002 bool X86TargetLowering::useSoftFloat() const {
2003   return Subtarget->useSoftFloat();
2004 }
2005
2006 const MCExpr *
2007 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2008                                              const MachineBasicBlock *MBB,
2009                                              unsigned uid,MCContext &Ctx) const{
2010   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2011          Subtarget->isPICStyleGOT());
2012   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2013   // entries.
2014   return MCSymbolRefExpr::create(MBB->getSymbol(),
2015                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2016 }
2017
2018 /// Returns relocation base for the given PIC jumptable.
2019 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2020                                                     SelectionDAG &DAG) const {
2021   if (!Subtarget->is64Bit())
2022     // This doesn't have SDLoc associated with it, but is not really the
2023     // same as a Register.
2024     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2025                        getPointerTy(DAG.getDataLayout()));
2026   return Table;
2027 }
2028
2029 /// This returns the relocation base for the given PIC jumptable,
2030 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2031 const MCExpr *X86TargetLowering::
2032 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2033                              MCContext &Ctx) const {
2034   // X86-64 uses RIP relative addressing based on the jump table label.
2035   if (Subtarget->isPICStyleRIPRel())
2036     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2037
2038   // Otherwise, the reference is relative to the PIC base.
2039   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2040 }
2041
2042 std::pair<const TargetRegisterClass *, uint8_t>
2043 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2044                                            MVT VT) const {
2045   const TargetRegisterClass *RRC = nullptr;
2046   uint8_t Cost = 1;
2047   switch (VT.SimpleTy) {
2048   default:
2049     return TargetLowering::findRepresentativeClass(TRI, VT);
2050   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2051     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2052     break;
2053   case MVT::x86mmx:
2054     RRC = &X86::VR64RegClass;
2055     break;
2056   case MVT::f32: case MVT::f64:
2057   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2058   case MVT::v4f32: case MVT::v2f64:
2059   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2060   case MVT::v4f64:
2061     RRC = &X86::VR128RegClass;
2062     break;
2063   }
2064   return std::make_pair(RRC, Cost);
2065 }
2066
2067 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2068                                                unsigned &Offset) const {
2069   if (!Subtarget->isTargetLinux())
2070     return false;
2071
2072   if (Subtarget->is64Bit()) {
2073     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2074     Offset = 0x28;
2075     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2076       AddressSpace = 256;
2077     else
2078       AddressSpace = 257;
2079   } else {
2080     // %gs:0x14 on i386
2081     Offset = 0x14;
2082     AddressSpace = 256;
2083   }
2084   return true;
2085 }
2086
2087 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2088                                             unsigned DestAS) const {
2089   assert(SrcAS != DestAS && "Expected different address spaces!");
2090
2091   return SrcAS < 256 && DestAS < 256;
2092 }
2093
2094 //===----------------------------------------------------------------------===//
2095 //               Return Value Calling Convention Implementation
2096 //===----------------------------------------------------------------------===//
2097
2098 #include "X86GenCallingConv.inc"
2099
2100 bool
2101 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2102                                   MachineFunction &MF, bool isVarArg,
2103                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2104                         LLVMContext &Context) const {
2105   SmallVector<CCValAssign, 16> RVLocs;
2106   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2107   return CCInfo.CheckReturn(Outs, RetCC_X86);
2108 }
2109
2110 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2111   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2112   return ScratchRegs;
2113 }
2114
2115 SDValue
2116 X86TargetLowering::LowerReturn(SDValue Chain,
2117                                CallingConv::ID CallConv, bool isVarArg,
2118                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2119                                const SmallVectorImpl<SDValue> &OutVals,
2120                                SDLoc dl, SelectionDAG &DAG) const {
2121   MachineFunction &MF = DAG.getMachineFunction();
2122   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2123
2124   SmallVector<CCValAssign, 16> RVLocs;
2125   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2126   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2127
2128   SDValue Flag;
2129   SmallVector<SDValue, 6> RetOps;
2130   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2131   // Operand #1 = Bytes To Pop
2132   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2133                    MVT::i16));
2134
2135   // Copy the result values into the output registers.
2136   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2137     CCValAssign &VA = RVLocs[i];
2138     assert(VA.isRegLoc() && "Can only return in registers!");
2139     SDValue ValToCopy = OutVals[i];
2140     EVT ValVT = ValToCopy.getValueType();
2141
2142     // Promote values to the appropriate types.
2143     if (VA.getLocInfo() == CCValAssign::SExt)
2144       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2145     else if (VA.getLocInfo() == CCValAssign::ZExt)
2146       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2147     else if (VA.getLocInfo() == CCValAssign::AExt) {
2148       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2149         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2150       else
2151         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2152     }
2153     else if (VA.getLocInfo() == CCValAssign::BCvt)
2154       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2155
2156     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2157            "Unexpected FP-extend for return value.");
2158
2159     // If this is x86-64, and we disabled SSE, we can't return FP values,
2160     // or SSE or MMX vectors.
2161     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2162          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2163           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2164       report_fatal_error("SSE register return with SSE disabled");
2165     }
2166     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2167     // llvm-gcc has never done it right and no one has noticed, so this
2168     // should be OK for now.
2169     if (ValVT == MVT::f64 &&
2170         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2171       report_fatal_error("SSE2 register return with SSE2 disabled");
2172
2173     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2174     // the RET instruction and handled by the FP Stackifier.
2175     if (VA.getLocReg() == X86::FP0 ||
2176         VA.getLocReg() == X86::FP1) {
2177       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2178       // change the value to the FP stack register class.
2179       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2180         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2181       RetOps.push_back(ValToCopy);
2182       // Don't emit a copytoreg.
2183       continue;
2184     }
2185
2186     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2187     // which is returned in RAX / RDX.
2188     if (Subtarget->is64Bit()) {
2189       if (ValVT == MVT::x86mmx) {
2190         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2191           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2192           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2193                                   ValToCopy);
2194           // If we don't have SSE2 available, convert to v4f32 so the generated
2195           // register is legal.
2196           if (!Subtarget->hasSSE2())
2197             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2198         }
2199       }
2200     }
2201
2202     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2203     Flag = Chain.getValue(1);
2204     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2205   }
2206
2207   // All x86 ABIs require that for returning structs by value we copy
2208   // the sret argument into %rax/%eax (depending on ABI) for the return.
2209   // We saved the argument into a virtual register in the entry block,
2210   // so now we copy the value out and into %rax/%eax.
2211   //
2212   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2213   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2214   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2215   // either case FuncInfo->setSRetReturnReg() will have been called.
2216   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2217     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2218                                      getPointerTy(MF.getDataLayout()));
2219
2220     unsigned RetValReg
2221         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2222           X86::RAX : X86::EAX;
2223     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2224     Flag = Chain.getValue(1);
2225
2226     // RAX/EAX now acts like a return value.
2227     RetOps.push_back(
2228         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2229   }
2230
2231   RetOps[0] = Chain;  // Update chain.
2232
2233   // Add the flag if we have it.
2234   if (Flag.getNode())
2235     RetOps.push_back(Flag);
2236
2237   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2238 }
2239
2240 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2241   if (N->getNumValues() != 1)
2242     return false;
2243   if (!N->hasNUsesOfValue(1, 0))
2244     return false;
2245
2246   SDValue TCChain = Chain;
2247   SDNode *Copy = *N->use_begin();
2248   if (Copy->getOpcode() == ISD::CopyToReg) {
2249     // If the copy has a glue operand, we conservatively assume it isn't safe to
2250     // perform a tail call.
2251     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2252       return false;
2253     TCChain = Copy->getOperand(0);
2254   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2255     return false;
2256
2257   bool HasRet = false;
2258   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2259        UI != UE; ++UI) {
2260     if (UI->getOpcode() != X86ISD::RET_FLAG)
2261       return false;
2262     // If we are returning more than one value, we can definitely
2263     // not make a tail call see PR19530
2264     if (UI->getNumOperands() > 4)
2265       return false;
2266     if (UI->getNumOperands() == 4 &&
2267         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2268       return false;
2269     HasRet = true;
2270   }
2271
2272   if (!HasRet)
2273     return false;
2274
2275   Chain = TCChain;
2276   return true;
2277 }
2278
2279 EVT
2280 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2281                                             ISD::NodeType ExtendKind) const {
2282   MVT ReturnMVT;
2283   // TODO: Is this also valid on 32-bit?
2284   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2285     ReturnMVT = MVT::i8;
2286   else
2287     ReturnMVT = MVT::i32;
2288
2289   EVT MinVT = getRegisterType(Context, ReturnMVT);
2290   return VT.bitsLT(MinVT) ? MinVT : VT;
2291 }
2292
2293 /// Lower the result values of a call into the
2294 /// appropriate copies out of appropriate physical registers.
2295 ///
2296 SDValue
2297 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2298                                    CallingConv::ID CallConv, bool isVarArg,
2299                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2300                                    SDLoc dl, SelectionDAG &DAG,
2301                                    SmallVectorImpl<SDValue> &InVals) const {
2302
2303   // Assign locations to each value returned by this call.
2304   SmallVector<CCValAssign, 16> RVLocs;
2305   bool Is64Bit = Subtarget->is64Bit();
2306   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2307                  *DAG.getContext());
2308   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2309
2310   // Copy all of the result registers out of their specified physreg.
2311   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2312     CCValAssign &VA = RVLocs[i];
2313     EVT CopyVT = VA.getLocVT();
2314
2315     // If this is x86-64, and we disabled SSE, we can't return FP values
2316     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2317         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2318       report_fatal_error("SSE register return with SSE disabled");
2319     }
2320
2321     // If we prefer to use the value in xmm registers, copy it out as f80 and
2322     // use a truncate to move it from fp stack reg to xmm reg.
2323     bool RoundAfterCopy = false;
2324     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2325         isScalarFPTypeInSSEReg(VA.getValVT())) {
2326       CopyVT = MVT::f80;
2327       RoundAfterCopy = (CopyVT != VA.getLocVT());
2328     }
2329
2330     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2331                                CopyVT, InFlag).getValue(1);
2332     SDValue Val = Chain.getValue(0);
2333
2334     if (RoundAfterCopy)
2335       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2336                         // This truncation won't change the value.
2337                         DAG.getIntPtrConstant(1, dl));
2338
2339     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2340       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2341
2342     InFlag = Chain.getValue(2);
2343     InVals.push_back(Val);
2344   }
2345
2346   return Chain;
2347 }
2348
2349 //===----------------------------------------------------------------------===//
2350 //                C & StdCall & Fast Calling Convention implementation
2351 //===----------------------------------------------------------------------===//
2352 //  StdCall calling convention seems to be standard for many Windows' API
2353 //  routines and around. It differs from C calling convention just a little:
2354 //  callee should clean up the stack, not caller. Symbols should be also
2355 //  decorated in some fancy way :) It doesn't support any vector arguments.
2356 //  For info on fast calling convention see Fast Calling Convention (tail call)
2357 //  implementation LowerX86_32FastCCCallTo.
2358
2359 /// CallIsStructReturn - Determines whether a call uses struct return
2360 /// semantics.
2361 enum StructReturnType {
2362   NotStructReturn,
2363   RegStructReturn,
2364   StackStructReturn
2365 };
2366 static StructReturnType
2367 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2368   if (Outs.empty())
2369     return NotStructReturn;
2370
2371   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2372   if (!Flags.isSRet())
2373     return NotStructReturn;
2374   if (Flags.isInReg())
2375     return RegStructReturn;
2376   return StackStructReturn;
2377 }
2378
2379 /// Determines whether a function uses struct return semantics.
2380 static StructReturnType
2381 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2382   if (Ins.empty())
2383     return NotStructReturn;
2384
2385   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2386   if (!Flags.isSRet())
2387     return NotStructReturn;
2388   if (Flags.isInReg())
2389     return RegStructReturn;
2390   return StackStructReturn;
2391 }
2392
2393 /// Make a copy of an aggregate at address specified by "Src" to address
2394 /// "Dst" with size and alignment information specified by the specific
2395 /// parameter attribute. The copy will be passed as a byval function parameter.
2396 static SDValue
2397 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2398                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2399                           SDLoc dl) {
2400   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2401
2402   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2403                        /*isVolatile*/false, /*AlwaysInline=*/true,
2404                        /*isTailCall*/false,
2405                        MachinePointerInfo(), MachinePointerInfo());
2406 }
2407
2408 /// Return true if the calling convention is one that
2409 /// supports tail call optimization.
2410 static bool IsTailCallConvention(CallingConv::ID CC) {
2411   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2412           CC == CallingConv::HiPE);
2413 }
2414
2415 /// \brief Return true if the calling convention is a C calling convention.
2416 static bool IsCCallConvention(CallingConv::ID CC) {
2417   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2418           CC == CallingConv::X86_64_SysV);
2419 }
2420
2421 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2422   auto Attr =
2423       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2424   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2425     return false;
2426
2427   CallSite CS(CI);
2428   CallingConv::ID CalleeCC = CS.getCallingConv();
2429   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2430     return false;
2431
2432   return true;
2433 }
2434
2435 /// Return true if the function is being made into
2436 /// a tailcall target by changing its ABI.
2437 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2438                                    bool GuaranteedTailCallOpt) {
2439   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2440 }
2441
2442 SDValue
2443 X86TargetLowering::LowerMemArgument(SDValue Chain,
2444                                     CallingConv::ID CallConv,
2445                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2446                                     SDLoc dl, SelectionDAG &DAG,
2447                                     const CCValAssign &VA,
2448                                     MachineFrameInfo *MFI,
2449                                     unsigned i) const {
2450   // Create the nodes corresponding to a load from this parameter slot.
2451   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2452   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2453       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2454   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2455   EVT ValVT;
2456
2457   // If value is passed by pointer we have address passed instead of the value
2458   // itself.
2459   bool ExtendedInMem = VA.isExtInLoc() &&
2460     VA.getValVT().getScalarType() == MVT::i1;
2461
2462   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2463     ValVT = VA.getLocVT();
2464   else
2465     ValVT = VA.getValVT();
2466
2467   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2468   // changed with more analysis.
2469   // In case of tail call optimization mark all arguments mutable. Since they
2470   // could be overwritten by lowering of arguments in case of a tail call.
2471   if (Flags.isByVal()) {
2472     unsigned Bytes = Flags.getByValSize();
2473     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2474     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2475     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2476   } else {
2477     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2478                                     VA.getLocMemOffset(), isImmutable);
2479     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2480     SDValue Val = DAG.getLoad(
2481         ValVT, dl, Chain, FIN,
2482         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2483         false, false, 0);
2484     return ExtendedInMem ?
2485       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2486   }
2487 }
2488
2489 // FIXME: Get this from tablegen.
2490 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2491                                                 const X86Subtarget *Subtarget) {
2492   assert(Subtarget->is64Bit());
2493
2494   if (Subtarget->isCallingConvWin64(CallConv)) {
2495     static const MCPhysReg GPR64ArgRegsWin64[] = {
2496       X86::RCX, X86::RDX, X86::R8,  X86::R9
2497     };
2498     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2499   }
2500
2501   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2502     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2503   };
2504   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2505 }
2506
2507 // FIXME: Get this from tablegen.
2508 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2509                                                 CallingConv::ID CallConv,
2510                                                 const X86Subtarget *Subtarget) {
2511   assert(Subtarget->is64Bit());
2512   if (Subtarget->isCallingConvWin64(CallConv)) {
2513     // The XMM registers which might contain var arg parameters are shadowed
2514     // in their paired GPR.  So we only need to save the GPR to their home
2515     // slots.
2516     // TODO: __vectorcall will change this.
2517     return None;
2518   }
2519
2520   const Function *Fn = MF.getFunction();
2521   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2522   bool isSoftFloat = Subtarget->useSoftFloat();
2523   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2524          "SSE register cannot be used when SSE is disabled!");
2525   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2526     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2527     // registers.
2528     return None;
2529
2530   static const MCPhysReg XMMArgRegs64Bit[] = {
2531     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2532     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2533   };
2534   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2535 }
2536
2537 SDValue
2538 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2539                                         CallingConv::ID CallConv,
2540                                         bool isVarArg,
2541                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2542                                         SDLoc dl,
2543                                         SelectionDAG &DAG,
2544                                         SmallVectorImpl<SDValue> &InVals)
2545                                           const {
2546   MachineFunction &MF = DAG.getMachineFunction();
2547   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2548   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2549
2550   const Function* Fn = MF.getFunction();
2551   if (Fn->hasExternalLinkage() &&
2552       Subtarget->isTargetCygMing() &&
2553       Fn->getName() == "main")
2554     FuncInfo->setForceFramePointer(true);
2555
2556   MachineFrameInfo *MFI = MF.getFrameInfo();
2557   bool Is64Bit = Subtarget->is64Bit();
2558   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2559
2560   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561          "Var args not supported with calling convention fastcc, ghc or hipe");
2562
2563   // Assign locations to all of the incoming arguments.
2564   SmallVector<CCValAssign, 16> ArgLocs;
2565   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2566
2567   // Allocate shadow area for Win64
2568   if (IsWin64)
2569     CCInfo.AllocateStack(32, 8);
2570
2571   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2572
2573   unsigned LastVal = ~0U;
2574   SDValue ArgValue;
2575   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2576     CCValAssign &VA = ArgLocs[i];
2577     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2578     // places.
2579     assert(VA.getValNo() != LastVal &&
2580            "Don't support value assigned to multiple locs yet");
2581     (void)LastVal;
2582     LastVal = VA.getValNo();
2583
2584     if (VA.isRegLoc()) {
2585       EVT RegVT = VA.getLocVT();
2586       const TargetRegisterClass *RC;
2587       if (RegVT == MVT::i32)
2588         RC = &X86::GR32RegClass;
2589       else if (Is64Bit && RegVT == MVT::i64)
2590         RC = &X86::GR64RegClass;
2591       else if (RegVT == MVT::f32)
2592         RC = &X86::FR32RegClass;
2593       else if (RegVT == MVT::f64)
2594         RC = &X86::FR64RegClass;
2595       else if (RegVT.is512BitVector())
2596         RC = &X86::VR512RegClass;
2597       else if (RegVT.is256BitVector())
2598         RC = &X86::VR256RegClass;
2599       else if (RegVT.is128BitVector())
2600         RC = &X86::VR128RegClass;
2601       else if (RegVT == MVT::x86mmx)
2602         RC = &X86::VR64RegClass;
2603       else if (RegVT == MVT::i1)
2604         RC = &X86::VK1RegClass;
2605       else if (RegVT == MVT::v8i1)
2606         RC = &X86::VK8RegClass;
2607       else if (RegVT == MVT::v16i1)
2608         RC = &X86::VK16RegClass;
2609       else if (RegVT == MVT::v32i1)
2610         RC = &X86::VK32RegClass;
2611       else if (RegVT == MVT::v64i1)
2612         RC = &X86::VK64RegClass;
2613       else
2614         llvm_unreachable("Unknown argument type!");
2615
2616       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2617       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2618
2619       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2620       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2621       // right size.
2622       if (VA.getLocInfo() == CCValAssign::SExt)
2623         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2624                                DAG.getValueType(VA.getValVT()));
2625       else if (VA.getLocInfo() == CCValAssign::ZExt)
2626         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2627                                DAG.getValueType(VA.getValVT()));
2628       else if (VA.getLocInfo() == CCValAssign::BCvt)
2629         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2630
2631       if (VA.isExtInLoc()) {
2632         // Handle MMX values passed in XMM regs.
2633         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2634           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2635         else
2636           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2637       }
2638     } else {
2639       assert(VA.isMemLoc());
2640       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2641     }
2642
2643     // If value is passed via pointer - do a load.
2644     if (VA.getLocInfo() == CCValAssign::Indirect)
2645       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2646                              MachinePointerInfo(), false, false, false, 0);
2647
2648     InVals.push_back(ArgValue);
2649   }
2650
2651   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2652     // All x86 ABIs require that for returning structs by value we copy the
2653     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2654     // the argument into a virtual register so that we can access it from the
2655     // return points.
2656     if (Ins[i].Flags.isSRet()) {
2657       unsigned Reg = FuncInfo->getSRetReturnReg();
2658       if (!Reg) {
2659         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2660         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2661         FuncInfo->setSRetReturnReg(Reg);
2662       }
2663       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2664       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2665       break;
2666     }
2667   }
2668
2669   unsigned StackSize = CCInfo.getNextStackOffset();
2670   // Align stack specially for tail calls.
2671   if (FuncIsMadeTailCallSafe(CallConv,
2672                              MF.getTarget().Options.GuaranteedTailCallOpt))
2673     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2674
2675   // If the function takes variable number of arguments, make a frame index for
2676   // the start of the first vararg value... for expansion of llvm.va_start. We
2677   // can skip this if there are no va_start calls.
2678   if (MFI->hasVAStart() &&
2679       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2680                    CallConv != CallingConv::X86_ThisCall))) {
2681     FuncInfo->setVarArgsFrameIndex(
2682         MFI->CreateFixedObject(1, StackSize, true));
2683   }
2684
2685   MachineModuleInfo &MMI = MF.getMMI();
2686   const Function *WinEHParent = nullptr;
2687   if (MMI.hasWinEHFuncInfo(Fn))
2688     WinEHParent = MMI.getWinEHParent(Fn);
2689   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2690
2691   // Figure out if XMM registers are in use.
2692   assert(!(Subtarget->useSoftFloat() &&
2693            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2694          "SSE register cannot be used when SSE is disabled!");
2695
2696   // 64-bit calling conventions support varargs and register parameters, so we
2697   // have to do extra work to spill them in the prologue.
2698   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2699     // Find the first unallocated argument registers.
2700     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2701     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2702     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2703     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2704     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2705            "SSE register cannot be used when SSE is disabled!");
2706
2707     // Gather all the live in physical registers.
2708     SmallVector<SDValue, 6> LiveGPRs;
2709     SmallVector<SDValue, 8> LiveXMMRegs;
2710     SDValue ALVal;
2711     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2712       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2713       LiveGPRs.push_back(
2714           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2715     }
2716     if (!ArgXMMs.empty()) {
2717       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2718       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2719       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2720         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2721         LiveXMMRegs.push_back(
2722             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2723       }
2724     }
2725
2726     if (IsWin64) {
2727       // Get to the caller-allocated home save location.  Add 8 to account
2728       // for the return address.
2729       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2730       FuncInfo->setRegSaveFrameIndex(
2731           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2732       // Fixup to set vararg frame on shadow area (4 x i64).
2733       if (NumIntRegs < 4)
2734         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2735     } else {
2736       // For X86-64, if there are vararg parameters that are passed via
2737       // registers, then we must store them to their spots on the stack so
2738       // they may be loaded by deferencing the result of va_next.
2739       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2740       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2741       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2742           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2743     }
2744
2745     // Store the integer parameter registers.
2746     SmallVector<SDValue, 8> MemOps;
2747     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2748                                       getPointerTy(DAG.getDataLayout()));
2749     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2750     for (SDValue Val : LiveGPRs) {
2751       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2752                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2753       SDValue Store =
2754           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2755                        MachinePointerInfo::getFixedStack(
2756                            DAG.getMachineFunction(),
2757                            FuncInfo->getRegSaveFrameIndex(), Offset),
2758                        false, false, 0);
2759       MemOps.push_back(Store);
2760       Offset += 8;
2761     }
2762
2763     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2764       // Now store the XMM (fp + vector) parameter registers.
2765       SmallVector<SDValue, 12> SaveXMMOps;
2766       SaveXMMOps.push_back(Chain);
2767       SaveXMMOps.push_back(ALVal);
2768       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2769                              FuncInfo->getRegSaveFrameIndex(), dl));
2770       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2771                              FuncInfo->getVarArgsFPOffset(), dl));
2772       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2773                         LiveXMMRegs.end());
2774       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2775                                    MVT::Other, SaveXMMOps));
2776     }
2777
2778     if (!MemOps.empty())
2779       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2780   }
2781
2782   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2783     // Find the largest legal vector type.
2784     MVT VecVT = MVT::Other;
2785     // FIXME: Only some x86_32 calling conventions support AVX512.
2786     if (Subtarget->hasAVX512() &&
2787         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2788                      CallConv == CallingConv::Intel_OCL_BI)))
2789       VecVT = MVT::v16f32;
2790     else if (Subtarget->hasAVX())
2791       VecVT = MVT::v8f32;
2792     else if (Subtarget->hasSSE2())
2793       VecVT = MVT::v4f32;
2794
2795     // We forward some GPRs and some vector types.
2796     SmallVector<MVT, 2> RegParmTypes;
2797     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2798     RegParmTypes.push_back(IntVT);
2799     if (VecVT != MVT::Other)
2800       RegParmTypes.push_back(VecVT);
2801
2802     // Compute the set of forwarded registers. The rest are scratch.
2803     SmallVectorImpl<ForwardedRegister> &Forwards =
2804         FuncInfo->getForwardedMustTailRegParms();
2805     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2806
2807     // Conservatively forward AL on x86_64, since it might be used for varargs.
2808     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2809       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2810       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2811     }
2812
2813     // Copy all forwards from physical to virtual registers.
2814     for (ForwardedRegister &F : Forwards) {
2815       // FIXME: Can we use a less constrained schedule?
2816       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2817       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2818       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2819     }
2820   }
2821
2822   // Some CCs need callee pop.
2823   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2824                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2825     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2826   } else {
2827     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2828     // If this is an sret function, the return should pop the hidden pointer.
2829     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2830         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2831         argsAreStructReturn(Ins) == StackStructReturn)
2832       FuncInfo->setBytesToPopOnReturn(4);
2833   }
2834
2835   if (!Is64Bit) {
2836     // RegSaveFrameIndex is X86-64 only.
2837     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2838     if (CallConv == CallingConv::X86_FastCall ||
2839         CallConv == CallingConv::X86_ThisCall)
2840       // fastcc functions can't have varargs.
2841       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2842   }
2843
2844   FuncInfo->setArgumentStackSize(StackSize);
2845
2846   if (IsWinEHParent) {
2847     if (Is64Bit) {
2848       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2849       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2850       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2851       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2852       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2853                            MachinePointerInfo::getFixedStack(
2854                                DAG.getMachineFunction(), UnwindHelpFI),
2855                            /*isVolatile=*/true,
2856                            /*isNonTemporal=*/false, /*Alignment=*/0);
2857     } else {
2858       // Functions using Win32 EH are considered to have opaque SP adjustments
2859       // to force local variables to be addressed from the frame or base
2860       // pointers.
2861       MFI->setHasOpaqueSPAdjustment(true);
2862     }
2863   }
2864
2865   return Chain;
2866 }
2867
2868 SDValue
2869 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2870                                     SDValue StackPtr, SDValue Arg,
2871                                     SDLoc dl, SelectionDAG &DAG,
2872                                     const CCValAssign &VA,
2873                                     ISD::ArgFlagsTy Flags) const {
2874   unsigned LocMemOffset = VA.getLocMemOffset();
2875   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2876   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2877                        StackPtr, PtrOff);
2878   if (Flags.isByVal())
2879     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2880
2881   return DAG.getStore(
2882       Chain, dl, Arg, PtrOff,
2883       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2884       false, false, 0);
2885 }
2886
2887 /// Emit a load of return address if tail call
2888 /// optimization is performed and it is required.
2889 SDValue
2890 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2891                                            SDValue &OutRetAddr, SDValue Chain,
2892                                            bool IsTailCall, bool Is64Bit,
2893                                            int FPDiff, SDLoc dl) const {
2894   // Adjust the Return address stack slot.
2895   EVT VT = getPointerTy(DAG.getDataLayout());
2896   OutRetAddr = getReturnAddressFrameIndex(DAG);
2897
2898   // Load the "old" Return address.
2899   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2900                            false, false, false, 0);
2901   return SDValue(OutRetAddr.getNode(), 1);
2902 }
2903
2904 /// Emit a store of the return address if tail call
2905 /// optimization is performed and it is required (FPDiff!=0).
2906 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2907                                         SDValue Chain, SDValue RetAddrFrIdx,
2908                                         EVT PtrVT, unsigned SlotSize,
2909                                         int FPDiff, SDLoc dl) {
2910   // Store the return address to the appropriate stack slot.
2911   if (!FPDiff) return Chain;
2912   // Calculate the new stack slot for the return address.
2913   int NewReturnAddrFI =
2914     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2915                                          false);
2916   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2917   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2918                        MachinePointerInfo::getFixedStack(
2919                            DAG.getMachineFunction(), NewReturnAddrFI),
2920                        false, false, 0);
2921   return Chain;
2922 }
2923
2924 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2925 /// operation of specified width.
2926 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2927                        SDValue V2) {
2928   unsigned NumElems = VT.getVectorNumElements();
2929   SmallVector<int, 8> Mask;
2930   Mask.push_back(NumElems);
2931   for (unsigned i = 1; i != NumElems; ++i)
2932     Mask.push_back(i);
2933   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2934 }
2935
2936 SDValue
2937 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2938                              SmallVectorImpl<SDValue> &InVals) const {
2939   SelectionDAG &DAG                     = CLI.DAG;
2940   SDLoc &dl                             = CLI.DL;
2941   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2942   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2943   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2944   SDValue Chain                         = CLI.Chain;
2945   SDValue Callee                        = CLI.Callee;
2946   CallingConv::ID CallConv              = CLI.CallConv;
2947   bool &isTailCall                      = CLI.IsTailCall;
2948   bool isVarArg                         = CLI.IsVarArg;
2949
2950   MachineFunction &MF = DAG.getMachineFunction();
2951   bool Is64Bit        = Subtarget->is64Bit();
2952   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2953   StructReturnType SR = callIsStructReturn(Outs);
2954   bool IsSibcall      = false;
2955   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2956   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2957
2958   if (Attr.getValueAsString() == "true")
2959     isTailCall = false;
2960
2961   if (Subtarget->isPICStyleGOT() &&
2962       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2963     // If we are using a GOT, disable tail calls to external symbols with
2964     // default visibility. Tail calling such a symbol requires using a GOT
2965     // relocation, which forces early binding of the symbol. This breaks code
2966     // that require lazy function symbol resolution. Using musttail or
2967     // GuaranteedTailCallOpt will override this.
2968     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2969     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2970                G->getGlobal()->hasDefaultVisibility()))
2971       isTailCall = false;
2972   }
2973
2974   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2975   if (IsMustTail) {
2976     // Force this to be a tail call.  The verifier rules are enough to ensure
2977     // that we can lower this successfully without moving the return address
2978     // around.
2979     isTailCall = true;
2980   } else if (isTailCall) {
2981     // Check if it's really possible to do a tail call.
2982     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2983                     isVarArg, SR != NotStructReturn,
2984                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2985                     Outs, OutVals, Ins, DAG);
2986
2987     // Sibcalls are automatically detected tailcalls which do not require
2988     // ABI changes.
2989     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2990       IsSibcall = true;
2991
2992     if (isTailCall)
2993       ++NumTailCalls;
2994   }
2995
2996   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2997          "Var args not supported with calling convention fastcc, ghc or hipe");
2998
2999   // Analyze operands of the call, assigning locations to each operand.
3000   SmallVector<CCValAssign, 16> ArgLocs;
3001   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3002
3003   // Allocate shadow area for Win64
3004   if (IsWin64)
3005     CCInfo.AllocateStack(32, 8);
3006
3007   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3008
3009   // Get a count of how many bytes are to be pushed on the stack.
3010   unsigned NumBytes = CCInfo.getNextStackOffset();
3011   if (IsSibcall)
3012     // This is a sibcall. The memory operands are available in caller's
3013     // own caller's stack.
3014     NumBytes = 0;
3015   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3016            IsTailCallConvention(CallConv))
3017     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3018
3019   int FPDiff = 0;
3020   if (isTailCall && !IsSibcall && !IsMustTail) {
3021     // Lower arguments at fp - stackoffset + fpdiff.
3022     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3023
3024     FPDiff = NumBytesCallerPushed - NumBytes;
3025
3026     // Set the delta of movement of the returnaddr stackslot.
3027     // But only set if delta is greater than previous delta.
3028     if (FPDiff < X86Info->getTCReturnAddrDelta())
3029       X86Info->setTCReturnAddrDelta(FPDiff);
3030   }
3031
3032   unsigned NumBytesToPush = NumBytes;
3033   unsigned NumBytesToPop = NumBytes;
3034
3035   // If we have an inalloca argument, all stack space has already been allocated
3036   // for us and be right at the top of the stack.  We don't support multiple
3037   // arguments passed in memory when using inalloca.
3038   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3039     NumBytesToPush = 0;
3040     if (!ArgLocs.back().isMemLoc())
3041       report_fatal_error("cannot use inalloca attribute on a register "
3042                          "parameter");
3043     if (ArgLocs.back().getLocMemOffset() != 0)
3044       report_fatal_error("any parameter with the inalloca attribute must be "
3045                          "the only memory argument");
3046   }
3047
3048   if (!IsSibcall)
3049     Chain = DAG.getCALLSEQ_START(
3050         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3051
3052   SDValue RetAddrFrIdx;
3053   // Load return address for tail calls.
3054   if (isTailCall && FPDiff)
3055     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3056                                     Is64Bit, FPDiff, dl);
3057
3058   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3059   SmallVector<SDValue, 8> MemOpChains;
3060   SDValue StackPtr;
3061
3062   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3063   // of tail call optimization arguments are handle later.
3064   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3065   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3066     // Skip inalloca arguments, they have already been written.
3067     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3068     if (Flags.isInAlloca())
3069       continue;
3070
3071     CCValAssign &VA = ArgLocs[i];
3072     EVT RegVT = VA.getLocVT();
3073     SDValue Arg = OutVals[i];
3074     bool isByVal = Flags.isByVal();
3075
3076     // Promote the value if needed.
3077     switch (VA.getLocInfo()) {
3078     default: llvm_unreachable("Unknown loc info!");
3079     case CCValAssign::Full: break;
3080     case CCValAssign::SExt:
3081       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3082       break;
3083     case CCValAssign::ZExt:
3084       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3085       break;
3086     case CCValAssign::AExt:
3087       if (Arg.getValueType().isVector() &&
3088           Arg.getValueType().getScalarType() == MVT::i1)
3089         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3090       else if (RegVT.is128BitVector()) {
3091         // Special case: passing MMX values in XMM registers.
3092         Arg = DAG.getBitcast(MVT::i64, Arg);
3093         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3094         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3095       } else
3096         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3097       break;
3098     case CCValAssign::BCvt:
3099       Arg = DAG.getBitcast(RegVT, Arg);
3100       break;
3101     case CCValAssign::Indirect: {
3102       // Store the argument.
3103       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3104       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3105       Chain = DAG.getStore(
3106           Chain, dl, Arg, SpillSlot,
3107           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3108           false, false, 0);
3109       Arg = SpillSlot;
3110       break;
3111     }
3112     }
3113
3114     if (VA.isRegLoc()) {
3115       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3116       if (isVarArg && IsWin64) {
3117         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3118         // shadow reg if callee is a varargs function.
3119         unsigned ShadowReg = 0;
3120         switch (VA.getLocReg()) {
3121         case X86::XMM0: ShadowReg = X86::RCX; break;
3122         case X86::XMM1: ShadowReg = X86::RDX; break;
3123         case X86::XMM2: ShadowReg = X86::R8; break;
3124         case X86::XMM3: ShadowReg = X86::R9; break;
3125         }
3126         if (ShadowReg)
3127           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3128       }
3129     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3130       assert(VA.isMemLoc());
3131       if (!StackPtr.getNode())
3132         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3133                                       getPointerTy(DAG.getDataLayout()));
3134       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3135                                              dl, DAG, VA, Flags));
3136     }
3137   }
3138
3139   if (!MemOpChains.empty())
3140     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3141
3142   if (Subtarget->isPICStyleGOT()) {
3143     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3144     // GOT pointer.
3145     if (!isTailCall) {
3146       RegsToPass.push_back(std::make_pair(
3147           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3148                                           getPointerTy(DAG.getDataLayout()))));
3149     } else {
3150       // If we are tail calling and generating PIC/GOT style code load the
3151       // address of the callee into ECX. The value in ecx is used as target of
3152       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3153       // for tail calls on PIC/GOT architectures. Normally we would just put the
3154       // address of GOT into ebx and then call target@PLT. But for tail calls
3155       // ebx would be restored (since ebx is callee saved) before jumping to the
3156       // target@PLT.
3157
3158       // Note: The actual moving to ECX is done further down.
3159       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3160       if (G && !G->getGlobal()->hasLocalLinkage() &&
3161           G->getGlobal()->hasDefaultVisibility())
3162         Callee = LowerGlobalAddress(Callee, DAG);
3163       else if (isa<ExternalSymbolSDNode>(Callee))
3164         Callee = LowerExternalSymbol(Callee, DAG);
3165     }
3166   }
3167
3168   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3169     // From AMD64 ABI document:
3170     // For calls that may call functions that use varargs or stdargs
3171     // (prototype-less calls or calls to functions containing ellipsis (...) in
3172     // the declaration) %al is used as hidden argument to specify the number
3173     // of SSE registers used. The contents of %al do not need to match exactly
3174     // the number of registers, but must be an ubound on the number of SSE
3175     // registers used and is in the range 0 - 8 inclusive.
3176
3177     // Count the number of XMM registers allocated.
3178     static const MCPhysReg XMMArgRegs[] = {
3179       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3180       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3181     };
3182     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3183     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3184            && "SSE registers cannot be used when SSE is disabled");
3185
3186     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3187                                         DAG.getConstant(NumXMMRegs, dl,
3188                                                         MVT::i8)));
3189   }
3190
3191   if (isVarArg && IsMustTail) {
3192     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3193     for (const auto &F : Forwards) {
3194       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3195       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3196     }
3197   }
3198
3199   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3200   // don't need this because the eligibility check rejects calls that require
3201   // shuffling arguments passed in memory.
3202   if (!IsSibcall && isTailCall) {
3203     // Force all the incoming stack arguments to be loaded from the stack
3204     // before any new outgoing arguments are stored to the stack, because the
3205     // outgoing stack slots may alias the incoming argument stack slots, and
3206     // the alias isn't otherwise explicit. This is slightly more conservative
3207     // than necessary, because it means that each store effectively depends
3208     // on every argument instead of just those arguments it would clobber.
3209     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3210
3211     SmallVector<SDValue, 8> MemOpChains2;
3212     SDValue FIN;
3213     int FI = 0;
3214     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3215       CCValAssign &VA = ArgLocs[i];
3216       if (VA.isRegLoc())
3217         continue;
3218       assert(VA.isMemLoc());
3219       SDValue Arg = OutVals[i];
3220       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3221       // Skip inalloca arguments.  They don't require any work.
3222       if (Flags.isInAlloca())
3223         continue;
3224       // Create frame index.
3225       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3226       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3227       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3228       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3229
3230       if (Flags.isByVal()) {
3231         // Copy relative to framepointer.
3232         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3233         if (!StackPtr.getNode())
3234           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3235                                         getPointerTy(DAG.getDataLayout()));
3236         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3237                              StackPtr, Source);
3238
3239         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3240                                                          ArgChain,
3241                                                          Flags, DAG, dl));
3242       } else {
3243         // Store relative to framepointer.
3244         MemOpChains2.push_back(DAG.getStore(
3245             ArgChain, dl, Arg, FIN,
3246             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3247             false, false, 0));
3248       }
3249     }
3250
3251     if (!MemOpChains2.empty())
3252       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3253
3254     // Store the return address to the appropriate stack slot.
3255     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3256                                      getPointerTy(DAG.getDataLayout()),
3257                                      RegInfo->getSlotSize(), FPDiff, dl);
3258   }
3259
3260   // Build a sequence of copy-to-reg nodes chained together with token chain
3261   // and flag operands which copy the outgoing args into registers.
3262   SDValue InFlag;
3263   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3264     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3265                              RegsToPass[i].second, InFlag);
3266     InFlag = Chain.getValue(1);
3267   }
3268
3269   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3270     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3271     // In the 64-bit large code model, we have to make all calls
3272     // through a register, since the call instruction's 32-bit
3273     // pc-relative offset may not be large enough to hold the whole
3274     // address.
3275   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3276     // If the callee is a GlobalAddress node (quite common, every direct call
3277     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3278     // it.
3279     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3280
3281     // We should use extra load for direct calls to dllimported functions in
3282     // non-JIT mode.
3283     const GlobalValue *GV = G->getGlobal();
3284     if (!GV->hasDLLImportStorageClass()) {
3285       unsigned char OpFlags = 0;
3286       bool ExtraLoad = false;
3287       unsigned WrapperKind = ISD::DELETED_NODE;
3288
3289       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3290       // external symbols most go through the PLT in PIC mode.  If the symbol
3291       // has hidden or protected visibility, or if it is static or local, then
3292       // we don't need to use the PLT - we can directly call it.
3293       if (Subtarget->isTargetELF() &&
3294           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3295           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3296         OpFlags = X86II::MO_PLT;
3297       } else if (Subtarget->isPICStyleStubAny() &&
3298                  !GV->isStrongDefinitionForLinker() &&
3299                  (!Subtarget->getTargetTriple().isMacOSX() ||
3300                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3301         // PC-relative references to external symbols should go through $stub,
3302         // unless we're building with the leopard linker or later, which
3303         // automatically synthesizes these stubs.
3304         OpFlags = X86II::MO_DARWIN_STUB;
3305       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3306                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3307         // If the function is marked as non-lazy, generate an indirect call
3308         // which loads from the GOT directly. This avoids runtime overhead
3309         // at the cost of eager binding (and one extra byte of encoding).
3310         OpFlags = X86II::MO_GOTPCREL;
3311         WrapperKind = X86ISD::WrapperRIP;
3312         ExtraLoad = true;
3313       }
3314
3315       Callee = DAG.getTargetGlobalAddress(
3316           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3317
3318       // Add a wrapper if needed.
3319       if (WrapperKind != ISD::DELETED_NODE)
3320         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3321                              getPointerTy(DAG.getDataLayout()), Callee);
3322       // Add extra indirection if needed.
3323       if (ExtraLoad)
3324         Callee = DAG.getLoad(
3325             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3326             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3327             false, 0);
3328     }
3329   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3330     unsigned char OpFlags = 0;
3331
3332     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3333     // external symbols should go through the PLT.
3334     if (Subtarget->isTargetELF() &&
3335         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3336       OpFlags = X86II::MO_PLT;
3337     } else if (Subtarget->isPICStyleStubAny() &&
3338                (!Subtarget->getTargetTriple().isMacOSX() ||
3339                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3340       // PC-relative references to external symbols should go through $stub,
3341       // unless we're building with the leopard linker or later, which
3342       // automatically synthesizes these stubs.
3343       OpFlags = X86II::MO_DARWIN_STUB;
3344     }
3345
3346     Callee = DAG.getTargetExternalSymbol(
3347         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3348   } else if (Subtarget->isTarget64BitILP32() &&
3349              Callee->getValueType(0) == MVT::i32) {
3350     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3351     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3352   }
3353
3354   // Returns a chain & a flag for retval copy to use.
3355   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3356   SmallVector<SDValue, 8> Ops;
3357
3358   if (!IsSibcall && isTailCall) {
3359     Chain = DAG.getCALLSEQ_END(Chain,
3360                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3361                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3362     InFlag = Chain.getValue(1);
3363   }
3364
3365   Ops.push_back(Chain);
3366   Ops.push_back(Callee);
3367
3368   if (isTailCall)
3369     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3370
3371   // Add argument registers to the end of the list so that they are known live
3372   // into the call.
3373   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3374     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3375                                   RegsToPass[i].second.getValueType()));
3376
3377   // Add a register mask operand representing the call-preserved registers.
3378   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3379   assert(Mask && "Missing call preserved mask for calling convention");
3380
3381   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3382   // the function clobbers all registers. If an exception is thrown, the runtime
3383   // will not restore CSRs.
3384   // FIXME: Model this more precisely so that we can register allocate across
3385   // the normal edge and spill and fill across the exceptional edge.
3386   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3387     const Function *CallerFn = MF.getFunction();
3388     EHPersonality Pers =
3389         CallerFn->hasPersonalityFn()
3390             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3391             : EHPersonality::Unknown;
3392     if (isMSVCEHPersonality(Pers))
3393       Mask = RegInfo->getNoPreservedMask();
3394   }
3395
3396   Ops.push_back(DAG.getRegisterMask(Mask));
3397
3398   if (InFlag.getNode())
3399     Ops.push_back(InFlag);
3400
3401   if (isTailCall) {
3402     // We used to do:
3403     //// If this is the first return lowered for this function, add the regs
3404     //// to the liveout set for the function.
3405     // This isn't right, although it's probably harmless on x86; liveouts
3406     // should be computed from returns not tail calls.  Consider a void
3407     // function making a tail call to a function returning int.
3408     MF.getFrameInfo()->setHasTailCall();
3409     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3410   }
3411
3412   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3413   InFlag = Chain.getValue(1);
3414
3415   // Create the CALLSEQ_END node.
3416   unsigned NumBytesForCalleeToPop;
3417   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3418                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3419     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3420   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3421            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3422            SR == StackStructReturn)
3423     // If this is a call to a struct-return function, the callee
3424     // pops the hidden struct pointer, so we have to push it back.
3425     // This is common for Darwin/X86, Linux & Mingw32 targets.
3426     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3427     NumBytesForCalleeToPop = 4;
3428   else
3429     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3430
3431   // Returns a flag for retval copy to use.
3432   if (!IsSibcall) {
3433     Chain = DAG.getCALLSEQ_END(Chain,
3434                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3435                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3436                                                      true),
3437                                InFlag, dl);
3438     InFlag = Chain.getValue(1);
3439   }
3440
3441   // Handle result values, copying them out of physregs into vregs that we
3442   // return.
3443   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3444                          Ins, dl, DAG, InVals);
3445 }
3446
3447 //===----------------------------------------------------------------------===//
3448 //                Fast Calling Convention (tail call) implementation
3449 //===----------------------------------------------------------------------===//
3450
3451 //  Like std call, callee cleans arguments, convention except that ECX is
3452 //  reserved for storing the tail called function address. Only 2 registers are
3453 //  free for argument passing (inreg). Tail call optimization is performed
3454 //  provided:
3455 //                * tailcallopt is enabled
3456 //                * caller/callee are fastcc
3457 //  On X86_64 architecture with GOT-style position independent code only local
3458 //  (within module) calls are supported at the moment.
3459 //  To keep the stack aligned according to platform abi the function
3460 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3461 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3462 //  If a tail called function callee has more arguments than the caller the
3463 //  caller needs to make sure that there is room to move the RETADDR to. This is
3464 //  achieved by reserving an area the size of the argument delta right after the
3465 //  original RETADDR, but before the saved framepointer or the spilled registers
3466 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3467 //  stack layout:
3468 //    arg1
3469 //    arg2
3470 //    RETADDR
3471 //    [ new RETADDR
3472 //      move area ]
3473 //    (possible EBP)
3474 //    ESI
3475 //    EDI
3476 //    local1 ..
3477
3478 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3479 /// requirement.
3480 unsigned
3481 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3482                                                SelectionDAG& DAG) const {
3483   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3484   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3485   unsigned StackAlignment = TFI.getStackAlignment();
3486   uint64_t AlignMask = StackAlignment - 1;
3487   int64_t Offset = StackSize;
3488   unsigned SlotSize = RegInfo->getSlotSize();
3489   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3490     // Number smaller than 12 so just add the difference.
3491     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3492   } else {
3493     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3494     Offset = ((~AlignMask) & Offset) + StackAlignment +
3495       (StackAlignment-SlotSize);
3496   }
3497   return Offset;
3498 }
3499
3500 /// Return true if the given stack call argument is already available in the
3501 /// same position (relatively) of the caller's incoming argument stack.
3502 static
3503 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3504                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3505                          const X86InstrInfo *TII) {
3506   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3507   int FI = INT_MAX;
3508   if (Arg.getOpcode() == ISD::CopyFromReg) {
3509     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3510     if (!TargetRegisterInfo::isVirtualRegister(VR))
3511       return false;
3512     MachineInstr *Def = MRI->getVRegDef(VR);
3513     if (!Def)
3514       return false;
3515     if (!Flags.isByVal()) {
3516       if (!TII->isLoadFromStackSlot(Def, FI))
3517         return false;
3518     } else {
3519       unsigned Opcode = Def->getOpcode();
3520       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3521            Opcode == X86::LEA64_32r) &&
3522           Def->getOperand(1).isFI()) {
3523         FI = Def->getOperand(1).getIndex();
3524         Bytes = Flags.getByValSize();
3525       } else
3526         return false;
3527     }
3528   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3529     if (Flags.isByVal())
3530       // ByVal argument is passed in as a pointer but it's now being
3531       // dereferenced. e.g.
3532       // define @foo(%struct.X* %A) {
3533       //   tail call @bar(%struct.X* byval %A)
3534       // }
3535       return false;
3536     SDValue Ptr = Ld->getBasePtr();
3537     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3538     if (!FINode)
3539       return false;
3540     FI = FINode->getIndex();
3541   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3542     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3543     FI = FINode->getIndex();
3544     Bytes = Flags.getByValSize();
3545   } else
3546     return false;
3547
3548   assert(FI != INT_MAX);
3549   if (!MFI->isFixedObjectIndex(FI))
3550     return false;
3551   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3552 }
3553
3554 /// Check whether the call is eligible for tail call optimization. Targets
3555 /// that want to do tail call optimization should implement this function.
3556 bool
3557 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3558                                                      CallingConv::ID CalleeCC,
3559                                                      bool isVarArg,
3560                                                      bool isCalleeStructRet,
3561                                                      bool isCallerStructRet,
3562                                                      Type *RetTy,
3563                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3564                                     const SmallVectorImpl<SDValue> &OutVals,
3565                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3566                                                      SelectionDAG &DAG) const {
3567   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3568     return false;
3569
3570   // If -tailcallopt is specified, make fastcc functions tail-callable.
3571   const MachineFunction &MF = DAG.getMachineFunction();
3572   const Function *CallerF = MF.getFunction();
3573
3574   // If the function return type is x86_fp80 and the callee return type is not,
3575   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3576   // perform a tailcall optimization here.
3577   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3578     return false;
3579
3580   CallingConv::ID CallerCC = CallerF->getCallingConv();
3581   bool CCMatch = CallerCC == CalleeCC;
3582   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3583   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3584
3585   // Win64 functions have extra shadow space for argument homing. Don't do the
3586   // sibcall if the caller and callee have mismatched expectations for this
3587   // space.
3588   if (IsCalleeWin64 != IsCallerWin64)
3589     return false;
3590
3591   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3592     if (IsTailCallConvention(CalleeCC) && CCMatch)
3593       return true;
3594     return false;
3595   }
3596
3597   // Look for obvious safe cases to perform tail call optimization that do not
3598   // require ABI changes. This is what gcc calls sibcall.
3599
3600   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3601   // emit a special epilogue.
3602   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3603   if (RegInfo->needsStackRealignment(MF))
3604     return false;
3605
3606   // Also avoid sibcall optimization if either caller or callee uses struct
3607   // return semantics.
3608   if (isCalleeStructRet || isCallerStructRet)
3609     return false;
3610
3611   // An stdcall/thiscall caller is expected to clean up its arguments; the
3612   // callee isn't going to do that.
3613   // FIXME: this is more restrictive than needed. We could produce a tailcall
3614   // when the stack adjustment matches. For example, with a thiscall that takes
3615   // only one argument.
3616   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3617                    CallerCC == CallingConv::X86_ThisCall))
3618     return false;
3619
3620   // Do not sibcall optimize vararg calls unless all arguments are passed via
3621   // registers.
3622   if (isVarArg && !Outs.empty()) {
3623
3624     // Optimizing for varargs on Win64 is unlikely to be safe without
3625     // additional testing.
3626     if (IsCalleeWin64 || IsCallerWin64)
3627       return false;
3628
3629     SmallVector<CCValAssign, 16> ArgLocs;
3630     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3631                    *DAG.getContext());
3632
3633     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3634     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3635       if (!ArgLocs[i].isRegLoc())
3636         return false;
3637   }
3638
3639   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3640   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3641   // this into a sibcall.
3642   bool Unused = false;
3643   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3644     if (!Ins[i].Used) {
3645       Unused = true;
3646       break;
3647     }
3648   }
3649   if (Unused) {
3650     SmallVector<CCValAssign, 16> RVLocs;
3651     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3652                    *DAG.getContext());
3653     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3654     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3655       CCValAssign &VA = RVLocs[i];
3656       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3657         return false;
3658     }
3659   }
3660
3661   // If the calling conventions do not match, then we'd better make sure the
3662   // results are returned in the same way as what the caller expects.
3663   if (!CCMatch) {
3664     SmallVector<CCValAssign, 16> RVLocs1;
3665     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3666                     *DAG.getContext());
3667     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3668
3669     SmallVector<CCValAssign, 16> RVLocs2;
3670     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3671                     *DAG.getContext());
3672     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3673
3674     if (RVLocs1.size() != RVLocs2.size())
3675       return false;
3676     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3677       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3678         return false;
3679       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3680         return false;
3681       if (RVLocs1[i].isRegLoc()) {
3682         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3683           return false;
3684       } else {
3685         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3686           return false;
3687       }
3688     }
3689   }
3690
3691   // If the callee takes no arguments then go on to check the results of the
3692   // call.
3693   if (!Outs.empty()) {
3694     // Check if stack adjustment is needed. For now, do not do this if any
3695     // argument is passed on the stack.
3696     SmallVector<CCValAssign, 16> ArgLocs;
3697     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3698                    *DAG.getContext());
3699
3700     // Allocate shadow area for Win64
3701     if (IsCalleeWin64)
3702       CCInfo.AllocateStack(32, 8);
3703
3704     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3705     if (CCInfo.getNextStackOffset()) {
3706       MachineFunction &MF = DAG.getMachineFunction();
3707       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3708         return false;
3709
3710       // Check if the arguments are already laid out in the right way as
3711       // the caller's fixed stack objects.
3712       MachineFrameInfo *MFI = MF.getFrameInfo();
3713       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3714       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3715       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3716         CCValAssign &VA = ArgLocs[i];
3717         SDValue Arg = OutVals[i];
3718         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3719         if (VA.getLocInfo() == CCValAssign::Indirect)
3720           return false;
3721         if (!VA.isRegLoc()) {
3722           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3723                                    MFI, MRI, TII))
3724             return false;
3725         }
3726       }
3727     }
3728
3729     // If the tailcall address may be in a register, then make sure it's
3730     // possible to register allocate for it. In 32-bit, the call address can
3731     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3732     // callee-saved registers are restored. These happen to be the same
3733     // registers used to pass 'inreg' arguments so watch out for those.
3734     if (!Subtarget->is64Bit() &&
3735         ((!isa<GlobalAddressSDNode>(Callee) &&
3736           !isa<ExternalSymbolSDNode>(Callee)) ||
3737          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3738       unsigned NumInRegs = 0;
3739       // In PIC we need an extra register to formulate the address computation
3740       // for the callee.
3741       unsigned MaxInRegs =
3742         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3743
3744       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3745         CCValAssign &VA = ArgLocs[i];
3746         if (!VA.isRegLoc())
3747           continue;
3748         unsigned Reg = VA.getLocReg();
3749         switch (Reg) {
3750         default: break;
3751         case X86::EAX: case X86::EDX: case X86::ECX:
3752           if (++NumInRegs == MaxInRegs)
3753             return false;
3754           break;
3755         }
3756       }
3757     }
3758   }
3759
3760   return true;
3761 }
3762
3763 FastISel *
3764 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3765                                   const TargetLibraryInfo *libInfo) const {
3766   return X86::createFastISel(funcInfo, libInfo);
3767 }
3768
3769 //===----------------------------------------------------------------------===//
3770 //                           Other Lowering Hooks
3771 //===----------------------------------------------------------------------===//
3772
3773 static bool MayFoldLoad(SDValue Op) {
3774   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3775 }
3776
3777 static bool MayFoldIntoStore(SDValue Op) {
3778   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3779 }
3780
3781 static bool isTargetShuffle(unsigned Opcode) {
3782   switch(Opcode) {
3783   default: return false;
3784   case X86ISD::BLENDI:
3785   case X86ISD::PSHUFB:
3786   case X86ISD::PSHUFD:
3787   case X86ISD::PSHUFHW:
3788   case X86ISD::PSHUFLW:
3789   case X86ISD::SHUFP:
3790   case X86ISD::PALIGNR:
3791   case X86ISD::MOVLHPS:
3792   case X86ISD::MOVLHPD:
3793   case X86ISD::MOVHLPS:
3794   case X86ISD::MOVLPS:
3795   case X86ISD::MOVLPD:
3796   case X86ISD::MOVSHDUP:
3797   case X86ISD::MOVSLDUP:
3798   case X86ISD::MOVDDUP:
3799   case X86ISD::MOVSS:
3800   case X86ISD::MOVSD:
3801   case X86ISD::UNPCKL:
3802   case X86ISD::UNPCKH:
3803   case X86ISD::VPERMILPI:
3804   case X86ISD::VPERM2X128:
3805   case X86ISD::VPERMI:
3806   case X86ISD::VPERMV:
3807   case X86ISD::VPERMV3:
3808     return true;
3809   }
3810 }
3811
3812 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3813                                     SDValue V1, unsigned TargetMask,
3814                                     SelectionDAG &DAG) {
3815   switch(Opc) {
3816   default: llvm_unreachable("Unknown x86 shuffle node");
3817   case X86ISD::PSHUFD:
3818   case X86ISD::PSHUFHW:
3819   case X86ISD::PSHUFLW:
3820   case X86ISD::VPERMILPI:
3821   case X86ISD::VPERMI:
3822     return DAG.getNode(Opc, dl, VT, V1,
3823                        DAG.getConstant(TargetMask, dl, MVT::i8));
3824   }
3825 }
3826
3827 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3828                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3829   switch(Opc) {
3830   default: llvm_unreachable("Unknown x86 shuffle node");
3831   case X86ISD::MOVLHPS:
3832   case X86ISD::MOVLHPD:
3833   case X86ISD::MOVHLPS:
3834   case X86ISD::MOVLPS:
3835   case X86ISD::MOVLPD:
3836   case X86ISD::MOVSS:
3837   case X86ISD::MOVSD:
3838   case X86ISD::UNPCKL:
3839   case X86ISD::UNPCKH:
3840     return DAG.getNode(Opc, dl, VT, V1, V2);
3841   }
3842 }
3843
3844 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3845   MachineFunction &MF = DAG.getMachineFunction();
3846   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3847   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3848   int ReturnAddrIndex = FuncInfo->getRAIndex();
3849
3850   if (ReturnAddrIndex == 0) {
3851     // Set up a frame object for the return address.
3852     unsigned SlotSize = RegInfo->getSlotSize();
3853     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3854                                                            -(int64_t)SlotSize,
3855                                                            false);
3856     FuncInfo->setRAIndex(ReturnAddrIndex);
3857   }
3858
3859   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3860 }
3861
3862 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3863                                        bool hasSymbolicDisplacement) {
3864   // Offset should fit into 32 bit immediate field.
3865   if (!isInt<32>(Offset))
3866     return false;
3867
3868   // If we don't have a symbolic displacement - we don't have any extra
3869   // restrictions.
3870   if (!hasSymbolicDisplacement)
3871     return true;
3872
3873   // FIXME: Some tweaks might be needed for medium code model.
3874   if (M != CodeModel::Small && M != CodeModel::Kernel)
3875     return false;
3876
3877   // For small code model we assume that latest object is 16MB before end of 31
3878   // bits boundary. We may also accept pretty large negative constants knowing
3879   // that all objects are in the positive half of address space.
3880   if (M == CodeModel::Small && Offset < 16*1024*1024)
3881     return true;
3882
3883   // For kernel code model we know that all object resist in the negative half
3884   // of 32bits address space. We may not accept negative offsets, since they may
3885   // be just off and we may accept pretty large positive ones.
3886   if (M == CodeModel::Kernel && Offset >= 0)
3887     return true;
3888
3889   return false;
3890 }
3891
3892 /// Determines whether the callee is required to pop its own arguments.
3893 /// Callee pop is necessary to support tail calls.
3894 bool X86::isCalleePop(CallingConv::ID CallingConv,
3895                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3896   switch (CallingConv) {
3897   default:
3898     return false;
3899   case CallingConv::X86_StdCall:
3900   case CallingConv::X86_FastCall:
3901   case CallingConv::X86_ThisCall:
3902     return !is64Bit;
3903   case CallingConv::Fast:
3904   case CallingConv::GHC:
3905   case CallingConv::HiPE:
3906     if (IsVarArg)
3907       return false;
3908     return TailCallOpt;
3909   }
3910 }
3911
3912 /// \brief Return true if the condition is an unsigned comparison operation.
3913 static bool isX86CCUnsigned(unsigned X86CC) {
3914   switch (X86CC) {
3915   default: llvm_unreachable("Invalid integer condition!");
3916   case X86::COND_E:     return true;
3917   case X86::COND_G:     return false;
3918   case X86::COND_GE:    return false;
3919   case X86::COND_L:     return false;
3920   case X86::COND_LE:    return false;
3921   case X86::COND_NE:    return true;
3922   case X86::COND_B:     return true;
3923   case X86::COND_A:     return true;
3924   case X86::COND_BE:    return true;
3925   case X86::COND_AE:    return true;
3926   }
3927   llvm_unreachable("covered switch fell through?!");
3928 }
3929
3930 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3931 /// condition code, returning the condition code and the LHS/RHS of the
3932 /// comparison to make.
3933 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3934                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3935   if (!isFP) {
3936     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3937       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3938         // X > -1   -> X == 0, jump !sign.
3939         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3940         return X86::COND_NS;
3941       }
3942       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3943         // X < 0   -> X == 0, jump on sign.
3944         return X86::COND_S;
3945       }
3946       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3947         // X < 1   -> X <= 0
3948         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3949         return X86::COND_LE;
3950       }
3951     }
3952
3953     switch (SetCCOpcode) {
3954     default: llvm_unreachable("Invalid integer condition!");
3955     case ISD::SETEQ:  return X86::COND_E;
3956     case ISD::SETGT:  return X86::COND_G;
3957     case ISD::SETGE:  return X86::COND_GE;
3958     case ISD::SETLT:  return X86::COND_L;
3959     case ISD::SETLE:  return X86::COND_LE;
3960     case ISD::SETNE:  return X86::COND_NE;
3961     case ISD::SETULT: return X86::COND_B;
3962     case ISD::SETUGT: return X86::COND_A;
3963     case ISD::SETULE: return X86::COND_BE;
3964     case ISD::SETUGE: return X86::COND_AE;
3965     }
3966   }
3967
3968   // First determine if it is required or is profitable to flip the operands.
3969
3970   // If LHS is a foldable load, but RHS is not, flip the condition.
3971   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3972       !ISD::isNON_EXTLoad(RHS.getNode())) {
3973     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3974     std::swap(LHS, RHS);
3975   }
3976
3977   switch (SetCCOpcode) {
3978   default: break;
3979   case ISD::SETOLT:
3980   case ISD::SETOLE:
3981   case ISD::SETUGT:
3982   case ISD::SETUGE:
3983     std::swap(LHS, RHS);
3984     break;
3985   }
3986
3987   // On a floating point condition, the flags are set as follows:
3988   // ZF  PF  CF   op
3989   //  0 | 0 | 0 | X > Y
3990   //  0 | 0 | 1 | X < Y
3991   //  1 | 0 | 0 | X == Y
3992   //  1 | 1 | 1 | unordered
3993   switch (SetCCOpcode) {
3994   default: llvm_unreachable("Condcode should be pre-legalized away");
3995   case ISD::SETUEQ:
3996   case ISD::SETEQ:   return X86::COND_E;
3997   case ISD::SETOLT:              // flipped
3998   case ISD::SETOGT:
3999   case ISD::SETGT:   return X86::COND_A;
4000   case ISD::SETOLE:              // flipped
4001   case ISD::SETOGE:
4002   case ISD::SETGE:   return X86::COND_AE;
4003   case ISD::SETUGT:              // flipped
4004   case ISD::SETULT:
4005   case ISD::SETLT:   return X86::COND_B;
4006   case ISD::SETUGE:              // flipped
4007   case ISD::SETULE:
4008   case ISD::SETLE:   return X86::COND_BE;
4009   case ISD::SETONE:
4010   case ISD::SETNE:   return X86::COND_NE;
4011   case ISD::SETUO:   return X86::COND_P;
4012   case ISD::SETO:    return X86::COND_NP;
4013   case ISD::SETOEQ:
4014   case ISD::SETUNE:  return X86::COND_INVALID;
4015   }
4016 }
4017
4018 /// Is there a floating point cmov for the specific X86 condition code?
4019 /// Current x86 isa includes the following FP cmov instructions:
4020 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4021 static bool hasFPCMov(unsigned X86CC) {
4022   switch (X86CC) {
4023   default:
4024     return false;
4025   case X86::COND_B:
4026   case X86::COND_BE:
4027   case X86::COND_E:
4028   case X86::COND_P:
4029   case X86::COND_A:
4030   case X86::COND_AE:
4031   case X86::COND_NE:
4032   case X86::COND_NP:
4033     return true;
4034   }
4035 }
4036
4037 /// Returns true if the target can instruction select the
4038 /// specified FP immediate natively. If false, the legalizer will
4039 /// materialize the FP immediate as a load from a constant pool.
4040 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4041   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4042     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4043       return true;
4044   }
4045   return false;
4046 }
4047
4048 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4049                                               ISD::LoadExtType ExtTy,
4050                                               EVT NewVT) const {
4051   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4052   // relocation target a movq or addq instruction: don't let the load shrink.
4053   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4054   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4055     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4056       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4057   return true;
4058 }
4059
4060 /// \brief Returns true if it is beneficial to convert a load of a constant
4061 /// to just the constant itself.
4062 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4063                                                           Type *Ty) const {
4064   assert(Ty->isIntegerTy());
4065
4066   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4067   if (BitSize == 0 || BitSize > 64)
4068     return false;
4069   return true;
4070 }
4071
4072 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4073                                                 unsigned Index) const {
4074   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4075     return false;
4076
4077   return (Index == 0 || Index == ResVT.getVectorNumElements());
4078 }
4079
4080 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4081   // Speculate cttz only if we can directly use TZCNT.
4082   return Subtarget->hasBMI();
4083 }
4084
4085 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4086   // Speculate ctlz only if we can directly use LZCNT.
4087   return Subtarget->hasLZCNT();
4088 }
4089
4090 /// Return true if every element in Mask, beginning
4091 /// from position Pos and ending in Pos+Size is undef.
4092 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4093   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4094     if (0 <= Mask[i])
4095       return false;
4096   return true;
4097 }
4098
4099 /// Return true if Val is undef or if its value falls within the
4100 /// specified range (L, H].
4101 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4102   return (Val < 0) || (Val >= Low && Val < Hi);
4103 }
4104
4105 /// Val is either less than zero (undef) or equal to the specified value.
4106 static bool isUndefOrEqual(int Val, int CmpVal) {
4107   return (Val < 0 || Val == CmpVal);
4108 }
4109
4110 /// Return true if every element in Mask, beginning
4111 /// from position Pos and ending in Pos+Size, falls within the specified
4112 /// sequential range (Low, Low+Size]. or is undef.
4113 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4114                                        unsigned Pos, unsigned Size, int Low) {
4115   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4116     if (!isUndefOrEqual(Mask[i], Low))
4117       return false;
4118   return true;
4119 }
4120
4121 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4122 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4123 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4124   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4125   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4126     return false;
4127
4128   // The index should be aligned on a vecWidth-bit boundary.
4129   uint64_t Index =
4130     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4131
4132   MVT VT = N->getSimpleValueType(0);
4133   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4134   bool Result = (Index * ElSize) % vecWidth == 0;
4135
4136   return Result;
4137 }
4138
4139 /// Return true if the specified INSERT_SUBVECTOR
4140 /// operand specifies a subvector insert that is suitable for input to
4141 /// insertion of 128 or 256-bit subvectors
4142 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4143   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4144   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4145     return false;
4146   // The index should be aligned on a vecWidth-bit boundary.
4147   uint64_t Index =
4148     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4149
4150   MVT VT = N->getSimpleValueType(0);
4151   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4152   bool Result = (Index * ElSize) % vecWidth == 0;
4153
4154   return Result;
4155 }
4156
4157 bool X86::isVINSERT128Index(SDNode *N) {
4158   return isVINSERTIndex(N, 128);
4159 }
4160
4161 bool X86::isVINSERT256Index(SDNode *N) {
4162   return isVINSERTIndex(N, 256);
4163 }
4164
4165 bool X86::isVEXTRACT128Index(SDNode *N) {
4166   return isVEXTRACTIndex(N, 128);
4167 }
4168
4169 bool X86::isVEXTRACT256Index(SDNode *N) {
4170   return isVEXTRACTIndex(N, 256);
4171 }
4172
4173 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4174   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4175   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4176     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4177
4178   uint64_t Index =
4179     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4180
4181   MVT VecVT = N->getOperand(0).getSimpleValueType();
4182   MVT ElVT = VecVT.getVectorElementType();
4183
4184   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4185   return Index / NumElemsPerChunk;
4186 }
4187
4188 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4189   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4190   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4191     llvm_unreachable("Illegal insert subvector for VINSERT");
4192
4193   uint64_t Index =
4194     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4195
4196   MVT VecVT = N->getSimpleValueType(0);
4197   MVT ElVT = VecVT.getVectorElementType();
4198
4199   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4200   return Index / NumElemsPerChunk;
4201 }
4202
4203 /// Return the appropriate immediate to extract the specified
4204 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4205 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4206   return getExtractVEXTRACTImmediate(N, 128);
4207 }
4208
4209 /// Return the appropriate immediate to extract the specified
4210 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4211 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4212   return getExtractVEXTRACTImmediate(N, 256);
4213 }
4214
4215 /// Return the appropriate immediate to insert at the specified
4216 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4217 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4218   return getInsertVINSERTImmediate(N, 128);
4219 }
4220
4221 /// Return the appropriate immediate to insert at the specified
4222 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4223 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4224   return getInsertVINSERTImmediate(N, 256);
4225 }
4226
4227 /// Returns true if Elt is a constant integer zero
4228 static bool isZero(SDValue V) {
4229   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4230   return C && C->isNullValue();
4231 }
4232
4233 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4234 bool X86::isZeroNode(SDValue Elt) {
4235   if (isZero(Elt))
4236     return true;
4237   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4238     return CFP->getValueAPF().isPosZero();
4239   return false;
4240 }
4241
4242 /// Returns a vector of specified type with all zero elements.
4243 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4244                              SelectionDAG &DAG, SDLoc dl) {
4245   assert(VT.isVector() && "Expected a vector type");
4246
4247   // Always build SSE zero vectors as <4 x i32> bitcasted
4248   // to their dest type. This ensures they get CSE'd.
4249   SDValue Vec;
4250   if (VT.is128BitVector()) {  // SSE
4251     if (Subtarget->hasSSE2()) {  // SSE2
4252       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4253       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4254     } else { // SSE1
4255       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4256       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4257     }
4258   } else if (VT.is256BitVector()) { // AVX
4259     if (Subtarget->hasInt256()) { // AVX2
4260       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4261       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4262       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4263     } else {
4264       // 256-bit logic and arithmetic instructions in AVX are all
4265       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4266       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4267       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4268       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4269     }
4270   } else if (VT.is512BitVector()) { // AVX-512
4271       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4272       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4273                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4274       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4275   } else if (VT.getScalarType() == MVT::i1) {
4276
4277     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4278             && "Unexpected vector type");
4279     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4280             && "Unexpected vector type");
4281     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4282     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4283     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4284   } else
4285     llvm_unreachable("Unexpected vector type");
4286
4287   return DAG.getBitcast(VT, Vec);
4288 }
4289
4290 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4291                                 SelectionDAG &DAG, SDLoc dl,
4292                                 unsigned vectorWidth) {
4293   assert((vectorWidth == 128 || vectorWidth == 256) &&
4294          "Unsupported vector width");
4295   EVT VT = Vec.getValueType();
4296   EVT ElVT = VT.getVectorElementType();
4297   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4298   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4299                                   VT.getVectorNumElements()/Factor);
4300
4301   // Extract from UNDEF is UNDEF.
4302   if (Vec.getOpcode() == ISD::UNDEF)
4303     return DAG.getUNDEF(ResultVT);
4304
4305   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4306   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4307
4308   // This is the index of the first element of the vectorWidth-bit chunk
4309   // we want.
4310   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4311                                * ElemsPerChunk);
4312
4313   // If the input is a buildvector just emit a smaller one.
4314   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4315     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4316                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4317                                     ElemsPerChunk));
4318
4319   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4320   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4321 }
4322
4323 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4324 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4325 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4326 /// instructions or a simple subregister reference. Idx is an index in the
4327 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4328 /// lowering EXTRACT_VECTOR_ELT operations easier.
4329 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4330                                    SelectionDAG &DAG, SDLoc dl) {
4331   assert((Vec.getValueType().is256BitVector() ||
4332           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4333   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4334 }
4335
4336 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4337 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4338                                    SelectionDAG &DAG, SDLoc dl) {
4339   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4340   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4341 }
4342
4343 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4344                                unsigned IdxVal, SelectionDAG &DAG,
4345                                SDLoc dl, unsigned vectorWidth) {
4346   assert((vectorWidth == 128 || vectorWidth == 256) &&
4347          "Unsupported vector width");
4348   // Inserting UNDEF is Result
4349   if (Vec.getOpcode() == ISD::UNDEF)
4350     return Result;
4351   EVT VT = Vec.getValueType();
4352   EVT ElVT = VT.getVectorElementType();
4353   EVT ResultVT = Result.getValueType();
4354
4355   // Insert the relevant vectorWidth bits.
4356   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4357
4358   // This is the index of the first element of the vectorWidth-bit chunk
4359   // we want.
4360   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4361                                * ElemsPerChunk);
4362
4363   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4364   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4365 }
4366
4367 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4368 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4369 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4370 /// simple superregister reference.  Idx is an index in the 128 bits
4371 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4372 /// lowering INSERT_VECTOR_ELT operations easier.
4373 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4374                                   SelectionDAG &DAG, SDLoc dl) {
4375   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4376
4377   // For insertion into the zero index (low half) of a 256-bit vector, it is
4378   // more efficient to generate a blend with immediate instead of an insert*128.
4379   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4380   // extend the subvector to the size of the result vector. Make sure that
4381   // we are not recursing on that node by checking for undef here.
4382   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4383       Result.getOpcode() != ISD::UNDEF) {
4384     EVT ResultVT = Result.getValueType();
4385     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4386     SDValue Undef = DAG.getUNDEF(ResultVT);
4387     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4388                                  Vec, ZeroIndex);
4389
4390     // The blend instruction, and therefore its mask, depend on the data type.
4391     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4392     if (ScalarType.isFloatingPoint()) {
4393       // Choose either vblendps (float) or vblendpd (double).
4394       unsigned ScalarSize = ScalarType.getSizeInBits();
4395       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4396       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4397       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4398       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4399     }
4400
4401     const X86Subtarget &Subtarget =
4402     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4403
4404     // AVX2 is needed for 256-bit integer blend support.
4405     // Integers must be cast to 32-bit because there is only vpblendd;
4406     // vpblendw can't be used for this because it has a handicapped mask.
4407
4408     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4409     // is still more efficient than using the wrong domain vinsertf128 that
4410     // will be created by InsertSubVector().
4411     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4412
4413     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4414     Vec256 = DAG.getBitcast(CastVT, Vec256);
4415     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4416     return DAG.getBitcast(ResultVT, Vec256);
4417   }
4418
4419   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4420 }
4421
4422 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4423                                   SelectionDAG &DAG, SDLoc dl) {
4424   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4425   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4426 }
4427
4428 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4429 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4430 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4431 /// large BUILD_VECTORS.
4432 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4433                                    unsigned NumElems, SelectionDAG &DAG,
4434                                    SDLoc dl) {
4435   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4436   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4437 }
4438
4439 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4440                                    unsigned NumElems, SelectionDAG &DAG,
4441                                    SDLoc dl) {
4442   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4443   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4444 }
4445
4446 /// Returns a vector of specified type with all bits set.
4447 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4448 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4449 /// Then bitcast to their original type, ensuring they get CSE'd.
4450 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4451                              SelectionDAG &DAG, SDLoc dl) {
4452   assert(VT.isVector() && "Expected a vector type");
4453
4454   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4455   SDValue Vec;
4456   if (VT.is512BitVector()) {
4457     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4458                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4459     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4460   } else if (VT.is256BitVector()) {
4461     if (Subtarget->hasInt256()) { // AVX2
4462       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4463       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4464     } else { // AVX
4465       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4466       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4467     }
4468   } else if (VT.is128BitVector()) {
4469     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4470   } else
4471     llvm_unreachable("Unexpected vector type");
4472
4473   return DAG.getBitcast(VT, Vec);
4474 }
4475
4476 /// Returns a vector_shuffle node for an unpackl operation.
4477 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4478                           SDValue V2) {
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SmallVector<int, 8> Mask;
4481   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4482     Mask.push_back(i);
4483     Mask.push_back(i + NumElems);
4484   }
4485   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4486 }
4487
4488 /// Returns a vector_shuffle node for an unpackh operation.
4489 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4490                           SDValue V2) {
4491   unsigned NumElems = VT.getVectorNumElements();
4492   SmallVector<int, 8> Mask;
4493   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4494     Mask.push_back(i + Half);
4495     Mask.push_back(i + NumElems + Half);
4496   }
4497   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4498 }
4499
4500 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4501 /// This produces a shuffle where the low element of V2 is swizzled into the
4502 /// zero/undef vector, landing at element Idx.
4503 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4504 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4505                                            bool IsZero,
4506                                            const X86Subtarget *Subtarget,
4507                                            SelectionDAG &DAG) {
4508   MVT VT = V2.getSimpleValueType();
4509   SDValue V1 = IsZero
4510     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4511   unsigned NumElems = VT.getVectorNumElements();
4512   SmallVector<int, 16> MaskVec;
4513   for (unsigned i = 0; i != NumElems; ++i)
4514     // If this is the insertion idx, put the low elt of V2 here.
4515     MaskVec.push_back(i == Idx ? NumElems : i);
4516   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4517 }
4518
4519 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4520 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4521 /// uses one source. Note that this will set IsUnary for shuffles which use a
4522 /// single input multiple times, and in those cases it will
4523 /// adjust the mask to only have indices within that single input.
4524 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4525 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4526                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4527   unsigned NumElems = VT.getVectorNumElements();
4528   SDValue ImmN;
4529
4530   IsUnary = false;
4531   bool IsFakeUnary = false;
4532   switch(N->getOpcode()) {
4533   case X86ISD::BLENDI:
4534     ImmN = N->getOperand(N->getNumOperands()-1);
4535     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4536     break;
4537   case X86ISD::SHUFP:
4538     ImmN = N->getOperand(N->getNumOperands()-1);
4539     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4540     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4541     break;
4542   case X86ISD::UNPCKH:
4543     DecodeUNPCKHMask(VT, Mask);
4544     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4545     break;
4546   case X86ISD::UNPCKL:
4547     DecodeUNPCKLMask(VT, Mask);
4548     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4549     break;
4550   case X86ISD::MOVHLPS:
4551     DecodeMOVHLPSMask(NumElems, Mask);
4552     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4553     break;
4554   case X86ISD::MOVLHPS:
4555     DecodeMOVLHPSMask(NumElems, Mask);
4556     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4557     break;
4558   case X86ISD::PALIGNR:
4559     ImmN = N->getOperand(N->getNumOperands()-1);
4560     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4561     break;
4562   case X86ISD::PSHUFD:
4563   case X86ISD::VPERMILPI:
4564     ImmN = N->getOperand(N->getNumOperands()-1);
4565     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4566     IsUnary = true;
4567     break;
4568   case X86ISD::PSHUFHW:
4569     ImmN = N->getOperand(N->getNumOperands()-1);
4570     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4571     IsUnary = true;
4572     break;
4573   case X86ISD::PSHUFLW:
4574     ImmN = N->getOperand(N->getNumOperands()-1);
4575     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4576     IsUnary = true;
4577     break;
4578   case X86ISD::PSHUFB: {
4579     IsUnary = true;
4580     SDValue MaskNode = N->getOperand(1);
4581     while (MaskNode->getOpcode() == ISD::BITCAST)
4582       MaskNode = MaskNode->getOperand(0);
4583
4584     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4585       // If we have a build-vector, then things are easy.
4586       EVT VT = MaskNode.getValueType();
4587       assert(VT.isVector() &&
4588              "Can't produce a non-vector with a build_vector!");
4589       if (!VT.isInteger())
4590         return false;
4591
4592       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4593
4594       SmallVector<uint64_t, 32> RawMask;
4595       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4596         SDValue Op = MaskNode->getOperand(i);
4597         if (Op->getOpcode() == ISD::UNDEF) {
4598           RawMask.push_back((uint64_t)SM_SentinelUndef);
4599           continue;
4600         }
4601         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4602         if (!CN)
4603           return false;
4604         APInt MaskElement = CN->getAPIntValue();
4605
4606         // We now have to decode the element which could be any integer size and
4607         // extract each byte of it.
4608         for (int j = 0; j < NumBytesPerElement; ++j) {
4609           // Note that this is x86 and so always little endian: the low byte is
4610           // the first byte of the mask.
4611           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4612           MaskElement = MaskElement.lshr(8);
4613         }
4614       }
4615       DecodePSHUFBMask(RawMask, Mask);
4616       break;
4617     }
4618
4619     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4620     if (!MaskLoad)
4621       return false;
4622
4623     SDValue Ptr = MaskLoad->getBasePtr();
4624     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4625         Ptr->getOpcode() == X86ISD::WrapperRIP)
4626       Ptr = Ptr->getOperand(0);
4627
4628     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4629     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4630       return false;
4631
4632     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4633       DecodePSHUFBMask(C, Mask);
4634       if (Mask.empty())
4635         return false;
4636       break;
4637     }
4638
4639     return false;
4640   }
4641   case X86ISD::VPERMI:
4642     ImmN = N->getOperand(N->getNumOperands()-1);
4643     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4644     IsUnary = true;
4645     break;
4646   case X86ISD::MOVSS:
4647   case X86ISD::MOVSD:
4648     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4649     break;
4650   case X86ISD::VPERM2X128:
4651     ImmN = N->getOperand(N->getNumOperands()-1);
4652     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4653     if (Mask.empty()) return false;
4654     // Mask only contains negative index if an element is zero.
4655     if (std::any_of(Mask.begin(), Mask.end(),
4656                     [](int M){ return M == SM_SentinelZero; }))
4657       return false;
4658     break;
4659   case X86ISD::MOVSLDUP:
4660     DecodeMOVSLDUPMask(VT, Mask);
4661     IsUnary = true;
4662     break;
4663   case X86ISD::MOVSHDUP:
4664     DecodeMOVSHDUPMask(VT, Mask);
4665     IsUnary = true;
4666     break;
4667   case X86ISD::MOVDDUP:
4668     DecodeMOVDDUPMask(VT, Mask);
4669     IsUnary = true;
4670     break;
4671   case X86ISD::MOVLHPD:
4672   case X86ISD::MOVLPD:
4673   case X86ISD::MOVLPS:
4674     // Not yet implemented
4675     return false;
4676   case X86ISD::VPERMV: {
4677     IsUnary = true;
4678     SDValue MaskNode = N->getOperand(0);
4679     while (MaskNode->getOpcode() == ISD::BITCAST)
4680       MaskNode = MaskNode->getOperand(0);
4681
4682     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4683     SmallVector<uint64_t, 32> RawMask;
4684     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4685       // If we have a build-vector, then things are easy.
4686       assert(MaskNode.getValueType().isInteger() &&
4687              MaskNode.getValueType().getVectorNumElements() ==
4688              VT.getVectorNumElements());
4689
4690       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4691         SDValue Op = MaskNode->getOperand(i);
4692         if (Op->getOpcode() == ISD::UNDEF)
4693           RawMask.push_back((uint64_t)SM_SentinelUndef);
4694         else if (isa<ConstantSDNode>(Op)) {
4695           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4696           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4697         } else
4698           return false;
4699       }
4700       DecodeVPERMVMask(RawMask, Mask);
4701       break;
4702     }
4703     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4704       unsigned NumEltsInMask = MaskNode->getNumOperands();
4705       MaskNode = MaskNode->getOperand(0);
4706       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4707       if (CN) {
4708         APInt MaskEltValue = CN->getAPIntValue();
4709         for (unsigned i = 0; i < NumEltsInMask; ++i)
4710           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4711         DecodeVPERMVMask(RawMask, Mask);
4712         break;
4713       }
4714       // It may be a scalar load
4715     }
4716
4717     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4718     if (!MaskLoad)
4719       return false;
4720
4721     SDValue Ptr = MaskLoad->getBasePtr();
4722     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4723         Ptr->getOpcode() == X86ISD::WrapperRIP)
4724       Ptr = Ptr->getOperand(0);
4725
4726     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4727     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4728       return false;
4729
4730     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4731     if (C) {
4732       DecodeVPERMVMask(C, VT, Mask);
4733       if (Mask.empty())
4734         return false;
4735       break;
4736     }
4737     return false;
4738   }
4739   case X86ISD::VPERMV3: {
4740     IsUnary = false;
4741     SDValue MaskNode = N->getOperand(1);
4742     while (MaskNode->getOpcode() == ISD::BITCAST)
4743       MaskNode = MaskNode->getOperand(1);
4744
4745     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4746       // If we have a build-vector, then things are easy.
4747       assert(MaskNode.getValueType().isInteger() &&
4748              MaskNode.getValueType().getVectorNumElements() ==
4749              VT.getVectorNumElements());
4750
4751       SmallVector<uint64_t, 32> RawMask;
4752       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4753
4754       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4755         SDValue Op = MaskNode->getOperand(i);
4756         if (Op->getOpcode() == ISD::UNDEF)
4757           RawMask.push_back((uint64_t)SM_SentinelUndef);
4758         else {
4759           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4760           if (!CN)
4761             return false;
4762           APInt MaskElement = CN->getAPIntValue();
4763           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4764         }
4765       }
4766       DecodeVPERMV3Mask(RawMask, Mask);
4767       break;
4768     }
4769
4770     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4771     if (!MaskLoad)
4772       return false;
4773
4774     SDValue Ptr = MaskLoad->getBasePtr();
4775     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4776         Ptr->getOpcode() == X86ISD::WrapperRIP)
4777       Ptr = Ptr->getOperand(0);
4778
4779     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4780     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4781       return false;
4782
4783     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4784     if (C) {
4785       DecodeVPERMV3Mask(C, VT, Mask);
4786       if (Mask.empty())
4787         return false;
4788       break;
4789     }
4790     return false;
4791   }
4792   default: llvm_unreachable("unknown target shuffle node");
4793   }
4794
4795   // If we have a fake unary shuffle, the shuffle mask is spread across two
4796   // inputs that are actually the same node. Re-map the mask to always point
4797   // into the first input.
4798   if (IsFakeUnary)
4799     for (int &M : Mask)
4800       if (M >= (int)Mask.size())
4801         M -= Mask.size();
4802
4803   return true;
4804 }
4805
4806 /// Returns the scalar element that will make up the ith
4807 /// element of the result of the vector shuffle.
4808 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4809                                    unsigned Depth) {
4810   if (Depth == 6)
4811     return SDValue();  // Limit search depth.
4812
4813   SDValue V = SDValue(N, 0);
4814   EVT VT = V.getValueType();
4815   unsigned Opcode = V.getOpcode();
4816
4817   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4818   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4819     int Elt = SV->getMaskElt(Index);
4820
4821     if (Elt < 0)
4822       return DAG.getUNDEF(VT.getVectorElementType());
4823
4824     unsigned NumElems = VT.getVectorNumElements();
4825     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4826                                          : SV->getOperand(1);
4827     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4828   }
4829
4830   // Recurse into target specific vector shuffles to find scalars.
4831   if (isTargetShuffle(Opcode)) {
4832     MVT ShufVT = V.getSimpleValueType();
4833     unsigned NumElems = ShufVT.getVectorNumElements();
4834     SmallVector<int, 16> ShuffleMask;
4835     bool IsUnary;
4836
4837     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4838       return SDValue();
4839
4840     int Elt = ShuffleMask[Index];
4841     if (Elt < 0)
4842       return DAG.getUNDEF(ShufVT.getVectorElementType());
4843
4844     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4845                                          : N->getOperand(1);
4846     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4847                                Depth+1);
4848   }
4849
4850   // Actual nodes that may contain scalar elements
4851   if (Opcode == ISD::BITCAST) {
4852     V = V.getOperand(0);
4853     EVT SrcVT = V.getValueType();
4854     unsigned NumElems = VT.getVectorNumElements();
4855
4856     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4857       return SDValue();
4858   }
4859
4860   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4861     return (Index == 0) ? V.getOperand(0)
4862                         : DAG.getUNDEF(VT.getVectorElementType());
4863
4864   if (V.getOpcode() == ISD::BUILD_VECTOR)
4865     return V.getOperand(Index);
4866
4867   return SDValue();
4868 }
4869
4870 /// Custom lower build_vector of v16i8.
4871 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4872                                        unsigned NumNonZero, unsigned NumZero,
4873                                        SelectionDAG &DAG,
4874                                        const X86Subtarget* Subtarget,
4875                                        const TargetLowering &TLI) {
4876   if (NumNonZero > 8)
4877     return SDValue();
4878
4879   SDLoc dl(Op);
4880   SDValue V;
4881   bool First = true;
4882
4883   // SSE4.1 - use PINSRB to insert each byte directly.
4884   if (Subtarget->hasSSE41()) {
4885     for (unsigned i = 0; i < 16; ++i) {
4886       bool isNonZero = (NonZeros & (1 << i)) != 0;
4887       if (isNonZero) {
4888         if (First) {
4889           if (NumZero)
4890             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4891           else
4892             V = DAG.getUNDEF(MVT::v16i8);
4893           First = false;
4894         }
4895         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4896                         MVT::v16i8, V, Op.getOperand(i),
4897                         DAG.getIntPtrConstant(i, dl));
4898       }
4899     }
4900
4901     return V;
4902   }
4903
4904   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4905   for (unsigned i = 0; i < 16; ++i) {
4906     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4907     if (ThisIsNonZero && First) {
4908       if (NumZero)
4909         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4910       else
4911         V = DAG.getUNDEF(MVT::v8i16);
4912       First = false;
4913     }
4914
4915     if ((i & 1) != 0) {
4916       SDValue ThisElt, LastElt;
4917       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4918       if (LastIsNonZero) {
4919         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4920                               MVT::i16, Op.getOperand(i-1));
4921       }
4922       if (ThisIsNonZero) {
4923         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4924         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4925                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4926         if (LastIsNonZero)
4927           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4928       } else
4929         ThisElt = LastElt;
4930
4931       if (ThisElt.getNode())
4932         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4933                         DAG.getIntPtrConstant(i/2, dl));
4934     }
4935   }
4936
4937   return DAG.getBitcast(MVT::v16i8, V);
4938 }
4939
4940 /// Custom lower build_vector of v8i16.
4941 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4942                                      unsigned NumNonZero, unsigned NumZero,
4943                                      SelectionDAG &DAG,
4944                                      const X86Subtarget* Subtarget,
4945                                      const TargetLowering &TLI) {
4946   if (NumNonZero > 4)
4947     return SDValue();
4948
4949   SDLoc dl(Op);
4950   SDValue V;
4951   bool First = true;
4952   for (unsigned i = 0; i < 8; ++i) {
4953     bool isNonZero = (NonZeros & (1 << i)) != 0;
4954     if (isNonZero) {
4955       if (First) {
4956         if (NumZero)
4957           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4958         else
4959           V = DAG.getUNDEF(MVT::v8i16);
4960         First = false;
4961       }
4962       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4963                       MVT::v8i16, V, Op.getOperand(i),
4964                       DAG.getIntPtrConstant(i, dl));
4965     }
4966   }
4967
4968   return V;
4969 }
4970
4971 /// Custom lower build_vector of v4i32 or v4f32.
4972 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4973                                      const X86Subtarget *Subtarget,
4974                                      const TargetLowering &TLI) {
4975   // Find all zeroable elements.
4976   std::bitset<4> Zeroable;
4977   for (int i=0; i < 4; ++i) {
4978     SDValue Elt = Op->getOperand(i);
4979     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4980   }
4981   assert(Zeroable.size() - Zeroable.count() > 1 &&
4982          "We expect at least two non-zero elements!");
4983
4984   // We only know how to deal with build_vector nodes where elements are either
4985   // zeroable or extract_vector_elt with constant index.
4986   SDValue FirstNonZero;
4987   unsigned FirstNonZeroIdx;
4988   for (unsigned i=0; i < 4; ++i) {
4989     if (Zeroable[i])
4990       continue;
4991     SDValue Elt = Op->getOperand(i);
4992     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4993         !isa<ConstantSDNode>(Elt.getOperand(1)))
4994       return SDValue();
4995     // Make sure that this node is extracting from a 128-bit vector.
4996     MVT VT = Elt.getOperand(0).getSimpleValueType();
4997     if (!VT.is128BitVector())
4998       return SDValue();
4999     if (!FirstNonZero.getNode()) {
5000       FirstNonZero = Elt;
5001       FirstNonZeroIdx = i;
5002     }
5003   }
5004
5005   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5006   SDValue V1 = FirstNonZero.getOperand(0);
5007   MVT VT = V1.getSimpleValueType();
5008
5009   // See if this build_vector can be lowered as a blend with zero.
5010   SDValue Elt;
5011   unsigned EltMaskIdx, EltIdx;
5012   int Mask[4];
5013   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5014     if (Zeroable[EltIdx]) {
5015       // The zero vector will be on the right hand side.
5016       Mask[EltIdx] = EltIdx+4;
5017       continue;
5018     }
5019
5020     Elt = Op->getOperand(EltIdx);
5021     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5022     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5023     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5024       break;
5025     Mask[EltIdx] = EltIdx;
5026   }
5027
5028   if (EltIdx == 4) {
5029     // Let the shuffle legalizer deal with blend operations.
5030     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5031     if (V1.getSimpleValueType() != VT)
5032       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5033     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5034   }
5035
5036   // See if we can lower this build_vector to a INSERTPS.
5037   if (!Subtarget->hasSSE41())
5038     return SDValue();
5039
5040   SDValue V2 = Elt.getOperand(0);
5041   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5042     V1 = SDValue();
5043
5044   bool CanFold = true;
5045   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5046     if (Zeroable[i])
5047       continue;
5048
5049     SDValue Current = Op->getOperand(i);
5050     SDValue SrcVector = Current->getOperand(0);
5051     if (!V1.getNode())
5052       V1 = SrcVector;
5053     CanFold = SrcVector == V1 &&
5054       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5055   }
5056
5057   if (!CanFold)
5058     return SDValue();
5059
5060   assert(V1.getNode() && "Expected at least two non-zero elements!");
5061   if (V1.getSimpleValueType() != MVT::v4f32)
5062     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5063   if (V2.getSimpleValueType() != MVT::v4f32)
5064     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5065
5066   // Ok, we can emit an INSERTPS instruction.
5067   unsigned ZMask = Zeroable.to_ulong();
5068
5069   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5070   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5071   SDLoc DL(Op);
5072   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5073                                DAG.getIntPtrConstant(InsertPSMask, DL));
5074   return DAG.getBitcast(VT, Result);
5075 }
5076
5077 /// Return a vector logical shift node.
5078 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5079                          unsigned NumBits, SelectionDAG &DAG,
5080                          const TargetLowering &TLI, SDLoc dl) {
5081   assert(VT.is128BitVector() && "Unknown type for VShift");
5082   MVT ShVT = MVT::v2i64;
5083   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5084   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5085   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5086   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5087   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5088   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5089 }
5090
5091 static SDValue
5092 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5093
5094   // Check if the scalar load can be widened into a vector load. And if
5095   // the address is "base + cst" see if the cst can be "absorbed" into
5096   // the shuffle mask.
5097   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5098     SDValue Ptr = LD->getBasePtr();
5099     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5100       return SDValue();
5101     EVT PVT = LD->getValueType(0);
5102     if (PVT != MVT::i32 && PVT != MVT::f32)
5103       return SDValue();
5104
5105     int FI = -1;
5106     int64_t Offset = 0;
5107     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5108       FI = FINode->getIndex();
5109       Offset = 0;
5110     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5111                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5112       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5113       Offset = Ptr.getConstantOperandVal(1);
5114       Ptr = Ptr.getOperand(0);
5115     } else {
5116       return SDValue();
5117     }
5118
5119     // FIXME: 256-bit vector instructions don't require a strict alignment,
5120     // improve this code to support it better.
5121     unsigned RequiredAlign = VT.getSizeInBits()/8;
5122     SDValue Chain = LD->getChain();
5123     // Make sure the stack object alignment is at least 16 or 32.
5124     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5125     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5126       if (MFI->isFixedObjectIndex(FI)) {
5127         // Can't change the alignment. FIXME: It's possible to compute
5128         // the exact stack offset and reference FI + adjust offset instead.
5129         // If someone *really* cares about this. That's the way to implement it.
5130         return SDValue();
5131       } else {
5132         MFI->setObjectAlignment(FI, RequiredAlign);
5133       }
5134     }
5135
5136     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5137     // Ptr + (Offset & ~15).
5138     if (Offset < 0)
5139       return SDValue();
5140     if ((Offset % RequiredAlign) & 3)
5141       return SDValue();
5142     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5143     if (StartOffset) {
5144       SDLoc DL(Ptr);
5145       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5146                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5147     }
5148
5149     int EltNo = (Offset - StartOffset) >> 2;
5150     unsigned NumElems = VT.getVectorNumElements();
5151
5152     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5153     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5154                              LD->getPointerInfo().getWithOffset(StartOffset),
5155                              false, false, false, 0);
5156
5157     SmallVector<int, 8> Mask(NumElems, EltNo);
5158
5159     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5160   }
5161
5162   return SDValue();
5163 }
5164
5165 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5166 /// elements can be replaced by a single large load which has the same value as
5167 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5168 ///
5169 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5170 ///
5171 /// FIXME: we'd also like to handle the case where the last elements are zero
5172 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5173 /// There's even a handy isZeroNode for that purpose.
5174 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5175                                         SDLoc &DL, SelectionDAG &DAG,
5176                                         bool isAfterLegalize) {
5177   unsigned NumElems = Elts.size();
5178
5179   LoadSDNode *LDBase = nullptr;
5180   unsigned LastLoadedElt = -1U;
5181
5182   // For each element in the initializer, see if we've found a load or an undef.
5183   // If we don't find an initial load element, or later load elements are
5184   // non-consecutive, bail out.
5185   for (unsigned i = 0; i < NumElems; ++i) {
5186     SDValue Elt = Elts[i];
5187     // Look through a bitcast.
5188     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5189       Elt = Elt.getOperand(0);
5190     if (!Elt.getNode() ||
5191         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5192       return SDValue();
5193     if (!LDBase) {
5194       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5195         return SDValue();
5196       LDBase = cast<LoadSDNode>(Elt.getNode());
5197       LastLoadedElt = i;
5198       continue;
5199     }
5200     if (Elt.getOpcode() == ISD::UNDEF)
5201       continue;
5202
5203     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5204     EVT LdVT = Elt.getValueType();
5205     // Each loaded element must be the correct fractional portion of the
5206     // requested vector load.
5207     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5208       return SDValue();
5209     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5210       return SDValue();
5211     LastLoadedElt = i;
5212   }
5213
5214   // If we have found an entire vector of loads and undefs, then return a large
5215   // load of the entire vector width starting at the base pointer.  If we found
5216   // consecutive loads for the low half, generate a vzext_load node.
5217   if (LastLoadedElt == NumElems - 1) {
5218     assert(LDBase && "Did not find base load for merging consecutive loads");
5219     EVT EltVT = LDBase->getValueType(0);
5220     // Ensure that the input vector size for the merged loads matches the
5221     // cumulative size of the input elements.
5222     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5223       return SDValue();
5224
5225     if (isAfterLegalize &&
5226         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5227       return SDValue();
5228
5229     SDValue NewLd = SDValue();
5230
5231     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5232                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5233                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5234                         LDBase->getAlignment());
5235
5236     if (LDBase->hasAnyUseOfValue(1)) {
5237       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5238                                      SDValue(LDBase, 1),
5239                                      SDValue(NewLd.getNode(), 1));
5240       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5241       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5242                              SDValue(NewLd.getNode(), 1));
5243     }
5244
5245     return NewLd;
5246   }
5247
5248   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5249   //of a v4i32 / v4f32. It's probably worth generalizing.
5250   EVT EltVT = VT.getVectorElementType();
5251   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5252       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5253     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5254     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5255     SDValue ResNode =
5256         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5257                                 LDBase->getPointerInfo(),
5258                                 LDBase->getAlignment(),
5259                                 false/*isVolatile*/, true/*ReadMem*/,
5260                                 false/*WriteMem*/);
5261
5262     // Make sure the newly-created LOAD is in the same position as LDBase in
5263     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5264     // update uses of LDBase's output chain to use the TokenFactor.
5265     if (LDBase->hasAnyUseOfValue(1)) {
5266       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5267                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5268       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5269       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5270                              SDValue(ResNode.getNode(), 1));
5271     }
5272
5273     return DAG.getBitcast(VT, ResNode);
5274   }
5275   return SDValue();
5276 }
5277
5278 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5279 /// to generate a splat value for the following cases:
5280 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5281 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5282 /// a scalar load, or a constant.
5283 /// The VBROADCAST node is returned when a pattern is found,
5284 /// or SDValue() otherwise.
5285 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5286                                     SelectionDAG &DAG) {
5287   // VBROADCAST requires AVX.
5288   // TODO: Splats could be generated for non-AVX CPUs using SSE
5289   // instructions, but there's less potential gain for only 128-bit vectors.
5290   if (!Subtarget->hasAVX())
5291     return SDValue();
5292
5293   MVT VT = Op.getSimpleValueType();
5294   SDLoc dl(Op);
5295
5296   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5297          "Unsupported vector type for broadcast.");
5298
5299   SDValue Ld;
5300   bool ConstSplatVal;
5301
5302   switch (Op.getOpcode()) {
5303     default:
5304       // Unknown pattern found.
5305       return SDValue();
5306
5307     case ISD::BUILD_VECTOR: {
5308       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5309       BitVector UndefElements;
5310       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5311
5312       // We need a splat of a single value to use broadcast, and it doesn't
5313       // make any sense if the value is only in one element of the vector.
5314       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5315         return SDValue();
5316
5317       Ld = Splat;
5318       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5319                        Ld.getOpcode() == ISD::ConstantFP);
5320
5321       // Make sure that all of the users of a non-constant load are from the
5322       // BUILD_VECTOR node.
5323       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5324         return SDValue();
5325       break;
5326     }
5327
5328     case ISD::VECTOR_SHUFFLE: {
5329       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5330
5331       // Shuffles must have a splat mask where the first element is
5332       // broadcasted.
5333       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5334         return SDValue();
5335
5336       SDValue Sc = Op.getOperand(0);
5337       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5338           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5339
5340         if (!Subtarget->hasInt256())
5341           return SDValue();
5342
5343         // Use the register form of the broadcast instruction available on AVX2.
5344         if (VT.getSizeInBits() >= 256)
5345           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5346         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5347       }
5348
5349       Ld = Sc.getOperand(0);
5350       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5351                        Ld.getOpcode() == ISD::ConstantFP);
5352
5353       // The scalar_to_vector node and the suspected
5354       // load node must have exactly one user.
5355       // Constants may have multiple users.
5356
5357       // AVX-512 has register version of the broadcast
5358       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5359         Ld.getValueType().getSizeInBits() >= 32;
5360       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5361           !hasRegVer))
5362         return SDValue();
5363       break;
5364     }
5365   }
5366
5367   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5368   bool IsGE256 = (VT.getSizeInBits() >= 256);
5369
5370   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5371   // instruction to save 8 or more bytes of constant pool data.
5372   // TODO: If multiple splats are generated to load the same constant,
5373   // it may be detrimental to overall size. There needs to be a way to detect
5374   // that condition to know if this is truly a size win.
5375   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5376
5377   // Handle broadcasting a single constant scalar from the constant pool
5378   // into a vector.
5379   // On Sandybridge (no AVX2), it is still better to load a constant vector
5380   // from the constant pool and not to broadcast it from a scalar.
5381   // But override that restriction when optimizing for size.
5382   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5383   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5384     EVT CVT = Ld.getValueType();
5385     assert(!CVT.isVector() && "Must not broadcast a vector type");
5386
5387     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5388     // For size optimization, also splat v2f64 and v2i64, and for size opt
5389     // with AVX2, also splat i8 and i16.
5390     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5391     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5392         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5393       const Constant *C = nullptr;
5394       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5395         C = CI->getConstantIntValue();
5396       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5397         C = CF->getConstantFPValue();
5398
5399       assert(C && "Invalid constant type");
5400
5401       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5402       SDValue CP =
5403           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5404       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5405       Ld = DAG.getLoad(
5406           CVT, dl, DAG.getEntryNode(), CP,
5407           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5408           false, false, Alignment);
5409
5410       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5411     }
5412   }
5413
5414   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5415
5416   // Handle AVX2 in-register broadcasts.
5417   if (!IsLoad && Subtarget->hasInt256() &&
5418       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5419     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5420
5421   // The scalar source must be a normal load.
5422   if (!IsLoad)
5423     return SDValue();
5424
5425   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5426       (Subtarget->hasVLX() && ScalarSize == 64))
5427     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5428
5429   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5430   // double since there is no vbroadcastsd xmm
5431   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5432     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5433       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5434   }
5435
5436   // Unsupported broadcast.
5437   return SDValue();
5438 }
5439
5440 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5441 /// underlying vector and index.
5442 ///
5443 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5444 /// index.
5445 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5446                                          SDValue ExtIdx) {
5447   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5448   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5449     return Idx;
5450
5451   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5452   // lowered this:
5453   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5454   // to:
5455   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5456   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5457   //                           undef)
5458   //                       Constant<0>)
5459   // In this case the vector is the extract_subvector expression and the index
5460   // is 2, as specified by the shuffle.
5461   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5462   SDValue ShuffleVec = SVOp->getOperand(0);
5463   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5464   assert(ShuffleVecVT.getVectorElementType() ==
5465          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5466
5467   int ShuffleIdx = SVOp->getMaskElt(Idx);
5468   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5469     ExtractedFromVec = ShuffleVec;
5470     return ShuffleIdx;
5471   }
5472   return Idx;
5473 }
5474
5475 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5476   MVT VT = Op.getSimpleValueType();
5477
5478   // Skip if insert_vec_elt is not supported.
5479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5480   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5481     return SDValue();
5482
5483   SDLoc DL(Op);
5484   unsigned NumElems = Op.getNumOperands();
5485
5486   SDValue VecIn1;
5487   SDValue VecIn2;
5488   SmallVector<unsigned, 4> InsertIndices;
5489   SmallVector<int, 8> Mask(NumElems, -1);
5490
5491   for (unsigned i = 0; i != NumElems; ++i) {
5492     unsigned Opc = Op.getOperand(i).getOpcode();
5493
5494     if (Opc == ISD::UNDEF)
5495       continue;
5496
5497     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5498       // Quit if more than 1 elements need inserting.
5499       if (InsertIndices.size() > 1)
5500         return SDValue();
5501
5502       InsertIndices.push_back(i);
5503       continue;
5504     }
5505
5506     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5507     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5508     // Quit if non-constant index.
5509     if (!isa<ConstantSDNode>(ExtIdx))
5510       return SDValue();
5511     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5512
5513     // Quit if extracted from vector of different type.
5514     if (ExtractedFromVec.getValueType() != VT)
5515       return SDValue();
5516
5517     if (!VecIn1.getNode())
5518       VecIn1 = ExtractedFromVec;
5519     else if (VecIn1 != ExtractedFromVec) {
5520       if (!VecIn2.getNode())
5521         VecIn2 = ExtractedFromVec;
5522       else if (VecIn2 != ExtractedFromVec)
5523         // Quit if more than 2 vectors to shuffle
5524         return SDValue();
5525     }
5526
5527     if (ExtractedFromVec == VecIn1)
5528       Mask[i] = Idx;
5529     else if (ExtractedFromVec == VecIn2)
5530       Mask[i] = Idx + NumElems;
5531   }
5532
5533   if (!VecIn1.getNode())
5534     return SDValue();
5535
5536   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5537   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5538   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5539     unsigned Idx = InsertIndices[i];
5540     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5541                      DAG.getIntPtrConstant(Idx, DL));
5542   }
5543
5544   return NV;
5545 }
5546
5547 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5548   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5549          Op.getScalarValueSizeInBits() == 1 &&
5550          "Can not convert non-constant vector");
5551   uint64_t Immediate = 0;
5552   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5553     SDValue In = Op.getOperand(idx);
5554     if (In.getOpcode() != ISD::UNDEF)
5555       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5556   }
5557   SDLoc dl(Op);
5558   MVT VT =
5559    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5560   return DAG.getConstant(Immediate, dl, VT);
5561 }
5562 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5563 SDValue
5564 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5565
5566   MVT VT = Op.getSimpleValueType();
5567   assert((VT.getVectorElementType() == MVT::i1) &&
5568          "Unexpected type in LowerBUILD_VECTORvXi1!");
5569
5570   SDLoc dl(Op);
5571   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5572     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5573     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5574     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5575   }
5576
5577   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5578     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5579     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5580     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5581   }
5582
5583   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5584     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5585     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5586       return DAG.getBitcast(VT, Imm);
5587     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5588     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5589                         DAG.getIntPtrConstant(0, dl));
5590   }
5591
5592   // Vector has one or more non-const elements
5593   uint64_t Immediate = 0;
5594   SmallVector<unsigned, 16> NonConstIdx;
5595   bool IsSplat = true;
5596   bool HasConstElts = false;
5597   int SplatIdx = -1;
5598   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5599     SDValue In = Op.getOperand(idx);
5600     if (In.getOpcode() == ISD::UNDEF)
5601       continue;
5602     if (!isa<ConstantSDNode>(In))
5603       NonConstIdx.push_back(idx);
5604     else {
5605       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5606       HasConstElts = true;
5607     }
5608     if (SplatIdx == -1)
5609       SplatIdx = idx;
5610     else if (In != Op.getOperand(SplatIdx))
5611       IsSplat = false;
5612   }
5613
5614   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5615   if (IsSplat)
5616     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5617                        DAG.getConstant(1, dl, VT),
5618                        DAG.getConstant(0, dl, VT));
5619
5620   // insert elements one by one
5621   SDValue DstVec;
5622   SDValue Imm;
5623   if (Immediate) {
5624     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5625     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5626   }
5627   else if (HasConstElts)
5628     Imm = DAG.getConstant(0, dl, VT);
5629   else
5630     Imm = DAG.getUNDEF(VT);
5631   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5632     DstVec = DAG.getBitcast(VT, Imm);
5633   else {
5634     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5635     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5636                          DAG.getIntPtrConstant(0, dl));
5637   }
5638
5639   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5640     unsigned InsertIdx = NonConstIdx[i];
5641     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5642                          Op.getOperand(InsertIdx),
5643                          DAG.getIntPtrConstant(InsertIdx, dl));
5644   }
5645   return DstVec;
5646 }
5647
5648 /// \brief Return true if \p N implements a horizontal binop and return the
5649 /// operands for the horizontal binop into V0 and V1.
5650 ///
5651 /// This is a helper function of LowerToHorizontalOp().
5652 /// This function checks that the build_vector \p N in input implements a
5653 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5654 /// operation to match.
5655 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5656 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5657 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5658 /// arithmetic sub.
5659 ///
5660 /// This function only analyzes elements of \p N whose indices are
5661 /// in range [BaseIdx, LastIdx).
5662 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5663                               SelectionDAG &DAG,
5664                               unsigned BaseIdx, unsigned LastIdx,
5665                               SDValue &V0, SDValue &V1) {
5666   EVT VT = N->getValueType(0);
5667
5668   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5669   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5670          "Invalid Vector in input!");
5671
5672   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5673   bool CanFold = true;
5674   unsigned ExpectedVExtractIdx = BaseIdx;
5675   unsigned NumElts = LastIdx - BaseIdx;
5676   V0 = DAG.getUNDEF(VT);
5677   V1 = DAG.getUNDEF(VT);
5678
5679   // Check if N implements a horizontal binop.
5680   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5681     SDValue Op = N->getOperand(i + BaseIdx);
5682
5683     // Skip UNDEFs.
5684     if (Op->getOpcode() == ISD::UNDEF) {
5685       // Update the expected vector extract index.
5686       if (i * 2 == NumElts)
5687         ExpectedVExtractIdx = BaseIdx;
5688       ExpectedVExtractIdx += 2;
5689       continue;
5690     }
5691
5692     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5693
5694     if (!CanFold)
5695       break;
5696
5697     SDValue Op0 = Op.getOperand(0);
5698     SDValue Op1 = Op.getOperand(1);
5699
5700     // Try to match the following pattern:
5701     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5702     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5703         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5704         Op0.getOperand(0) == Op1.getOperand(0) &&
5705         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5706         isa<ConstantSDNode>(Op1.getOperand(1)));
5707     if (!CanFold)
5708       break;
5709
5710     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5711     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5712
5713     if (i * 2 < NumElts) {
5714       if (V0.getOpcode() == ISD::UNDEF) {
5715         V0 = Op0.getOperand(0);
5716         if (V0.getValueType() != VT)
5717           return false;
5718       }
5719     } else {
5720       if (V1.getOpcode() == ISD::UNDEF) {
5721         V1 = Op0.getOperand(0);
5722         if (V1.getValueType() != VT)
5723           return false;
5724       }
5725       if (i * 2 == NumElts)
5726         ExpectedVExtractIdx = BaseIdx;
5727     }
5728
5729     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5730     if (I0 == ExpectedVExtractIdx)
5731       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5732     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5733       // Try to match the following dag sequence:
5734       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5735       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5736     } else
5737       CanFold = false;
5738
5739     ExpectedVExtractIdx += 2;
5740   }
5741
5742   return CanFold;
5743 }
5744
5745 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5746 /// a concat_vector.
5747 ///
5748 /// This is a helper function of LowerToHorizontalOp().
5749 /// This function expects two 256-bit vectors called V0 and V1.
5750 /// At first, each vector is split into two separate 128-bit vectors.
5751 /// Then, the resulting 128-bit vectors are used to implement two
5752 /// horizontal binary operations.
5753 ///
5754 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5755 ///
5756 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5757 /// the two new horizontal binop.
5758 /// When Mode is set, the first horizontal binop dag node would take as input
5759 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5760 /// horizontal binop dag node would take as input the lower 128-bit of V1
5761 /// and the upper 128-bit of V1.
5762 ///   Example:
5763 ///     HADD V0_LO, V0_HI
5764 ///     HADD V1_LO, V1_HI
5765 ///
5766 /// Otherwise, the first horizontal binop dag node takes as input the lower
5767 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5768 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5769 ///   Example:
5770 ///     HADD V0_LO, V1_LO
5771 ///     HADD V0_HI, V1_HI
5772 ///
5773 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5774 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5775 /// the upper 128-bits of the result.
5776 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5777                                      SDLoc DL, SelectionDAG &DAG,
5778                                      unsigned X86Opcode, bool Mode,
5779                                      bool isUndefLO, bool isUndefHI) {
5780   EVT VT = V0.getValueType();
5781   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5782          "Invalid nodes in input!");
5783
5784   unsigned NumElts = VT.getVectorNumElements();
5785   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5786   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5787   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5788   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5789   EVT NewVT = V0_LO.getValueType();
5790
5791   SDValue LO = DAG.getUNDEF(NewVT);
5792   SDValue HI = DAG.getUNDEF(NewVT);
5793
5794   if (Mode) {
5795     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5796     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5797       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5798     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5799       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5800   } else {
5801     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5802     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5803                        V1_LO->getOpcode() != ISD::UNDEF))
5804       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5805
5806     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5807                        V1_HI->getOpcode() != ISD::UNDEF))
5808       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5809   }
5810
5811   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5812 }
5813
5814 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5815 /// node.
5816 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5817                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5818   EVT VT = BV->getValueType(0);
5819   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5820       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5821     return SDValue();
5822
5823   SDLoc DL(BV);
5824   unsigned NumElts = VT.getVectorNumElements();
5825   SDValue InVec0 = DAG.getUNDEF(VT);
5826   SDValue InVec1 = DAG.getUNDEF(VT);
5827
5828   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5829           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5830
5831   // Odd-numbered elements in the input build vector are obtained from
5832   // adding two integer/float elements.
5833   // Even-numbered elements in the input build vector are obtained from
5834   // subtracting two integer/float elements.
5835   unsigned ExpectedOpcode = ISD::FSUB;
5836   unsigned NextExpectedOpcode = ISD::FADD;
5837   bool AddFound = false;
5838   bool SubFound = false;
5839
5840   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5841     SDValue Op = BV->getOperand(i);
5842
5843     // Skip 'undef' values.
5844     unsigned Opcode = Op.getOpcode();
5845     if (Opcode == ISD::UNDEF) {
5846       std::swap(ExpectedOpcode, NextExpectedOpcode);
5847       continue;
5848     }
5849
5850     // Early exit if we found an unexpected opcode.
5851     if (Opcode != ExpectedOpcode)
5852       return SDValue();
5853
5854     SDValue Op0 = Op.getOperand(0);
5855     SDValue Op1 = Op.getOperand(1);
5856
5857     // Try to match the following pattern:
5858     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5859     // Early exit if we cannot match that sequence.
5860     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5861         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5862         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5863         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5864         Op0.getOperand(1) != Op1.getOperand(1))
5865       return SDValue();
5866
5867     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5868     if (I0 != i)
5869       return SDValue();
5870
5871     // We found a valid add/sub node. Update the information accordingly.
5872     if (i & 1)
5873       AddFound = true;
5874     else
5875       SubFound = true;
5876
5877     // Update InVec0 and InVec1.
5878     if (InVec0.getOpcode() == ISD::UNDEF) {
5879       InVec0 = Op0.getOperand(0);
5880       if (InVec0.getValueType() != VT)
5881         return SDValue();
5882     }
5883     if (InVec1.getOpcode() == ISD::UNDEF) {
5884       InVec1 = Op1.getOperand(0);
5885       if (InVec1.getValueType() != VT)
5886         return SDValue();
5887     }
5888
5889     // Make sure that operands in input to each add/sub node always
5890     // come from a same pair of vectors.
5891     if (InVec0 != Op0.getOperand(0)) {
5892       if (ExpectedOpcode == ISD::FSUB)
5893         return SDValue();
5894
5895       // FADD is commutable. Try to commute the operands
5896       // and then test again.
5897       std::swap(Op0, Op1);
5898       if (InVec0 != Op0.getOperand(0))
5899         return SDValue();
5900     }
5901
5902     if (InVec1 != Op1.getOperand(0))
5903       return SDValue();
5904
5905     // Update the pair of expected opcodes.
5906     std::swap(ExpectedOpcode, NextExpectedOpcode);
5907   }
5908
5909   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5910   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5911       InVec1.getOpcode() != ISD::UNDEF)
5912     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5913
5914   return SDValue();
5915 }
5916
5917 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5918 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5919                                    const X86Subtarget *Subtarget,
5920                                    SelectionDAG &DAG) {
5921   EVT VT = BV->getValueType(0);
5922   unsigned NumElts = VT.getVectorNumElements();
5923   unsigned NumUndefsLO = 0;
5924   unsigned NumUndefsHI = 0;
5925   unsigned Half = NumElts/2;
5926
5927   // Count the number of UNDEF operands in the build_vector in input.
5928   for (unsigned i = 0, e = Half; i != e; ++i)
5929     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5930       NumUndefsLO++;
5931
5932   for (unsigned i = Half, e = NumElts; i != e; ++i)
5933     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5934       NumUndefsHI++;
5935
5936   // Early exit if this is either a build_vector of all UNDEFs or all the
5937   // operands but one are UNDEF.
5938   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5939     return SDValue();
5940
5941   SDLoc DL(BV);
5942   SDValue InVec0, InVec1;
5943   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5944     // Try to match an SSE3 float HADD/HSUB.
5945     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5946       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5947
5948     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5949       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5950   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5951     // Try to match an SSSE3 integer HADD/HSUB.
5952     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5953       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5954
5955     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5956       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5957   }
5958
5959   if (!Subtarget->hasAVX())
5960     return SDValue();
5961
5962   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5963     // Try to match an AVX horizontal add/sub of packed single/double
5964     // precision floating point values from 256-bit vectors.
5965     SDValue InVec2, InVec3;
5966     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5967         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5968         ((InVec0.getOpcode() == ISD::UNDEF ||
5969           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5970         ((InVec1.getOpcode() == ISD::UNDEF ||
5971           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5972       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5973
5974     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5975         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5976         ((InVec0.getOpcode() == ISD::UNDEF ||
5977           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5978         ((InVec1.getOpcode() == ISD::UNDEF ||
5979           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5980       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5981   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5982     // Try to match an AVX2 horizontal add/sub of signed integers.
5983     SDValue InVec2, InVec3;
5984     unsigned X86Opcode;
5985     bool CanFold = true;
5986
5987     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5988         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5989         ((InVec0.getOpcode() == ISD::UNDEF ||
5990           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5991         ((InVec1.getOpcode() == ISD::UNDEF ||
5992           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5993       X86Opcode = X86ISD::HADD;
5994     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5995         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5996         ((InVec0.getOpcode() == ISD::UNDEF ||
5997           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5998         ((InVec1.getOpcode() == ISD::UNDEF ||
5999           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6000       X86Opcode = X86ISD::HSUB;
6001     else
6002       CanFold = false;
6003
6004     if (CanFold) {
6005       // Fold this build_vector into a single horizontal add/sub.
6006       // Do this only if the target has AVX2.
6007       if (Subtarget->hasAVX2())
6008         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6009
6010       // Do not try to expand this build_vector into a pair of horizontal
6011       // add/sub if we can emit a pair of scalar add/sub.
6012       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6013         return SDValue();
6014
6015       // Convert this build_vector into a pair of horizontal binop followed by
6016       // a concat vector.
6017       bool isUndefLO = NumUndefsLO == Half;
6018       bool isUndefHI = NumUndefsHI == Half;
6019       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6020                                    isUndefLO, isUndefHI);
6021     }
6022   }
6023
6024   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6025        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6026     unsigned X86Opcode;
6027     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6028       X86Opcode = X86ISD::HADD;
6029     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6030       X86Opcode = X86ISD::HSUB;
6031     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6032       X86Opcode = X86ISD::FHADD;
6033     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6034       X86Opcode = X86ISD::FHSUB;
6035     else
6036       return SDValue();
6037
6038     // Don't try to expand this build_vector into a pair of horizontal add/sub
6039     // if we can simply emit a pair of scalar add/sub.
6040     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6041       return SDValue();
6042
6043     // Convert this build_vector into two horizontal add/sub followed by
6044     // a concat vector.
6045     bool isUndefLO = NumUndefsLO == Half;
6046     bool isUndefHI = NumUndefsHI == Half;
6047     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6048                                  isUndefLO, isUndefHI);
6049   }
6050
6051   return SDValue();
6052 }
6053
6054 SDValue
6055 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6056   SDLoc dl(Op);
6057
6058   MVT VT = Op.getSimpleValueType();
6059   MVT ExtVT = VT.getVectorElementType();
6060   unsigned NumElems = Op.getNumOperands();
6061
6062   // Generate vectors for predicate vectors.
6063   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6064     return LowerBUILD_VECTORvXi1(Op, DAG);
6065
6066   // Vectors containing all zeros can be matched by pxor and xorps later
6067   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6068     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6069     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6070     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6071       return Op;
6072
6073     return getZeroVector(VT, Subtarget, DAG, dl);
6074   }
6075
6076   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6077   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6078   // vpcmpeqd on 256-bit vectors.
6079   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6080     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6081       return Op;
6082
6083     if (!VT.is512BitVector())
6084       return getOnesVector(VT, Subtarget, DAG, dl);
6085   }
6086
6087   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6088   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6089     return AddSub;
6090   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6091     return HorizontalOp;
6092   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6093     return Broadcast;
6094
6095   unsigned EVTBits = ExtVT.getSizeInBits();
6096
6097   unsigned NumZero  = 0;
6098   unsigned NumNonZero = 0;
6099   unsigned NonZeros = 0;
6100   bool IsAllConstants = true;
6101   SmallSet<SDValue, 8> Values;
6102   for (unsigned i = 0; i < NumElems; ++i) {
6103     SDValue Elt = Op.getOperand(i);
6104     if (Elt.getOpcode() == ISD::UNDEF)
6105       continue;
6106     Values.insert(Elt);
6107     if (Elt.getOpcode() != ISD::Constant &&
6108         Elt.getOpcode() != ISD::ConstantFP)
6109       IsAllConstants = false;
6110     if (X86::isZeroNode(Elt))
6111       NumZero++;
6112     else {
6113       NonZeros |= (1 << i);
6114       NumNonZero++;
6115     }
6116   }
6117
6118   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6119   if (NumNonZero == 0)
6120     return DAG.getUNDEF(VT);
6121
6122   // Special case for single non-zero, non-undef, element.
6123   if (NumNonZero == 1) {
6124     unsigned Idx = countTrailingZeros(NonZeros);
6125     SDValue Item = Op.getOperand(Idx);
6126
6127     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6128     // the value are obviously zero, truncate the value to i32 and do the
6129     // insertion that way.  Only do this if the value is non-constant or if the
6130     // value is a constant being inserted into element 0.  It is cheaper to do
6131     // a constant pool load than it is to do a movd + shuffle.
6132     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6133         (!IsAllConstants || Idx == 0)) {
6134       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6135         // Handle SSE only.
6136         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6137         EVT VecVT = MVT::v4i32;
6138
6139         // Truncate the value (which may itself be a constant) to i32, and
6140         // convert it to a vector with movd (S2V+shuffle to zero extend).
6141         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6142         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6143         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6144                                       Item, Idx * 2, true, Subtarget, DAG));
6145       }
6146     }
6147
6148     // If we have a constant or non-constant insertion into the low element of
6149     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6150     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6151     // depending on what the source datatype is.
6152     if (Idx == 0) {
6153       if (NumZero == 0)
6154         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6155
6156       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6157           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6158         if (VT.is512BitVector()) {
6159           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6160           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6161                              Item, DAG.getIntPtrConstant(0, dl));
6162         }
6163         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6164                "Expected an SSE value type!");
6165         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6166         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6167         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6168       }
6169
6170       // We can't directly insert an i8 or i16 into a vector, so zero extend
6171       // it to i32 first.
6172       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6173         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6174         if (VT.is256BitVector()) {
6175           if (Subtarget->hasAVX()) {
6176             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6177             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6178           } else {
6179             // Without AVX, we need to extend to a 128-bit vector and then
6180             // insert into the 256-bit vector.
6181             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6182             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6183             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6184           }
6185         } else {
6186           assert(VT.is128BitVector() && "Expected an SSE value type!");
6187           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6188           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6189         }
6190         return DAG.getBitcast(VT, Item);
6191       }
6192     }
6193
6194     // Is it a vector logical left shift?
6195     if (NumElems == 2 && Idx == 1 &&
6196         X86::isZeroNode(Op.getOperand(0)) &&
6197         !X86::isZeroNode(Op.getOperand(1))) {
6198       unsigned NumBits = VT.getSizeInBits();
6199       return getVShift(true, VT,
6200                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6201                                    VT, Op.getOperand(1)),
6202                        NumBits/2, DAG, *this, dl);
6203     }
6204
6205     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6206       return SDValue();
6207
6208     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6209     // is a non-constant being inserted into an element other than the low one,
6210     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6211     // movd/movss) to move this into the low element, then shuffle it into
6212     // place.
6213     if (EVTBits == 32) {
6214       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6215       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6216     }
6217   }
6218
6219   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6220   if (Values.size() == 1) {
6221     if (EVTBits == 32) {
6222       // Instead of a shuffle like this:
6223       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6224       // Check if it's possible to issue this instead.
6225       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6226       unsigned Idx = countTrailingZeros(NonZeros);
6227       SDValue Item = Op.getOperand(Idx);
6228       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6229         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6230     }
6231     return SDValue();
6232   }
6233
6234   // A vector full of immediates; various special cases are already
6235   // handled, so this is best done with a single constant-pool load.
6236   if (IsAllConstants)
6237     return SDValue();
6238
6239   // For AVX-length vectors, see if we can use a vector load to get all of the
6240   // elements, otherwise build the individual 128-bit pieces and use
6241   // shuffles to put them in place.
6242   if (VT.is256BitVector() || VT.is512BitVector()) {
6243     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6244
6245     // Check for a build vector of consecutive loads.
6246     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6247       return LD;
6248
6249     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6250
6251     // Build both the lower and upper subvector.
6252     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6253                                 makeArrayRef(&V[0], NumElems/2));
6254     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6255                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6256
6257     // Recreate the wider vector with the lower and upper part.
6258     if (VT.is256BitVector())
6259       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6260     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6261   }
6262
6263   // Let legalizer expand 2-wide build_vectors.
6264   if (EVTBits == 64) {
6265     if (NumNonZero == 1) {
6266       // One half is zero or undef.
6267       unsigned Idx = countTrailingZeros(NonZeros);
6268       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6269                                  Op.getOperand(Idx));
6270       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6271     }
6272     return SDValue();
6273   }
6274
6275   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6276   if (EVTBits == 8 && NumElems == 16)
6277     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6278                                         Subtarget, *this))
6279       return V;
6280
6281   if (EVTBits == 16 && NumElems == 8)
6282     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6283                                       Subtarget, *this))
6284       return V;
6285
6286   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6287   if (EVTBits == 32 && NumElems == 4)
6288     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6289       return V;
6290
6291   // If element VT is == 32 bits, turn it into a number of shuffles.
6292   SmallVector<SDValue, 8> V(NumElems);
6293   if (NumElems == 4 && NumZero > 0) {
6294     for (unsigned i = 0; i < 4; ++i) {
6295       bool isZero = !(NonZeros & (1 << i));
6296       if (isZero)
6297         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6298       else
6299         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6300     }
6301
6302     for (unsigned i = 0; i < 2; ++i) {
6303       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6304         default: break;
6305         case 0:
6306           V[i] = V[i*2];  // Must be a zero vector.
6307           break;
6308         case 1:
6309           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6310           break;
6311         case 2:
6312           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6313           break;
6314         case 3:
6315           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6316           break;
6317       }
6318     }
6319
6320     bool Reverse1 = (NonZeros & 0x3) == 2;
6321     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6322     int MaskVec[] = {
6323       Reverse1 ? 1 : 0,
6324       Reverse1 ? 0 : 1,
6325       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6326       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6327     };
6328     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6329   }
6330
6331   if (Values.size() > 1 && VT.is128BitVector()) {
6332     // Check for a build vector of consecutive loads.
6333     for (unsigned i = 0; i < NumElems; ++i)
6334       V[i] = Op.getOperand(i);
6335
6336     // Check for elements which are consecutive loads.
6337     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6338       return LD;
6339
6340     // Check for a build vector from mostly shuffle plus few inserting.
6341     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6342       return Sh;
6343
6344     // For SSE 4.1, use insertps to put the high elements into the low element.
6345     if (Subtarget->hasSSE41()) {
6346       SDValue Result;
6347       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6348         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6349       else
6350         Result = DAG.getUNDEF(VT);
6351
6352       for (unsigned i = 1; i < NumElems; ++i) {
6353         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6354         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6355                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6356       }
6357       return Result;
6358     }
6359
6360     // Otherwise, expand into a number of unpckl*, start by extending each of
6361     // our (non-undef) elements to the full vector width with the element in the
6362     // bottom slot of the vector (which generates no code for SSE).
6363     for (unsigned i = 0; i < NumElems; ++i) {
6364       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6365         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6366       else
6367         V[i] = DAG.getUNDEF(VT);
6368     }
6369
6370     // Next, we iteratively mix elements, e.g. for v4f32:
6371     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6372     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6373     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6374     unsigned EltStride = NumElems >> 1;
6375     while (EltStride != 0) {
6376       for (unsigned i = 0; i < EltStride; ++i) {
6377         // If V[i+EltStride] is undef and this is the first round of mixing,
6378         // then it is safe to just drop this shuffle: V[i] is already in the
6379         // right place, the one element (since it's the first round) being
6380         // inserted as undef can be dropped.  This isn't safe for successive
6381         // rounds because they will permute elements within both vectors.
6382         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6383             EltStride == NumElems/2)
6384           continue;
6385
6386         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6387       }
6388       EltStride >>= 1;
6389     }
6390     return V[0];
6391   }
6392   return SDValue();
6393 }
6394
6395 // 256-bit AVX can use the vinsertf128 instruction
6396 // to create 256-bit vectors from two other 128-bit ones.
6397 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6398   SDLoc dl(Op);
6399   MVT ResVT = Op.getSimpleValueType();
6400
6401   assert((ResVT.is256BitVector() ||
6402           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6403
6404   SDValue V1 = Op.getOperand(0);
6405   SDValue V2 = Op.getOperand(1);
6406   unsigned NumElems = ResVT.getVectorNumElements();
6407   if (ResVT.is256BitVector())
6408     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6409
6410   if (Op.getNumOperands() == 4) {
6411     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6412                                 ResVT.getVectorNumElements()/2);
6413     SDValue V3 = Op.getOperand(2);
6414     SDValue V4 = Op.getOperand(3);
6415     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6416       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6417   }
6418   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6419 }
6420
6421 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6422                                        const X86Subtarget *Subtarget,
6423                                        SelectionDAG & DAG) {
6424   SDLoc dl(Op);
6425   MVT ResVT = Op.getSimpleValueType();
6426   unsigned NumOfOperands = Op.getNumOperands();
6427
6428   assert(isPowerOf2_32(NumOfOperands) &&
6429          "Unexpected number of operands in CONCAT_VECTORS");
6430
6431   if (NumOfOperands > 2) {
6432     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6433                                   ResVT.getVectorNumElements()/2);
6434     SmallVector<SDValue, 2> Ops;
6435     for (unsigned i = 0; i < NumOfOperands/2; i++)
6436       Ops.push_back(Op.getOperand(i));
6437     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6438     Ops.clear();
6439     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6440       Ops.push_back(Op.getOperand(i));
6441     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6442     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6443   }
6444
6445   SDValue V1 = Op.getOperand(0);
6446   SDValue V2 = Op.getOperand(1);
6447   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6448   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6449
6450   if (IsZeroV1 && IsZeroV2)
6451     return getZeroVector(ResVT, Subtarget, DAG, dl);
6452
6453   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6454   SDValue Undef = DAG.getUNDEF(ResVT);
6455   unsigned NumElems = ResVT.getVectorNumElements();
6456   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6457
6458   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6459   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6460   if (IsZeroV1)
6461     return V2;
6462
6463   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6464   // Zero the upper bits of V1
6465   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6466   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6467   if (IsZeroV2)
6468     return V1;
6469   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6470 }
6471
6472 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6473                                    const X86Subtarget *Subtarget,
6474                                    SelectionDAG &DAG) {
6475   MVT VT = Op.getSimpleValueType();
6476   if (VT.getVectorElementType() == MVT::i1)
6477     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6478
6479   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6480          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6481           Op.getNumOperands() == 4)));
6482
6483   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6484   // from two other 128-bit ones.
6485
6486   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6487   return LowerAVXCONCAT_VECTORS(Op, DAG);
6488 }
6489
6490
6491 //===----------------------------------------------------------------------===//
6492 // Vector shuffle lowering
6493 //
6494 // This is an experimental code path for lowering vector shuffles on x86. It is
6495 // designed to handle arbitrary vector shuffles and blends, gracefully
6496 // degrading performance as necessary. It works hard to recognize idiomatic
6497 // shuffles and lower them to optimal instruction patterns without leaving
6498 // a framework that allows reasonably efficient handling of all vector shuffle
6499 // patterns.
6500 //===----------------------------------------------------------------------===//
6501
6502 /// \brief Tiny helper function to identify a no-op mask.
6503 ///
6504 /// This is a somewhat boring predicate function. It checks whether the mask
6505 /// array input, which is assumed to be a single-input shuffle mask of the kind
6506 /// used by the X86 shuffle instructions (not a fully general
6507 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6508 /// in-place shuffle are 'no-op's.
6509 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6510   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6511     if (Mask[i] != -1 && Mask[i] != i)
6512       return false;
6513   return true;
6514 }
6515
6516 /// \brief Helper function to classify a mask as a single-input mask.
6517 ///
6518 /// This isn't a generic single-input test because in the vector shuffle
6519 /// lowering we canonicalize single inputs to be the first input operand. This
6520 /// means we can more quickly test for a single input by only checking whether
6521 /// an input from the second operand exists. We also assume that the size of
6522 /// mask corresponds to the size of the input vectors which isn't true in the
6523 /// fully general case.
6524 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6525   for (int M : Mask)
6526     if (M >= (int)Mask.size())
6527       return false;
6528   return true;
6529 }
6530
6531 /// \brief Test whether there are elements crossing 128-bit lanes in this
6532 /// shuffle mask.
6533 ///
6534 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6535 /// and we routinely test for these.
6536 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6537   int LaneSize = 128 / VT.getScalarSizeInBits();
6538   int Size = Mask.size();
6539   for (int i = 0; i < Size; ++i)
6540     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6541       return true;
6542   return false;
6543 }
6544
6545 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6546 ///
6547 /// This checks a shuffle mask to see if it is performing the same
6548 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6549 /// that it is also not lane-crossing. It may however involve a blend from the
6550 /// same lane of a second vector.
6551 ///
6552 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6553 /// non-trivial to compute in the face of undef lanes. The representation is
6554 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6555 /// entries from both V1 and V2 inputs to the wider mask.
6556 static bool
6557 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6558                                 SmallVectorImpl<int> &RepeatedMask) {
6559   int LaneSize = 128 / VT.getScalarSizeInBits();
6560   RepeatedMask.resize(LaneSize, -1);
6561   int Size = Mask.size();
6562   for (int i = 0; i < Size; ++i) {
6563     if (Mask[i] < 0)
6564       continue;
6565     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6566       // This entry crosses lanes, so there is no way to model this shuffle.
6567       return false;
6568
6569     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6570     if (RepeatedMask[i % LaneSize] == -1)
6571       // This is the first non-undef entry in this slot of a 128-bit lane.
6572       RepeatedMask[i % LaneSize] =
6573           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6574     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6575       // Found a mismatch with the repeated mask.
6576       return false;
6577   }
6578   return true;
6579 }
6580
6581 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6582 /// arguments.
6583 ///
6584 /// This is a fast way to test a shuffle mask against a fixed pattern:
6585 ///
6586 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6587 ///
6588 /// It returns true if the mask is exactly as wide as the argument list, and
6589 /// each element of the mask is either -1 (signifying undef) or the value given
6590 /// in the argument.
6591 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6592                                 ArrayRef<int> ExpectedMask) {
6593   if (Mask.size() != ExpectedMask.size())
6594     return false;
6595
6596   int Size = Mask.size();
6597
6598   // If the values are build vectors, we can look through them to find
6599   // equivalent inputs that make the shuffles equivalent.
6600   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6601   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6602
6603   for (int i = 0; i < Size; ++i)
6604     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6605       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6606       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6607       if (!MaskBV || !ExpectedBV ||
6608           MaskBV->getOperand(Mask[i] % Size) !=
6609               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6610         return false;
6611     }
6612
6613   return true;
6614 }
6615
6616 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6617 ///
6618 /// This helper function produces an 8-bit shuffle immediate corresponding to
6619 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6620 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6621 /// example.
6622 ///
6623 /// NB: We rely heavily on "undef" masks preserving the input lane.
6624 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6625                                           SelectionDAG &DAG) {
6626   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6627   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6628   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6629   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6630   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6631
6632   unsigned Imm = 0;
6633   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6634   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6635   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6636   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6637   return DAG.getConstant(Imm, DL, MVT::i8);
6638 }
6639
6640 /// \brief Compute whether each element of a shuffle is zeroable.
6641 ///
6642 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6643 /// Either it is an undef element in the shuffle mask, the element of the input
6644 /// referenced is undef, or the element of the input referenced is known to be
6645 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6646 /// as many lanes with this technique as possible to simplify the remaining
6647 /// shuffle.
6648 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6649                                                      SDValue V1, SDValue V2) {
6650   SmallBitVector Zeroable(Mask.size(), false);
6651
6652   while (V1.getOpcode() == ISD::BITCAST)
6653     V1 = V1->getOperand(0);
6654   while (V2.getOpcode() == ISD::BITCAST)
6655     V2 = V2->getOperand(0);
6656
6657   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6658   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6659
6660   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6661     int M = Mask[i];
6662     // Handle the easy cases.
6663     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6664       Zeroable[i] = true;
6665       continue;
6666     }
6667
6668     // If this is an index into a build_vector node (which has the same number
6669     // of elements), dig out the input value and use it.
6670     SDValue V = M < Size ? V1 : V2;
6671     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6672       continue;
6673
6674     SDValue Input = V.getOperand(M % Size);
6675     // The UNDEF opcode check really should be dead code here, but not quite
6676     // worth asserting on (it isn't invalid, just unexpected).
6677     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6678       Zeroable[i] = true;
6679   }
6680
6681   return Zeroable;
6682 }
6683
6684 // X86 has dedicated unpack instructions that can handle specific blend
6685 // operations: UNPCKH and UNPCKL.
6686 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6687                                            SDValue V1, SDValue V2,
6688                                            SelectionDAG &DAG) {
6689   int NumElts = VT.getVectorNumElements();
6690   bool Unpckl = true;
6691   bool Unpckh = true;
6692   bool UnpcklSwapped = true;
6693   bool UnpckhSwapped = true;
6694   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6695
6696   for (int i = 0; i < NumElts; ++i) {
6697     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6698
6699     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6700     int HiPos = LoPos + NumEltsInLane / 2;
6701     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6702     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6703
6704     if (Mask[i] == -1)
6705       continue;
6706     if (Mask[i] != LoPos)
6707       Unpckl = false;
6708     if (Mask[i] != HiPos)
6709       Unpckh = false;
6710     if (Mask[i] != LoPosSwapped)
6711       UnpcklSwapped = false;
6712     if (Mask[i] != HiPosSwapped)
6713       UnpckhSwapped = false;
6714     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6715       return SDValue();
6716   }
6717   if (Unpckl)
6718     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6719   if (Unpckh)
6720     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6721   if (UnpcklSwapped)
6722     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6723   if (UnpckhSwapped)
6724     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6725
6726   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6727   return SDValue();
6728 }
6729
6730 /// \brief Try to emit a bitmask instruction for a shuffle.
6731 ///
6732 /// This handles cases where we can model a blend exactly as a bitmask due to
6733 /// one of the inputs being zeroable.
6734 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6735                                            SDValue V2, ArrayRef<int> Mask,
6736                                            SelectionDAG &DAG) {
6737   MVT EltVT = VT.getScalarType();
6738   int NumEltBits = EltVT.getSizeInBits();
6739   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6740   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6741   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6742                                     IntEltVT);
6743   if (EltVT.isFloatingPoint()) {
6744     Zero = DAG.getBitcast(EltVT, Zero);
6745     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6746   }
6747   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6748   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6749   SDValue V;
6750   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6751     if (Zeroable[i])
6752       continue;
6753     if (Mask[i] % Size != i)
6754       return SDValue(); // Not a blend.
6755     if (!V)
6756       V = Mask[i] < Size ? V1 : V2;
6757     else if (V != (Mask[i] < Size ? V1 : V2))
6758       return SDValue(); // Can only let one input through the mask.
6759
6760     VMaskOps[i] = AllOnes;
6761   }
6762   if (!V)
6763     return SDValue(); // No non-zeroable elements!
6764
6765   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6766   V = DAG.getNode(VT.isFloatingPoint()
6767                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6768                   DL, VT, V, VMask);
6769   return V;
6770 }
6771
6772 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6773 ///
6774 /// This is used as a fallback approach when first class blend instructions are
6775 /// unavailable. Currently it is only suitable for integer vectors, but could
6776 /// be generalized for floating point vectors if desirable.
6777 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6778                                             SDValue V2, ArrayRef<int> Mask,
6779                                             SelectionDAG &DAG) {
6780   assert(VT.isInteger() && "Only supports integer vector types!");
6781   MVT EltVT = VT.getScalarType();
6782   int NumEltBits = EltVT.getSizeInBits();
6783   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6784   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6785                                     EltVT);
6786   SmallVector<SDValue, 16> MaskOps;
6787   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6788     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6789       return SDValue(); // Shuffled input!
6790     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6791   }
6792
6793   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6794   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6795   // We have to cast V2 around.
6796   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6797   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6798                                       DAG.getBitcast(MaskVT, V1Mask),
6799                                       DAG.getBitcast(MaskVT, V2)));
6800   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6801 }
6802
6803 /// \brief Try to emit a blend instruction for a shuffle.
6804 ///
6805 /// This doesn't do any checks for the availability of instructions for blending
6806 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6807 /// be matched in the backend with the type given. What it does check for is
6808 /// that the shuffle mask is in fact a blend.
6809 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6810                                          SDValue V2, ArrayRef<int> Mask,
6811                                          const X86Subtarget *Subtarget,
6812                                          SelectionDAG &DAG) {
6813   unsigned BlendMask = 0;
6814   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6815     if (Mask[i] >= Size) {
6816       if (Mask[i] != i + Size)
6817         return SDValue(); // Shuffled V2 input!
6818       BlendMask |= 1u << i;
6819       continue;
6820     }
6821     if (Mask[i] >= 0 && Mask[i] != i)
6822       return SDValue(); // Shuffled V1 input!
6823   }
6824   switch (VT.SimpleTy) {
6825   case MVT::v2f64:
6826   case MVT::v4f32:
6827   case MVT::v4f64:
6828   case MVT::v8f32:
6829     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6830                        DAG.getConstant(BlendMask, DL, MVT::i8));
6831
6832   case MVT::v4i64:
6833   case MVT::v8i32:
6834     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6835     // FALLTHROUGH
6836   case MVT::v2i64:
6837   case MVT::v4i32:
6838     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6839     // that instruction.
6840     if (Subtarget->hasAVX2()) {
6841       // Scale the blend by the number of 32-bit dwords per element.
6842       int Scale =  VT.getScalarSizeInBits() / 32;
6843       BlendMask = 0;
6844       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6845         if (Mask[i] >= Size)
6846           for (int j = 0; j < Scale; ++j)
6847             BlendMask |= 1u << (i * Scale + j);
6848
6849       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6850       V1 = DAG.getBitcast(BlendVT, V1);
6851       V2 = DAG.getBitcast(BlendVT, V2);
6852       return DAG.getBitcast(
6853           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6854                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6855     }
6856     // FALLTHROUGH
6857   case MVT::v8i16: {
6858     // For integer shuffles we need to expand the mask and cast the inputs to
6859     // v8i16s prior to blending.
6860     int Scale = 8 / VT.getVectorNumElements();
6861     BlendMask = 0;
6862     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6863       if (Mask[i] >= Size)
6864         for (int j = 0; j < Scale; ++j)
6865           BlendMask |= 1u << (i * Scale + j);
6866
6867     V1 = DAG.getBitcast(MVT::v8i16, V1);
6868     V2 = DAG.getBitcast(MVT::v8i16, V2);
6869     return DAG.getBitcast(VT,
6870                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6871                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6872   }
6873
6874   case MVT::v16i16: {
6875     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6876     SmallVector<int, 8> RepeatedMask;
6877     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6878       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6879       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6880       BlendMask = 0;
6881       for (int i = 0; i < 8; ++i)
6882         if (RepeatedMask[i] >= 16)
6883           BlendMask |= 1u << i;
6884       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6885                          DAG.getConstant(BlendMask, DL, MVT::i8));
6886     }
6887   }
6888     // FALLTHROUGH
6889   case MVT::v16i8:
6890   case MVT::v32i8: {
6891     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6892            "256-bit byte-blends require AVX2 support!");
6893
6894     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6895     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6896       return Masked;
6897
6898     // Scale the blend by the number of bytes per element.
6899     int Scale = VT.getScalarSizeInBits() / 8;
6900
6901     // This form of blend is always done on bytes. Compute the byte vector
6902     // type.
6903     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6904
6905     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6906     // mix of LLVM's code generator and the x86 backend. We tell the code
6907     // generator that boolean values in the elements of an x86 vector register
6908     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6909     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6910     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6911     // of the element (the remaining are ignored) and 0 in that high bit would
6912     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6913     // the LLVM model for boolean values in vector elements gets the relevant
6914     // bit set, it is set backwards and over constrained relative to x86's
6915     // actual model.
6916     SmallVector<SDValue, 32> VSELECTMask;
6917     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6918       for (int j = 0; j < Scale; ++j)
6919         VSELECTMask.push_back(
6920             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6921                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6922                                           MVT::i8));
6923
6924     V1 = DAG.getBitcast(BlendVT, V1);
6925     V2 = DAG.getBitcast(BlendVT, V2);
6926     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6927                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6928                                                       BlendVT, VSELECTMask),
6929                                           V1, V2));
6930   }
6931
6932   default:
6933     llvm_unreachable("Not a supported integer vector type!");
6934   }
6935 }
6936
6937 /// \brief Try to lower as a blend of elements from two inputs followed by
6938 /// a single-input permutation.
6939 ///
6940 /// This matches the pattern where we can blend elements from two inputs and
6941 /// then reduce the shuffle to a single-input permutation.
6942 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6943                                                    SDValue V2,
6944                                                    ArrayRef<int> Mask,
6945                                                    SelectionDAG &DAG) {
6946   // We build up the blend mask while checking whether a blend is a viable way
6947   // to reduce the shuffle.
6948   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6949   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6950
6951   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6952     if (Mask[i] < 0)
6953       continue;
6954
6955     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6956
6957     if (BlendMask[Mask[i] % Size] == -1)
6958       BlendMask[Mask[i] % Size] = Mask[i];
6959     else if (BlendMask[Mask[i] % Size] != Mask[i])
6960       return SDValue(); // Can't blend in the needed input!
6961
6962     PermuteMask[i] = Mask[i] % Size;
6963   }
6964
6965   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6966   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6967 }
6968
6969 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6970 /// blends and permutes.
6971 ///
6972 /// This matches the extremely common pattern for handling combined
6973 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6974 /// operations. It will try to pick the best arrangement of shuffles and
6975 /// blends.
6976 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6977                                                           SDValue V1,
6978                                                           SDValue V2,
6979                                                           ArrayRef<int> Mask,
6980                                                           SelectionDAG &DAG) {
6981   // Shuffle the input elements into the desired positions in V1 and V2 and
6982   // blend them together.
6983   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6984   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6985   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6986   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6987     if (Mask[i] >= 0 && Mask[i] < Size) {
6988       V1Mask[i] = Mask[i];
6989       BlendMask[i] = i;
6990     } else if (Mask[i] >= Size) {
6991       V2Mask[i] = Mask[i] - Size;
6992       BlendMask[i] = i + Size;
6993     }
6994
6995   // Try to lower with the simpler initial blend strategy unless one of the
6996   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6997   // shuffle may be able to fold with a load or other benefit. However, when
6998   // we'll have to do 2x as many shuffles in order to achieve this, blending
6999   // first is a better strategy.
7000   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7001     if (SDValue BlendPerm =
7002             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7003       return BlendPerm;
7004
7005   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7006   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7007   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7008 }
7009
7010 /// \brief Try to lower a vector shuffle as a byte rotation.
7011 ///
7012 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7013 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7014 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7015 /// try to generically lower a vector shuffle through such an pattern. It
7016 /// does not check for the profitability of lowering either as PALIGNR or
7017 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7018 /// This matches shuffle vectors that look like:
7019 ///
7020 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7021 ///
7022 /// Essentially it concatenates V1 and V2, shifts right by some number of
7023 /// elements, and takes the low elements as the result. Note that while this is
7024 /// specified as a *right shift* because x86 is little-endian, it is a *left
7025 /// rotate* of the vector lanes.
7026 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7027                                               SDValue V2,
7028                                               ArrayRef<int> Mask,
7029                                               const X86Subtarget *Subtarget,
7030                                               SelectionDAG &DAG) {
7031   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7032
7033   int NumElts = Mask.size();
7034   int NumLanes = VT.getSizeInBits() / 128;
7035   int NumLaneElts = NumElts / NumLanes;
7036
7037   // We need to detect various ways of spelling a rotation:
7038   //   [11, 12, 13, 14, 15,  0,  1,  2]
7039   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7040   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7041   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7042   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7043   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7044   int Rotation = 0;
7045   SDValue Lo, Hi;
7046   for (int l = 0; l < NumElts; l += NumLaneElts) {
7047     for (int i = 0; i < NumLaneElts; ++i) {
7048       if (Mask[l + i] == -1)
7049         continue;
7050       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7051
7052       // Get the mod-Size index and lane correct it.
7053       int LaneIdx = (Mask[l + i] % NumElts) - l;
7054       // Make sure it was in this lane.
7055       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7056         return SDValue();
7057
7058       // Determine where a rotated vector would have started.
7059       int StartIdx = i - LaneIdx;
7060       if (StartIdx == 0)
7061         // The identity rotation isn't interesting, stop.
7062         return SDValue();
7063
7064       // If we found the tail of a vector the rotation must be the missing
7065       // front. If we found the head of a vector, it must be how much of the
7066       // head.
7067       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7068
7069       if (Rotation == 0)
7070         Rotation = CandidateRotation;
7071       else if (Rotation != CandidateRotation)
7072         // The rotations don't match, so we can't match this mask.
7073         return SDValue();
7074
7075       // Compute which value this mask is pointing at.
7076       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7077
7078       // Compute which of the two target values this index should be assigned
7079       // to. This reflects whether the high elements are remaining or the low
7080       // elements are remaining.
7081       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7082
7083       // Either set up this value if we've not encountered it before, or check
7084       // that it remains consistent.
7085       if (!TargetV)
7086         TargetV = MaskV;
7087       else if (TargetV != MaskV)
7088         // This may be a rotation, but it pulls from the inputs in some
7089         // unsupported interleaving.
7090         return SDValue();
7091     }
7092   }
7093
7094   // Check that we successfully analyzed the mask, and normalize the results.
7095   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7096   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7097   if (!Lo)
7098     Lo = Hi;
7099   else if (!Hi)
7100     Hi = Lo;
7101
7102   // The actual rotate instruction rotates bytes, so we need to scale the
7103   // rotation based on how many bytes are in the vector lane.
7104   int Scale = 16 / NumLaneElts;
7105
7106   // SSSE3 targets can use the palignr instruction.
7107   if (Subtarget->hasSSSE3()) {
7108     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7109     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7110     Lo = DAG.getBitcast(AlignVT, Lo);
7111     Hi = DAG.getBitcast(AlignVT, Hi);
7112
7113     return DAG.getBitcast(
7114         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7115                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7116   }
7117
7118   assert(VT.getSizeInBits() == 128 &&
7119          "Rotate-based lowering only supports 128-bit lowering!");
7120   assert(Mask.size() <= 16 &&
7121          "Can shuffle at most 16 bytes in a 128-bit vector!");
7122
7123   // Default SSE2 implementation
7124   int LoByteShift = 16 - Rotation * Scale;
7125   int HiByteShift = Rotation * Scale;
7126
7127   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7128   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7129   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7130
7131   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7132                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7133   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7134                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7135   return DAG.getBitcast(VT,
7136                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7137 }
7138
7139 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7140 ///
7141 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7142 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7143 /// matches elements from one of the input vectors shuffled to the left or
7144 /// right with zeroable elements 'shifted in'. It handles both the strictly
7145 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7146 /// quad word lane.
7147 ///
7148 /// PSHL : (little-endian) left bit shift.
7149 /// [ zz, 0, zz,  2 ]
7150 /// [ -1, 4, zz, -1 ]
7151 /// PSRL : (little-endian) right bit shift.
7152 /// [  1, zz,  3, zz]
7153 /// [ -1, -1,  7, zz]
7154 /// PSLLDQ : (little-endian) left byte shift
7155 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7156 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7157 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7158 /// PSRLDQ : (little-endian) right byte shift
7159 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7160 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7161 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7162 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7163                                          SDValue V2, ArrayRef<int> Mask,
7164                                          SelectionDAG &DAG) {
7165   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7166
7167   int Size = Mask.size();
7168   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7169
7170   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7171     for (int i = 0; i < Size; i += Scale)
7172       for (int j = 0; j < Shift; ++j)
7173         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7174           return false;
7175
7176     return true;
7177   };
7178
7179   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7180     for (int i = 0; i != Size; i += Scale) {
7181       unsigned Pos = Left ? i + Shift : i;
7182       unsigned Low = Left ? i : i + Shift;
7183       unsigned Len = Scale - Shift;
7184       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7185                                       Low + (V == V1 ? 0 : Size)))
7186         return SDValue();
7187     }
7188
7189     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7190     bool ByteShift = ShiftEltBits > 64;
7191     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7192                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7193     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7194
7195     // Normalize the scale for byte shifts to still produce an i64 element
7196     // type.
7197     Scale = ByteShift ? Scale / 2 : Scale;
7198
7199     // We need to round trip through the appropriate type for the shift.
7200     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7201     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7202     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7203            "Illegal integer vector type");
7204     V = DAG.getBitcast(ShiftVT, V);
7205
7206     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7207                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7208     return DAG.getBitcast(VT, V);
7209   };
7210
7211   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7212   // keep doubling the size of the integer elements up to that. We can
7213   // then shift the elements of the integer vector by whole multiples of
7214   // their width within the elements of the larger integer vector. Test each
7215   // multiple to see if we can find a match with the moved element indices
7216   // and that the shifted in elements are all zeroable.
7217   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7218     for (int Shift = 1; Shift != Scale; ++Shift)
7219       for (bool Left : {true, false})
7220         if (CheckZeros(Shift, Scale, Left))
7221           for (SDValue V : {V1, V2})
7222             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7223               return Match;
7224
7225   // no match
7226   return SDValue();
7227 }
7228
7229 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7230 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7231                                            SDValue V2, ArrayRef<int> Mask,
7232                                            SelectionDAG &DAG) {
7233   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7234   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7235
7236   int Size = Mask.size();
7237   int HalfSize = Size / 2;
7238   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7239
7240   // Upper half must be undefined.
7241   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7242     return SDValue();
7243
7244   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7245   // Remainder of lower half result is zero and upper half is all undef.
7246   auto LowerAsEXTRQ = [&]() {
7247     // Determine the extraction length from the part of the
7248     // lower half that isn't zeroable.
7249     int Len = HalfSize;
7250     for (; Len >= 0; --Len)
7251       if (!Zeroable[Len - 1])
7252         break;
7253     assert(Len > 0 && "Zeroable shuffle mask");
7254
7255     // Attempt to match first Len sequential elements from the lower half.
7256     SDValue Src;
7257     int Idx = -1;
7258     for (int i = 0; i != Len; ++i) {
7259       int M = Mask[i];
7260       if (M < 0)
7261         continue;
7262       SDValue &V = (M < Size ? V1 : V2);
7263       M = M % Size;
7264
7265       // All mask elements must be in the lower half.
7266       if (M > HalfSize)
7267         return SDValue();
7268
7269       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7270         Src = V;
7271         Idx = M - i;
7272         continue;
7273       }
7274       return SDValue();
7275     }
7276
7277     if (Idx < 0)
7278       return SDValue();
7279
7280     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7281     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7282     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7283     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7284                        DAG.getConstant(BitLen, DL, MVT::i8),
7285                        DAG.getConstant(BitIdx, DL, MVT::i8));
7286   };
7287
7288   if (SDValue ExtrQ = LowerAsEXTRQ())
7289     return ExtrQ;
7290
7291   // INSERTQ: Extract lowest Len elements from lower half of second source and
7292   // insert over first source, starting at Idx.
7293   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7294   auto LowerAsInsertQ = [&]() {
7295     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7296       SDValue Base;
7297
7298       // Attempt to match first source from mask before insertion point.
7299       if (isUndefInRange(Mask, 0, Idx)) {
7300         /* EMPTY */
7301       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7302         Base = V1;
7303       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7304         Base = V2;
7305       } else {
7306         continue;
7307       }
7308
7309       // Extend the extraction length looking to match both the insertion of
7310       // the second source and the remaining elements of the first.
7311       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7312         SDValue Insert;
7313         int Len = Hi - Idx;
7314
7315         // Match insertion.
7316         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7317           Insert = V1;
7318         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7319           Insert = V2;
7320         } else {
7321           continue;
7322         }
7323
7324         // Match the remaining elements of the lower half.
7325         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7326           /* EMPTY */
7327         } else if ((!Base || (Base == V1)) &&
7328                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7329           Base = V1;
7330         } else if ((!Base || (Base == V2)) &&
7331                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7332                                               Size + Hi)) {
7333           Base = V2;
7334         } else {
7335           continue;
7336         }
7337
7338         // We may not have a base (first source) - this can safely be undefined.
7339         if (!Base)
7340           Base = DAG.getUNDEF(VT);
7341
7342         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7343         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7344         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7345                            DAG.getConstant(BitLen, DL, MVT::i8),
7346                            DAG.getConstant(BitIdx, DL, MVT::i8));
7347       }
7348     }
7349
7350     return SDValue();
7351   };
7352
7353   if (SDValue InsertQ = LowerAsInsertQ())
7354     return InsertQ;
7355
7356   return SDValue();
7357 }
7358
7359 /// \brief Lower a vector shuffle as a zero or any extension.
7360 ///
7361 /// Given a specific number of elements, element bit width, and extension
7362 /// stride, produce either a zero or any extension based on the available
7363 /// features of the subtarget.
7364 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7365     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7366     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7367   assert(Scale > 1 && "Need a scale to extend.");
7368   int NumElements = VT.getVectorNumElements();
7369   int EltBits = VT.getScalarSizeInBits();
7370   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7371          "Only 8, 16, and 32 bit elements can be extended.");
7372   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7373
7374   // Found a valid zext mask! Try various lowering strategies based on the
7375   // input type and available ISA extensions.
7376   if (Subtarget->hasSSE41()) {
7377     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7378                                  NumElements / Scale);
7379     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7380   }
7381
7382   // For any extends we can cheat for larger element sizes and use shuffle
7383   // instructions that can fold with a load and/or copy.
7384   if (AnyExt && EltBits == 32) {
7385     int PSHUFDMask[4] = {0, -1, 1, -1};
7386     return DAG.getBitcast(
7387         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7388                         DAG.getBitcast(MVT::v4i32, InputV),
7389                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7390   }
7391   if (AnyExt && EltBits == 16 && Scale > 2) {
7392     int PSHUFDMask[4] = {0, -1, 0, -1};
7393     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7394                          DAG.getBitcast(MVT::v4i32, InputV),
7395                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7396     int PSHUFHWMask[4] = {1, -1, -1, -1};
7397     return DAG.getBitcast(
7398         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7399                         DAG.getBitcast(MVT::v8i16, InputV),
7400                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7401   }
7402
7403   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7404   // to 64-bits.
7405   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7406     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7407     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7408
7409     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7410                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7411                                          DAG.getConstant(EltBits, DL, MVT::i8),
7412                                          DAG.getConstant(0, DL, MVT::i8)));
7413     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7414       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7415
7416     SDValue Hi =
7417         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7418                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7419                                 DAG.getConstant(EltBits, DL, MVT::i8),
7420                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7421     return DAG.getNode(ISD::BITCAST, DL, VT,
7422                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7423   }
7424
7425   // If this would require more than 2 unpack instructions to expand, use
7426   // pshufb when available. We can only use more than 2 unpack instructions
7427   // when zero extending i8 elements which also makes it easier to use pshufb.
7428   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7429     assert(NumElements == 16 && "Unexpected byte vector width!");
7430     SDValue PSHUFBMask[16];
7431     for (int i = 0; i < 16; ++i)
7432       PSHUFBMask[i] =
7433           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7434     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7435     return DAG.getBitcast(VT,
7436                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7437                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7438                                                   MVT::v16i8, PSHUFBMask)));
7439   }
7440
7441   // Otherwise emit a sequence of unpacks.
7442   do {
7443     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7444     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7445                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7446     InputV = DAG.getBitcast(InputVT, InputV);
7447     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7448     Scale /= 2;
7449     EltBits *= 2;
7450     NumElements /= 2;
7451   } while (Scale > 1);
7452   return DAG.getBitcast(VT, InputV);
7453 }
7454
7455 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7456 ///
7457 /// This routine will try to do everything in its power to cleverly lower
7458 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7459 /// check for the profitability of this lowering,  it tries to aggressively
7460 /// match this pattern. It will use all of the micro-architectural details it
7461 /// can to emit an efficient lowering. It handles both blends with all-zero
7462 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7463 /// masking out later).
7464 ///
7465 /// The reason we have dedicated lowering for zext-style shuffles is that they
7466 /// are both incredibly common and often quite performance sensitive.
7467 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7468     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7469     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7470   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7471
7472   int Bits = VT.getSizeInBits();
7473   int NumElements = VT.getVectorNumElements();
7474   assert(VT.getScalarSizeInBits() <= 32 &&
7475          "Exceeds 32-bit integer zero extension limit");
7476   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7477
7478   // Define a helper function to check a particular ext-scale and lower to it if
7479   // valid.
7480   auto Lower = [&](int Scale) -> SDValue {
7481     SDValue InputV;
7482     bool AnyExt = true;
7483     for (int i = 0; i < NumElements; ++i) {
7484       if (Mask[i] == -1)
7485         continue; // Valid anywhere but doesn't tell us anything.
7486       if (i % Scale != 0) {
7487         // Each of the extended elements need to be zeroable.
7488         if (!Zeroable[i])
7489           return SDValue();
7490
7491         // We no longer are in the anyext case.
7492         AnyExt = false;
7493         continue;
7494       }
7495
7496       // Each of the base elements needs to be consecutive indices into the
7497       // same input vector.
7498       SDValue V = Mask[i] < NumElements ? V1 : V2;
7499       if (!InputV)
7500         InputV = V;
7501       else if (InputV != V)
7502         return SDValue(); // Flip-flopping inputs.
7503
7504       if (Mask[i] % NumElements != i / Scale)
7505         return SDValue(); // Non-consecutive strided elements.
7506     }
7507
7508     // If we fail to find an input, we have a zero-shuffle which should always
7509     // have already been handled.
7510     // FIXME: Maybe handle this here in case during blending we end up with one?
7511     if (!InputV)
7512       return SDValue();
7513
7514     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7515         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7516   };
7517
7518   // The widest scale possible for extending is to a 64-bit integer.
7519   assert(Bits % 64 == 0 &&
7520          "The number of bits in a vector must be divisible by 64 on x86!");
7521   int NumExtElements = Bits / 64;
7522
7523   // Each iteration, try extending the elements half as much, but into twice as
7524   // many elements.
7525   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7526     assert(NumElements % NumExtElements == 0 &&
7527            "The input vector size must be divisible by the extended size.");
7528     if (SDValue V = Lower(NumElements / NumExtElements))
7529       return V;
7530   }
7531
7532   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7533   if (Bits != 128)
7534     return SDValue();
7535
7536   // Returns one of the source operands if the shuffle can be reduced to a
7537   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7538   auto CanZExtLowHalf = [&]() {
7539     for (int i = NumElements / 2; i != NumElements; ++i)
7540       if (!Zeroable[i])
7541         return SDValue();
7542     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7543       return V1;
7544     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7545       return V2;
7546     return SDValue();
7547   };
7548
7549   if (SDValue V = CanZExtLowHalf()) {
7550     V = DAG.getBitcast(MVT::v2i64, V);
7551     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7552     return DAG.getBitcast(VT, V);
7553   }
7554
7555   // No viable ext lowering found.
7556   return SDValue();
7557 }
7558
7559 /// \brief Try to get a scalar value for a specific element of a vector.
7560 ///
7561 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7562 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7563                                               SelectionDAG &DAG) {
7564   MVT VT = V.getSimpleValueType();
7565   MVT EltVT = VT.getVectorElementType();
7566   while (V.getOpcode() == ISD::BITCAST)
7567     V = V.getOperand(0);
7568   // If the bitcasts shift the element size, we can't extract an equivalent
7569   // element from it.
7570   MVT NewVT = V.getSimpleValueType();
7571   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7572     return SDValue();
7573
7574   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7575       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7576     // Ensure the scalar operand is the same size as the destination.
7577     // FIXME: Add support for scalar truncation where possible.
7578     SDValue S = V.getOperand(Idx);
7579     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7580       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7581   }
7582
7583   return SDValue();
7584 }
7585
7586 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7587 ///
7588 /// This is particularly important because the set of instructions varies
7589 /// significantly based on whether the operand is a load or not.
7590 static bool isShuffleFoldableLoad(SDValue V) {
7591   while (V.getOpcode() == ISD::BITCAST)
7592     V = V.getOperand(0);
7593
7594   return ISD::isNON_EXTLoad(V.getNode());
7595 }
7596
7597 /// \brief Try to lower insertion of a single element into a zero vector.
7598 ///
7599 /// This is a common pattern that we have especially efficient patterns to lower
7600 /// across all subtarget feature sets.
7601 static SDValue lowerVectorShuffleAsElementInsertion(
7602     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7603     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7604   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7605   MVT ExtVT = VT;
7606   MVT EltVT = VT.getVectorElementType();
7607
7608   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7609                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7610                 Mask.begin();
7611   bool IsV1Zeroable = true;
7612   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7613     if (i != V2Index && !Zeroable[i]) {
7614       IsV1Zeroable = false;
7615       break;
7616     }
7617
7618   // Check for a single input from a SCALAR_TO_VECTOR node.
7619   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7620   // all the smarts here sunk into that routine. However, the current
7621   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7622   // vector shuffle lowering is dead.
7623   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7624                                                DAG);
7625   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7626     // We need to zext the scalar if it is smaller than an i32.
7627     V2S = DAG.getBitcast(EltVT, V2S);
7628     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7629       // Using zext to expand a narrow element won't work for non-zero
7630       // insertions.
7631       if (!IsV1Zeroable)
7632         return SDValue();
7633
7634       // Zero-extend directly to i32.
7635       ExtVT = MVT::v4i32;
7636       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7637     }
7638     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7639   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7640              EltVT == MVT::i16) {
7641     // Either not inserting from the low element of the input or the input
7642     // element size is too small to use VZEXT_MOVL to clear the high bits.
7643     return SDValue();
7644   }
7645
7646   if (!IsV1Zeroable) {
7647     // If V1 can't be treated as a zero vector we have fewer options to lower
7648     // this. We can't support integer vectors or non-zero targets cheaply, and
7649     // the V1 elements can't be permuted in any way.
7650     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7651     if (!VT.isFloatingPoint() || V2Index != 0)
7652       return SDValue();
7653     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7654     V1Mask[V2Index] = -1;
7655     if (!isNoopShuffleMask(V1Mask))
7656       return SDValue();
7657     // This is essentially a special case blend operation, but if we have
7658     // general purpose blend operations, they are always faster. Bail and let
7659     // the rest of the lowering handle these as blends.
7660     if (Subtarget->hasSSE41())
7661       return SDValue();
7662
7663     // Otherwise, use MOVSD or MOVSS.
7664     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7665            "Only two types of floating point element types to handle!");
7666     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7667                        ExtVT, V1, V2);
7668   }
7669
7670   // This lowering only works for the low element with floating point vectors.
7671   if (VT.isFloatingPoint() && V2Index != 0)
7672     return SDValue();
7673
7674   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7675   if (ExtVT != VT)
7676     V2 = DAG.getBitcast(VT, V2);
7677
7678   if (V2Index != 0) {
7679     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7680     // the desired position. Otherwise it is more efficient to do a vector
7681     // shift left. We know that we can do a vector shift left because all
7682     // the inputs are zero.
7683     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7684       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7685       V2Shuffle[V2Index] = 0;
7686       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7687     } else {
7688       V2 = DAG.getBitcast(MVT::v2i64, V2);
7689       V2 = DAG.getNode(
7690           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7691           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7692                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7693                               DAG.getDataLayout(), VT)));
7694       V2 = DAG.getBitcast(VT, V2);
7695     }
7696   }
7697   return V2;
7698 }
7699
7700 /// \brief Try to lower broadcast of a single element.
7701 ///
7702 /// For convenience, this code also bundles all of the subtarget feature set
7703 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7704 /// a convenient way to factor it out.
7705 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7706                                              ArrayRef<int> Mask,
7707                                              const X86Subtarget *Subtarget,
7708                                              SelectionDAG &DAG) {
7709   if (!Subtarget->hasAVX())
7710     return SDValue();
7711   if (VT.isInteger() && !Subtarget->hasAVX2())
7712     return SDValue();
7713
7714   // Check that the mask is a broadcast.
7715   int BroadcastIdx = -1;
7716   for (int M : Mask)
7717     if (M >= 0 && BroadcastIdx == -1)
7718       BroadcastIdx = M;
7719     else if (M >= 0 && M != BroadcastIdx)
7720       return SDValue();
7721
7722   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7723                                             "a sorted mask where the broadcast "
7724                                             "comes from V1.");
7725
7726   // Go up the chain of (vector) values to find a scalar load that we can
7727   // combine with the broadcast.
7728   for (;;) {
7729     switch (V.getOpcode()) {
7730     case ISD::CONCAT_VECTORS: {
7731       int OperandSize = Mask.size() / V.getNumOperands();
7732       V = V.getOperand(BroadcastIdx / OperandSize);
7733       BroadcastIdx %= OperandSize;
7734       continue;
7735     }
7736
7737     case ISD::INSERT_SUBVECTOR: {
7738       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7739       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7740       if (!ConstantIdx)
7741         break;
7742
7743       int BeginIdx = (int)ConstantIdx->getZExtValue();
7744       int EndIdx =
7745           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7746       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7747         BroadcastIdx -= BeginIdx;
7748         V = VInner;
7749       } else {
7750         V = VOuter;
7751       }
7752       continue;
7753     }
7754     }
7755     break;
7756   }
7757
7758   // Check if this is a broadcast of a scalar. We special case lowering
7759   // for scalars so that we can more effectively fold with loads.
7760   // First, look through bitcast: if the original value has a larger element
7761   // type than the shuffle, the broadcast element is in essence truncated.
7762   // Make that explicit to ease folding.
7763   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7764     EVT EltVT = VT.getVectorElementType();
7765     SDValue V0 = V.getOperand(0);
7766     EVT V0VT = V0.getValueType();
7767
7768     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7769         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7770          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7771       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7772       BroadcastIdx = 0;
7773     }
7774   }
7775
7776   // Also check the simpler case, where we can directly reuse the scalar.
7777   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7778       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7779     V = V.getOperand(BroadcastIdx);
7780
7781     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7782     // Only AVX2 has register broadcasts.
7783     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7784       return SDValue();
7785   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7786     // We can't broadcast from a vector register without AVX2, and we can only
7787     // broadcast from the zero-element of a vector register.
7788     return SDValue();
7789   }
7790
7791   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7792 }
7793
7794 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7795 // INSERTPS when the V1 elements are already in the correct locations
7796 // because otherwise we can just always use two SHUFPS instructions which
7797 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7798 // perform INSERTPS if a single V1 element is out of place and all V2
7799 // elements are zeroable.
7800 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7801                                             ArrayRef<int> Mask,
7802                                             SelectionDAG &DAG) {
7803   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7804   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7805   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7806   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7807
7808   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7809
7810   unsigned ZMask = 0;
7811   int V1DstIndex = -1;
7812   int V2DstIndex = -1;
7813   bool V1UsedInPlace = false;
7814
7815   for (int i = 0; i < 4; ++i) {
7816     // Synthesize a zero mask from the zeroable elements (includes undefs).
7817     if (Zeroable[i]) {
7818       ZMask |= 1 << i;
7819       continue;
7820     }
7821
7822     // Flag if we use any V1 inputs in place.
7823     if (i == Mask[i]) {
7824       V1UsedInPlace = true;
7825       continue;
7826     }
7827
7828     // We can only insert a single non-zeroable element.
7829     if (V1DstIndex != -1 || V2DstIndex != -1)
7830       return SDValue();
7831
7832     if (Mask[i] < 4) {
7833       // V1 input out of place for insertion.
7834       V1DstIndex = i;
7835     } else {
7836       // V2 input for insertion.
7837       V2DstIndex = i;
7838     }
7839   }
7840
7841   // Don't bother if we have no (non-zeroable) element for insertion.
7842   if (V1DstIndex == -1 && V2DstIndex == -1)
7843     return SDValue();
7844
7845   // Determine element insertion src/dst indices. The src index is from the
7846   // start of the inserted vector, not the start of the concatenated vector.
7847   unsigned V2SrcIndex = 0;
7848   if (V1DstIndex != -1) {
7849     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7850     // and don't use the original V2 at all.
7851     V2SrcIndex = Mask[V1DstIndex];
7852     V2DstIndex = V1DstIndex;
7853     V2 = V1;
7854   } else {
7855     V2SrcIndex = Mask[V2DstIndex] - 4;
7856   }
7857
7858   // If no V1 inputs are used in place, then the result is created only from
7859   // the zero mask and the V2 insertion - so remove V1 dependency.
7860   if (!V1UsedInPlace)
7861     V1 = DAG.getUNDEF(MVT::v4f32);
7862
7863   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7864   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7865
7866   // Insert the V2 element into the desired position.
7867   SDLoc DL(Op);
7868   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7869                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7870 }
7871
7872 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7873 /// UNPCK instruction.
7874 ///
7875 /// This specifically targets cases where we end up with alternating between
7876 /// the two inputs, and so can permute them into something that feeds a single
7877 /// UNPCK instruction. Note that this routine only targets integer vectors
7878 /// because for floating point vectors we have a generalized SHUFPS lowering
7879 /// strategy that handles everything that doesn't *exactly* match an unpack,
7880 /// making this clever lowering unnecessary.
7881 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7882                                                     SDValue V1, SDValue V2,
7883                                                     ArrayRef<int> Mask,
7884                                                     SelectionDAG &DAG) {
7885   assert(!VT.isFloatingPoint() &&
7886          "This routine only supports integer vectors.");
7887   assert(!isSingleInputShuffleMask(Mask) &&
7888          "This routine should only be used when blending two inputs.");
7889   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7890
7891   int Size = Mask.size();
7892
7893   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7894     return M >= 0 && M % Size < Size / 2;
7895   });
7896   int NumHiInputs = std::count_if(
7897       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7898
7899   bool UnpackLo = NumLoInputs >= NumHiInputs;
7900
7901   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7902     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7903     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7904
7905     for (int i = 0; i < Size; ++i) {
7906       if (Mask[i] < 0)
7907         continue;
7908
7909       // Each element of the unpack contains Scale elements from this mask.
7910       int UnpackIdx = i / Scale;
7911
7912       // We only handle the case where V1 feeds the first slots of the unpack.
7913       // We rely on canonicalization to ensure this is the case.
7914       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7915         return SDValue();
7916
7917       // Setup the mask for this input. The indexing is tricky as we have to
7918       // handle the unpack stride.
7919       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7920       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7921           Mask[i] % Size;
7922     }
7923
7924     // If we will have to shuffle both inputs to use the unpack, check whether
7925     // we can just unpack first and shuffle the result. If so, skip this unpack.
7926     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7927         !isNoopShuffleMask(V2Mask))
7928       return SDValue();
7929
7930     // Shuffle the inputs into place.
7931     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7932     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7933
7934     // Cast the inputs to the type we will use to unpack them.
7935     V1 = DAG.getBitcast(UnpackVT, V1);
7936     V2 = DAG.getBitcast(UnpackVT, V2);
7937
7938     // Unpack the inputs and cast the result back to the desired type.
7939     return DAG.getBitcast(
7940         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7941                         UnpackVT, V1, V2));
7942   };
7943
7944   // We try each unpack from the largest to the smallest to try and find one
7945   // that fits this mask.
7946   int OrigNumElements = VT.getVectorNumElements();
7947   int OrigScalarSize = VT.getScalarSizeInBits();
7948   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7949     int Scale = ScalarSize / OrigScalarSize;
7950     int NumElements = OrigNumElements / Scale;
7951     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7952     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7953       return Unpack;
7954   }
7955
7956   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7957   // initial unpack.
7958   if (NumLoInputs == 0 || NumHiInputs == 0) {
7959     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7960            "We have to have *some* inputs!");
7961     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7962
7963     // FIXME: We could consider the total complexity of the permute of each
7964     // possible unpacking. Or at the least we should consider how many
7965     // half-crossings are created.
7966     // FIXME: We could consider commuting the unpacks.
7967
7968     SmallVector<int, 32> PermMask;
7969     PermMask.assign(Size, -1);
7970     for (int i = 0; i < Size; ++i) {
7971       if (Mask[i] < 0)
7972         continue;
7973
7974       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7975
7976       PermMask[i] =
7977           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7978     }
7979     return DAG.getVectorShuffle(
7980         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7981                             DL, VT, V1, V2),
7982         DAG.getUNDEF(VT), PermMask);
7983   }
7984
7985   return SDValue();
7986 }
7987
7988 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7989 ///
7990 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7991 /// support for floating point shuffles but not integer shuffles. These
7992 /// instructions will incur a domain crossing penalty on some chips though so
7993 /// it is better to avoid lowering through this for integer vectors where
7994 /// possible.
7995 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7996                                        const X86Subtarget *Subtarget,
7997                                        SelectionDAG &DAG) {
7998   SDLoc DL(Op);
7999   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8000   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8001   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8003   ArrayRef<int> Mask = SVOp->getMask();
8004   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8005
8006   if (isSingleInputShuffleMask(Mask)) {
8007     // Use low duplicate instructions for masks that match their pattern.
8008     if (Subtarget->hasSSE3())
8009       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8010         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8011
8012     // Straight shuffle of a single input vector. Simulate this by using the
8013     // single input as both of the "inputs" to this instruction..
8014     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8015
8016     if (Subtarget->hasAVX()) {
8017       // If we have AVX, we can use VPERMILPS which will allow folding a load
8018       // into the shuffle.
8019       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8020                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8021     }
8022
8023     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8024                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8025   }
8026   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8027   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8028
8029   // If we have a single input, insert that into V1 if we can do so cheaply.
8030   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8031     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8032             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8033       return Insertion;
8034     // Try inverting the insertion since for v2 masks it is easy to do and we
8035     // can't reliably sort the mask one way or the other.
8036     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8037                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8038     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8039             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8040       return Insertion;
8041   }
8042
8043   // Try to use one of the special instruction patterns to handle two common
8044   // blend patterns if a zero-blend above didn't work.
8045   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8046       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8047     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8048       // We can either use a special instruction to load over the low double or
8049       // to move just the low double.
8050       return DAG.getNode(
8051           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8052           DL, MVT::v2f64, V2,
8053           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8054
8055   if (Subtarget->hasSSE41())
8056     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8057                                                   Subtarget, DAG))
8058       return Blend;
8059
8060   // Use dedicated unpack instructions for masks that match their pattern.
8061   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8062     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8063   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8064     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8065
8066   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8067   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8068                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8069 }
8070
8071 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8072 ///
8073 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8074 /// the integer unit to minimize domain crossing penalties. However, for blends
8075 /// it falls back to the floating point shuffle operation with appropriate bit
8076 /// casting.
8077 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8078                                        const X86Subtarget *Subtarget,
8079                                        SelectionDAG &DAG) {
8080   SDLoc DL(Op);
8081   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8082   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8083   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8084   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8085   ArrayRef<int> Mask = SVOp->getMask();
8086   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8087
8088   if (isSingleInputShuffleMask(Mask)) {
8089     // Check for being able to broadcast a single element.
8090     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8091                                                           Mask, Subtarget, DAG))
8092       return Broadcast;
8093
8094     // Straight shuffle of a single input vector. For everything from SSE2
8095     // onward this has a single fast instruction with no scary immediates.
8096     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8097     V1 = DAG.getBitcast(MVT::v4i32, V1);
8098     int WidenedMask[4] = {
8099         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8100         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8101     return DAG.getBitcast(
8102         MVT::v2i64,
8103         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8104                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8105   }
8106   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8107   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8108   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8109   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8110
8111   // If we have a blend of two PACKUS operations an the blend aligns with the
8112   // low and half halves, we can just merge the PACKUS operations. This is
8113   // particularly important as it lets us merge shuffles that this routine itself
8114   // creates.
8115   auto GetPackNode = [](SDValue V) {
8116     while (V.getOpcode() == ISD::BITCAST)
8117       V = V.getOperand(0);
8118
8119     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8120   };
8121   if (SDValue V1Pack = GetPackNode(V1))
8122     if (SDValue V2Pack = GetPackNode(V2))
8123       return DAG.getBitcast(MVT::v2i64,
8124                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8125                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8126                                                      : V1Pack.getOperand(1),
8127                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8128                                                      : V2Pack.getOperand(1)));
8129
8130   // Try to use shift instructions.
8131   if (SDValue Shift =
8132           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8133     return Shift;
8134
8135   // When loading a scalar and then shuffling it into a vector we can often do
8136   // the insertion cheaply.
8137   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8138           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8139     return Insertion;
8140   // Try inverting the insertion since for v2 masks it is easy to do and we
8141   // can't reliably sort the mask one way or the other.
8142   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8143   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8144           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8145     return Insertion;
8146
8147   // We have different paths for blend lowering, but they all must use the
8148   // *exact* same predicate.
8149   bool IsBlendSupported = Subtarget->hasSSE41();
8150   if (IsBlendSupported)
8151     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8152                                                   Subtarget, DAG))
8153       return Blend;
8154
8155   // Use dedicated unpack instructions for masks that match their pattern.
8156   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8157     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8158   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8159     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8160
8161   // Try to use byte rotation instructions.
8162   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8163   if (Subtarget->hasSSSE3())
8164     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8165             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8166       return Rotate;
8167
8168   // If we have direct support for blends, we should lower by decomposing into
8169   // a permute. That will be faster than the domain cross.
8170   if (IsBlendSupported)
8171     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8172                                                       Mask, DAG);
8173
8174   // We implement this with SHUFPD which is pretty lame because it will likely
8175   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8176   // However, all the alternatives are still more cycles and newer chips don't
8177   // have this problem. It would be really nice if x86 had better shuffles here.
8178   V1 = DAG.getBitcast(MVT::v2f64, V1);
8179   V2 = DAG.getBitcast(MVT::v2f64, V2);
8180   return DAG.getBitcast(MVT::v2i64,
8181                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8182 }
8183
8184 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8185 ///
8186 /// This is used to disable more specialized lowerings when the shufps lowering
8187 /// will happen to be efficient.
8188 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8189   // This routine only handles 128-bit shufps.
8190   assert(Mask.size() == 4 && "Unsupported mask size!");
8191
8192   // To lower with a single SHUFPS we need to have the low half and high half
8193   // each requiring a single input.
8194   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8195     return false;
8196   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8197     return false;
8198
8199   return true;
8200 }
8201
8202 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8203 ///
8204 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8205 /// It makes no assumptions about whether this is the *best* lowering, it simply
8206 /// uses it.
8207 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8208                                             ArrayRef<int> Mask, SDValue V1,
8209                                             SDValue V2, SelectionDAG &DAG) {
8210   SDValue LowV = V1, HighV = V2;
8211   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8212
8213   int NumV2Elements =
8214       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8215
8216   if (NumV2Elements == 1) {
8217     int V2Index =
8218         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8219         Mask.begin();
8220
8221     // Compute the index adjacent to V2Index and in the same half by toggling
8222     // the low bit.
8223     int V2AdjIndex = V2Index ^ 1;
8224
8225     if (Mask[V2AdjIndex] == -1) {
8226       // Handles all the cases where we have a single V2 element and an undef.
8227       // This will only ever happen in the high lanes because we commute the
8228       // vector otherwise.
8229       if (V2Index < 2)
8230         std::swap(LowV, HighV);
8231       NewMask[V2Index] -= 4;
8232     } else {
8233       // Handle the case where the V2 element ends up adjacent to a V1 element.
8234       // To make this work, blend them together as the first step.
8235       int V1Index = V2AdjIndex;
8236       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8237       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8238                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8239
8240       // Now proceed to reconstruct the final blend as we have the necessary
8241       // high or low half formed.
8242       if (V2Index < 2) {
8243         LowV = V2;
8244         HighV = V1;
8245       } else {
8246         HighV = V2;
8247       }
8248       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8249       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8250     }
8251   } else if (NumV2Elements == 2) {
8252     if (Mask[0] < 4 && Mask[1] < 4) {
8253       // Handle the easy case where we have V1 in the low lanes and V2 in the
8254       // high lanes.
8255       NewMask[2] -= 4;
8256       NewMask[3] -= 4;
8257     } else if (Mask[2] < 4 && Mask[3] < 4) {
8258       // We also handle the reversed case because this utility may get called
8259       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8260       // arrange things in the right direction.
8261       NewMask[0] -= 4;
8262       NewMask[1] -= 4;
8263       HighV = V1;
8264       LowV = V2;
8265     } else {
8266       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8267       // trying to place elements directly, just blend them and set up the final
8268       // shuffle to place them.
8269
8270       // The first two blend mask elements are for V1, the second two are for
8271       // V2.
8272       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8273                           Mask[2] < 4 ? Mask[2] : Mask[3],
8274                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8275                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8276       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8277                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8278
8279       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8280       // a blend.
8281       LowV = HighV = V1;
8282       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8283       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8284       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8285       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8286     }
8287   }
8288   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8289                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8290 }
8291
8292 /// \brief Lower 4-lane 32-bit floating point shuffles.
8293 ///
8294 /// Uses instructions exclusively from the floating point unit to minimize
8295 /// domain crossing penalties, as these are sufficient to implement all v4f32
8296 /// shuffles.
8297 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8298                                        const X86Subtarget *Subtarget,
8299                                        SelectionDAG &DAG) {
8300   SDLoc DL(Op);
8301   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8302   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8303   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8304   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8305   ArrayRef<int> Mask = SVOp->getMask();
8306   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8307
8308   int NumV2Elements =
8309       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8310
8311   if (NumV2Elements == 0) {
8312     // Check for being able to broadcast a single element.
8313     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8314                                                           Mask, Subtarget, DAG))
8315       return Broadcast;
8316
8317     // Use even/odd duplicate instructions for masks that match their pattern.
8318     if (Subtarget->hasSSE3()) {
8319       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8320         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8321       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8322         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8323     }
8324
8325     if (Subtarget->hasAVX()) {
8326       // If we have AVX, we can use VPERMILPS which will allow folding a load
8327       // into the shuffle.
8328       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8329                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8330     }
8331
8332     // Otherwise, use a straight shuffle of a single input vector. We pass the
8333     // input vector to both operands to simulate this with a SHUFPS.
8334     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8335                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8336   }
8337
8338   // There are special ways we can lower some single-element blends. However, we
8339   // have custom ways we can lower more complex single-element blends below that
8340   // we defer to if both this and BLENDPS fail to match, so restrict this to
8341   // when the V2 input is targeting element 0 of the mask -- that is the fast
8342   // case here.
8343   if (NumV2Elements == 1 && Mask[0] >= 4)
8344     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8345                                                          Mask, Subtarget, DAG))
8346       return V;
8347
8348   if (Subtarget->hasSSE41()) {
8349     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8350                                                   Subtarget, DAG))
8351       return Blend;
8352
8353     // Use INSERTPS if we can complete the shuffle efficiently.
8354     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8355       return V;
8356
8357     if (!isSingleSHUFPSMask(Mask))
8358       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8359               DL, MVT::v4f32, V1, V2, Mask, DAG))
8360         return BlendPerm;
8361   }
8362
8363   // Use dedicated unpack instructions for masks that match their pattern.
8364   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8365     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8366   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8367     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8368   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8369     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8370   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8371     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8372
8373   // Otherwise fall back to a SHUFPS lowering strategy.
8374   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8375 }
8376
8377 /// \brief Lower 4-lane i32 vector shuffles.
8378 ///
8379 /// We try to handle these with integer-domain shuffles where we can, but for
8380 /// blends we use the floating point domain blend instructions.
8381 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8382                                        const X86Subtarget *Subtarget,
8383                                        SelectionDAG &DAG) {
8384   SDLoc DL(Op);
8385   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8386   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8387   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8389   ArrayRef<int> Mask = SVOp->getMask();
8390   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8391
8392   // Whenever we can lower this as a zext, that instruction is strictly faster
8393   // than any alternative. It also allows us to fold memory operands into the
8394   // shuffle in many cases.
8395   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8396                                                          Mask, Subtarget, DAG))
8397     return ZExt;
8398
8399   int NumV2Elements =
8400       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8401
8402   if (NumV2Elements == 0) {
8403     // Check for being able to broadcast a single element.
8404     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8405                                                           Mask, Subtarget, DAG))
8406       return Broadcast;
8407
8408     // Straight shuffle of a single input vector. For everything from SSE2
8409     // onward this has a single fast instruction with no scary immediates.
8410     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8411     // but we aren't actually going to use the UNPCK instruction because doing
8412     // so prevents folding a load into this instruction or making a copy.
8413     const int UnpackLoMask[] = {0, 0, 1, 1};
8414     const int UnpackHiMask[] = {2, 2, 3, 3};
8415     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8416       Mask = UnpackLoMask;
8417     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8418       Mask = UnpackHiMask;
8419
8420     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8421                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8422   }
8423
8424   // Try to use shift instructions.
8425   if (SDValue Shift =
8426           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8427     return Shift;
8428
8429   // There are special ways we can lower some single-element blends.
8430   if (NumV2Elements == 1)
8431     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8432                                                          Mask, Subtarget, DAG))
8433       return V;
8434
8435   // We have different paths for blend lowering, but they all must use the
8436   // *exact* same predicate.
8437   bool IsBlendSupported = Subtarget->hasSSE41();
8438   if (IsBlendSupported)
8439     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8440                                                   Subtarget, DAG))
8441       return Blend;
8442
8443   if (SDValue Masked =
8444           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8445     return Masked;
8446
8447   // Use dedicated unpack instructions for masks that match their pattern.
8448   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8449     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8450   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8451     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8452   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8453     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8454   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8455     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8456
8457   // Try to use byte rotation instructions.
8458   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8459   if (Subtarget->hasSSSE3())
8460     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8461             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8462       return Rotate;
8463
8464   // If we have direct support for blends, we should lower by decomposing into
8465   // a permute. That will be faster than the domain cross.
8466   if (IsBlendSupported)
8467     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8468                                                       Mask, DAG);
8469
8470   // Try to lower by permuting the inputs into an unpack instruction.
8471   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8472                                                             V2, Mask, DAG))
8473     return Unpack;
8474
8475   // We implement this with SHUFPS because it can blend from two vectors.
8476   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8477   // up the inputs, bypassing domain shift penalties that we would encur if we
8478   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8479   // relevant.
8480   return DAG.getBitcast(
8481       MVT::v4i32,
8482       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8483                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8484 }
8485
8486 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8487 /// shuffle lowering, and the most complex part.
8488 ///
8489 /// The lowering strategy is to try to form pairs of input lanes which are
8490 /// targeted at the same half of the final vector, and then use a dword shuffle
8491 /// to place them onto the right half, and finally unpack the paired lanes into
8492 /// their final position.
8493 ///
8494 /// The exact breakdown of how to form these dword pairs and align them on the
8495 /// correct sides is really tricky. See the comments within the function for
8496 /// more of the details.
8497 ///
8498 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8499 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8500 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8501 /// vector, form the analogous 128-bit 8-element Mask.
8502 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8503     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8504     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8505   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8506   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8507
8508   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8509   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8510   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8511
8512   SmallVector<int, 4> LoInputs;
8513   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8514                [](int M) { return M >= 0; });
8515   std::sort(LoInputs.begin(), LoInputs.end());
8516   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8517   SmallVector<int, 4> HiInputs;
8518   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8519                [](int M) { return M >= 0; });
8520   std::sort(HiInputs.begin(), HiInputs.end());
8521   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8522   int NumLToL =
8523       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8524   int NumHToL = LoInputs.size() - NumLToL;
8525   int NumLToH =
8526       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8527   int NumHToH = HiInputs.size() - NumLToH;
8528   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8529   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8530   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8531   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8532
8533   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8534   // such inputs we can swap two of the dwords across the half mark and end up
8535   // with <=2 inputs to each half in each half. Once there, we can fall through
8536   // to the generic code below. For example:
8537   //
8538   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8539   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8540   //
8541   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8542   // and an existing 2-into-2 on the other half. In this case we may have to
8543   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8544   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8545   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8546   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8547   // half than the one we target for fixing) will be fixed when we re-enter this
8548   // path. We will also combine away any sequence of PSHUFD instructions that
8549   // result into a single instruction. Here is an example of the tricky case:
8550   //
8551   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8552   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8553   //
8554   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8555   //
8556   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8557   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8558   //
8559   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8560   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8561   //
8562   // The result is fine to be handled by the generic logic.
8563   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8564                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8565                           int AOffset, int BOffset) {
8566     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8567            "Must call this with A having 3 or 1 inputs from the A half.");
8568     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8569            "Must call this with B having 1 or 3 inputs from the B half.");
8570     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8571            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8572
8573     bool ThreeAInputs = AToAInputs.size() == 3;
8574
8575     // Compute the index of dword with only one word among the three inputs in
8576     // a half by taking the sum of the half with three inputs and subtracting
8577     // the sum of the actual three inputs. The difference is the remaining
8578     // slot.
8579     int ADWord, BDWord;
8580     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8581     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8582     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8583     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8584     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8585     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8586     int TripleNonInputIdx =
8587         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8588     TripleDWord = TripleNonInputIdx / 2;
8589
8590     // We use xor with one to compute the adjacent DWord to whichever one the
8591     // OneInput is in.
8592     OneInputDWord = (OneInput / 2) ^ 1;
8593
8594     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8595     // and BToA inputs. If there is also such a problem with the BToB and AToB
8596     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8597     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8598     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8599     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8600       // Compute how many inputs will be flipped by swapping these DWords. We
8601       // need
8602       // to balance this to ensure we don't form a 3-1 shuffle in the other
8603       // half.
8604       int NumFlippedAToBInputs =
8605           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8606           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8607       int NumFlippedBToBInputs =
8608           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8609           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8610       if ((NumFlippedAToBInputs == 1 &&
8611            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8612           (NumFlippedBToBInputs == 1 &&
8613            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8614         // We choose whether to fix the A half or B half based on whether that
8615         // half has zero flipped inputs. At zero, we may not be able to fix it
8616         // with that half. We also bias towards fixing the B half because that
8617         // will more commonly be the high half, and we have to bias one way.
8618         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8619                                                        ArrayRef<int> Inputs) {
8620           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8621           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8622                                          PinnedIdx ^ 1) != Inputs.end();
8623           // Determine whether the free index is in the flipped dword or the
8624           // unflipped dword based on where the pinned index is. We use this bit
8625           // in an xor to conditionally select the adjacent dword.
8626           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8627           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8628                                              FixFreeIdx) != Inputs.end();
8629           if (IsFixIdxInput == IsFixFreeIdxInput)
8630             FixFreeIdx += 1;
8631           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8632                                         FixFreeIdx) != Inputs.end();
8633           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8634                  "We need to be changing the number of flipped inputs!");
8635           int PSHUFHalfMask[] = {0, 1, 2, 3};
8636           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8637           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8638                           MVT::v8i16, V,
8639                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8640
8641           for (int &M : Mask)
8642             if (M != -1 && M == FixIdx)
8643               M = FixFreeIdx;
8644             else if (M != -1 && M == FixFreeIdx)
8645               M = FixIdx;
8646         };
8647         if (NumFlippedBToBInputs != 0) {
8648           int BPinnedIdx =
8649               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8650           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8651         } else {
8652           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8653           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8654           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8655         }
8656       }
8657     }
8658
8659     int PSHUFDMask[] = {0, 1, 2, 3};
8660     PSHUFDMask[ADWord] = BDWord;
8661     PSHUFDMask[BDWord] = ADWord;
8662     V = DAG.getBitcast(
8663         VT,
8664         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8665                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8666
8667     // Adjust the mask to match the new locations of A and B.
8668     for (int &M : Mask)
8669       if (M != -1 && M/2 == ADWord)
8670         M = 2 * BDWord + M % 2;
8671       else if (M != -1 && M/2 == BDWord)
8672         M = 2 * ADWord + M % 2;
8673
8674     // Recurse back into this routine to re-compute state now that this isn't
8675     // a 3 and 1 problem.
8676     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8677                                                      DAG);
8678   };
8679   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8680     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8681   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8682     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8683
8684   // At this point there are at most two inputs to the low and high halves from
8685   // each half. That means the inputs can always be grouped into dwords and
8686   // those dwords can then be moved to the correct half with a dword shuffle.
8687   // We use at most one low and one high word shuffle to collect these paired
8688   // inputs into dwords, and finally a dword shuffle to place them.
8689   int PSHUFLMask[4] = {-1, -1, -1, -1};
8690   int PSHUFHMask[4] = {-1, -1, -1, -1};
8691   int PSHUFDMask[4] = {-1, -1, -1, -1};
8692
8693   // First fix the masks for all the inputs that are staying in their
8694   // original halves. This will then dictate the targets of the cross-half
8695   // shuffles.
8696   auto fixInPlaceInputs =
8697       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8698                     MutableArrayRef<int> SourceHalfMask,
8699                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8700     if (InPlaceInputs.empty())
8701       return;
8702     if (InPlaceInputs.size() == 1) {
8703       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8704           InPlaceInputs[0] - HalfOffset;
8705       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8706       return;
8707     }
8708     if (IncomingInputs.empty()) {
8709       // Just fix all of the in place inputs.
8710       for (int Input : InPlaceInputs) {
8711         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8712         PSHUFDMask[Input / 2] = Input / 2;
8713       }
8714       return;
8715     }
8716
8717     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8718     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8719         InPlaceInputs[0] - HalfOffset;
8720     // Put the second input next to the first so that they are packed into
8721     // a dword. We find the adjacent index by toggling the low bit.
8722     int AdjIndex = InPlaceInputs[0] ^ 1;
8723     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8724     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8725     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8726   };
8727   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8728   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8729
8730   // Now gather the cross-half inputs and place them into a free dword of
8731   // their target half.
8732   // FIXME: This operation could almost certainly be simplified dramatically to
8733   // look more like the 3-1 fixing operation.
8734   auto moveInputsToRightHalf = [&PSHUFDMask](
8735       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8736       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8737       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8738       int DestOffset) {
8739     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8740       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8741     };
8742     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8743                                                int Word) {
8744       int LowWord = Word & ~1;
8745       int HighWord = Word | 1;
8746       return isWordClobbered(SourceHalfMask, LowWord) ||
8747              isWordClobbered(SourceHalfMask, HighWord);
8748     };
8749
8750     if (IncomingInputs.empty())
8751       return;
8752
8753     if (ExistingInputs.empty()) {
8754       // Map any dwords with inputs from them into the right half.
8755       for (int Input : IncomingInputs) {
8756         // If the source half mask maps over the inputs, turn those into
8757         // swaps and use the swapped lane.
8758         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8759           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8760             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8761                 Input - SourceOffset;
8762             // We have to swap the uses in our half mask in one sweep.
8763             for (int &M : HalfMask)
8764               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8765                 M = Input;
8766               else if (M == Input)
8767                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8768           } else {
8769             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8770                        Input - SourceOffset &&
8771                    "Previous placement doesn't match!");
8772           }
8773           // Note that this correctly re-maps both when we do a swap and when
8774           // we observe the other side of the swap above. We rely on that to
8775           // avoid swapping the members of the input list directly.
8776           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8777         }
8778
8779         // Map the input's dword into the correct half.
8780         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8781           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8782         else
8783           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8784                      Input / 2 &&
8785                  "Previous placement doesn't match!");
8786       }
8787
8788       // And just directly shift any other-half mask elements to be same-half
8789       // as we will have mirrored the dword containing the element into the
8790       // same position within that half.
8791       for (int &M : HalfMask)
8792         if (M >= SourceOffset && M < SourceOffset + 4) {
8793           M = M - SourceOffset + DestOffset;
8794           assert(M >= 0 && "This should never wrap below zero!");
8795         }
8796       return;
8797     }
8798
8799     // Ensure we have the input in a viable dword of its current half. This
8800     // is particularly tricky because the original position may be clobbered
8801     // by inputs being moved and *staying* in that half.
8802     if (IncomingInputs.size() == 1) {
8803       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8804         int InputFixed = std::find(std::begin(SourceHalfMask),
8805                                    std::end(SourceHalfMask), -1) -
8806                          std::begin(SourceHalfMask) + SourceOffset;
8807         SourceHalfMask[InputFixed - SourceOffset] =
8808             IncomingInputs[0] - SourceOffset;
8809         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8810                      InputFixed);
8811         IncomingInputs[0] = InputFixed;
8812       }
8813     } else if (IncomingInputs.size() == 2) {
8814       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8815           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8816         // We have two non-adjacent or clobbered inputs we need to extract from
8817         // the source half. To do this, we need to map them into some adjacent
8818         // dword slot in the source mask.
8819         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8820                               IncomingInputs[1] - SourceOffset};
8821
8822         // If there is a free slot in the source half mask adjacent to one of
8823         // the inputs, place the other input in it. We use (Index XOR 1) to
8824         // compute an adjacent index.
8825         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8826             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8827           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8828           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8829           InputsFixed[1] = InputsFixed[0] ^ 1;
8830         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8831                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8832           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8833           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8834           InputsFixed[0] = InputsFixed[1] ^ 1;
8835         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8836                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8837           // The two inputs are in the same DWord but it is clobbered and the
8838           // adjacent DWord isn't used at all. Move both inputs to the free
8839           // slot.
8840           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8841           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8842           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8843           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8844         } else {
8845           // The only way we hit this point is if there is no clobbering
8846           // (because there are no off-half inputs to this half) and there is no
8847           // free slot adjacent to one of the inputs. In this case, we have to
8848           // swap an input with a non-input.
8849           for (int i = 0; i < 4; ++i)
8850             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8851                    "We can't handle any clobbers here!");
8852           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8853                  "Cannot have adjacent inputs here!");
8854
8855           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8856           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8857
8858           // We also have to update the final source mask in this case because
8859           // it may need to undo the above swap.
8860           for (int &M : FinalSourceHalfMask)
8861             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8862               M = InputsFixed[1] + SourceOffset;
8863             else if (M == InputsFixed[1] + SourceOffset)
8864               M = (InputsFixed[0] ^ 1) + SourceOffset;
8865
8866           InputsFixed[1] = InputsFixed[0] ^ 1;
8867         }
8868
8869         // Point everything at the fixed inputs.
8870         for (int &M : HalfMask)
8871           if (M == IncomingInputs[0])
8872             M = InputsFixed[0] + SourceOffset;
8873           else if (M == IncomingInputs[1])
8874             M = InputsFixed[1] + SourceOffset;
8875
8876         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8877         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8878       }
8879     } else {
8880       llvm_unreachable("Unhandled input size!");
8881     }
8882
8883     // Now hoist the DWord down to the right half.
8884     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8885     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8886     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8887     for (int &M : HalfMask)
8888       for (int Input : IncomingInputs)
8889         if (M == Input)
8890           M = FreeDWord * 2 + Input % 2;
8891   };
8892   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8893                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8894   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8895                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8896
8897   // Now enact all the shuffles we've computed to move the inputs into their
8898   // target half.
8899   if (!isNoopShuffleMask(PSHUFLMask))
8900     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8901                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8902   if (!isNoopShuffleMask(PSHUFHMask))
8903     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8904                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8905   if (!isNoopShuffleMask(PSHUFDMask))
8906     V = DAG.getBitcast(
8907         VT,
8908         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8909                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8910
8911   // At this point, each half should contain all its inputs, and we can then
8912   // just shuffle them into their final position.
8913   assert(std::count_if(LoMask.begin(), LoMask.end(),
8914                        [](int M) { return M >= 4; }) == 0 &&
8915          "Failed to lift all the high half inputs to the low mask!");
8916   assert(std::count_if(HiMask.begin(), HiMask.end(),
8917                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8918          "Failed to lift all the low half inputs to the high mask!");
8919
8920   // Do a half shuffle for the low mask.
8921   if (!isNoopShuffleMask(LoMask))
8922     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8923                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8924
8925   // Do a half shuffle with the high mask after shifting its values down.
8926   for (int &M : HiMask)
8927     if (M >= 0)
8928       M -= 4;
8929   if (!isNoopShuffleMask(HiMask))
8930     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8931                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8932
8933   return V;
8934 }
8935
8936 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8937 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8938                                           SDValue V2, ArrayRef<int> Mask,
8939                                           SelectionDAG &DAG, bool &V1InUse,
8940                                           bool &V2InUse) {
8941   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8942   SDValue V1Mask[16];
8943   SDValue V2Mask[16];
8944   V1InUse = false;
8945   V2InUse = false;
8946
8947   int Size = Mask.size();
8948   int Scale = 16 / Size;
8949   for (int i = 0; i < 16; ++i) {
8950     if (Mask[i / Scale] == -1) {
8951       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8952     } else {
8953       const int ZeroMask = 0x80;
8954       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8955                                           : ZeroMask;
8956       int V2Idx = Mask[i / Scale] < Size
8957                       ? ZeroMask
8958                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8959       if (Zeroable[i / Scale])
8960         V1Idx = V2Idx = ZeroMask;
8961       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8962       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8963       V1InUse |= (ZeroMask != V1Idx);
8964       V2InUse |= (ZeroMask != V2Idx);
8965     }
8966   }
8967
8968   if (V1InUse)
8969     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8970                      DAG.getBitcast(MVT::v16i8, V1),
8971                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8972   if (V2InUse)
8973     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8974                      DAG.getBitcast(MVT::v16i8, V2),
8975                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8976
8977   // If we need shuffled inputs from both, blend the two.
8978   SDValue V;
8979   if (V1InUse && V2InUse)
8980     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8981   else
8982     V = V1InUse ? V1 : V2;
8983
8984   // Cast the result back to the correct type.
8985   return DAG.getBitcast(VT, V);
8986 }
8987
8988 /// \brief Generic lowering of 8-lane i16 shuffles.
8989 ///
8990 /// This handles both single-input shuffles and combined shuffle/blends with
8991 /// two inputs. The single input shuffles are immediately delegated to
8992 /// a dedicated lowering routine.
8993 ///
8994 /// The blends are lowered in one of three fundamental ways. If there are few
8995 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8996 /// of the input is significantly cheaper when lowered as an interleaving of
8997 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8998 /// halves of the inputs separately (making them have relatively few inputs)
8999 /// and then concatenate them.
9000 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9001                                        const X86Subtarget *Subtarget,
9002                                        SelectionDAG &DAG) {
9003   SDLoc DL(Op);
9004   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9005   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9006   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9007   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9008   ArrayRef<int> OrigMask = SVOp->getMask();
9009   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9010                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9011   MutableArrayRef<int> Mask(MaskStorage);
9012
9013   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9014
9015   // Whenever we can lower this as a zext, that instruction is strictly faster
9016   // than any alternative.
9017   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9018           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9019     return ZExt;
9020
9021   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9022   (void)isV1;
9023   auto isV2 = [](int M) { return M >= 8; };
9024
9025   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9026
9027   if (NumV2Inputs == 0) {
9028     // Check for being able to broadcast a single element.
9029     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9030                                                           Mask, Subtarget, DAG))
9031       return Broadcast;
9032
9033     // Try to use shift instructions.
9034     if (SDValue Shift =
9035             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9036       return Shift;
9037
9038     // Use dedicated unpack instructions for masks that match their pattern.
9039     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9040       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9041     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9042       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9043
9044     // Try to use byte rotation instructions.
9045     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9046                                                         Mask, Subtarget, DAG))
9047       return Rotate;
9048
9049     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9050                                                      Subtarget, DAG);
9051   }
9052
9053   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9054          "All single-input shuffles should be canonicalized to be V1-input "
9055          "shuffles.");
9056
9057   // Try to use shift instructions.
9058   if (SDValue Shift =
9059           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9060     return Shift;
9061
9062   // See if we can use SSE4A Extraction / Insertion.
9063   if (Subtarget->hasSSE4A())
9064     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9065       return V;
9066
9067   // There are special ways we can lower some single-element blends.
9068   if (NumV2Inputs == 1)
9069     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9070                                                          Mask, Subtarget, DAG))
9071       return V;
9072
9073   // We have different paths for blend lowering, but they all must use the
9074   // *exact* same predicate.
9075   bool IsBlendSupported = Subtarget->hasSSE41();
9076   if (IsBlendSupported)
9077     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9078                                                   Subtarget, DAG))
9079       return Blend;
9080
9081   if (SDValue Masked =
9082           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9083     return Masked;
9084
9085   // Use dedicated unpack instructions for masks that match their pattern.
9086   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9087     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9088   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9089     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9090
9091   // Try to use byte rotation instructions.
9092   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9093           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9094     return Rotate;
9095
9096   if (SDValue BitBlend =
9097           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9098     return BitBlend;
9099
9100   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9101                                                             V2, Mask, DAG))
9102     return Unpack;
9103
9104   // If we can't directly blend but can use PSHUFB, that will be better as it
9105   // can both shuffle and set up the inefficient blend.
9106   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9107     bool V1InUse, V2InUse;
9108     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9109                                       V1InUse, V2InUse);
9110   }
9111
9112   // We can always bit-blend if we have to so the fallback strategy is to
9113   // decompose into single-input permutes and blends.
9114   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9115                                                       Mask, DAG);
9116 }
9117
9118 /// \brief Check whether a compaction lowering can be done by dropping even
9119 /// elements and compute how many times even elements must be dropped.
9120 ///
9121 /// This handles shuffles which take every Nth element where N is a power of
9122 /// two. Example shuffle masks:
9123 ///
9124 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9125 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9126 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9127 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9128 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9129 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9130 ///
9131 /// Any of these lanes can of course be undef.
9132 ///
9133 /// This routine only supports N <= 3.
9134 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9135 /// for larger N.
9136 ///
9137 /// \returns N above, or the number of times even elements must be dropped if
9138 /// there is such a number. Otherwise returns zero.
9139 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9140   // Figure out whether we're looping over two inputs or just one.
9141   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9142
9143   // The modulus for the shuffle vector entries is based on whether this is
9144   // a single input or not.
9145   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9146   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9147          "We should only be called with masks with a power-of-2 size!");
9148
9149   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9150
9151   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9152   // and 2^3 simultaneously. This is because we may have ambiguity with
9153   // partially undef inputs.
9154   bool ViableForN[3] = {true, true, true};
9155
9156   for (int i = 0, e = Mask.size(); i < e; ++i) {
9157     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9158     // want.
9159     if (Mask[i] == -1)
9160       continue;
9161
9162     bool IsAnyViable = false;
9163     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9164       if (ViableForN[j]) {
9165         uint64_t N = j + 1;
9166
9167         // The shuffle mask must be equal to (i * 2^N) % M.
9168         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9169           IsAnyViable = true;
9170         else
9171           ViableForN[j] = false;
9172       }
9173     // Early exit if we exhaust the possible powers of two.
9174     if (!IsAnyViable)
9175       break;
9176   }
9177
9178   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9179     if (ViableForN[j])
9180       return j + 1;
9181
9182   // Return 0 as there is no viable power of two.
9183   return 0;
9184 }
9185
9186 /// \brief Generic lowering of v16i8 shuffles.
9187 ///
9188 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9189 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9190 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9191 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9192 /// back together.
9193 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9194                                        const X86Subtarget *Subtarget,
9195                                        SelectionDAG &DAG) {
9196   SDLoc DL(Op);
9197   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9198   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9199   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9200   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9201   ArrayRef<int> Mask = SVOp->getMask();
9202   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9203
9204   // Try to use shift instructions.
9205   if (SDValue Shift =
9206           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9207     return Shift;
9208
9209   // Try to use byte rotation instructions.
9210   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9211           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9212     return Rotate;
9213
9214   // Try to use a zext lowering.
9215   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9216           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9217     return ZExt;
9218
9219   // See if we can use SSE4A Extraction / Insertion.
9220   if (Subtarget->hasSSE4A())
9221     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9222       return V;
9223
9224   int NumV2Elements =
9225       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9226
9227   // For single-input shuffles, there are some nicer lowering tricks we can use.
9228   if (NumV2Elements == 0) {
9229     // Check for being able to broadcast a single element.
9230     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9231                                                           Mask, Subtarget, DAG))
9232       return Broadcast;
9233
9234     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9235     // Notably, this handles splat and partial-splat shuffles more efficiently.
9236     // However, it only makes sense if the pre-duplication shuffle simplifies
9237     // things significantly. Currently, this means we need to be able to
9238     // express the pre-duplication shuffle as an i16 shuffle.
9239     //
9240     // FIXME: We should check for other patterns which can be widened into an
9241     // i16 shuffle as well.
9242     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9243       for (int i = 0; i < 16; i += 2)
9244         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9245           return false;
9246
9247       return true;
9248     };
9249     auto tryToWidenViaDuplication = [&]() -> SDValue {
9250       if (!canWidenViaDuplication(Mask))
9251         return SDValue();
9252       SmallVector<int, 4> LoInputs;
9253       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9254                    [](int M) { return M >= 0 && M < 8; });
9255       std::sort(LoInputs.begin(), LoInputs.end());
9256       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9257                      LoInputs.end());
9258       SmallVector<int, 4> HiInputs;
9259       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9260                    [](int M) { return M >= 8; });
9261       std::sort(HiInputs.begin(), HiInputs.end());
9262       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9263                      HiInputs.end());
9264
9265       bool TargetLo = LoInputs.size() >= HiInputs.size();
9266       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9267       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9268
9269       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9270       SmallDenseMap<int, int, 8> LaneMap;
9271       for (int I : InPlaceInputs) {
9272         PreDupI16Shuffle[I/2] = I/2;
9273         LaneMap[I] = I;
9274       }
9275       int j = TargetLo ? 0 : 4, je = j + 4;
9276       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9277         // Check if j is already a shuffle of this input. This happens when
9278         // there are two adjacent bytes after we move the low one.
9279         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9280           // If we haven't yet mapped the input, search for a slot into which
9281           // we can map it.
9282           while (j < je && PreDupI16Shuffle[j] != -1)
9283             ++j;
9284
9285           if (j == je)
9286             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9287             return SDValue();
9288
9289           // Map this input with the i16 shuffle.
9290           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9291         }
9292
9293         // Update the lane map based on the mapping we ended up with.
9294         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9295       }
9296       V1 = DAG.getBitcast(
9297           MVT::v16i8,
9298           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9299                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9300
9301       // Unpack the bytes to form the i16s that will be shuffled into place.
9302       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9303                        MVT::v16i8, V1, V1);
9304
9305       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9306       for (int i = 0; i < 16; ++i)
9307         if (Mask[i] != -1) {
9308           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9309           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9310           if (PostDupI16Shuffle[i / 2] == -1)
9311             PostDupI16Shuffle[i / 2] = MappedMask;
9312           else
9313             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9314                    "Conflicting entrties in the original shuffle!");
9315         }
9316       return DAG.getBitcast(
9317           MVT::v16i8,
9318           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9319                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9320     };
9321     if (SDValue V = tryToWidenViaDuplication())
9322       return V;
9323   }
9324
9325   if (SDValue Masked =
9326           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9327     return Masked;
9328
9329   // Use dedicated unpack instructions for masks that match their pattern.
9330   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9331                                          0, 16, 1, 17, 2, 18, 3, 19,
9332                                          // High half.
9333                                          4, 20, 5, 21, 6, 22, 7, 23}))
9334     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9335   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9336                                          8, 24, 9, 25, 10, 26, 11, 27,
9337                                          // High half.
9338                                          12, 28, 13, 29, 14, 30, 15, 31}))
9339     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9340
9341   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9342   // with PSHUFB. It is important to do this before we attempt to generate any
9343   // blends but after all of the single-input lowerings. If the single input
9344   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9345   // want to preserve that and we can DAG combine any longer sequences into
9346   // a PSHUFB in the end. But once we start blending from multiple inputs,
9347   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9348   // and there are *very* few patterns that would actually be faster than the
9349   // PSHUFB approach because of its ability to zero lanes.
9350   //
9351   // FIXME: The only exceptions to the above are blends which are exact
9352   // interleavings with direct instructions supporting them. We currently don't
9353   // handle those well here.
9354   if (Subtarget->hasSSSE3()) {
9355     bool V1InUse = false;
9356     bool V2InUse = false;
9357
9358     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9359                                                 DAG, V1InUse, V2InUse);
9360
9361     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9362     // do so. This avoids using them to handle blends-with-zero which is
9363     // important as a single pshufb is significantly faster for that.
9364     if (V1InUse && V2InUse) {
9365       if (Subtarget->hasSSE41())
9366         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9367                                                       Mask, Subtarget, DAG))
9368           return Blend;
9369
9370       // We can use an unpack to do the blending rather than an or in some
9371       // cases. Even though the or may be (very minorly) more efficient, we
9372       // preference this lowering because there are common cases where part of
9373       // the complexity of the shuffles goes away when we do the final blend as
9374       // an unpack.
9375       // FIXME: It might be worth trying to detect if the unpack-feeding
9376       // shuffles will both be pshufb, in which case we shouldn't bother with
9377       // this.
9378       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9379               DL, MVT::v16i8, V1, V2, Mask, DAG))
9380         return Unpack;
9381     }
9382
9383     return PSHUFB;
9384   }
9385
9386   // There are special ways we can lower some single-element blends.
9387   if (NumV2Elements == 1)
9388     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9389                                                          Mask, Subtarget, DAG))
9390       return V;
9391
9392   if (SDValue BitBlend =
9393           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9394     return BitBlend;
9395
9396   // Check whether a compaction lowering can be done. This handles shuffles
9397   // which take every Nth element for some even N. See the helper function for
9398   // details.
9399   //
9400   // We special case these as they can be particularly efficiently handled with
9401   // the PACKUSB instruction on x86 and they show up in common patterns of
9402   // rearranging bytes to truncate wide elements.
9403   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9404     // NumEvenDrops is the power of two stride of the elements. Another way of
9405     // thinking about it is that we need to drop the even elements this many
9406     // times to get the original input.
9407     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9408
9409     // First we need to zero all the dropped bytes.
9410     assert(NumEvenDrops <= 3 &&
9411            "No support for dropping even elements more than 3 times.");
9412     // We use the mask type to pick which bytes are preserved based on how many
9413     // elements are dropped.
9414     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9415     SDValue ByteClearMask = DAG.getBitcast(
9416         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9417     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9418     if (!IsSingleInput)
9419       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9420
9421     // Now pack things back together.
9422     V1 = DAG.getBitcast(MVT::v8i16, V1);
9423     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9424     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9425     for (int i = 1; i < NumEvenDrops; ++i) {
9426       Result = DAG.getBitcast(MVT::v8i16, Result);
9427       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9428     }
9429
9430     return Result;
9431   }
9432
9433   // Handle multi-input cases by blending single-input shuffles.
9434   if (NumV2Elements > 0)
9435     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9436                                                       Mask, DAG);
9437
9438   // The fallback path for single-input shuffles widens this into two v8i16
9439   // vectors with unpacks, shuffles those, and then pulls them back together
9440   // with a pack.
9441   SDValue V = V1;
9442
9443   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9444   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9445   for (int i = 0; i < 16; ++i)
9446     if (Mask[i] >= 0)
9447       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9448
9449   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9450
9451   SDValue VLoHalf, VHiHalf;
9452   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9453   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9454   // i16s.
9455   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9456                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9457       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9458                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9459     // Use a mask to drop the high bytes.
9460     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9461     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9462                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9463
9464     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9465     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9466
9467     // Squash the masks to point directly into VLoHalf.
9468     for (int &M : LoBlendMask)
9469       if (M >= 0)
9470         M /= 2;
9471     for (int &M : HiBlendMask)
9472       if (M >= 0)
9473         M /= 2;
9474   } else {
9475     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9476     // VHiHalf so that we can blend them as i16s.
9477     VLoHalf = DAG.getBitcast(
9478         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9479     VHiHalf = DAG.getBitcast(
9480         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9481   }
9482
9483   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9484   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9485
9486   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9487 }
9488
9489 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9490 ///
9491 /// This routine breaks down the specific type of 128-bit shuffle and
9492 /// dispatches to the lowering routines accordingly.
9493 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9494                                         MVT VT, const X86Subtarget *Subtarget,
9495                                         SelectionDAG &DAG) {
9496   switch (VT.SimpleTy) {
9497   case MVT::v2i64:
9498     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9499   case MVT::v2f64:
9500     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9501   case MVT::v4i32:
9502     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9503   case MVT::v4f32:
9504     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9505   case MVT::v8i16:
9506     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9507   case MVT::v16i8:
9508     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9509
9510   default:
9511     llvm_unreachable("Unimplemented!");
9512   }
9513 }
9514
9515 /// \brief Helper function to test whether a shuffle mask could be
9516 /// simplified by widening the elements being shuffled.
9517 ///
9518 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9519 /// leaves it in an unspecified state.
9520 ///
9521 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9522 /// shuffle masks. The latter have the special property of a '-2' representing
9523 /// a zero-ed lane of a vector.
9524 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9525                                     SmallVectorImpl<int> &WidenedMask) {
9526   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9527     // If both elements are undef, its trivial.
9528     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9529       WidenedMask.push_back(SM_SentinelUndef);
9530       continue;
9531     }
9532
9533     // Check for an undef mask and a mask value properly aligned to fit with
9534     // a pair of values. If we find such a case, use the non-undef mask's value.
9535     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9536       WidenedMask.push_back(Mask[i + 1] / 2);
9537       continue;
9538     }
9539     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9540       WidenedMask.push_back(Mask[i] / 2);
9541       continue;
9542     }
9543
9544     // When zeroing, we need to spread the zeroing across both lanes to widen.
9545     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9546       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9547           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9548         WidenedMask.push_back(SM_SentinelZero);
9549         continue;
9550       }
9551       return false;
9552     }
9553
9554     // Finally check if the two mask values are adjacent and aligned with
9555     // a pair.
9556     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9557       WidenedMask.push_back(Mask[i] / 2);
9558       continue;
9559     }
9560
9561     // Otherwise we can't safely widen the elements used in this shuffle.
9562     return false;
9563   }
9564   assert(WidenedMask.size() == Mask.size() / 2 &&
9565          "Incorrect size of mask after widening the elements!");
9566
9567   return true;
9568 }
9569
9570 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9571 ///
9572 /// This routine just extracts two subvectors, shuffles them independently, and
9573 /// then concatenates them back together. This should work effectively with all
9574 /// AVX vector shuffle types.
9575 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9576                                           SDValue V2, ArrayRef<int> Mask,
9577                                           SelectionDAG &DAG) {
9578   assert(VT.getSizeInBits() >= 256 &&
9579          "Only for 256-bit or wider vector shuffles!");
9580   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9581   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9582
9583   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9584   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9585
9586   int NumElements = VT.getVectorNumElements();
9587   int SplitNumElements = NumElements / 2;
9588   MVT ScalarVT = VT.getScalarType();
9589   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9590
9591   // Rather than splitting build-vectors, just build two narrower build
9592   // vectors. This helps shuffling with splats and zeros.
9593   auto SplitVector = [&](SDValue V) {
9594     while (V.getOpcode() == ISD::BITCAST)
9595       V = V->getOperand(0);
9596
9597     MVT OrigVT = V.getSimpleValueType();
9598     int OrigNumElements = OrigVT.getVectorNumElements();
9599     int OrigSplitNumElements = OrigNumElements / 2;
9600     MVT OrigScalarVT = OrigVT.getScalarType();
9601     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9602
9603     SDValue LoV, HiV;
9604
9605     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9606     if (!BV) {
9607       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9608                         DAG.getIntPtrConstant(0, DL));
9609       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9610                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9611     } else {
9612
9613       SmallVector<SDValue, 16> LoOps, HiOps;
9614       for (int i = 0; i < OrigSplitNumElements; ++i) {
9615         LoOps.push_back(BV->getOperand(i));
9616         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9617       }
9618       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9619       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9620     }
9621     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9622                           DAG.getBitcast(SplitVT, HiV));
9623   };
9624
9625   SDValue LoV1, HiV1, LoV2, HiV2;
9626   std::tie(LoV1, HiV1) = SplitVector(V1);
9627   std::tie(LoV2, HiV2) = SplitVector(V2);
9628
9629   // Now create two 4-way blends of these half-width vectors.
9630   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9631     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9632     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9633     for (int i = 0; i < SplitNumElements; ++i) {
9634       int M = HalfMask[i];
9635       if (M >= NumElements) {
9636         if (M >= NumElements + SplitNumElements)
9637           UseHiV2 = true;
9638         else
9639           UseLoV2 = true;
9640         V2BlendMask.push_back(M - NumElements);
9641         V1BlendMask.push_back(-1);
9642         BlendMask.push_back(SplitNumElements + i);
9643       } else if (M >= 0) {
9644         if (M >= SplitNumElements)
9645           UseHiV1 = true;
9646         else
9647           UseLoV1 = true;
9648         V2BlendMask.push_back(-1);
9649         V1BlendMask.push_back(M);
9650         BlendMask.push_back(i);
9651       } else {
9652         V2BlendMask.push_back(-1);
9653         V1BlendMask.push_back(-1);
9654         BlendMask.push_back(-1);
9655       }
9656     }
9657
9658     // Because the lowering happens after all combining takes place, we need to
9659     // manually combine these blend masks as much as possible so that we create
9660     // a minimal number of high-level vector shuffle nodes.
9661
9662     // First try just blending the halves of V1 or V2.
9663     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9664       return DAG.getUNDEF(SplitVT);
9665     if (!UseLoV2 && !UseHiV2)
9666       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9667     if (!UseLoV1 && !UseHiV1)
9668       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9669
9670     SDValue V1Blend, V2Blend;
9671     if (UseLoV1 && UseHiV1) {
9672       V1Blend =
9673         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9674     } else {
9675       // We only use half of V1 so map the usage down into the final blend mask.
9676       V1Blend = UseLoV1 ? LoV1 : HiV1;
9677       for (int i = 0; i < SplitNumElements; ++i)
9678         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9679           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9680     }
9681     if (UseLoV2 && UseHiV2) {
9682       V2Blend =
9683         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9684     } else {
9685       // We only use half of V2 so map the usage down into the final blend mask.
9686       V2Blend = UseLoV2 ? LoV2 : HiV2;
9687       for (int i = 0; i < SplitNumElements; ++i)
9688         if (BlendMask[i] >= SplitNumElements)
9689           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9690     }
9691     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9692   };
9693   SDValue Lo = HalfBlend(LoMask);
9694   SDValue Hi = HalfBlend(HiMask);
9695   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9696 }
9697
9698 /// \brief Either split a vector in halves or decompose the shuffles and the
9699 /// blend.
9700 ///
9701 /// This is provided as a good fallback for many lowerings of non-single-input
9702 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9703 /// between splitting the shuffle into 128-bit components and stitching those
9704 /// back together vs. extracting the single-input shuffles and blending those
9705 /// results.
9706 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9707                                                 SDValue V2, ArrayRef<int> Mask,
9708                                                 SelectionDAG &DAG) {
9709   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9710                                             "lower single-input shuffles as it "
9711                                             "could then recurse on itself.");
9712   int Size = Mask.size();
9713
9714   // If this can be modeled as a broadcast of two elements followed by a blend,
9715   // prefer that lowering. This is especially important because broadcasts can
9716   // often fold with memory operands.
9717   auto DoBothBroadcast = [&] {
9718     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9719     for (int M : Mask)
9720       if (M >= Size) {
9721         if (V2BroadcastIdx == -1)
9722           V2BroadcastIdx = M - Size;
9723         else if (M - Size != V2BroadcastIdx)
9724           return false;
9725       } else if (M >= 0) {
9726         if (V1BroadcastIdx == -1)
9727           V1BroadcastIdx = M;
9728         else if (M != V1BroadcastIdx)
9729           return false;
9730       }
9731     return true;
9732   };
9733   if (DoBothBroadcast())
9734     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9735                                                       DAG);
9736
9737   // If the inputs all stem from a single 128-bit lane of each input, then we
9738   // split them rather than blending because the split will decompose to
9739   // unusually few instructions.
9740   int LaneCount = VT.getSizeInBits() / 128;
9741   int LaneSize = Size / LaneCount;
9742   SmallBitVector LaneInputs[2];
9743   LaneInputs[0].resize(LaneCount, false);
9744   LaneInputs[1].resize(LaneCount, false);
9745   for (int i = 0; i < Size; ++i)
9746     if (Mask[i] >= 0)
9747       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9748   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9749     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9750
9751   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9752   // that the decomposed single-input shuffles don't end up here.
9753   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9754 }
9755
9756 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9757 /// a permutation and blend of those lanes.
9758 ///
9759 /// This essentially blends the out-of-lane inputs to each lane into the lane
9760 /// from a permuted copy of the vector. This lowering strategy results in four
9761 /// instructions in the worst case for a single-input cross lane shuffle which
9762 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9763 /// of. Special cases for each particular shuffle pattern should be handled
9764 /// prior to trying this lowering.
9765 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9766                                                        SDValue V1, SDValue V2,
9767                                                        ArrayRef<int> Mask,
9768                                                        SelectionDAG &DAG) {
9769   // FIXME: This should probably be generalized for 512-bit vectors as well.
9770   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9771   int LaneSize = Mask.size() / 2;
9772
9773   // If there are only inputs from one 128-bit lane, splitting will in fact be
9774   // less expensive. The flags track whether the given lane contains an element
9775   // that crosses to another lane.
9776   bool LaneCrossing[2] = {false, false};
9777   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9778     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9779       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9780   if (!LaneCrossing[0] || !LaneCrossing[1])
9781     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9782
9783   if (isSingleInputShuffleMask(Mask)) {
9784     SmallVector<int, 32> FlippedBlendMask;
9785     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9786       FlippedBlendMask.push_back(
9787           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9788                                   ? Mask[i]
9789                                   : Mask[i] % LaneSize +
9790                                         (i / LaneSize) * LaneSize + Size));
9791
9792     // Flip the vector, and blend the results which should now be in-lane. The
9793     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9794     // 5 for the high source. The value 3 selects the high half of source 2 and
9795     // the value 2 selects the low half of source 2. We only use source 2 to
9796     // allow folding it into a memory operand.
9797     unsigned PERMMask = 3 | 2 << 4;
9798     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9799                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9800     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9801   }
9802
9803   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9804   // will be handled by the above logic and a blend of the results, much like
9805   // other patterns in AVX.
9806   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9807 }
9808
9809 /// \brief Handle lowering 2-lane 128-bit shuffles.
9810 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9811                                         SDValue V2, ArrayRef<int> Mask,
9812                                         const X86Subtarget *Subtarget,
9813                                         SelectionDAG &DAG) {
9814   // TODO: If minimizing size and one of the inputs is a zero vector and the
9815   // the zero vector has only one use, we could use a VPERM2X128 to save the
9816   // instruction bytes needed to explicitly generate the zero vector.
9817
9818   // Blends are faster and handle all the non-lane-crossing cases.
9819   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9820                                                 Subtarget, DAG))
9821     return Blend;
9822
9823   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9824   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9825
9826   // If either input operand is a zero vector, use VPERM2X128 because its mask
9827   // allows us to replace the zero input with an implicit zero.
9828   if (!IsV1Zero && !IsV2Zero) {
9829     // Check for patterns which can be matched with a single insert of a 128-bit
9830     // subvector.
9831     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9832     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9833       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9834                                    VT.getVectorNumElements() / 2);
9835       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9836                                 DAG.getIntPtrConstant(0, DL));
9837       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9838                                 OnlyUsesV1 ? V1 : V2,
9839                                 DAG.getIntPtrConstant(0, DL));
9840       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9841     }
9842   }
9843
9844   // Otherwise form a 128-bit permutation. After accounting for undefs,
9845   // convert the 64-bit shuffle mask selection values into 128-bit
9846   // selection bits by dividing the indexes by 2 and shifting into positions
9847   // defined by a vperm2*128 instruction's immediate control byte.
9848
9849   // The immediate permute control byte looks like this:
9850   //    [1:0] - select 128 bits from sources for low half of destination
9851   //    [2]   - ignore
9852   //    [3]   - zero low half of destination
9853   //    [5:4] - select 128 bits from sources for high half of destination
9854   //    [6]   - ignore
9855   //    [7]   - zero high half of destination
9856
9857   int MaskLO = Mask[0];
9858   if (MaskLO == SM_SentinelUndef)
9859     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9860
9861   int MaskHI = Mask[2];
9862   if (MaskHI == SM_SentinelUndef)
9863     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9864
9865   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9866
9867   // If either input is a zero vector, replace it with an undef input.
9868   // Shuffle mask values <  4 are selecting elements of V1.
9869   // Shuffle mask values >= 4 are selecting elements of V2.
9870   // Adjust each half of the permute mask by clearing the half that was
9871   // selecting the zero vector and setting the zero mask bit.
9872   if (IsV1Zero) {
9873     V1 = DAG.getUNDEF(VT);
9874     if (MaskLO < 4)
9875       PermMask = (PermMask & 0xf0) | 0x08;
9876     if (MaskHI < 4)
9877       PermMask = (PermMask & 0x0f) | 0x80;
9878   }
9879   if (IsV2Zero) {
9880     V2 = DAG.getUNDEF(VT);
9881     if (MaskLO >= 4)
9882       PermMask = (PermMask & 0xf0) | 0x08;
9883     if (MaskHI >= 4)
9884       PermMask = (PermMask & 0x0f) | 0x80;
9885   }
9886
9887   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9888                      DAG.getConstant(PermMask, DL, MVT::i8));
9889 }
9890
9891 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9892 /// shuffling each lane.
9893 ///
9894 /// This will only succeed when the result of fixing the 128-bit lanes results
9895 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9896 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9897 /// the lane crosses early and then use simpler shuffles within each lane.
9898 ///
9899 /// FIXME: It might be worthwhile at some point to support this without
9900 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9901 /// in x86 only floating point has interesting non-repeating shuffles, and even
9902 /// those are still *marginally* more expensive.
9903 static SDValue lowerVectorShuffleByMerging128BitLanes(
9904     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9905     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9906   assert(!isSingleInputShuffleMask(Mask) &&
9907          "This is only useful with multiple inputs.");
9908
9909   int Size = Mask.size();
9910   int LaneSize = 128 / VT.getScalarSizeInBits();
9911   int NumLanes = Size / LaneSize;
9912   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9913
9914   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9915   // check whether the in-128-bit lane shuffles share a repeating pattern.
9916   SmallVector<int, 4> Lanes;
9917   Lanes.resize(NumLanes, -1);
9918   SmallVector<int, 4> InLaneMask;
9919   InLaneMask.resize(LaneSize, -1);
9920   for (int i = 0; i < Size; ++i) {
9921     if (Mask[i] < 0)
9922       continue;
9923
9924     int j = i / LaneSize;
9925
9926     if (Lanes[j] < 0) {
9927       // First entry we've seen for this lane.
9928       Lanes[j] = Mask[i] / LaneSize;
9929     } else if (Lanes[j] != Mask[i] / LaneSize) {
9930       // This doesn't match the lane selected previously!
9931       return SDValue();
9932     }
9933
9934     // Check that within each lane we have a consistent shuffle mask.
9935     int k = i % LaneSize;
9936     if (InLaneMask[k] < 0) {
9937       InLaneMask[k] = Mask[i] % LaneSize;
9938     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9939       // This doesn't fit a repeating in-lane mask.
9940       return SDValue();
9941     }
9942   }
9943
9944   // First shuffle the lanes into place.
9945   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9946                                 VT.getSizeInBits() / 64);
9947   SmallVector<int, 8> LaneMask;
9948   LaneMask.resize(NumLanes * 2, -1);
9949   for (int i = 0; i < NumLanes; ++i)
9950     if (Lanes[i] >= 0) {
9951       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9952       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9953     }
9954
9955   V1 = DAG.getBitcast(LaneVT, V1);
9956   V2 = DAG.getBitcast(LaneVT, V2);
9957   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9958
9959   // Cast it back to the type we actually want.
9960   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9961
9962   // Now do a simple shuffle that isn't lane crossing.
9963   SmallVector<int, 8> NewMask;
9964   NewMask.resize(Size, -1);
9965   for (int i = 0; i < Size; ++i)
9966     if (Mask[i] >= 0)
9967       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9968   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9969          "Must not introduce lane crosses at this point!");
9970
9971   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9972 }
9973
9974 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9975 /// given mask.
9976 ///
9977 /// This returns true if the elements from a particular input are already in the
9978 /// slot required by the given mask and require no permutation.
9979 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9980   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9981   int Size = Mask.size();
9982   for (int i = 0; i < Size; ++i)
9983     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9984       return false;
9985
9986   return true;
9987 }
9988
9989 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9990                                             ArrayRef<int> Mask, SDValue V1,
9991                                             SDValue V2, SelectionDAG &DAG) {
9992
9993   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9994   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9995   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9996   int NumElts = VT.getVectorNumElements();
9997   bool ShufpdMask = true;
9998   bool CommutableMask = true;
9999   unsigned Immediate = 0;
10000   for (int i = 0; i < NumElts; ++i) {
10001     if (Mask[i] < 0)
10002       continue;
10003     int Val = (i & 6) + NumElts * (i & 1);
10004     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10005     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10006       ShufpdMask = false;
10007     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10008       CommutableMask = false;
10009     Immediate |= (Mask[i] % 2) << i;
10010   }
10011   if (ShufpdMask)
10012     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10013                        DAG.getConstant(Immediate, DL, MVT::i8));
10014   if (CommutableMask)
10015     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10016                        DAG.getConstant(Immediate, DL, MVT::i8));
10017   return SDValue();
10018 }
10019
10020 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10021 ///
10022 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10023 /// isn't available.
10024 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10025                                        const X86Subtarget *Subtarget,
10026                                        SelectionDAG &DAG) {
10027   SDLoc DL(Op);
10028   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10029   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10030   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10031   ArrayRef<int> Mask = SVOp->getMask();
10032   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10033
10034   SmallVector<int, 4> WidenedMask;
10035   if (canWidenShuffleElements(Mask, WidenedMask))
10036     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10037                                     DAG);
10038
10039   if (isSingleInputShuffleMask(Mask)) {
10040     // Check for being able to broadcast a single element.
10041     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10042                                                           Mask, Subtarget, DAG))
10043       return Broadcast;
10044
10045     // Use low duplicate instructions for masks that match their pattern.
10046     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10047       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10048
10049     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10050       // Non-half-crossing single input shuffles can be lowerid with an
10051       // interleaved permutation.
10052       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10053                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10054       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10055                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10056     }
10057
10058     // With AVX2 we have direct support for this permutation.
10059     if (Subtarget->hasAVX2())
10060       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10061                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10062
10063     // Otherwise, fall back.
10064     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10065                                                    DAG);
10066   }
10067
10068   // X86 has dedicated unpack instructions that can handle specific blend
10069   // operations: UNPCKH and UNPCKL.
10070   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10071     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10072   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10073     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10074   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10075     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10076   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10077     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10078
10079   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10080                                                 Subtarget, DAG))
10081     return Blend;
10082
10083   // Check if the blend happens to exactly fit that of SHUFPD.
10084   if (SDValue Op =
10085       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10086     return Op;
10087
10088   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10089   // shuffle. However, if we have AVX2 and either inputs are already in place,
10090   // we will be able to shuffle even across lanes the other input in a single
10091   // instruction so skip this pattern.
10092   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10093                                  isShuffleMaskInputInPlace(1, Mask))))
10094     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10095             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10096       return Result;
10097
10098   // If we have AVX2 then we always want to lower with a blend because an v4 we
10099   // can fully permute the elements.
10100   if (Subtarget->hasAVX2())
10101     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10102                                                       Mask, DAG);
10103
10104   // Otherwise fall back on generic lowering.
10105   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10106 }
10107
10108 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10109 ///
10110 /// This routine is only called when we have AVX2 and thus a reasonable
10111 /// instruction set for v4i64 shuffling..
10112 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10113                                        const X86Subtarget *Subtarget,
10114                                        SelectionDAG &DAG) {
10115   SDLoc DL(Op);
10116   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10117   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10118   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10119   ArrayRef<int> Mask = SVOp->getMask();
10120   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10121   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10122
10123   SmallVector<int, 4> WidenedMask;
10124   if (canWidenShuffleElements(Mask, WidenedMask))
10125     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10126                                     DAG);
10127
10128   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10129                                                 Subtarget, DAG))
10130     return Blend;
10131
10132   // Check for being able to broadcast a single element.
10133   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10134                                                         Mask, Subtarget, DAG))
10135     return Broadcast;
10136
10137   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10138   // use lower latency instructions that will operate on both 128-bit lanes.
10139   SmallVector<int, 2> RepeatedMask;
10140   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10141     if (isSingleInputShuffleMask(Mask)) {
10142       int PSHUFDMask[] = {-1, -1, -1, -1};
10143       for (int i = 0; i < 2; ++i)
10144         if (RepeatedMask[i] >= 0) {
10145           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10146           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10147         }
10148       return DAG.getBitcast(
10149           MVT::v4i64,
10150           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10151                       DAG.getBitcast(MVT::v8i32, V1),
10152                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10153     }
10154   }
10155
10156   // AVX2 provides a direct instruction for permuting a single input across
10157   // lanes.
10158   if (isSingleInputShuffleMask(Mask))
10159     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10160                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10161
10162   // Try to use shift instructions.
10163   if (SDValue Shift =
10164           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10165     return Shift;
10166
10167   // Use dedicated unpack instructions for masks that match their pattern.
10168   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10169     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10170   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10171     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10172   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10173     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10174   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10175     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10176
10177   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10178   // shuffle. However, if we have AVX2 and either inputs are already in place,
10179   // we will be able to shuffle even across lanes the other input in a single
10180   // instruction so skip this pattern.
10181   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10182                                  isShuffleMaskInputInPlace(1, Mask))))
10183     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10184             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10185       return Result;
10186
10187   // Otherwise fall back on generic blend lowering.
10188   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10189                                                     Mask, DAG);
10190 }
10191
10192 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10193 ///
10194 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10195 /// isn't available.
10196 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10197                                        const X86Subtarget *Subtarget,
10198                                        SelectionDAG &DAG) {
10199   SDLoc DL(Op);
10200   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10201   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10202   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10203   ArrayRef<int> Mask = SVOp->getMask();
10204   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10205
10206   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10207                                                 Subtarget, DAG))
10208     return Blend;
10209
10210   // Check for being able to broadcast a single element.
10211   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10212                                                         Mask, Subtarget, DAG))
10213     return Broadcast;
10214
10215   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10216   // options to efficiently lower the shuffle.
10217   SmallVector<int, 4> RepeatedMask;
10218   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10219     assert(RepeatedMask.size() == 4 &&
10220            "Repeated masks must be half the mask width!");
10221
10222     // Use even/odd duplicate instructions for masks that match their pattern.
10223     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10224       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10225     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10226       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10227
10228     if (isSingleInputShuffleMask(Mask))
10229       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10230                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10231
10232     // Use dedicated unpack instructions for masks that match their pattern.
10233     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10234       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10235     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10236       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10237     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10238       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10239     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10240       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10241
10242     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10243     // have already handled any direct blends. We also need to squash the
10244     // repeated mask into a simulated v4f32 mask.
10245     for (int i = 0; i < 4; ++i)
10246       if (RepeatedMask[i] >= 8)
10247         RepeatedMask[i] -= 4;
10248     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10249   }
10250
10251   // If we have a single input shuffle with different shuffle patterns in the
10252   // two 128-bit lanes use the variable mask to VPERMILPS.
10253   if (isSingleInputShuffleMask(Mask)) {
10254     SDValue VPermMask[8];
10255     for (int i = 0; i < 8; ++i)
10256       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10257                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10258     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10259       return DAG.getNode(
10260           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10261           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10262
10263     if (Subtarget->hasAVX2())
10264       return DAG.getNode(
10265           X86ISD::VPERMV, DL, MVT::v8f32,
10266           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10267                                                  MVT::v8i32, VPermMask)),
10268           V1);
10269
10270     // Otherwise, fall back.
10271     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10272                                                    DAG);
10273   }
10274
10275   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10276   // shuffle.
10277   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10278           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10279     return Result;
10280
10281   // If we have AVX2 then we always want to lower with a blend because at v8 we
10282   // can fully permute the elements.
10283   if (Subtarget->hasAVX2())
10284     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10285                                                       Mask, DAG);
10286
10287   // Otherwise fall back on generic lowering.
10288   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10289 }
10290
10291 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10292 ///
10293 /// This routine is only called when we have AVX2 and thus a reasonable
10294 /// instruction set for v8i32 shuffling..
10295 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10296                                        const X86Subtarget *Subtarget,
10297                                        SelectionDAG &DAG) {
10298   SDLoc DL(Op);
10299   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10300   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10302   ArrayRef<int> Mask = SVOp->getMask();
10303   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10304   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10305
10306   // Whenever we can lower this as a zext, that instruction is strictly faster
10307   // than any alternative. It also allows us to fold memory operands into the
10308   // shuffle in many cases.
10309   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10310                                                          Mask, Subtarget, DAG))
10311     return ZExt;
10312
10313   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10314                                                 Subtarget, DAG))
10315     return Blend;
10316
10317   // Check for being able to broadcast a single element.
10318   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10319                                                         Mask, Subtarget, DAG))
10320     return Broadcast;
10321
10322   // If the shuffle mask is repeated in each 128-bit lane we can use more
10323   // efficient instructions that mirror the shuffles across the two 128-bit
10324   // lanes.
10325   SmallVector<int, 4> RepeatedMask;
10326   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10327     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10328     if (isSingleInputShuffleMask(Mask))
10329       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10330                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10331
10332     // Use dedicated unpack instructions for masks that match their pattern.
10333     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10334       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10335     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10336       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10337     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10338       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10339     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10340       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10341   }
10342
10343   // Try to use shift instructions.
10344   if (SDValue Shift =
10345           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10346     return Shift;
10347
10348   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10349           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10350     return Rotate;
10351
10352   // If the shuffle patterns aren't repeated but it is a single input, directly
10353   // generate a cross-lane VPERMD instruction.
10354   if (isSingleInputShuffleMask(Mask)) {
10355     SDValue VPermMask[8];
10356     for (int i = 0; i < 8; ++i)
10357       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10358                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10359     return DAG.getNode(
10360         X86ISD::VPERMV, DL, MVT::v8i32,
10361         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10362   }
10363
10364   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10365   // shuffle.
10366   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10367           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10368     return Result;
10369
10370   // Otherwise fall back on generic blend lowering.
10371   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10372                                                     Mask, DAG);
10373 }
10374
10375 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10376 ///
10377 /// This routine is only called when we have AVX2 and thus a reasonable
10378 /// instruction set for v16i16 shuffling..
10379 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10380                                         const X86Subtarget *Subtarget,
10381                                         SelectionDAG &DAG) {
10382   SDLoc DL(Op);
10383   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10384   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10385   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10386   ArrayRef<int> Mask = SVOp->getMask();
10387   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10388   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10389
10390   // Whenever we can lower this as a zext, that instruction is strictly faster
10391   // than any alternative. It also allows us to fold memory operands into the
10392   // shuffle in many cases.
10393   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10394                                                          Mask, Subtarget, DAG))
10395     return ZExt;
10396
10397   // Check for being able to broadcast a single element.
10398   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10399                                                         Mask, Subtarget, DAG))
10400     return Broadcast;
10401
10402   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10403                                                 Subtarget, DAG))
10404     return Blend;
10405
10406   // Use dedicated unpack instructions for masks that match their pattern.
10407   if (isShuffleEquivalent(V1, V2, Mask,
10408                           {// First 128-bit lane:
10409                            0, 16, 1, 17, 2, 18, 3, 19,
10410                            // Second 128-bit lane:
10411                            8, 24, 9, 25, 10, 26, 11, 27}))
10412     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10413   if (isShuffleEquivalent(V1, V2, Mask,
10414                           {// First 128-bit lane:
10415                            4, 20, 5, 21, 6, 22, 7, 23,
10416                            // Second 128-bit lane:
10417                            12, 28, 13, 29, 14, 30, 15, 31}))
10418     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10419
10420   // Try to use shift instructions.
10421   if (SDValue Shift =
10422           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10423     return Shift;
10424
10425   // Try to use byte rotation instructions.
10426   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10427           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10428     return Rotate;
10429
10430   if (isSingleInputShuffleMask(Mask)) {
10431     // There are no generalized cross-lane shuffle operations available on i16
10432     // element types.
10433     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10434       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10435                                                      Mask, DAG);
10436
10437     SmallVector<int, 8> RepeatedMask;
10438     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10439       // As this is a single-input shuffle, the repeated mask should be
10440       // a strictly valid v8i16 mask that we can pass through to the v8i16
10441       // lowering to handle even the v16 case.
10442       return lowerV8I16GeneralSingleInputVectorShuffle(
10443           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10444     }
10445
10446     SDValue PSHUFBMask[32];
10447     for (int i = 0; i < 16; ++i) {
10448       if (Mask[i] == -1) {
10449         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10450         continue;
10451       }
10452
10453       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10454       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10455       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10456       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10457     }
10458     return DAG.getBitcast(MVT::v16i16,
10459                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10460                                       DAG.getBitcast(MVT::v32i8, V1),
10461                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10462                                                   MVT::v32i8, PSHUFBMask)));
10463   }
10464
10465   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10466   // shuffle.
10467   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10468           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10469     return Result;
10470
10471   // Otherwise fall back on generic lowering.
10472   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10473 }
10474
10475 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10476 ///
10477 /// This routine is only called when we have AVX2 and thus a reasonable
10478 /// instruction set for v32i8 shuffling..
10479 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10480                                        const X86Subtarget *Subtarget,
10481                                        SelectionDAG &DAG) {
10482   SDLoc DL(Op);
10483   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10484   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10485   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10486   ArrayRef<int> Mask = SVOp->getMask();
10487   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10488   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10489
10490   // Whenever we can lower this as a zext, that instruction is strictly faster
10491   // than any alternative. It also allows us to fold memory operands into the
10492   // shuffle in many cases.
10493   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10494                                                          Mask, Subtarget, DAG))
10495     return ZExt;
10496
10497   // Check for being able to broadcast a single element.
10498   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10499                                                         Mask, Subtarget, DAG))
10500     return Broadcast;
10501
10502   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10503                                                 Subtarget, DAG))
10504     return Blend;
10505
10506   // Use dedicated unpack instructions for masks that match their pattern.
10507   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10508   // 256-bit lanes.
10509   if (isShuffleEquivalent(
10510           V1, V2, Mask,
10511           {// First 128-bit lane:
10512            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10513            // Second 128-bit lane:
10514            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10515     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10516   if (isShuffleEquivalent(
10517           V1, V2, Mask,
10518           {// First 128-bit lane:
10519            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10520            // Second 128-bit lane:
10521            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10522     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10523
10524   // Try to use shift instructions.
10525   if (SDValue Shift =
10526           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10527     return Shift;
10528
10529   // Try to use byte rotation instructions.
10530   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10531           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10532     return Rotate;
10533
10534   if (isSingleInputShuffleMask(Mask)) {
10535     // There are no generalized cross-lane shuffle operations available on i8
10536     // element types.
10537     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10538       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10539                                                      Mask, DAG);
10540
10541     SDValue PSHUFBMask[32];
10542     for (int i = 0; i < 32; ++i)
10543       PSHUFBMask[i] =
10544           Mask[i] < 0
10545               ? DAG.getUNDEF(MVT::i8)
10546               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10547                                 MVT::i8);
10548
10549     return DAG.getNode(
10550         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10551         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10552   }
10553
10554   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10555   // shuffle.
10556   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10557           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10558     return Result;
10559
10560   // Otherwise fall back on generic lowering.
10561   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10562 }
10563
10564 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10565 ///
10566 /// This routine either breaks down the specific type of a 256-bit x86 vector
10567 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10568 /// together based on the available instructions.
10569 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10570                                         MVT VT, const X86Subtarget *Subtarget,
10571                                         SelectionDAG &DAG) {
10572   SDLoc DL(Op);
10573   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10574   ArrayRef<int> Mask = SVOp->getMask();
10575
10576   // If we have a single input to the zero element, insert that into V1 if we
10577   // can do so cheaply.
10578   int NumElts = VT.getVectorNumElements();
10579   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10580     return M >= NumElts;
10581   });
10582
10583   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10584     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10585                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10586       return Insertion;
10587
10588   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10589   // check for those subtargets here and avoid much of the subtarget querying in
10590   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10591   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10592   // floating point types there eventually, just immediately cast everything to
10593   // a float and operate entirely in that domain.
10594   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10595     int ElementBits = VT.getScalarSizeInBits();
10596     if (ElementBits < 32)
10597       // No floating point type available, decompose into 128-bit vectors.
10598       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10599
10600     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10601                                 VT.getVectorNumElements());
10602     V1 = DAG.getBitcast(FpVT, V1);
10603     V2 = DAG.getBitcast(FpVT, V2);
10604     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10605   }
10606
10607   switch (VT.SimpleTy) {
10608   case MVT::v4f64:
10609     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10610   case MVT::v4i64:
10611     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10612   case MVT::v8f32:
10613     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10614   case MVT::v8i32:
10615     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10616   case MVT::v16i16:
10617     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10618   case MVT::v32i8:
10619     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10620
10621   default:
10622     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10623   }
10624 }
10625
10626 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10627                                            ArrayRef<int> Mask, SDValue V1,
10628                                            SDValue V2, SelectionDAG &DAG) {
10629
10630   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10631
10632   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10633   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10634
10635   SmallVector<SDValue, 32>  VPermMask;
10636   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10637     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10638                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10639   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10640                                  VPermMask);
10641   if (isSingleInputShuffleMask(Mask))
10642     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10643
10644   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10645 }
10646
10647 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10648 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10649                                        const X86Subtarget *Subtarget,
10650                                        SelectionDAG &DAG) {
10651   SDLoc DL(Op);
10652   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10653   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10654   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10655   ArrayRef<int> Mask = SVOp->getMask();
10656   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10657
10658   if (SDValue Unpck =
10659           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10660     return Unpck;
10661
10662   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10663 }
10664
10665 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10666 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10667                                        const X86Subtarget *Subtarget,
10668                                        SelectionDAG &DAG) {
10669   SDLoc DL(Op);
10670   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10671   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10672   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10673   ArrayRef<int> Mask = SVOp->getMask();
10674   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10675
10676   if (SDValue Unpck =
10677           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10678     return Unpck;
10679
10680   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10681 }
10682
10683 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10684 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10685                                        const X86Subtarget *Subtarget,
10686                                        SelectionDAG &DAG) {
10687   SDLoc DL(Op);
10688   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10689   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10691   ArrayRef<int> Mask = SVOp->getMask();
10692   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10693
10694   if (SDValue Unpck =
10695           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10696     return Unpck;
10697
10698   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10699 }
10700
10701 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10702 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10703                                        const X86Subtarget *Subtarget,
10704                                        SelectionDAG &DAG) {
10705   SDLoc DL(Op);
10706   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10707   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10709   ArrayRef<int> Mask = SVOp->getMask();
10710   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10711
10712   if (SDValue Unpck =
10713           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10714     return Unpck;
10715
10716   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10717 }
10718
10719 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10720 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10721                                         const X86Subtarget *Subtarget,
10722                                         SelectionDAG &DAG) {
10723   SDLoc DL(Op);
10724   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10725   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10726   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10727   ArrayRef<int> Mask = SVOp->getMask();
10728   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10729   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10730
10731   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10732 }
10733
10734 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10735 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10736                                        const X86Subtarget *Subtarget,
10737                                        SelectionDAG &DAG) {
10738   SDLoc DL(Op);
10739   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10740   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10742   ArrayRef<int> Mask = SVOp->getMask();
10743   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10744   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10745
10746   // FIXME: Implement direct support for this type!
10747   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10748 }
10749
10750 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10751 ///
10752 /// This routine either breaks down the specific type of a 512-bit x86 vector
10753 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10754 /// together based on the available instructions.
10755 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10756                                         MVT VT, const X86Subtarget *Subtarget,
10757                                         SelectionDAG &DAG) {
10758   SDLoc DL(Op);
10759   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10760   ArrayRef<int> Mask = SVOp->getMask();
10761   assert(Subtarget->hasAVX512() &&
10762          "Cannot lower 512-bit vectors w/ basic ISA!");
10763
10764   // Check for being able to broadcast a single element.
10765   if (SDValue Broadcast =
10766           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10767     return Broadcast;
10768
10769   // Dispatch to each element type for lowering. If we don't have supprot for
10770   // specific element type shuffles at 512 bits, immediately split them and
10771   // lower them. Each lowering routine of a given type is allowed to assume that
10772   // the requisite ISA extensions for that element type are available.
10773   switch (VT.SimpleTy) {
10774   case MVT::v8f64:
10775     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10776   case MVT::v16f32:
10777     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10778   case MVT::v8i64:
10779     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10780   case MVT::v16i32:
10781     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10782   case MVT::v32i16:
10783     if (Subtarget->hasBWI())
10784       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10785     break;
10786   case MVT::v64i8:
10787     if (Subtarget->hasBWI())
10788       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10789     break;
10790
10791   default:
10792     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10793   }
10794
10795   // Otherwise fall back on splitting.
10796   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10797 }
10798
10799 // Lower vXi1 vector shuffles.
10800 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10801 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10802 // vector, shuffle and then truncate it back.
10803 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10804                                       MVT VT, const X86Subtarget *Subtarget,
10805                                       SelectionDAG &DAG) {
10806   SDLoc DL(Op);
10807   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10808   ArrayRef<int> Mask = SVOp->getMask();
10809   assert(Subtarget->hasAVX512() &&
10810          "Cannot lower 512-bit vectors w/o basic ISA!");
10811   EVT ExtVT;
10812   switch (VT.SimpleTy) {
10813   default:
10814     assert(false && "Expected a vector of i1 elements");
10815     break;
10816   case MVT::v2i1:
10817     ExtVT = MVT::v2i64;
10818     break;
10819   case MVT::v4i1:
10820     ExtVT = MVT::v4i32;
10821     break;
10822   case MVT::v8i1:
10823     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10824     break;
10825   case MVT::v16i1:
10826     ExtVT = MVT::v16i32;
10827     break;
10828   case MVT::v32i1:
10829     ExtVT = MVT::v32i16;
10830     break;
10831   case MVT::v64i1:
10832     ExtVT = MVT::v64i8;
10833     break;
10834   }
10835
10836   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10837     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10838   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10839     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10840   else
10841     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10842
10843   if (V2.isUndef())
10844     V2 = DAG.getUNDEF(ExtVT);
10845   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10846     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10847   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10848     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10849   else
10850     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10851   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10852                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10853 }
10854 /// \brief Top-level lowering for x86 vector shuffles.
10855 ///
10856 /// This handles decomposition, canonicalization, and lowering of all x86
10857 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10858 /// above in helper routines. The canonicalization attempts to widen shuffles
10859 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10860 /// s.t. only one of the two inputs needs to be tested, etc.
10861 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10862                                   SelectionDAG &DAG) {
10863   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10864   ArrayRef<int> Mask = SVOp->getMask();
10865   SDValue V1 = Op.getOperand(0);
10866   SDValue V2 = Op.getOperand(1);
10867   MVT VT = Op.getSimpleValueType();
10868   int NumElements = VT.getVectorNumElements();
10869   SDLoc dl(Op);
10870   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10871
10872   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10873          "Can't lower MMX shuffles");
10874
10875   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10876   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10877   if (V1IsUndef && V2IsUndef)
10878     return DAG.getUNDEF(VT);
10879
10880   // When we create a shuffle node we put the UNDEF node to second operand,
10881   // but in some cases the first operand may be transformed to UNDEF.
10882   // In this case we should just commute the node.
10883   if (V1IsUndef)
10884     return DAG.getCommutedVectorShuffle(*SVOp);
10885
10886   // Check for non-undef masks pointing at an undef vector and make the masks
10887   // undef as well. This makes it easier to match the shuffle based solely on
10888   // the mask.
10889   if (V2IsUndef)
10890     for (int M : Mask)
10891       if (M >= NumElements) {
10892         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10893         for (int &M : NewMask)
10894           if (M >= NumElements)
10895             M = -1;
10896         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10897       }
10898
10899   // We actually see shuffles that are entirely re-arrangements of a set of
10900   // zero inputs. This mostly happens while decomposing complex shuffles into
10901   // simple ones. Directly lower these as a buildvector of zeros.
10902   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10903   if (Zeroable.all())
10904     return getZeroVector(VT, Subtarget, DAG, dl);
10905
10906   // Try to collapse shuffles into using a vector type with fewer elements but
10907   // wider element types. We cap this to not form integers or floating point
10908   // elements wider than 64 bits, but it might be interesting to form i128
10909   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10910   SmallVector<int, 16> WidenedMask;
10911   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10912       canWidenShuffleElements(Mask, WidenedMask)) {
10913     MVT NewEltVT = VT.isFloatingPoint()
10914                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10915                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10916     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10917     // Make sure that the new vector type is legal. For example, v2f64 isn't
10918     // legal on SSE1.
10919     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10920       V1 = DAG.getBitcast(NewVT, V1);
10921       V2 = DAG.getBitcast(NewVT, V2);
10922       return DAG.getBitcast(
10923           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10924     }
10925   }
10926
10927   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10928   for (int M : SVOp->getMask())
10929     if (M < 0)
10930       ++NumUndefElements;
10931     else if (M < NumElements)
10932       ++NumV1Elements;
10933     else
10934       ++NumV2Elements;
10935
10936   // Commute the shuffle as needed such that more elements come from V1 than
10937   // V2. This allows us to match the shuffle pattern strictly on how many
10938   // elements come from V1 without handling the symmetric cases.
10939   if (NumV2Elements > NumV1Elements)
10940     return DAG.getCommutedVectorShuffle(*SVOp);
10941
10942   // When the number of V1 and V2 elements are the same, try to minimize the
10943   // number of uses of V2 in the low half of the vector. When that is tied,
10944   // ensure that the sum of indices for V1 is equal to or lower than the sum
10945   // indices for V2. When those are equal, try to ensure that the number of odd
10946   // indices for V1 is lower than the number of odd indices for V2.
10947   if (NumV1Elements == NumV2Elements) {
10948     int LowV1Elements = 0, LowV2Elements = 0;
10949     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10950       if (M >= NumElements)
10951         ++LowV2Elements;
10952       else if (M >= 0)
10953         ++LowV1Elements;
10954     if (LowV2Elements > LowV1Elements) {
10955       return DAG.getCommutedVectorShuffle(*SVOp);
10956     } else if (LowV2Elements == LowV1Elements) {
10957       int SumV1Indices = 0, SumV2Indices = 0;
10958       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10959         if (SVOp->getMask()[i] >= NumElements)
10960           SumV2Indices += i;
10961         else if (SVOp->getMask()[i] >= 0)
10962           SumV1Indices += i;
10963       if (SumV2Indices < SumV1Indices) {
10964         return DAG.getCommutedVectorShuffle(*SVOp);
10965       } else if (SumV2Indices == SumV1Indices) {
10966         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10967         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10968           if (SVOp->getMask()[i] >= NumElements)
10969             NumV2OddIndices += i % 2;
10970           else if (SVOp->getMask()[i] >= 0)
10971             NumV1OddIndices += i % 2;
10972         if (NumV2OddIndices < NumV1OddIndices)
10973           return DAG.getCommutedVectorShuffle(*SVOp);
10974       }
10975     }
10976   }
10977
10978   // For each vector width, delegate to a specialized lowering routine.
10979   if (VT.getSizeInBits() == 128)
10980     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10981
10982   if (VT.getSizeInBits() == 256)
10983     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10984
10985   if (VT.getSizeInBits() == 512)
10986     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10987
10988   if (Is1BitVector)
10989     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10990   llvm_unreachable("Unimplemented!");
10991 }
10992
10993 // This function assumes its argument is a BUILD_VECTOR of constants or
10994 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10995 // true.
10996 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10997                                     unsigned &MaskValue) {
10998   MaskValue = 0;
10999   unsigned NumElems = BuildVector->getNumOperands();
11000   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11001   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11002   unsigned NumElemsInLane = NumElems / NumLanes;
11003
11004   // Blend for v16i16 should be symmetric for the both lanes.
11005   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11006     SDValue EltCond = BuildVector->getOperand(i);
11007     SDValue SndLaneEltCond =
11008         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11009
11010     int Lane1Cond = -1, Lane2Cond = -1;
11011     if (isa<ConstantSDNode>(EltCond))
11012       Lane1Cond = !isZero(EltCond);
11013     if (isa<ConstantSDNode>(SndLaneEltCond))
11014       Lane2Cond = !isZero(SndLaneEltCond);
11015
11016     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11017       // Lane1Cond != 0, means we want the first argument.
11018       // Lane1Cond == 0, means we want the second argument.
11019       // The encoding of this argument is 0 for the first argument, 1
11020       // for the second. Therefore, invert the condition.
11021       MaskValue |= !Lane1Cond << i;
11022     else if (Lane1Cond < 0)
11023       MaskValue |= !Lane2Cond << i;
11024     else
11025       return false;
11026   }
11027   return true;
11028 }
11029
11030 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11031 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11032                                            const X86Subtarget *Subtarget,
11033                                            SelectionDAG &DAG) {
11034   SDValue Cond = Op.getOperand(0);
11035   SDValue LHS = Op.getOperand(1);
11036   SDValue RHS = Op.getOperand(2);
11037   SDLoc dl(Op);
11038   MVT VT = Op.getSimpleValueType();
11039
11040   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11041     return SDValue();
11042   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11043
11044   // Only non-legal VSELECTs reach this lowering, convert those into generic
11045   // shuffles and re-use the shuffle lowering path for blends.
11046   SmallVector<int, 32> Mask;
11047   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11048     SDValue CondElt = CondBV->getOperand(i);
11049     Mask.push_back(
11050         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11051   }
11052   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11053 }
11054
11055 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11056   // A vselect where all conditions and data are constants can be optimized into
11057   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11058   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11059       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11060       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11061     return SDValue();
11062
11063   // Try to lower this to a blend-style vector shuffle. This can handle all
11064   // constant condition cases.
11065   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11066     return BlendOp;
11067
11068   // Variable blends are only legal from SSE4.1 onward.
11069   if (!Subtarget->hasSSE41())
11070     return SDValue();
11071
11072   // Only some types will be legal on some subtargets. If we can emit a legal
11073   // VSELECT-matching blend, return Op, and but if we need to expand, return
11074   // a null value.
11075   switch (Op.getSimpleValueType().SimpleTy) {
11076   default:
11077     // Most of the vector types have blends past SSE4.1.
11078     return Op;
11079
11080   case MVT::v32i8:
11081     // The byte blends for AVX vectors were introduced only in AVX2.
11082     if (Subtarget->hasAVX2())
11083       return Op;
11084
11085     return SDValue();
11086
11087   case MVT::v8i16:
11088   case MVT::v16i16:
11089     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11090     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11091       return Op;
11092
11093     // FIXME: We should custom lower this by fixing the condition and using i8
11094     // blends.
11095     return SDValue();
11096   }
11097 }
11098
11099 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11100   MVT VT = Op.getSimpleValueType();
11101   SDLoc dl(Op);
11102
11103   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11104     return SDValue();
11105
11106   if (VT.getSizeInBits() == 8) {
11107     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11108                                   Op.getOperand(0), Op.getOperand(1));
11109     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11110                                   DAG.getValueType(VT));
11111     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11112   }
11113
11114   if (VT.getSizeInBits() == 16) {
11115     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11116     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11117     if (Idx == 0)
11118       return DAG.getNode(
11119           ISD::TRUNCATE, dl, MVT::i16,
11120           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11121                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11122                       Op.getOperand(1)));
11123     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11124                                   Op.getOperand(0), Op.getOperand(1));
11125     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11126                                   DAG.getValueType(VT));
11127     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11128   }
11129
11130   if (VT == MVT::f32) {
11131     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11132     // the result back to FR32 register. It's only worth matching if the
11133     // result has a single use which is a store or a bitcast to i32.  And in
11134     // the case of a store, it's not worth it if the index is a constant 0,
11135     // because a MOVSSmr can be used instead, which is smaller and faster.
11136     if (!Op.hasOneUse())
11137       return SDValue();
11138     SDNode *User = *Op.getNode()->use_begin();
11139     if ((User->getOpcode() != ISD::STORE ||
11140          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11141           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11142         (User->getOpcode() != ISD::BITCAST ||
11143          User->getValueType(0) != MVT::i32))
11144       return SDValue();
11145     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11146                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11147                                   Op.getOperand(1));
11148     return DAG.getBitcast(MVT::f32, Extract);
11149   }
11150
11151   if (VT == MVT::i32 || VT == MVT::i64) {
11152     // ExtractPS/pextrq works with constant index.
11153     if (isa<ConstantSDNode>(Op.getOperand(1)))
11154       return Op;
11155   }
11156   return SDValue();
11157 }
11158
11159 /// Extract one bit from mask vector, like v16i1 or v8i1.
11160 /// AVX-512 feature.
11161 SDValue
11162 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11163   SDValue Vec = Op.getOperand(0);
11164   SDLoc dl(Vec);
11165   MVT VecVT = Vec.getSimpleValueType();
11166   SDValue Idx = Op.getOperand(1);
11167   MVT EltVT = Op.getSimpleValueType();
11168
11169   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11170   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11171          "Unexpected vector type in ExtractBitFromMaskVector");
11172
11173   // variable index can't be handled in mask registers,
11174   // extend vector to VR512
11175   if (!isa<ConstantSDNode>(Idx)) {
11176     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11177     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11178     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11179                               ExtVT.getVectorElementType(), Ext, Idx);
11180     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11181   }
11182
11183   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11184   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11185   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11186     rc = getRegClassFor(MVT::v16i1);
11187   unsigned MaxSift = rc->getSize()*8 - 1;
11188   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11189                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11190   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11191                     DAG.getConstant(MaxSift, dl, MVT::i8));
11192   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11193                        DAG.getIntPtrConstant(0, dl));
11194 }
11195
11196 SDValue
11197 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11198                                            SelectionDAG &DAG) const {
11199   SDLoc dl(Op);
11200   SDValue Vec = Op.getOperand(0);
11201   MVT VecVT = Vec.getSimpleValueType();
11202   SDValue Idx = Op.getOperand(1);
11203
11204   if (Op.getSimpleValueType() == MVT::i1)
11205     return ExtractBitFromMaskVector(Op, DAG);
11206
11207   if (!isa<ConstantSDNode>(Idx)) {
11208     if (VecVT.is512BitVector() ||
11209         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11210          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11211
11212       MVT MaskEltVT =
11213         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11214       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11215                                     MaskEltVT.getSizeInBits());
11216
11217       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11218       auto PtrVT = getPointerTy(DAG.getDataLayout());
11219       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11220                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11221                                  DAG.getConstant(0, dl, PtrVT));
11222       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11223       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11224                          DAG.getConstant(0, dl, PtrVT));
11225     }
11226     return SDValue();
11227   }
11228
11229   // If this is a 256-bit vector result, first extract the 128-bit vector and
11230   // then extract the element from the 128-bit vector.
11231   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11232
11233     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11234     // Get the 128-bit vector.
11235     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11236     MVT EltVT = VecVT.getVectorElementType();
11237
11238     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11239
11240     //if (IdxVal >= NumElems/2)
11241     //  IdxVal -= NumElems/2;
11242     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11243     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11244                        DAG.getConstant(IdxVal, dl, MVT::i32));
11245   }
11246
11247   assert(VecVT.is128BitVector() && "Unexpected vector length");
11248
11249   if (Subtarget->hasSSE41())
11250     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11251       return Res;
11252
11253   MVT VT = Op.getSimpleValueType();
11254   // TODO: handle v16i8.
11255   if (VT.getSizeInBits() == 16) {
11256     SDValue Vec = Op.getOperand(0);
11257     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11258     if (Idx == 0)
11259       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11260                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11261                                      DAG.getBitcast(MVT::v4i32, Vec),
11262                                      Op.getOperand(1)));
11263     // Transform it so it match pextrw which produces a 32-bit result.
11264     MVT EltVT = MVT::i32;
11265     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11266                                   Op.getOperand(0), Op.getOperand(1));
11267     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11268                                   DAG.getValueType(VT));
11269     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11270   }
11271
11272   if (VT.getSizeInBits() == 32) {
11273     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11274     if (Idx == 0)
11275       return Op;
11276
11277     // SHUFPS the element to the lowest double word, then movss.
11278     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11279     MVT VVT = Op.getOperand(0).getSimpleValueType();
11280     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11281                                        DAG.getUNDEF(VVT), Mask);
11282     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11283                        DAG.getIntPtrConstant(0, dl));
11284   }
11285
11286   if (VT.getSizeInBits() == 64) {
11287     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11288     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11289     //        to match extract_elt for f64.
11290     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11291     if (Idx == 0)
11292       return Op;
11293
11294     // UNPCKHPD the element to the lowest double word, then movsd.
11295     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11296     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11297     int Mask[2] = { 1, -1 };
11298     MVT VVT = Op.getOperand(0).getSimpleValueType();
11299     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11300                                        DAG.getUNDEF(VVT), Mask);
11301     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11302                        DAG.getIntPtrConstant(0, dl));
11303   }
11304
11305   return SDValue();
11306 }
11307
11308 /// Insert one bit to mask vector, like v16i1 or v8i1.
11309 /// AVX-512 feature.
11310 SDValue
11311 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11312   SDLoc dl(Op);
11313   SDValue Vec = Op.getOperand(0);
11314   SDValue Elt = Op.getOperand(1);
11315   SDValue Idx = Op.getOperand(2);
11316   MVT VecVT = Vec.getSimpleValueType();
11317
11318   if (!isa<ConstantSDNode>(Idx)) {
11319     // Non constant index. Extend source and destination,
11320     // insert element and then truncate the result.
11321     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11322     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11323     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11324       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11325       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11326     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11327   }
11328
11329   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11330   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11331   if (IdxVal)
11332     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11333                            DAG.getConstant(IdxVal, dl, MVT::i8));
11334   if (Vec.getOpcode() == ISD::UNDEF)
11335     return EltInVec;
11336   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11337 }
11338
11339 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11340                                                   SelectionDAG &DAG) const {
11341   MVT VT = Op.getSimpleValueType();
11342   MVT EltVT = VT.getVectorElementType();
11343
11344   if (EltVT == MVT::i1)
11345     return InsertBitToMaskVector(Op, DAG);
11346
11347   SDLoc dl(Op);
11348   SDValue N0 = Op.getOperand(0);
11349   SDValue N1 = Op.getOperand(1);
11350   SDValue N2 = Op.getOperand(2);
11351   if (!isa<ConstantSDNode>(N2))
11352     return SDValue();
11353   auto *N2C = cast<ConstantSDNode>(N2);
11354   unsigned IdxVal = N2C->getZExtValue();
11355
11356   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11357   // into that, and then insert the subvector back into the result.
11358   if (VT.is256BitVector() || VT.is512BitVector()) {
11359     // With a 256-bit vector, we can insert into the zero element efficiently
11360     // using a blend if we have AVX or AVX2 and the right data type.
11361     if (VT.is256BitVector() && IdxVal == 0) {
11362       // TODO: It is worthwhile to cast integer to floating point and back
11363       // and incur a domain crossing penalty if that's what we'll end up
11364       // doing anyway after extracting to a 128-bit vector.
11365       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11366           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11367         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11368         N2 = DAG.getIntPtrConstant(1, dl);
11369         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11370       }
11371     }
11372
11373     // Get the desired 128-bit vector chunk.
11374     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11375
11376     // Insert the element into the desired chunk.
11377     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11378     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11379
11380     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11381                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11382
11383     // Insert the changed part back into the bigger vector
11384     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11385   }
11386   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11387
11388   if (Subtarget->hasSSE41()) {
11389     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11390       unsigned Opc;
11391       if (VT == MVT::v8i16) {
11392         Opc = X86ISD::PINSRW;
11393       } else {
11394         assert(VT == MVT::v16i8);
11395         Opc = X86ISD::PINSRB;
11396       }
11397
11398       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11399       // argument.
11400       if (N1.getValueType() != MVT::i32)
11401         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11402       if (N2.getValueType() != MVT::i32)
11403         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11404       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11405     }
11406
11407     if (EltVT == MVT::f32) {
11408       // Bits [7:6] of the constant are the source select. This will always be
11409       //   zero here. The DAG Combiner may combine an extract_elt index into
11410       //   these bits. For example (insert (extract, 3), 2) could be matched by
11411       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11412       // Bits [5:4] of the constant are the destination select. This is the
11413       //   value of the incoming immediate.
11414       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11415       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11416
11417       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11418       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11419         // If this is an insertion of 32-bits into the low 32-bits of
11420         // a vector, we prefer to generate a blend with immediate rather
11421         // than an insertps. Blends are simpler operations in hardware and so
11422         // will always have equal or better performance than insertps.
11423         // But if optimizing for size and there's a load folding opportunity,
11424         // generate insertps because blendps does not have a 32-bit memory
11425         // operand form.
11426         N2 = DAG.getIntPtrConstant(1, dl);
11427         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11428         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11429       }
11430       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11431       // Create this as a scalar to vector..
11432       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11433       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11434     }
11435
11436     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11437       // PINSR* works with constant index.
11438       return Op;
11439     }
11440   }
11441
11442   if (EltVT == MVT::i8)
11443     return SDValue();
11444
11445   if (EltVT.getSizeInBits() == 16) {
11446     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11447     // as its second argument.
11448     if (N1.getValueType() != MVT::i32)
11449       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11450     if (N2.getValueType() != MVT::i32)
11451       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11452     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11453   }
11454   return SDValue();
11455 }
11456
11457 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11458   SDLoc dl(Op);
11459   MVT OpVT = Op.getSimpleValueType();
11460
11461   // If this is a 256-bit vector result, first insert into a 128-bit
11462   // vector and then insert into the 256-bit vector.
11463   if (!OpVT.is128BitVector()) {
11464     // Insert into a 128-bit vector.
11465     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11466     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11467                                  OpVT.getVectorNumElements() / SizeFactor);
11468
11469     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11470
11471     // Insert the 128-bit vector.
11472     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11473   }
11474
11475   if (OpVT == MVT::v1i64 &&
11476       Op.getOperand(0).getValueType() == MVT::i64)
11477     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11478
11479   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11480   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11481   return DAG.getBitcast(
11482       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11483 }
11484
11485 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11486 // a simple subregister reference or explicit instructions to grab
11487 // upper bits of a vector.
11488 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11489                                       SelectionDAG &DAG) {
11490   SDLoc dl(Op);
11491   SDValue In =  Op.getOperand(0);
11492   SDValue Idx = Op.getOperand(1);
11493   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11494   MVT ResVT   = Op.getSimpleValueType();
11495   MVT InVT    = In.getSimpleValueType();
11496
11497   if (Subtarget->hasFp256()) {
11498     if (ResVT.is128BitVector() &&
11499         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11500         isa<ConstantSDNode>(Idx)) {
11501       return Extract128BitVector(In, IdxVal, DAG, dl);
11502     }
11503     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11504         isa<ConstantSDNode>(Idx)) {
11505       return Extract256BitVector(In, IdxVal, DAG, dl);
11506     }
11507   }
11508   return SDValue();
11509 }
11510
11511 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11512 // simple superregister reference or explicit instructions to insert
11513 // the upper bits of a vector.
11514 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11515                                      SelectionDAG &DAG) {
11516   if (!Subtarget->hasAVX())
11517     return SDValue();
11518
11519   SDLoc dl(Op);
11520   SDValue Vec = Op.getOperand(0);
11521   SDValue SubVec = Op.getOperand(1);
11522   SDValue Idx = Op.getOperand(2);
11523
11524   if (!isa<ConstantSDNode>(Idx))
11525     return SDValue();
11526
11527   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11528   MVT OpVT = Op.getSimpleValueType();
11529   MVT SubVecVT = SubVec.getSimpleValueType();
11530
11531   // Fold two 16-byte subvector loads into one 32-byte load:
11532   // (insert_subvector (insert_subvector undef, (load addr), 0),
11533   //                   (load addr + 16), Elts/2)
11534   // --> load32 addr
11535   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11536       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11537       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11538     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11539     if (Idx2 && Idx2->getZExtValue() == 0) {
11540       SDValue SubVec2 = Vec.getOperand(1);
11541       // If needed, look through a bitcast to get to the load.
11542       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11543         SubVec2 = SubVec2.getOperand(0);
11544
11545       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11546         bool Fast;
11547         unsigned Alignment = FirstLd->getAlignment();
11548         unsigned AS = FirstLd->getAddressSpace();
11549         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11550         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11551                                     OpVT, AS, Alignment, &Fast) && Fast) {
11552           SDValue Ops[] = { SubVec2, SubVec };
11553           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11554             return Ld;
11555         }
11556       }
11557     }
11558   }
11559
11560   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11561       SubVecVT.is128BitVector())
11562     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11563
11564   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11565     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11566
11567   if (OpVT.getVectorElementType() == MVT::i1) {
11568     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11569       return Op;
11570     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11571     SDValue Undef = DAG.getUNDEF(OpVT);
11572     unsigned NumElems = OpVT.getVectorNumElements();
11573     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11574
11575     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11576       // Zero upper bits of the Vec
11577       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11578       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11579
11580       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11581                                  SubVec, ZeroIdx);
11582       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11583       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11584     }
11585     if (IdxVal == 0) {
11586       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11587                                  SubVec, ZeroIdx);
11588       // Zero upper bits of the Vec2
11589       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11590       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11591       // Zero lower bits of the Vec
11592       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11593       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11594       // Merge them together
11595       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11596     }
11597   }
11598   return SDValue();
11599 }
11600
11601 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11602 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11603 // one of the above mentioned nodes. It has to be wrapped because otherwise
11604 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11605 // be used to form addressing mode. These wrapped nodes will be selected
11606 // into MOV32ri.
11607 SDValue
11608 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11609   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11610
11611   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11612   // global base reg.
11613   unsigned char OpFlag = 0;
11614   unsigned WrapperKind = X86ISD::Wrapper;
11615   CodeModel::Model M = DAG.getTarget().getCodeModel();
11616
11617   if (Subtarget->isPICStyleRIPRel() &&
11618       (M == CodeModel::Small || M == CodeModel::Kernel))
11619     WrapperKind = X86ISD::WrapperRIP;
11620   else if (Subtarget->isPICStyleGOT())
11621     OpFlag = X86II::MO_GOTOFF;
11622   else if (Subtarget->isPICStyleStubPIC())
11623     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11624
11625   auto PtrVT = getPointerTy(DAG.getDataLayout());
11626   SDValue Result = DAG.getTargetConstantPool(
11627       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11628   SDLoc DL(CP);
11629   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11630   // With PIC, the address is actually $g + Offset.
11631   if (OpFlag) {
11632     Result =
11633         DAG.getNode(ISD::ADD, DL, PtrVT,
11634                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11635   }
11636
11637   return Result;
11638 }
11639
11640 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11641   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11642
11643   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11644   // global base reg.
11645   unsigned char OpFlag = 0;
11646   unsigned WrapperKind = X86ISD::Wrapper;
11647   CodeModel::Model M = DAG.getTarget().getCodeModel();
11648
11649   if (Subtarget->isPICStyleRIPRel() &&
11650       (M == CodeModel::Small || M == CodeModel::Kernel))
11651     WrapperKind = X86ISD::WrapperRIP;
11652   else if (Subtarget->isPICStyleGOT())
11653     OpFlag = X86II::MO_GOTOFF;
11654   else if (Subtarget->isPICStyleStubPIC())
11655     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11656
11657   auto PtrVT = getPointerTy(DAG.getDataLayout());
11658   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11659   SDLoc DL(JT);
11660   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11661
11662   // With PIC, the address is actually $g + Offset.
11663   if (OpFlag)
11664     Result =
11665         DAG.getNode(ISD::ADD, DL, PtrVT,
11666                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11667
11668   return Result;
11669 }
11670
11671 SDValue
11672 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11673   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11674
11675   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11676   // global base reg.
11677   unsigned char OpFlag = 0;
11678   unsigned WrapperKind = X86ISD::Wrapper;
11679   CodeModel::Model M = DAG.getTarget().getCodeModel();
11680
11681   if (Subtarget->isPICStyleRIPRel() &&
11682       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11683     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11684       OpFlag = X86II::MO_GOTPCREL;
11685     WrapperKind = X86ISD::WrapperRIP;
11686   } else if (Subtarget->isPICStyleGOT()) {
11687     OpFlag = X86II::MO_GOT;
11688   } else if (Subtarget->isPICStyleStubPIC()) {
11689     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11690   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11691     OpFlag = X86II::MO_DARWIN_NONLAZY;
11692   }
11693
11694   auto PtrVT = getPointerTy(DAG.getDataLayout());
11695   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11696
11697   SDLoc DL(Op);
11698   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11699
11700   // With PIC, the address is actually $g + Offset.
11701   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11702       !Subtarget->is64Bit()) {
11703     Result =
11704         DAG.getNode(ISD::ADD, DL, PtrVT,
11705                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11706   }
11707
11708   // For symbols that require a load from a stub to get the address, emit the
11709   // load.
11710   if (isGlobalStubReference(OpFlag))
11711     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11712                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11713                          false, false, false, 0);
11714
11715   return Result;
11716 }
11717
11718 SDValue
11719 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11720   // Create the TargetBlockAddressAddress node.
11721   unsigned char OpFlags =
11722     Subtarget->ClassifyBlockAddressReference();
11723   CodeModel::Model M = DAG.getTarget().getCodeModel();
11724   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11725   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11726   SDLoc dl(Op);
11727   auto PtrVT = getPointerTy(DAG.getDataLayout());
11728   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11729
11730   if (Subtarget->isPICStyleRIPRel() &&
11731       (M == CodeModel::Small || M == CodeModel::Kernel))
11732     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11733   else
11734     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11735
11736   // With PIC, the address is actually $g + Offset.
11737   if (isGlobalRelativeToPICBase(OpFlags)) {
11738     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11739                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11740   }
11741
11742   return Result;
11743 }
11744
11745 SDValue
11746 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11747                                       int64_t Offset, SelectionDAG &DAG) const {
11748   // Create the TargetGlobalAddress node, folding in the constant
11749   // offset if it is legal.
11750   unsigned char OpFlags =
11751       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11752   CodeModel::Model M = DAG.getTarget().getCodeModel();
11753   auto PtrVT = getPointerTy(DAG.getDataLayout());
11754   SDValue Result;
11755   if (OpFlags == X86II::MO_NO_FLAG &&
11756       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11757     // A direct static reference to a global.
11758     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11759     Offset = 0;
11760   } else {
11761     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11762   }
11763
11764   if (Subtarget->isPICStyleRIPRel() &&
11765       (M == CodeModel::Small || M == CodeModel::Kernel))
11766     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11767   else
11768     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11769
11770   // With PIC, the address is actually $g + Offset.
11771   if (isGlobalRelativeToPICBase(OpFlags)) {
11772     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11773                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11774   }
11775
11776   // For globals that require a load from a stub to get the address, emit the
11777   // load.
11778   if (isGlobalStubReference(OpFlags))
11779     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11780                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11781                          false, false, false, 0);
11782
11783   // If there was a non-zero offset that we didn't fold, create an explicit
11784   // addition for it.
11785   if (Offset != 0)
11786     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11787                          DAG.getConstant(Offset, dl, PtrVT));
11788
11789   return Result;
11790 }
11791
11792 SDValue
11793 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11794   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11795   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11796   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11797 }
11798
11799 static SDValue
11800 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11801            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11802            unsigned char OperandFlags, bool LocalDynamic = false) {
11803   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11804   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11805   SDLoc dl(GA);
11806   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11807                                            GA->getValueType(0),
11808                                            GA->getOffset(),
11809                                            OperandFlags);
11810
11811   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11812                                            : X86ISD::TLSADDR;
11813
11814   if (InFlag) {
11815     SDValue Ops[] = { Chain,  TGA, *InFlag };
11816     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11817   } else {
11818     SDValue Ops[]  = { Chain, TGA };
11819     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11820   }
11821
11822   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11823   MFI->setAdjustsStack(true);
11824   MFI->setHasCalls(true);
11825
11826   SDValue Flag = Chain.getValue(1);
11827   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11828 }
11829
11830 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11831 static SDValue
11832 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11833                                 const EVT PtrVT) {
11834   SDValue InFlag;
11835   SDLoc dl(GA);  // ? function entry point might be better
11836   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11837                                    DAG.getNode(X86ISD::GlobalBaseReg,
11838                                                SDLoc(), PtrVT), InFlag);
11839   InFlag = Chain.getValue(1);
11840
11841   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11842 }
11843
11844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11845 static SDValue
11846 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11847                                 const EVT PtrVT) {
11848   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11849                     X86::RAX, X86II::MO_TLSGD);
11850 }
11851
11852 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11853                                            SelectionDAG &DAG,
11854                                            const EVT PtrVT,
11855                                            bool is64Bit) {
11856   SDLoc dl(GA);
11857
11858   // Get the start address of the TLS block for this module.
11859   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11860       .getInfo<X86MachineFunctionInfo>();
11861   MFI->incNumLocalDynamicTLSAccesses();
11862
11863   SDValue Base;
11864   if (is64Bit) {
11865     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11866                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11867   } else {
11868     SDValue InFlag;
11869     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11870         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11871     InFlag = Chain.getValue(1);
11872     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11873                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11874   }
11875
11876   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11877   // of Base.
11878
11879   // Build x@dtpoff.
11880   unsigned char OperandFlags = X86II::MO_DTPOFF;
11881   unsigned WrapperKind = X86ISD::Wrapper;
11882   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11883                                            GA->getValueType(0),
11884                                            GA->getOffset(), OperandFlags);
11885   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11886
11887   // Add x@dtpoff with the base.
11888   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11889 }
11890
11891 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11892 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11893                                    const EVT PtrVT, TLSModel::Model model,
11894                                    bool is64Bit, bool isPIC) {
11895   SDLoc dl(GA);
11896
11897   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11898   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11899                                                          is64Bit ? 257 : 256));
11900
11901   SDValue ThreadPointer =
11902       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11903                   MachinePointerInfo(Ptr), false, false, false, 0);
11904
11905   unsigned char OperandFlags = 0;
11906   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11907   // initialexec.
11908   unsigned WrapperKind = X86ISD::Wrapper;
11909   if (model == TLSModel::LocalExec) {
11910     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11911   } else if (model == TLSModel::InitialExec) {
11912     if (is64Bit) {
11913       OperandFlags = X86II::MO_GOTTPOFF;
11914       WrapperKind = X86ISD::WrapperRIP;
11915     } else {
11916       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11917     }
11918   } else {
11919     llvm_unreachable("Unexpected model");
11920   }
11921
11922   // emit "addl x@ntpoff,%eax" (local exec)
11923   // or "addl x@indntpoff,%eax" (initial exec)
11924   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11925   SDValue TGA =
11926       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11927                                  GA->getOffset(), OperandFlags);
11928   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11929
11930   if (model == TLSModel::InitialExec) {
11931     if (isPIC && !is64Bit) {
11932       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11933                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11934                            Offset);
11935     }
11936
11937     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11938                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11939                          false, false, false, 0);
11940   }
11941
11942   // The address of the thread local variable is the add of the thread
11943   // pointer with the offset of the variable.
11944   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11945 }
11946
11947 SDValue
11948 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11949
11950   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11951   const GlobalValue *GV = GA->getGlobal();
11952   auto PtrVT = getPointerTy(DAG.getDataLayout());
11953
11954   if (Subtarget->isTargetELF()) {
11955     if (DAG.getTarget().Options.EmulatedTLS)
11956       return LowerToTLSEmulatedModel(GA, DAG);
11957     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11958     switch (model) {
11959       case TLSModel::GeneralDynamic:
11960         if (Subtarget->is64Bit())
11961           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11962         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11963       case TLSModel::LocalDynamic:
11964         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11965                                            Subtarget->is64Bit());
11966       case TLSModel::InitialExec:
11967       case TLSModel::LocalExec:
11968         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11969                                    DAG.getTarget().getRelocationModel() ==
11970                                        Reloc::PIC_);
11971     }
11972     llvm_unreachable("Unknown TLS model.");
11973   }
11974
11975   if (Subtarget->isTargetDarwin()) {
11976     // Darwin only has one model of TLS.  Lower to that.
11977     unsigned char OpFlag = 0;
11978     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11979                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11980
11981     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11982     // global base reg.
11983     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11984                  !Subtarget->is64Bit();
11985     if (PIC32)
11986       OpFlag = X86II::MO_TLVP_PIC_BASE;
11987     else
11988       OpFlag = X86II::MO_TLVP;
11989     SDLoc DL(Op);
11990     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11991                                                 GA->getValueType(0),
11992                                                 GA->getOffset(), OpFlag);
11993     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11994
11995     // With PIC32, the address is actually $g + Offset.
11996     if (PIC32)
11997       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11998                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11999                            Offset);
12000
12001     // Lowering the machine isd will make sure everything is in the right
12002     // location.
12003     SDValue Chain = DAG.getEntryNode();
12004     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12005     SDValue Args[] = { Chain, Offset };
12006     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12007
12008     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12009     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12010     MFI->setAdjustsStack(true);
12011
12012     // And our return value (tls address) is in the standard call return value
12013     // location.
12014     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12015     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12016   }
12017
12018   if (Subtarget->isTargetKnownWindowsMSVC() ||
12019       Subtarget->isTargetWindowsGNU()) {
12020     // Just use the implicit TLS architecture
12021     // Need to generate someting similar to:
12022     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12023     //                                  ; from TEB
12024     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12025     //   mov     rcx, qword [rdx+rcx*8]
12026     //   mov     eax, .tls$:tlsvar
12027     //   [rax+rcx] contains the address
12028     // Windows 64bit: gs:0x58
12029     // Windows 32bit: fs:__tls_array
12030
12031     SDLoc dl(GA);
12032     SDValue Chain = DAG.getEntryNode();
12033
12034     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12035     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12036     // use its literal value of 0x2C.
12037     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12038                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12039                                                              256)
12040                                         : Type::getInt32PtrTy(*DAG.getContext(),
12041                                                               257));
12042
12043     SDValue TlsArray = Subtarget->is64Bit()
12044                            ? DAG.getIntPtrConstant(0x58, dl)
12045                            : (Subtarget->isTargetWindowsGNU()
12046                                   ? DAG.getIntPtrConstant(0x2C, dl)
12047                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12048
12049     SDValue ThreadPointer =
12050         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12051                     false, false, 0);
12052
12053     SDValue res;
12054     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12055       res = ThreadPointer;
12056     } else {
12057       // Load the _tls_index variable
12058       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12059       if (Subtarget->is64Bit())
12060         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12061                              MachinePointerInfo(), MVT::i32, false, false,
12062                              false, 0);
12063       else
12064         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12065                           false, false, 0);
12066
12067       auto &DL = DAG.getDataLayout();
12068       SDValue Scale =
12069           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12070       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12071
12072       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12073     }
12074
12075     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12076                       false, 0);
12077
12078     // Get the offset of start of .tls section
12079     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12080                                              GA->getValueType(0),
12081                                              GA->getOffset(), X86II::MO_SECREL);
12082     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12083
12084     // The address of the thread local variable is the add of the thread
12085     // pointer with the offset of the variable.
12086     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12087   }
12088
12089   llvm_unreachable("TLS not implemented for this target.");
12090 }
12091
12092 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12093 /// and take a 2 x i32 value to shift plus a shift amount.
12094 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12095   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12096   MVT VT = Op.getSimpleValueType();
12097   unsigned VTBits = VT.getSizeInBits();
12098   SDLoc dl(Op);
12099   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12100   SDValue ShOpLo = Op.getOperand(0);
12101   SDValue ShOpHi = Op.getOperand(1);
12102   SDValue ShAmt  = Op.getOperand(2);
12103   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12104   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12105   // during isel.
12106   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12107                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12108   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12109                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12110                        : DAG.getConstant(0, dl, VT);
12111
12112   SDValue Tmp2, Tmp3;
12113   if (Op.getOpcode() == ISD::SHL_PARTS) {
12114     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12115     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12116   } else {
12117     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12118     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12119   }
12120
12121   // If the shift amount is larger or equal than the width of a part we can't
12122   // rely on the results of shld/shrd. Insert a test and select the appropriate
12123   // values for large shift amounts.
12124   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12125                                 DAG.getConstant(VTBits, dl, MVT::i8));
12126   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12127                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12128
12129   SDValue Hi, Lo;
12130   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12131   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12132   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12133
12134   if (Op.getOpcode() == ISD::SHL_PARTS) {
12135     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12136     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12137   } else {
12138     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12139     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12140   }
12141
12142   SDValue Ops[2] = { Lo, Hi };
12143   return DAG.getMergeValues(Ops, dl);
12144 }
12145
12146 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12147                                            SelectionDAG &DAG) const {
12148   SDValue Src = Op.getOperand(0);
12149   MVT SrcVT = Src.getSimpleValueType();
12150   MVT VT = Op.getSimpleValueType();
12151   SDLoc dl(Op);
12152
12153   if (SrcVT.isVector()) {
12154     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12155       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12156                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12157                          DAG.getUNDEF(SrcVT)));
12158     }
12159     if (SrcVT.getVectorElementType() == MVT::i1) {
12160       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12161       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12162                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12163     }
12164     return SDValue();
12165   }
12166
12167   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12168          "Unknown SINT_TO_FP to lower!");
12169
12170   // These are really Legal; return the operand so the caller accepts it as
12171   // Legal.
12172   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12173     return Op;
12174   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12175       Subtarget->is64Bit()) {
12176     return Op;
12177   }
12178
12179   unsigned Size = SrcVT.getSizeInBits()/8;
12180   MachineFunction &MF = DAG.getMachineFunction();
12181   auto PtrVT = getPointerTy(MF.getDataLayout());
12182   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12183   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12184   SDValue Chain = DAG.getStore(
12185       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12186       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12187       false, 0);
12188   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12189 }
12190
12191 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12192                                      SDValue StackSlot,
12193                                      SelectionDAG &DAG) const {
12194   // Build the FILD
12195   SDLoc DL(Op);
12196   SDVTList Tys;
12197   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12198   if (useSSE)
12199     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12200   else
12201     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12202
12203   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12204
12205   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12206   MachineMemOperand *MMO;
12207   if (FI) {
12208     int SSFI = FI->getIndex();
12209     MMO = DAG.getMachineFunction().getMachineMemOperand(
12210         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12211         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12212   } else {
12213     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12214     StackSlot = StackSlot.getOperand(1);
12215   }
12216   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12217   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12218                                            X86ISD::FILD, DL,
12219                                            Tys, Ops, SrcVT, MMO);
12220
12221   if (useSSE) {
12222     Chain = Result.getValue(1);
12223     SDValue InFlag = Result.getValue(2);
12224
12225     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12226     // shouldn't be necessary except that RFP cannot be live across
12227     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12228     MachineFunction &MF = DAG.getMachineFunction();
12229     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12230     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12231     auto PtrVT = getPointerTy(MF.getDataLayout());
12232     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12233     Tys = DAG.getVTList(MVT::Other);
12234     SDValue Ops[] = {
12235       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12236     };
12237     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12238         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12239         MachineMemOperand::MOStore, SSFISize, SSFISize);
12240
12241     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12242                                     Ops, Op.getValueType(), MMO);
12243     Result = DAG.getLoad(
12244         Op.getValueType(), DL, Chain, StackSlot,
12245         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12246         false, false, false, 0);
12247   }
12248
12249   return Result;
12250 }
12251
12252 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12253 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12254                                                SelectionDAG &DAG) const {
12255   // This algorithm is not obvious. Here it is what we're trying to output:
12256   /*
12257      movq       %rax,  %xmm0
12258      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12259      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12260      #ifdef __SSE3__
12261        haddpd   %xmm0, %xmm0
12262      #else
12263        pshufd   $0x4e, %xmm0, %xmm1
12264        addpd    %xmm1, %xmm0
12265      #endif
12266   */
12267
12268   SDLoc dl(Op);
12269   LLVMContext *Context = DAG.getContext();
12270
12271   // Build some magic constants.
12272   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12273   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12274   auto PtrVT = getPointerTy(DAG.getDataLayout());
12275   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12276
12277   SmallVector<Constant*,2> CV1;
12278   CV1.push_back(
12279     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12280                                       APInt(64, 0x4330000000000000ULL))));
12281   CV1.push_back(
12282     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12283                                       APInt(64, 0x4530000000000000ULL))));
12284   Constant *C1 = ConstantVector::get(CV1);
12285   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12286
12287   // Load the 64-bit value into an XMM register.
12288   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12289                             Op.getOperand(0));
12290   SDValue CLod0 =
12291       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12292                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12293                   false, false, false, 16);
12294   SDValue Unpck1 =
12295       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12296
12297   SDValue CLod1 =
12298       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12299                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12300                   false, false, false, 16);
12301   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12302   // TODO: Are there any fast-math-flags to propagate here?
12303   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12304   SDValue Result;
12305
12306   if (Subtarget->hasSSE3()) {
12307     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12308     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12309   } else {
12310     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12311     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12312                                            S2F, 0x4E, DAG);
12313     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12314                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12315   }
12316
12317   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12318                      DAG.getIntPtrConstant(0, dl));
12319 }
12320
12321 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12322 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12323                                                SelectionDAG &DAG) const {
12324   SDLoc dl(Op);
12325   // FP constant to bias correct the final result.
12326   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12327                                    MVT::f64);
12328
12329   // Load the 32-bit value into an XMM register.
12330   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12331                              Op.getOperand(0));
12332
12333   // Zero out the upper parts of the register.
12334   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12335
12336   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12337                      DAG.getBitcast(MVT::v2f64, Load),
12338                      DAG.getIntPtrConstant(0, dl));
12339
12340   // Or the load with the bias.
12341   SDValue Or = DAG.getNode(
12342       ISD::OR, dl, MVT::v2i64,
12343       DAG.getBitcast(MVT::v2i64,
12344                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12345       DAG.getBitcast(MVT::v2i64,
12346                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12347   Or =
12348       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12349                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12350
12351   // Subtract the bias.
12352   // TODO: Are there any fast-math-flags to propagate here?
12353   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12354
12355   // Handle final rounding.
12356   EVT DestVT = Op.getValueType();
12357
12358   if (DestVT.bitsLT(MVT::f64))
12359     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12360                        DAG.getIntPtrConstant(0, dl));
12361   if (DestVT.bitsGT(MVT::f64))
12362     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12363
12364   // Handle final rounding.
12365   return Sub;
12366 }
12367
12368 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12369                                      const X86Subtarget &Subtarget) {
12370   // The algorithm is the following:
12371   // #ifdef __SSE4_1__
12372   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12373   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12374   //                                 (uint4) 0x53000000, 0xaa);
12375   // #else
12376   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12377   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12378   // #endif
12379   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12380   //     return (float4) lo + fhi;
12381
12382   SDLoc DL(Op);
12383   SDValue V = Op->getOperand(0);
12384   EVT VecIntVT = V.getValueType();
12385   bool Is128 = VecIntVT == MVT::v4i32;
12386   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12387   // If we convert to something else than the supported type, e.g., to v4f64,
12388   // abort early.
12389   if (VecFloatVT != Op->getValueType(0))
12390     return SDValue();
12391
12392   unsigned NumElts = VecIntVT.getVectorNumElements();
12393   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12394          "Unsupported custom type");
12395   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12396
12397   // In the #idef/#else code, we have in common:
12398   // - The vector of constants:
12399   // -- 0x4b000000
12400   // -- 0x53000000
12401   // - A shift:
12402   // -- v >> 16
12403
12404   // Create the splat vector for 0x4b000000.
12405   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12406   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12407                            CstLow, CstLow, CstLow, CstLow};
12408   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12409                                   makeArrayRef(&CstLowArray[0], NumElts));
12410   // Create the splat vector for 0x53000000.
12411   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12412   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12413                             CstHigh, CstHigh, CstHigh, CstHigh};
12414   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12415                                    makeArrayRef(&CstHighArray[0], NumElts));
12416
12417   // Create the right shift.
12418   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12419   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12420                              CstShift, CstShift, CstShift, CstShift};
12421   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12422                                     makeArrayRef(&CstShiftArray[0], NumElts));
12423   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12424
12425   SDValue Low, High;
12426   if (Subtarget.hasSSE41()) {
12427     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12428     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12429     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12430     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12431     // Low will be bitcasted right away, so do not bother bitcasting back to its
12432     // original type.
12433     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12434                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12435     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12436     //                                 (uint4) 0x53000000, 0xaa);
12437     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12438     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12439     // High will be bitcasted right away, so do not bother bitcasting back to
12440     // its original type.
12441     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12442                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12443   } else {
12444     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12445     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12446                                      CstMask, CstMask, CstMask);
12447     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12448     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12449     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12450
12451     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12452     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12453   }
12454
12455   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12456   SDValue CstFAdd = DAG.getConstantFP(
12457       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12458   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12459                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12460   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12461                                    makeArrayRef(&CstFAddArray[0], NumElts));
12462
12463   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12464   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12465   // TODO: Are there any fast-math-flags to propagate here?
12466   SDValue FHigh =
12467       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12468   //     return (float4) lo + fhi;
12469   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12470   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12471 }
12472
12473 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12474                                                SelectionDAG &DAG) const {
12475   SDValue N0 = Op.getOperand(0);
12476   MVT SVT = N0.getSimpleValueType();
12477   SDLoc dl(Op);
12478
12479   switch (SVT.SimpleTy) {
12480   default:
12481     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12482   case MVT::v4i8:
12483   case MVT::v4i16:
12484   case MVT::v8i8:
12485   case MVT::v8i16: {
12486     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12487     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12488                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12489   }
12490   case MVT::v4i32:
12491   case MVT::v8i32:
12492     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12493   case MVT::v16i8:
12494   case MVT::v16i16:
12495     if (Subtarget->hasAVX512())
12496       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12497                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12498   }
12499   llvm_unreachable(nullptr);
12500 }
12501
12502 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12503                                            SelectionDAG &DAG) const {
12504   SDValue N0 = Op.getOperand(0);
12505   SDLoc dl(Op);
12506   auto PtrVT = getPointerTy(DAG.getDataLayout());
12507
12508   if (Op.getValueType().isVector())
12509     return lowerUINT_TO_FP_vec(Op, DAG);
12510
12511   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12512   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12513   // the optimization here.
12514   if (DAG.SignBitIsZero(N0))
12515     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12516
12517   MVT SrcVT = N0.getSimpleValueType();
12518   MVT DstVT = Op.getSimpleValueType();
12519   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12520     return LowerUINT_TO_FP_i64(Op, DAG);
12521   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12522     return LowerUINT_TO_FP_i32(Op, DAG);
12523   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12524     return SDValue();
12525
12526   // Make a 64-bit buffer, and use it to build an FILD.
12527   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12528   if (SrcVT == MVT::i32) {
12529     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12530     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12531     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12532                                   StackSlot, MachinePointerInfo(),
12533                                   false, false, 0);
12534     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12535                                   OffsetSlot, MachinePointerInfo(),
12536                                   false, false, 0);
12537     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12538     return Fild;
12539   }
12540
12541   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12542   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12543                                StackSlot, MachinePointerInfo(),
12544                                false, false, 0);
12545   // For i64 source, we need to add the appropriate power of 2 if the input
12546   // was negative.  This is the same as the optimization in
12547   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12548   // we must be careful to do the computation in x87 extended precision, not
12549   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12550   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12551   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12552       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12553       MachineMemOperand::MOLoad, 8, 8);
12554
12555   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12556   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12557   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12558                                          MVT::i64, MMO);
12559
12560   APInt FF(32, 0x5F800000ULL);
12561
12562   // Check whether the sign bit is set.
12563   SDValue SignSet = DAG.getSetCC(
12564       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12565       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12566
12567   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12568   SDValue FudgePtr = DAG.getConstantPool(
12569       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12570
12571   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12572   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12573   SDValue Four = DAG.getIntPtrConstant(4, dl);
12574   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12575                                Zero, Four);
12576   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12577
12578   // Load the value out, extending it from f32 to f80.
12579   // FIXME: Avoid the extend by constructing the right constant pool?
12580   SDValue Fudge = DAG.getExtLoad(
12581       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12582       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12583       false, false, false, 4);
12584   // Extend everything to 80 bits to force it to be done on x87.
12585   // TODO: Are there any fast-math-flags to propagate here?
12586   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12587   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12588                      DAG.getIntPtrConstant(0, dl));
12589 }
12590
12591 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12592 // is legal, or has an f16 source (which needs to be promoted to f32),
12593 // just return an <SDValue(), SDValue()> pair.
12594 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12595 // to i16, i32 or i64, and we lower it to a legal sequence.
12596 // If lowered to the final integer result we return a <result, SDValue()> pair.
12597 // Otherwise we lower it to a sequence ending with a FIST, return a
12598 // <FIST, StackSlot> pair, and the caller is responsible for loading
12599 // the final integer result from StackSlot.
12600 std::pair<SDValue,SDValue>
12601 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12602                                    bool IsSigned, bool IsReplace) const {
12603   SDLoc DL(Op);
12604
12605   EVT DstTy = Op.getValueType();
12606   EVT TheVT = Op.getOperand(0).getValueType();
12607   auto PtrVT = getPointerTy(DAG.getDataLayout());
12608
12609   if (TheVT == MVT::f16)
12610     // We need to promote the f16 to f32 before using the lowering
12611     // in this routine.
12612     return std::make_pair(SDValue(), SDValue());
12613
12614   assert((TheVT == MVT::f32 ||
12615           TheVT == MVT::f64 ||
12616           TheVT == MVT::f80) &&
12617          "Unexpected FP operand type in FP_TO_INTHelper");
12618
12619   // If using FIST to compute an unsigned i64, we'll need some fixup
12620   // to handle values above the maximum signed i64.  A FIST is always
12621   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12622   bool UnsignedFixup = !IsSigned &&
12623                        DstTy == MVT::i64 &&
12624                        (!Subtarget->is64Bit() ||
12625                         !isScalarFPTypeInSSEReg(TheVT));
12626
12627   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12628     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12629     // The low 32 bits of the fist result will have the correct uint32 result.
12630     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12631     DstTy = MVT::i64;
12632   }
12633
12634   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12635          DstTy.getSimpleVT() >= MVT::i16 &&
12636          "Unknown FP_TO_INT to lower!");
12637
12638   // These are really Legal.
12639   if (DstTy == MVT::i32 &&
12640       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12641     return std::make_pair(SDValue(), SDValue());
12642   if (Subtarget->is64Bit() &&
12643       DstTy == MVT::i64 &&
12644       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12645     return std::make_pair(SDValue(), SDValue());
12646
12647   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12648   // stack slot.
12649   MachineFunction &MF = DAG.getMachineFunction();
12650   unsigned MemSize = DstTy.getSizeInBits()/8;
12651   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12652   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12653
12654   unsigned Opc;
12655   switch (DstTy.getSimpleVT().SimpleTy) {
12656   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12657   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12658   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12659   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12660   }
12661
12662   SDValue Chain = DAG.getEntryNode();
12663   SDValue Value = Op.getOperand(0);
12664   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12665
12666   if (UnsignedFixup) {
12667     //
12668     // Conversion to unsigned i64 is implemented with a select,
12669     // depending on whether the source value fits in the range
12670     // of a signed i64.  Let Thresh be the FP equivalent of
12671     // 0x8000000000000000ULL.
12672     //
12673     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12674     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12675     //  Fist-to-mem64 FistSrc
12676     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12677     //  to XOR'ing the high 32 bits with Adjust.
12678     //
12679     // Being a power of 2, Thresh is exactly representable in all FP formats.
12680     // For X87 we'd like to use the smallest FP type for this constant, but
12681     // for DAG type consistency we have to match the FP operand type.
12682
12683     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12684     APFloat::opStatus Status = APFloat::opOK;
12685     bool LosesInfo = false;
12686     if (TheVT == MVT::f64)
12687       // The rounding mode is irrelevant as the conversion should be exact.
12688       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12689                               &LosesInfo);
12690     else if (TheVT == MVT::f80)
12691       Status = Thresh.convert(APFloat::x87DoubleExtended,
12692                               APFloat::rmNearestTiesToEven, &LosesInfo);
12693
12694     assert(Status == APFloat::opOK && !LosesInfo &&
12695            "FP conversion should have been exact");
12696
12697     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12698
12699     SDValue Cmp = DAG.getSetCC(DL,
12700                                getSetCCResultType(DAG.getDataLayout(),
12701                                                   *DAG.getContext(), TheVT),
12702                                Value, ThreshVal, ISD::SETLT);
12703     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12704                            DAG.getConstant(0, DL, MVT::i32),
12705                            DAG.getConstant(0x80000000, DL, MVT::i32));
12706     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12707     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12708                                               *DAG.getContext(), TheVT),
12709                        Value, ThreshVal, ISD::SETLT);
12710     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12711   }
12712
12713   // FIXME This causes a redundant load/store if the SSE-class value is already
12714   // in memory, such as if it is on the callstack.
12715   if (isScalarFPTypeInSSEReg(TheVT)) {
12716     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12717     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12718                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12719                          false, 0);
12720     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12721     SDValue Ops[] = {
12722       Chain, StackSlot, DAG.getValueType(TheVT)
12723     };
12724
12725     MachineMemOperand *MMO =
12726         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12727                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12728     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12729     Chain = Value.getValue(1);
12730     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12731     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12732   }
12733
12734   MachineMemOperand *MMO =
12735       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12736                               MachineMemOperand::MOStore, MemSize, MemSize);
12737
12738   if (UnsignedFixup) {
12739
12740     // Insert the FIST, load its result as two i32's,
12741     // and XOR the high i32 with Adjust.
12742
12743     SDValue FistOps[] = { Chain, Value, StackSlot };
12744     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12745                                            FistOps, DstTy, MMO);
12746
12747     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12748                                 MachinePointerInfo(),
12749                                 false, false, false, 0);
12750     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12751                                    DAG.getConstant(4, DL, PtrVT));
12752
12753     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12754                                  MachinePointerInfo(),
12755                                  false, false, false, 0);
12756     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12757
12758     if (Subtarget->is64Bit()) {
12759       // Join High32 and Low32 into a 64-bit result.
12760       // (High32 << 32) | Low32
12761       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12762       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12763       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12764                            DAG.getConstant(32, DL, MVT::i8));
12765       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12766       return std::make_pair(Result, SDValue());
12767     }
12768
12769     SDValue ResultOps[] = { Low32, High32 };
12770
12771     SDValue pair = IsReplace
12772       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12773       : DAG.getMergeValues(ResultOps, DL);
12774     return std::make_pair(pair, SDValue());
12775   } else {
12776     // Build the FP_TO_INT*_IN_MEM
12777     SDValue Ops[] = { Chain, Value, StackSlot };
12778     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12779                                            Ops, DstTy, MMO);
12780     return std::make_pair(FIST, StackSlot);
12781   }
12782 }
12783
12784 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12785                               const X86Subtarget *Subtarget) {
12786   MVT VT = Op->getSimpleValueType(0);
12787   SDValue In = Op->getOperand(0);
12788   MVT InVT = In.getSimpleValueType();
12789   SDLoc dl(Op);
12790
12791   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12792     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12793
12794   // Optimize vectors in AVX mode:
12795   //
12796   //   v8i16 -> v8i32
12797   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12798   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12799   //   Concat upper and lower parts.
12800   //
12801   //   v4i32 -> v4i64
12802   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12803   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12804   //   Concat upper and lower parts.
12805   //
12806
12807   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12808       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12809       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12810     return SDValue();
12811
12812   if (Subtarget->hasInt256())
12813     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12814
12815   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12816   SDValue Undef = DAG.getUNDEF(InVT);
12817   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12818   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12819   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12820
12821   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12822                              VT.getVectorNumElements()/2);
12823
12824   OpLo = DAG.getBitcast(HVT, OpLo);
12825   OpHi = DAG.getBitcast(HVT, OpHi);
12826
12827   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12828 }
12829
12830 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12831                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12832   MVT VT = Op->getSimpleValueType(0);
12833   SDValue In = Op->getOperand(0);
12834   MVT InVT = In.getSimpleValueType();
12835   SDLoc DL(Op);
12836   unsigned int NumElts = VT.getVectorNumElements();
12837   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12838     return SDValue();
12839
12840   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12841     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12842
12843   assert(InVT.getVectorElementType() == MVT::i1);
12844   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12845   SDValue One =
12846    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12847   SDValue Zero =
12848    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12849
12850   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12851   if (VT.is512BitVector())
12852     return V;
12853   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12854 }
12855
12856 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12857                                SelectionDAG &DAG) {
12858   if (Subtarget->hasFp256())
12859     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12860       return Res;
12861
12862   return SDValue();
12863 }
12864
12865 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12866                                 SelectionDAG &DAG) {
12867   SDLoc DL(Op);
12868   MVT VT = Op.getSimpleValueType();
12869   SDValue In = Op.getOperand(0);
12870   MVT SVT = In.getSimpleValueType();
12871
12872   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12873     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12874
12875   if (Subtarget->hasFp256())
12876     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12877       return Res;
12878
12879   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12880          VT.getVectorNumElements() != SVT.getVectorNumElements());
12881   return SDValue();
12882 }
12883
12884 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12885   SDLoc DL(Op);
12886   MVT VT = Op.getSimpleValueType();
12887   SDValue In = Op.getOperand(0);
12888   MVT InVT = In.getSimpleValueType();
12889
12890   if (VT == MVT::i1) {
12891     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12892            "Invalid scalar TRUNCATE operation");
12893     if (InVT.getSizeInBits() >= 32)
12894       return SDValue();
12895     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12896     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12897   }
12898   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12899          "Invalid TRUNCATE operation");
12900
12901   // move vector to mask - truncate solution for SKX
12902   if (VT.getVectorElementType() == MVT::i1) {
12903     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12904         Subtarget->hasBWI())
12905       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12906     if ((InVT.is256BitVector() || InVT.is128BitVector())
12907         && InVT.getScalarSizeInBits() <= 16 &&
12908         Subtarget->hasBWI() && Subtarget->hasVLX())
12909       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12910     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12911         Subtarget->hasDQI())
12912       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12913     if ((InVT.is256BitVector() || InVT.is128BitVector())
12914         && InVT.getScalarSizeInBits() >= 32 &&
12915         Subtarget->hasDQI() && Subtarget->hasVLX())
12916       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12917   }
12918
12919   if (VT.getVectorElementType() == MVT::i1) {
12920     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12921     unsigned NumElts = InVT.getVectorNumElements();
12922     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12923     if (InVT.getSizeInBits() < 512) {
12924       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12925       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12926       InVT = ExtVT;
12927     }
12928
12929     SDValue OneV =
12930      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12931     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12932     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12933   }
12934
12935   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12936   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12937       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12938     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12939
12940   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12941     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12942     if (Subtarget->hasInt256()) {
12943       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12944       In = DAG.getBitcast(MVT::v8i32, In);
12945       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12946                                 ShufMask);
12947       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12948                          DAG.getIntPtrConstant(0, DL));
12949     }
12950
12951     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12952                                DAG.getIntPtrConstant(0, DL));
12953     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12954                                DAG.getIntPtrConstant(2, DL));
12955     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12956     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12957     static const int ShufMask[] = {0, 2, 4, 6};
12958     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12959   }
12960
12961   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12962     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12963     if (Subtarget->hasInt256()) {
12964       In = DAG.getBitcast(MVT::v32i8, In);
12965
12966       SmallVector<SDValue,32> pshufbMask;
12967       for (unsigned i = 0; i < 2; ++i) {
12968         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12969         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12970         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12971         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12972         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12973         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12974         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12975         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12976         for (unsigned j = 0; j < 8; ++j)
12977           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12978       }
12979       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12980       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12981       In = DAG.getBitcast(MVT::v4i64, In);
12982
12983       static const int ShufMask[] = {0,  2,  -1,  -1};
12984       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12985                                 &ShufMask[0]);
12986       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12987                        DAG.getIntPtrConstant(0, DL));
12988       return DAG.getBitcast(VT, In);
12989     }
12990
12991     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12992                                DAG.getIntPtrConstant(0, DL));
12993
12994     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12995                                DAG.getIntPtrConstant(4, DL));
12996
12997     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12998     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12999
13000     // The PSHUFB mask:
13001     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13002                                    -1, -1, -1, -1, -1, -1, -1, -1};
13003
13004     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13005     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13006     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13007
13008     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13009     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13010
13011     // The MOVLHPS Mask:
13012     static const int ShufMask2[] = {0, 1, 4, 5};
13013     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13014     return DAG.getBitcast(MVT::v8i16, res);
13015   }
13016
13017   // Handle truncation of V256 to V128 using shuffles.
13018   if (!VT.is128BitVector() || !InVT.is256BitVector())
13019     return SDValue();
13020
13021   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13022
13023   unsigned NumElems = VT.getVectorNumElements();
13024   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13025
13026   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13027   // Prepare truncation shuffle mask
13028   for (unsigned i = 0; i != NumElems; ++i)
13029     MaskVec[i] = i * 2;
13030   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13031                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13032   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13033                      DAG.getIntPtrConstant(0, DL));
13034 }
13035
13036 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13037                                            SelectionDAG &DAG) const {
13038   assert(!Op.getSimpleValueType().isVector());
13039
13040   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13041     /*IsSigned=*/ true, /*IsReplace=*/ false);
13042   SDValue FIST = Vals.first, StackSlot = Vals.second;
13043   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13044   if (!FIST.getNode())
13045     return Op;
13046
13047   if (StackSlot.getNode())
13048     // Load the result.
13049     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13050                        FIST, StackSlot, MachinePointerInfo(),
13051                        false, false, false, 0);
13052
13053   // The node is the result.
13054   return FIST;
13055 }
13056
13057 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13058                                            SelectionDAG &DAG) const {
13059   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13060     /*IsSigned=*/ false, /*IsReplace=*/ false);
13061   SDValue FIST = Vals.first, StackSlot = Vals.second;
13062   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13063   if (!FIST.getNode())
13064     return Op;
13065
13066   if (StackSlot.getNode())
13067     // Load the result.
13068     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13069                        FIST, StackSlot, MachinePointerInfo(),
13070                        false, false, false, 0);
13071
13072   // The node is the result.
13073   return FIST;
13074 }
13075
13076 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13077   SDLoc DL(Op);
13078   MVT VT = Op.getSimpleValueType();
13079   SDValue In = Op.getOperand(0);
13080   MVT SVT = In.getSimpleValueType();
13081
13082   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13083
13084   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13085                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13086                                  In, DAG.getUNDEF(SVT)));
13087 }
13088
13089 /// The only differences between FABS and FNEG are the mask and the logic op.
13090 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13091 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13092   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13093          "Wrong opcode for lowering FABS or FNEG.");
13094
13095   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13096
13097   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13098   // into an FNABS. We'll lower the FABS after that if it is still in use.
13099   if (IsFABS)
13100     for (SDNode *User : Op->uses())
13101       if (User->getOpcode() == ISD::FNEG)
13102         return Op;
13103
13104   SDLoc dl(Op);
13105   MVT VT = Op.getSimpleValueType();
13106
13107   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13108   // decide if we should generate a 16-byte constant mask when we only need 4 or
13109   // 8 bytes for the scalar case.
13110
13111   MVT LogicVT;
13112   MVT EltVT;
13113   unsigned NumElts;
13114
13115   if (VT.isVector()) {
13116     LogicVT = VT;
13117     EltVT = VT.getVectorElementType();
13118     NumElts = VT.getVectorNumElements();
13119   } else {
13120     // There are no scalar bitwise logical SSE/AVX instructions, so we
13121     // generate a 16-byte vector constant and logic op even for the scalar case.
13122     // Using a 16-byte mask allows folding the load of the mask with
13123     // the logic op, so it can save (~4 bytes) on code size.
13124     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13125     EltVT = VT;
13126     NumElts = (VT == MVT::f64) ? 2 : 4;
13127   }
13128
13129   unsigned EltBits = EltVT.getSizeInBits();
13130   LLVMContext *Context = DAG.getContext();
13131   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13132   APInt MaskElt =
13133     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13134   Constant *C = ConstantInt::get(*Context, MaskElt);
13135   C = ConstantVector::getSplat(NumElts, C);
13136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13137   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13138   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13139   SDValue Mask =
13140       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13141                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13142                   false, false, false, Alignment);
13143
13144   SDValue Op0 = Op.getOperand(0);
13145   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13146   unsigned LogicOp =
13147     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13148   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13149
13150   if (VT.isVector())
13151     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13152
13153   // For the scalar case extend to a 128-bit vector, perform the logic op,
13154   // and extract the scalar result back out.
13155   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13156   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13157   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13158                      DAG.getIntPtrConstant(0, dl));
13159 }
13160
13161 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13163   LLVMContext *Context = DAG.getContext();
13164   SDValue Op0 = Op.getOperand(0);
13165   SDValue Op1 = Op.getOperand(1);
13166   SDLoc dl(Op);
13167   MVT VT = Op.getSimpleValueType();
13168   MVT SrcVT = Op1.getSimpleValueType();
13169
13170   // If second operand is smaller, extend it first.
13171   if (SrcVT.bitsLT(VT)) {
13172     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13173     SrcVT = VT;
13174   }
13175   // And if it is bigger, shrink it first.
13176   if (SrcVT.bitsGT(VT)) {
13177     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13178     SrcVT = VT;
13179   }
13180
13181   // At this point the operands and the result should have the same
13182   // type, and that won't be f80 since that is not custom lowered.
13183
13184   const fltSemantics &Sem =
13185       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13186   const unsigned SizeInBits = VT.getSizeInBits();
13187
13188   SmallVector<Constant *, 4> CV(
13189       VT == MVT::f64 ? 2 : 4,
13190       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13191
13192   // First, clear all bits but the sign bit from the second operand (sign).
13193   CV[0] = ConstantFP::get(*Context,
13194                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13195   Constant *C = ConstantVector::get(CV);
13196   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13197   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13198
13199   // Perform all logic operations as 16-byte vectors because there are no
13200   // scalar FP logic instructions in SSE. This allows load folding of the
13201   // constants into the logic instructions.
13202   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13203   SDValue Mask1 =
13204       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13205                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13206                   false, false, false, 16);
13207   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13208   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13209
13210   // Next, clear the sign bit from the first operand (magnitude).
13211   // If it's a constant, we can clear it here.
13212   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13213     APFloat APF = Op0CN->getValueAPF();
13214     // If the magnitude is a positive zero, the sign bit alone is enough.
13215     if (APF.isPosZero())
13216       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13217                          DAG.getIntPtrConstant(0, dl));
13218     APF.clearSign();
13219     CV[0] = ConstantFP::get(*Context, APF);
13220   } else {
13221     CV[0] = ConstantFP::get(
13222         *Context,
13223         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13224   }
13225   C = ConstantVector::get(CV);
13226   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13227   SDValue Val =
13228       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13229                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13230                   false, false, false, 16);
13231   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13232   if (!isa<ConstantFPSDNode>(Op0)) {
13233     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13234     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13235   }
13236   // OR the magnitude value with the sign bit.
13237   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13238   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13239                      DAG.getIntPtrConstant(0, dl));
13240 }
13241
13242 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13243   SDValue N0 = Op.getOperand(0);
13244   SDLoc dl(Op);
13245   MVT VT = Op.getSimpleValueType();
13246
13247   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13248   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13249                                   DAG.getConstant(1, dl, VT));
13250   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13251 }
13252
13253 // Check whether an OR'd tree is PTEST-able.
13254 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13255                                       SelectionDAG &DAG) {
13256   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13257
13258   if (!Subtarget->hasSSE41())
13259     return SDValue();
13260
13261   if (!Op->hasOneUse())
13262     return SDValue();
13263
13264   SDNode *N = Op.getNode();
13265   SDLoc DL(N);
13266
13267   SmallVector<SDValue, 8> Opnds;
13268   DenseMap<SDValue, unsigned> VecInMap;
13269   SmallVector<SDValue, 8> VecIns;
13270   EVT VT = MVT::Other;
13271
13272   // Recognize a special case where a vector is casted into wide integer to
13273   // test all 0s.
13274   Opnds.push_back(N->getOperand(0));
13275   Opnds.push_back(N->getOperand(1));
13276
13277   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13278     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13279     // BFS traverse all OR'd operands.
13280     if (I->getOpcode() == ISD::OR) {
13281       Opnds.push_back(I->getOperand(0));
13282       Opnds.push_back(I->getOperand(1));
13283       // Re-evaluate the number of nodes to be traversed.
13284       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13285       continue;
13286     }
13287
13288     // Quit if a non-EXTRACT_VECTOR_ELT
13289     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13290       return SDValue();
13291
13292     // Quit if without a constant index.
13293     SDValue Idx = I->getOperand(1);
13294     if (!isa<ConstantSDNode>(Idx))
13295       return SDValue();
13296
13297     SDValue ExtractedFromVec = I->getOperand(0);
13298     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13299     if (M == VecInMap.end()) {
13300       VT = ExtractedFromVec.getValueType();
13301       // Quit if not 128/256-bit vector.
13302       if (!VT.is128BitVector() && !VT.is256BitVector())
13303         return SDValue();
13304       // Quit if not the same type.
13305       if (VecInMap.begin() != VecInMap.end() &&
13306           VT != VecInMap.begin()->first.getValueType())
13307         return SDValue();
13308       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13309       VecIns.push_back(ExtractedFromVec);
13310     }
13311     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13312   }
13313
13314   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13315          "Not extracted from 128-/256-bit vector.");
13316
13317   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13318
13319   for (DenseMap<SDValue, unsigned>::const_iterator
13320         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13321     // Quit if not all elements are used.
13322     if (I->second != FullMask)
13323       return SDValue();
13324   }
13325
13326   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13327
13328   // Cast all vectors into TestVT for PTEST.
13329   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13330     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13331
13332   // If more than one full vectors are evaluated, OR them first before PTEST.
13333   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13334     // Each iteration will OR 2 nodes and append the result until there is only
13335     // 1 node left, i.e. the final OR'd value of all vectors.
13336     SDValue LHS = VecIns[Slot];
13337     SDValue RHS = VecIns[Slot + 1];
13338     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13339   }
13340
13341   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13342                      VecIns.back(), VecIns.back());
13343 }
13344
13345 /// \brief return true if \c Op has a use that doesn't just read flags.
13346 static bool hasNonFlagsUse(SDValue Op) {
13347   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13348        ++UI) {
13349     SDNode *User = *UI;
13350     unsigned UOpNo = UI.getOperandNo();
13351     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13352       // Look pass truncate.
13353       UOpNo = User->use_begin().getOperandNo();
13354       User = *User->use_begin();
13355     }
13356
13357     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13358         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13359       return true;
13360   }
13361   return false;
13362 }
13363
13364 /// Emit nodes that will be selected as "test Op0,Op0", or something
13365 /// equivalent.
13366 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13367                                     SelectionDAG &DAG) const {
13368   if (Op.getValueType() == MVT::i1) {
13369     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13370     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13371                        DAG.getConstant(0, dl, MVT::i8));
13372   }
13373   // CF and OF aren't always set the way we want. Determine which
13374   // of these we need.
13375   bool NeedCF = false;
13376   bool NeedOF = false;
13377   switch (X86CC) {
13378   default: break;
13379   case X86::COND_A: case X86::COND_AE:
13380   case X86::COND_B: case X86::COND_BE:
13381     NeedCF = true;
13382     break;
13383   case X86::COND_G: case X86::COND_GE:
13384   case X86::COND_L: case X86::COND_LE:
13385   case X86::COND_O: case X86::COND_NO: {
13386     // Check if we really need to set the
13387     // Overflow flag. If NoSignedWrap is present
13388     // that is not actually needed.
13389     switch (Op->getOpcode()) {
13390     case ISD::ADD:
13391     case ISD::SUB:
13392     case ISD::MUL:
13393     case ISD::SHL: {
13394       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13395       if (BinNode->Flags.hasNoSignedWrap())
13396         break;
13397     }
13398     default:
13399       NeedOF = true;
13400       break;
13401     }
13402     break;
13403   }
13404   }
13405   // See if we can use the EFLAGS value from the operand instead of
13406   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13407   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13408   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13409     // Emit a CMP with 0, which is the TEST pattern.
13410     //if (Op.getValueType() == MVT::i1)
13411     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13412     //                     DAG.getConstant(0, MVT::i1));
13413     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13414                        DAG.getConstant(0, dl, Op.getValueType()));
13415   }
13416   unsigned Opcode = 0;
13417   unsigned NumOperands = 0;
13418
13419   // Truncate operations may prevent the merge of the SETCC instruction
13420   // and the arithmetic instruction before it. Attempt to truncate the operands
13421   // of the arithmetic instruction and use a reduced bit-width instruction.
13422   bool NeedTruncation = false;
13423   SDValue ArithOp = Op;
13424   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13425     SDValue Arith = Op->getOperand(0);
13426     // Both the trunc and the arithmetic op need to have one user each.
13427     if (Arith->hasOneUse())
13428       switch (Arith.getOpcode()) {
13429         default: break;
13430         case ISD::ADD:
13431         case ISD::SUB:
13432         case ISD::AND:
13433         case ISD::OR:
13434         case ISD::XOR: {
13435           NeedTruncation = true;
13436           ArithOp = Arith;
13437         }
13438       }
13439   }
13440
13441   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13442   // which may be the result of a CAST.  We use the variable 'Op', which is the
13443   // non-casted variable when we check for possible users.
13444   switch (ArithOp.getOpcode()) {
13445   case ISD::ADD:
13446     // Due to an isel shortcoming, be conservative if this add is likely to be
13447     // selected as part of a load-modify-store instruction. When the root node
13448     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13449     // uses of other nodes in the match, such as the ADD in this case. This
13450     // leads to the ADD being left around and reselected, with the result being
13451     // two adds in the output.  Alas, even if none our users are stores, that
13452     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13453     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13454     // climbing the DAG back to the root, and it doesn't seem to be worth the
13455     // effort.
13456     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13457          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13458       if (UI->getOpcode() != ISD::CopyToReg &&
13459           UI->getOpcode() != ISD::SETCC &&
13460           UI->getOpcode() != ISD::STORE)
13461         goto default_case;
13462
13463     if (ConstantSDNode *C =
13464         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13465       // An add of one will be selected as an INC.
13466       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13467         Opcode = X86ISD::INC;
13468         NumOperands = 1;
13469         break;
13470       }
13471
13472       // An add of negative one (subtract of one) will be selected as a DEC.
13473       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13474         Opcode = X86ISD::DEC;
13475         NumOperands = 1;
13476         break;
13477       }
13478     }
13479
13480     // Otherwise use a regular EFLAGS-setting add.
13481     Opcode = X86ISD::ADD;
13482     NumOperands = 2;
13483     break;
13484   case ISD::SHL:
13485   case ISD::SRL:
13486     // If we have a constant logical shift that's only used in a comparison
13487     // against zero turn it into an equivalent AND. This allows turning it into
13488     // a TEST instruction later.
13489     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13490         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13491       EVT VT = Op.getValueType();
13492       unsigned BitWidth = VT.getSizeInBits();
13493       unsigned ShAmt = Op->getConstantOperandVal(1);
13494       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13495         break;
13496       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13497                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13498                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13499       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13500         break;
13501       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13502                                 DAG.getConstant(Mask, dl, VT));
13503       DAG.ReplaceAllUsesWith(Op, New);
13504       Op = New;
13505     }
13506     break;
13507
13508   case ISD::AND:
13509     // If the primary and result isn't used, don't bother using X86ISD::AND,
13510     // because a TEST instruction will be better.
13511     if (!hasNonFlagsUse(Op))
13512       break;
13513     // FALL THROUGH
13514   case ISD::SUB:
13515   case ISD::OR:
13516   case ISD::XOR:
13517     // Due to the ISEL shortcoming noted above, be conservative if this op is
13518     // likely to be selected as part of a load-modify-store instruction.
13519     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13520            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13521       if (UI->getOpcode() == ISD::STORE)
13522         goto default_case;
13523
13524     // Otherwise use a regular EFLAGS-setting instruction.
13525     switch (ArithOp.getOpcode()) {
13526     default: llvm_unreachable("unexpected operator!");
13527     case ISD::SUB: Opcode = X86ISD::SUB; break;
13528     case ISD::XOR: Opcode = X86ISD::XOR; break;
13529     case ISD::AND: Opcode = X86ISD::AND; break;
13530     case ISD::OR: {
13531       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13532         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13533         if (EFLAGS.getNode())
13534           return EFLAGS;
13535       }
13536       Opcode = X86ISD::OR;
13537       break;
13538     }
13539     }
13540
13541     NumOperands = 2;
13542     break;
13543   case X86ISD::ADD:
13544   case X86ISD::SUB:
13545   case X86ISD::INC:
13546   case X86ISD::DEC:
13547   case X86ISD::OR:
13548   case X86ISD::XOR:
13549   case X86ISD::AND:
13550     return SDValue(Op.getNode(), 1);
13551   default:
13552   default_case:
13553     break;
13554   }
13555
13556   // If we found that truncation is beneficial, perform the truncation and
13557   // update 'Op'.
13558   if (NeedTruncation) {
13559     EVT VT = Op.getValueType();
13560     SDValue WideVal = Op->getOperand(0);
13561     EVT WideVT = WideVal.getValueType();
13562     unsigned ConvertedOp = 0;
13563     // Use a target machine opcode to prevent further DAGCombine
13564     // optimizations that may separate the arithmetic operations
13565     // from the setcc node.
13566     switch (WideVal.getOpcode()) {
13567       default: break;
13568       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13569       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13570       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13571       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13572       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13573     }
13574
13575     if (ConvertedOp) {
13576       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13577       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13578         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13579         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13580         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13581       }
13582     }
13583   }
13584
13585   if (Opcode == 0)
13586     // Emit a CMP with 0, which is the TEST pattern.
13587     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13588                        DAG.getConstant(0, dl, Op.getValueType()));
13589
13590   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13591   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13592
13593   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13594   DAG.ReplaceAllUsesWith(Op, New);
13595   return SDValue(New.getNode(), 1);
13596 }
13597
13598 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13599 /// equivalent.
13600 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13601                                    SDLoc dl, SelectionDAG &DAG) const {
13602   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13603     if (C->getAPIntValue() == 0)
13604       return EmitTest(Op0, X86CC, dl, DAG);
13605
13606      if (Op0.getValueType() == MVT::i1)
13607        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13608   }
13609
13610   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13611        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13612     // Do the comparison at i32 if it's smaller, besides the Atom case.
13613     // This avoids subregister aliasing issues. Keep the smaller reference
13614     // if we're optimizing for size, however, as that'll allow better folding
13615     // of memory operations.
13616     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13617         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13618         !Subtarget->isAtom()) {
13619       unsigned ExtendOp =
13620           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13621       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13622       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13623     }
13624     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13625     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13626     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13627                               Op0, Op1);
13628     return SDValue(Sub.getNode(), 1);
13629   }
13630   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13631 }
13632
13633 /// Convert a comparison if required by the subtarget.
13634 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13635                                                  SelectionDAG &DAG) const {
13636   // If the subtarget does not support the FUCOMI instruction, floating-point
13637   // comparisons have to be converted.
13638   if (Subtarget->hasCMov() ||
13639       Cmp.getOpcode() != X86ISD::CMP ||
13640       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13641       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13642     return Cmp;
13643
13644   // The instruction selector will select an FUCOM instruction instead of
13645   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13646   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13647   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13648   SDLoc dl(Cmp);
13649   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13650   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13651   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13652                             DAG.getConstant(8, dl, MVT::i8));
13653   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13654   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13655 }
13656
13657 /// The minimum architected relative accuracy is 2^-12. We need one
13658 /// Newton-Raphson step to have a good float result (24 bits of precision).
13659 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13660                                             DAGCombinerInfo &DCI,
13661                                             unsigned &RefinementSteps,
13662                                             bool &UseOneConstNR) const {
13663   EVT VT = Op.getValueType();
13664   const char *RecipOp;
13665
13666   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13667   // TODO: Add support for AVX512 (v16f32).
13668   // It is likely not profitable to do this for f64 because a double-precision
13669   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13670   // instructions: convert to single, rsqrtss, convert back to double, refine
13671   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13672   // along with FMA, this could be a throughput win.
13673   if (VT == MVT::f32 && Subtarget->hasSSE1())
13674     RecipOp = "sqrtf";
13675   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13676            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13677     RecipOp = "vec-sqrtf";
13678   else
13679     return SDValue();
13680
13681   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13682   if (!Recips.isEnabled(RecipOp))
13683     return SDValue();
13684
13685   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13686   UseOneConstNR = false;
13687   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13688 }
13689
13690 /// The minimum architected relative accuracy is 2^-12. We need one
13691 /// Newton-Raphson step to have a good float result (24 bits of precision).
13692 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13693                                             DAGCombinerInfo &DCI,
13694                                             unsigned &RefinementSteps) const {
13695   EVT VT = Op.getValueType();
13696   const char *RecipOp;
13697
13698   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13699   // TODO: Add support for AVX512 (v16f32).
13700   // It is likely not profitable to do this for f64 because a double-precision
13701   // reciprocal estimate with refinement on x86 prior to FMA requires
13702   // 15 instructions: convert to single, rcpss, convert back to double, refine
13703   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13704   // along with FMA, this could be a throughput win.
13705   if (VT == MVT::f32 && Subtarget->hasSSE1())
13706     RecipOp = "divf";
13707   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13708            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13709     RecipOp = "vec-divf";
13710   else
13711     return SDValue();
13712
13713   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13714   if (!Recips.isEnabled(RecipOp))
13715     return SDValue();
13716
13717   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13718   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13719 }
13720
13721 /// If we have at least two divisions that use the same divisor, convert to
13722 /// multplication by a reciprocal. This may need to be adjusted for a given
13723 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13724 /// This is because we still need one division to calculate the reciprocal and
13725 /// then we need two multiplies by that reciprocal as replacements for the
13726 /// original divisions.
13727 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13728   return 2;
13729 }
13730
13731 static bool isAllOnes(SDValue V) {
13732   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13733   return C && C->isAllOnesValue();
13734 }
13735
13736 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13737 /// if it's possible.
13738 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13739                                      SDLoc dl, SelectionDAG &DAG) const {
13740   SDValue Op0 = And.getOperand(0);
13741   SDValue Op1 = And.getOperand(1);
13742   if (Op0.getOpcode() == ISD::TRUNCATE)
13743     Op0 = Op0.getOperand(0);
13744   if (Op1.getOpcode() == ISD::TRUNCATE)
13745     Op1 = Op1.getOperand(0);
13746
13747   SDValue LHS, RHS;
13748   if (Op1.getOpcode() == ISD::SHL)
13749     std::swap(Op0, Op1);
13750   if (Op0.getOpcode() == ISD::SHL) {
13751     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13752       if (And00C->getZExtValue() == 1) {
13753         // If we looked past a truncate, check that it's only truncating away
13754         // known zeros.
13755         unsigned BitWidth = Op0.getValueSizeInBits();
13756         unsigned AndBitWidth = And.getValueSizeInBits();
13757         if (BitWidth > AndBitWidth) {
13758           APInt Zeros, Ones;
13759           DAG.computeKnownBits(Op0, Zeros, Ones);
13760           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13761             return SDValue();
13762         }
13763         LHS = Op1;
13764         RHS = Op0.getOperand(1);
13765       }
13766   } else if (Op1.getOpcode() == ISD::Constant) {
13767     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13768     uint64_t AndRHSVal = AndRHS->getZExtValue();
13769     SDValue AndLHS = Op0;
13770
13771     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13772       LHS = AndLHS.getOperand(0);
13773       RHS = AndLHS.getOperand(1);
13774     }
13775
13776     // Use BT if the immediate can't be encoded in a TEST instruction.
13777     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13778       LHS = AndLHS;
13779       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13780     }
13781   }
13782
13783   if (LHS.getNode()) {
13784     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13785     // instruction.  Since the shift amount is in-range-or-undefined, we know
13786     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13787     // the encoding for the i16 version is larger than the i32 version.
13788     // Also promote i16 to i32 for performance / code size reason.
13789     if (LHS.getValueType() == MVT::i8 ||
13790         LHS.getValueType() == MVT::i16)
13791       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13792
13793     // If the operand types disagree, extend the shift amount to match.  Since
13794     // BT ignores high bits (like shifts) we can use anyextend.
13795     if (LHS.getValueType() != RHS.getValueType())
13796       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13797
13798     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13799     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13800     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13801                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13802   }
13803
13804   return SDValue();
13805 }
13806
13807 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13808 /// mask CMPs.
13809 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13810                               SDValue &Op1) {
13811   unsigned SSECC;
13812   bool Swap = false;
13813
13814   // SSE Condition code mapping:
13815   //  0 - EQ
13816   //  1 - LT
13817   //  2 - LE
13818   //  3 - UNORD
13819   //  4 - NEQ
13820   //  5 - NLT
13821   //  6 - NLE
13822   //  7 - ORD
13823   switch (SetCCOpcode) {
13824   default: llvm_unreachable("Unexpected SETCC condition");
13825   case ISD::SETOEQ:
13826   case ISD::SETEQ:  SSECC = 0; break;
13827   case ISD::SETOGT:
13828   case ISD::SETGT:  Swap = true; // Fallthrough
13829   case ISD::SETLT:
13830   case ISD::SETOLT: SSECC = 1; break;
13831   case ISD::SETOGE:
13832   case ISD::SETGE:  Swap = true; // Fallthrough
13833   case ISD::SETLE:
13834   case ISD::SETOLE: SSECC = 2; break;
13835   case ISD::SETUO:  SSECC = 3; break;
13836   case ISD::SETUNE:
13837   case ISD::SETNE:  SSECC = 4; break;
13838   case ISD::SETULE: Swap = true; // Fallthrough
13839   case ISD::SETUGE: SSECC = 5; break;
13840   case ISD::SETULT: Swap = true; // Fallthrough
13841   case ISD::SETUGT: SSECC = 6; break;
13842   case ISD::SETO:   SSECC = 7; break;
13843   case ISD::SETUEQ:
13844   case ISD::SETONE: SSECC = 8; break;
13845   }
13846   if (Swap)
13847     std::swap(Op0, Op1);
13848
13849   return SSECC;
13850 }
13851
13852 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13853 // ones, and then concatenate the result back.
13854 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13855   MVT VT = Op.getSimpleValueType();
13856
13857   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13858          "Unsupported value type for operation");
13859
13860   unsigned NumElems = VT.getVectorNumElements();
13861   SDLoc dl(Op);
13862   SDValue CC = Op.getOperand(2);
13863
13864   // Extract the LHS vectors
13865   SDValue LHS = Op.getOperand(0);
13866   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13867   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13868
13869   // Extract the RHS vectors
13870   SDValue RHS = Op.getOperand(1);
13871   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13872   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13873
13874   // Issue the operation on the smaller types and concatenate the result back
13875   MVT EltVT = VT.getVectorElementType();
13876   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13877   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13878                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13879                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13880 }
13881
13882 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13883   SDValue Op0 = Op.getOperand(0);
13884   SDValue Op1 = Op.getOperand(1);
13885   SDValue CC = Op.getOperand(2);
13886   MVT VT = Op.getSimpleValueType();
13887   SDLoc dl(Op);
13888
13889   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13890          "Unexpected type for boolean compare operation");
13891   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13892   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13893                                DAG.getConstant(-1, dl, VT));
13894   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13895                                DAG.getConstant(-1, dl, VT));
13896   switch (SetCCOpcode) {
13897   default: llvm_unreachable("Unexpected SETCC condition");
13898   case ISD::SETEQ:
13899     // (x == y) -> ~(x ^ y)
13900     return DAG.getNode(ISD::XOR, dl, VT,
13901                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13902                        DAG.getConstant(-1, dl, VT));
13903   case ISD::SETNE:
13904     // (x != y) -> (x ^ y)
13905     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13906   case ISD::SETUGT:
13907   case ISD::SETGT:
13908     // (x > y) -> (x & ~y)
13909     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13910   case ISD::SETULT:
13911   case ISD::SETLT:
13912     // (x < y) -> (~x & y)
13913     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13914   case ISD::SETULE:
13915   case ISD::SETLE:
13916     // (x <= y) -> (~x | y)
13917     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13918   case ISD::SETUGE:
13919   case ISD::SETGE:
13920     // (x >=y) -> (x | ~y)
13921     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13922   }
13923 }
13924
13925 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13926                                      const X86Subtarget *Subtarget) {
13927   SDValue Op0 = Op.getOperand(0);
13928   SDValue Op1 = Op.getOperand(1);
13929   SDValue CC = Op.getOperand(2);
13930   MVT VT = Op.getSimpleValueType();
13931   SDLoc dl(Op);
13932
13933   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13934          Op.getValueType().getScalarType() == MVT::i1 &&
13935          "Cannot set masked compare for this operation");
13936
13937   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13938   unsigned  Opc = 0;
13939   bool Unsigned = false;
13940   bool Swap = false;
13941   unsigned SSECC;
13942   switch (SetCCOpcode) {
13943   default: llvm_unreachable("Unexpected SETCC condition");
13944   case ISD::SETNE:  SSECC = 4; break;
13945   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13946   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13947   case ISD::SETLT:  Swap = true; //fall-through
13948   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13949   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13950   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13951   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13952   case ISD::SETULE: Unsigned = true; //fall-through
13953   case ISD::SETLE:  SSECC = 2; break;
13954   }
13955
13956   if (Swap)
13957     std::swap(Op0, Op1);
13958   if (Opc)
13959     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13960   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13961   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13962                      DAG.getConstant(SSECC, dl, MVT::i8));
13963 }
13964
13965 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13966 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13967 /// return an empty value.
13968 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13969 {
13970   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13971   if (!BV)
13972     return SDValue();
13973
13974   MVT VT = Op1.getSimpleValueType();
13975   MVT EVT = VT.getVectorElementType();
13976   unsigned n = VT.getVectorNumElements();
13977   SmallVector<SDValue, 8> ULTOp1;
13978
13979   for (unsigned i = 0; i < n; ++i) {
13980     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13981     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13982       return SDValue();
13983
13984     // Avoid underflow.
13985     APInt Val = Elt->getAPIntValue();
13986     if (Val == 0)
13987       return SDValue();
13988
13989     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13990   }
13991
13992   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13993 }
13994
13995 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13996                            SelectionDAG &DAG) {
13997   SDValue Op0 = Op.getOperand(0);
13998   SDValue Op1 = Op.getOperand(1);
13999   SDValue CC = Op.getOperand(2);
14000   MVT VT = Op.getSimpleValueType();
14001   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14002   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14003   SDLoc dl(Op);
14004
14005   if (isFP) {
14006 #ifndef NDEBUG
14007     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14008     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14009 #endif
14010
14011     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14012     unsigned Opc = X86ISD::CMPP;
14013     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14014       assert(VT.getVectorNumElements() <= 16);
14015       Opc = X86ISD::CMPM;
14016     }
14017     // In the two special cases we can't handle, emit two comparisons.
14018     if (SSECC == 8) {
14019       unsigned CC0, CC1;
14020       unsigned CombineOpc;
14021       if (SetCCOpcode == ISD::SETUEQ) {
14022         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14023       } else {
14024         assert(SetCCOpcode == ISD::SETONE);
14025         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14026       }
14027
14028       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14029                                  DAG.getConstant(CC0, dl, MVT::i8));
14030       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14031                                  DAG.getConstant(CC1, dl, MVT::i8));
14032       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14033     }
14034     // Handle all other FP comparisons here.
14035     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14036                        DAG.getConstant(SSECC, dl, MVT::i8));
14037   }
14038
14039   // Break 256-bit integer vector compare into smaller ones.
14040   if (VT.is256BitVector() && !Subtarget->hasInt256())
14041     return Lower256IntVSETCC(Op, DAG);
14042
14043   EVT OpVT = Op1.getValueType();
14044   if (OpVT.getVectorElementType() == MVT::i1)
14045     return LowerBoolVSETCC_AVX512(Op, DAG);
14046
14047   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14048   if (Subtarget->hasAVX512()) {
14049     if (Op1.getValueType().is512BitVector() ||
14050         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14051         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14052       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14053
14054     // In AVX-512 architecture setcc returns mask with i1 elements,
14055     // But there is no compare instruction for i8 and i16 elements in KNL.
14056     // We are not talking about 512-bit operands in this case, these
14057     // types are illegal.
14058     if (MaskResult &&
14059         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14060          OpVT.getVectorElementType().getSizeInBits() >= 8))
14061       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14062                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14063   }
14064
14065   // We are handling one of the integer comparisons here.  Since SSE only has
14066   // GT and EQ comparisons for integer, swapping operands and multiple
14067   // operations may be required for some comparisons.
14068   unsigned Opc;
14069   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14070   bool Subus = false;
14071
14072   switch (SetCCOpcode) {
14073   default: llvm_unreachable("Unexpected SETCC condition");
14074   case ISD::SETNE:  Invert = true;
14075   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14076   case ISD::SETLT:  Swap = true;
14077   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14078   case ISD::SETGE:  Swap = true;
14079   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14080                     Invert = true; break;
14081   case ISD::SETULT: Swap = true;
14082   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14083                     FlipSigns = true; break;
14084   case ISD::SETUGE: Swap = true;
14085   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14086                     FlipSigns = true; Invert = true; break;
14087   }
14088
14089   // Special case: Use min/max operations for SETULE/SETUGE
14090   MVT VET = VT.getVectorElementType();
14091   bool hasMinMax =
14092        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14093     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14094
14095   if (hasMinMax) {
14096     switch (SetCCOpcode) {
14097     default: break;
14098     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14099     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14100     }
14101
14102     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14103   }
14104
14105   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14106   if (!MinMax && hasSubus) {
14107     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14108     // Op0 u<= Op1:
14109     //   t = psubus Op0, Op1
14110     //   pcmpeq t, <0..0>
14111     switch (SetCCOpcode) {
14112     default: break;
14113     case ISD::SETULT: {
14114       // If the comparison is against a constant we can turn this into a
14115       // setule.  With psubus, setule does not require a swap.  This is
14116       // beneficial because the constant in the register is no longer
14117       // destructed as the destination so it can be hoisted out of a loop.
14118       // Only do this pre-AVX since vpcmp* is no longer destructive.
14119       if (Subtarget->hasAVX())
14120         break;
14121       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14122       if (ULEOp1.getNode()) {
14123         Op1 = ULEOp1;
14124         Subus = true; Invert = false; Swap = false;
14125       }
14126       break;
14127     }
14128     // Psubus is better than flip-sign because it requires no inversion.
14129     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14130     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14131     }
14132
14133     if (Subus) {
14134       Opc = X86ISD::SUBUS;
14135       FlipSigns = false;
14136     }
14137   }
14138
14139   if (Swap)
14140     std::swap(Op0, Op1);
14141
14142   // Check that the operation in question is available (most are plain SSE2,
14143   // but PCMPGTQ and PCMPEQQ have different requirements).
14144   if (VT == MVT::v2i64) {
14145     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14146       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14147
14148       // First cast everything to the right type.
14149       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14150       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14151
14152       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14153       // bits of the inputs before performing those operations. The lower
14154       // compare is always unsigned.
14155       SDValue SB;
14156       if (FlipSigns) {
14157         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14158       } else {
14159         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14160         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14161         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14162                          Sign, Zero, Sign, Zero);
14163       }
14164       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14165       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14166
14167       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14168       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14169       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14170
14171       // Create masks for only the low parts/high parts of the 64 bit integers.
14172       static const int MaskHi[] = { 1, 1, 3, 3 };
14173       static const int MaskLo[] = { 0, 0, 2, 2 };
14174       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14175       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14176       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14177
14178       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14179       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14180
14181       if (Invert)
14182         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14183
14184       return DAG.getBitcast(VT, Result);
14185     }
14186
14187     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14188       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14189       // pcmpeqd + pshufd + pand.
14190       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14191
14192       // First cast everything to the right type.
14193       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14194       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14195
14196       // Do the compare.
14197       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14198
14199       // Make sure the lower and upper halves are both all-ones.
14200       static const int Mask[] = { 1, 0, 3, 2 };
14201       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14202       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14203
14204       if (Invert)
14205         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14206
14207       return DAG.getBitcast(VT, Result);
14208     }
14209   }
14210
14211   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14212   // bits of the inputs before performing those operations.
14213   if (FlipSigns) {
14214     EVT EltVT = VT.getVectorElementType();
14215     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14216                                  VT);
14217     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14218     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14219   }
14220
14221   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14222
14223   // If the logical-not of the result is required, perform that now.
14224   if (Invert)
14225     Result = DAG.getNOT(dl, Result, VT);
14226
14227   if (MinMax)
14228     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14229
14230   if (Subus)
14231     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14232                          getZeroVector(VT, Subtarget, DAG, dl));
14233
14234   return Result;
14235 }
14236
14237 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14238
14239   MVT VT = Op.getSimpleValueType();
14240
14241   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14242
14243   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14244          && "SetCC type must be 8-bit or 1-bit integer");
14245   SDValue Op0 = Op.getOperand(0);
14246   SDValue Op1 = Op.getOperand(1);
14247   SDLoc dl(Op);
14248   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14249
14250   // Optimize to BT if possible.
14251   // Lower (X & (1 << N)) == 0 to BT(X, N).
14252   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14253   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14254   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14255       Op1.getOpcode() == ISD::Constant &&
14256       cast<ConstantSDNode>(Op1)->isNullValue() &&
14257       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14258     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14259     if (NewSetCC.getNode()) {
14260       if (VT == MVT::i1)
14261         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14262       return NewSetCC;
14263     }
14264   }
14265
14266   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14267   // these.
14268   if (Op1.getOpcode() == ISD::Constant &&
14269       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14270        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14271       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14272
14273     // If the input is a setcc, then reuse the input setcc or use a new one with
14274     // the inverted condition.
14275     if (Op0.getOpcode() == X86ISD::SETCC) {
14276       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14277       bool Invert = (CC == ISD::SETNE) ^
14278         cast<ConstantSDNode>(Op1)->isNullValue();
14279       if (!Invert)
14280         return Op0;
14281
14282       CCode = X86::GetOppositeBranchCondition(CCode);
14283       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14284                                   DAG.getConstant(CCode, dl, MVT::i8),
14285                                   Op0.getOperand(1));
14286       if (VT == MVT::i1)
14287         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14288       return SetCC;
14289     }
14290   }
14291   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14292       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14293       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14294
14295     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14296     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14297   }
14298
14299   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14300   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14301   if (X86CC == X86::COND_INVALID)
14302     return SDValue();
14303
14304   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14305   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14306   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14307                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14308   if (VT == MVT::i1)
14309     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14310   return SetCC;
14311 }
14312
14313 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14314 static bool isX86LogicalCmp(SDValue Op) {
14315   unsigned Opc = Op.getNode()->getOpcode();
14316   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14317       Opc == X86ISD::SAHF)
14318     return true;
14319   if (Op.getResNo() == 1 &&
14320       (Opc == X86ISD::ADD ||
14321        Opc == X86ISD::SUB ||
14322        Opc == X86ISD::ADC ||
14323        Opc == X86ISD::SBB ||
14324        Opc == X86ISD::SMUL ||
14325        Opc == X86ISD::UMUL ||
14326        Opc == X86ISD::INC ||
14327        Opc == X86ISD::DEC ||
14328        Opc == X86ISD::OR ||
14329        Opc == X86ISD::XOR ||
14330        Opc == X86ISD::AND))
14331     return true;
14332
14333   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14334     return true;
14335
14336   return false;
14337 }
14338
14339 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14340   if (V.getOpcode() != ISD::TRUNCATE)
14341     return false;
14342
14343   SDValue VOp0 = V.getOperand(0);
14344   unsigned InBits = VOp0.getValueSizeInBits();
14345   unsigned Bits = V.getValueSizeInBits();
14346   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14347 }
14348
14349 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14350   bool addTest = true;
14351   SDValue Cond  = Op.getOperand(0);
14352   SDValue Op1 = Op.getOperand(1);
14353   SDValue Op2 = Op.getOperand(2);
14354   SDLoc DL(Op);
14355   EVT VT = Op1.getValueType();
14356   SDValue CC;
14357
14358   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14359   // are available or VBLENDV if AVX is available.
14360   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14361   if (Cond.getOpcode() == ISD::SETCC &&
14362       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14363        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14364       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14365     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14366     int SSECC = translateX86FSETCC(
14367         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14368
14369     if (SSECC != 8) {
14370       if (Subtarget->hasAVX512()) {
14371         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14372                                   DAG.getConstant(SSECC, DL, MVT::i8));
14373         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14374       }
14375
14376       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14377                                 DAG.getConstant(SSECC, DL, MVT::i8));
14378
14379       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14380       // of 3 logic instructions for size savings and potentially speed.
14381       // Unfortunately, there is no scalar form of VBLENDV.
14382
14383       // If either operand is a constant, don't try this. We can expect to
14384       // optimize away at least one of the logic instructions later in that
14385       // case, so that sequence would be faster than a variable blend.
14386
14387       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14388       // uses XMM0 as the selection register. That may need just as many
14389       // instructions as the AND/ANDN/OR sequence due to register moves, so
14390       // don't bother.
14391
14392       if (Subtarget->hasAVX() &&
14393           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14394
14395         // Convert to vectors, do a VSELECT, and convert back to scalar.
14396         // All of the conversions should be optimized away.
14397
14398         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14399         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14400         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14401         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14402
14403         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14404         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14405
14406         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14407
14408         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14409                            VSel, DAG.getIntPtrConstant(0, DL));
14410       }
14411       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14412       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14413       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14414     }
14415   }
14416
14417   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14418     SDValue Op1Scalar;
14419     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14420       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14421     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14422       Op1Scalar = Op1.getOperand(0);
14423     SDValue Op2Scalar;
14424     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14425       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14426     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14427       Op2Scalar = Op2.getOperand(0);
14428     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14429       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14430                                       Op1Scalar.getValueType(),
14431                                       Cond, Op1Scalar, Op2Scalar);
14432       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14433         return DAG.getBitcast(VT, newSelect);
14434       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14435       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14436                          DAG.getIntPtrConstant(0, DL));
14437     }
14438   }
14439
14440   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14441     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14442     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14443                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14444     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14445                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14446     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14447                                     Cond, Op1, Op2);
14448     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14449   }
14450
14451   if (Cond.getOpcode() == ISD::SETCC) {
14452     SDValue NewCond = LowerSETCC(Cond, DAG);
14453     if (NewCond.getNode())
14454       Cond = NewCond;
14455   }
14456
14457   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14458   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14459   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14460   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14461   if (Cond.getOpcode() == X86ISD::SETCC &&
14462       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14463       isZero(Cond.getOperand(1).getOperand(1))) {
14464     SDValue Cmp = Cond.getOperand(1);
14465
14466     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14467
14468     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14469         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14470       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14471
14472       SDValue CmpOp0 = Cmp.getOperand(0);
14473       // Apply further optimizations for special cases
14474       // (select (x != 0), -1, 0) -> neg & sbb
14475       // (select (x == 0), 0, -1) -> neg & sbb
14476       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14477         if (YC->isNullValue() &&
14478             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14479           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14480           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14481                                     DAG.getConstant(0, DL,
14482                                                     CmpOp0.getValueType()),
14483                                     CmpOp0);
14484           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14485                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14486                                     SDValue(Neg.getNode(), 1));
14487           return Res;
14488         }
14489
14490       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14491                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14492       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14493
14494       SDValue Res =   // Res = 0 or -1.
14495         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14496                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14497
14498       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14499         Res = DAG.getNOT(DL, Res, Res.getValueType());
14500
14501       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14502       if (!N2C || !N2C->isNullValue())
14503         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14504       return Res;
14505     }
14506   }
14507
14508   // Look past (and (setcc_carry (cmp ...)), 1).
14509   if (Cond.getOpcode() == ISD::AND &&
14510       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14511     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14512     if (C && C->getAPIntValue() == 1)
14513       Cond = Cond.getOperand(0);
14514   }
14515
14516   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14517   // setting operand in place of the X86ISD::SETCC.
14518   unsigned CondOpcode = Cond.getOpcode();
14519   if (CondOpcode == X86ISD::SETCC ||
14520       CondOpcode == X86ISD::SETCC_CARRY) {
14521     CC = Cond.getOperand(0);
14522
14523     SDValue Cmp = Cond.getOperand(1);
14524     unsigned Opc = Cmp.getOpcode();
14525     MVT VT = Op.getSimpleValueType();
14526
14527     bool IllegalFPCMov = false;
14528     if (VT.isFloatingPoint() && !VT.isVector() &&
14529         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14530       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14531
14532     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14533         Opc == X86ISD::BT) { // FIXME
14534       Cond = Cmp;
14535       addTest = false;
14536     }
14537   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14538              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14539              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14540               Cond.getOperand(0).getValueType() != MVT::i8)) {
14541     SDValue LHS = Cond.getOperand(0);
14542     SDValue RHS = Cond.getOperand(1);
14543     unsigned X86Opcode;
14544     unsigned X86Cond;
14545     SDVTList VTs;
14546     switch (CondOpcode) {
14547     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14548     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14549     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14550     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14551     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14552     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14553     default: llvm_unreachable("unexpected overflowing operator");
14554     }
14555     if (CondOpcode == ISD::UMULO)
14556       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14557                           MVT::i32);
14558     else
14559       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14560
14561     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14562
14563     if (CondOpcode == ISD::UMULO)
14564       Cond = X86Op.getValue(2);
14565     else
14566       Cond = X86Op.getValue(1);
14567
14568     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14569     addTest = false;
14570   }
14571
14572   if (addTest) {
14573     // Look past the truncate if the high bits are known zero.
14574     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14575       Cond = Cond.getOperand(0);
14576
14577     // We know the result of AND is compared against zero. Try to match
14578     // it to BT.
14579     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14580       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14581       if (NewSetCC.getNode()) {
14582         CC = NewSetCC.getOperand(0);
14583         Cond = NewSetCC.getOperand(1);
14584         addTest = false;
14585       }
14586     }
14587   }
14588
14589   if (addTest) {
14590     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14591     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14592   }
14593
14594   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14595   // a <  b ?  0 : -1 -> RES = setcc_carry
14596   // a >= b ? -1 :  0 -> RES = setcc_carry
14597   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14598   if (Cond.getOpcode() == X86ISD::SUB) {
14599     Cond = ConvertCmpIfNecessary(Cond, DAG);
14600     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14601
14602     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14603         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14604       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14605                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14606                                 Cond);
14607       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14608         return DAG.getNOT(DL, Res, Res.getValueType());
14609       return Res;
14610     }
14611   }
14612
14613   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14614   // widen the cmov and push the truncate through. This avoids introducing a new
14615   // branch during isel and doesn't add any extensions.
14616   if (Op.getValueType() == MVT::i8 &&
14617       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14618     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14619     if (T1.getValueType() == T2.getValueType() &&
14620         // Blacklist CopyFromReg to avoid partial register stalls.
14621         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14622       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14623       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14624       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14625     }
14626   }
14627
14628   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14629   // condition is true.
14630   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14631   SDValue Ops[] = { Op2, Op1, CC, Cond };
14632   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14633 }
14634
14635 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14636                                        const X86Subtarget *Subtarget,
14637                                        SelectionDAG &DAG) {
14638   MVT VT = Op->getSimpleValueType(0);
14639   SDValue In = Op->getOperand(0);
14640   MVT InVT = In.getSimpleValueType();
14641   MVT VTElt = VT.getVectorElementType();
14642   MVT InVTElt = InVT.getVectorElementType();
14643   SDLoc dl(Op);
14644
14645   // SKX processor
14646   if ((InVTElt == MVT::i1) &&
14647       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14648         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14649
14650        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14651         VTElt.getSizeInBits() <= 16)) ||
14652
14653        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14654         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14655
14656        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14657         VTElt.getSizeInBits() >= 32))))
14658     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14659
14660   unsigned int NumElts = VT.getVectorNumElements();
14661
14662   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14663     return SDValue();
14664
14665   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14666     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14667       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14668     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14669   }
14670
14671   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14672   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14673   SDValue NegOne =
14674    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14675                    ExtVT);
14676   SDValue Zero =
14677    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14678
14679   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14680   if (VT.is512BitVector())
14681     return V;
14682   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14683 }
14684
14685 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14686                                              const X86Subtarget *Subtarget,
14687                                              SelectionDAG &DAG) {
14688   SDValue In = Op->getOperand(0);
14689   MVT VT = Op->getSimpleValueType(0);
14690   MVT InVT = In.getSimpleValueType();
14691   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14692
14693   MVT InSVT = InVT.getScalarType();
14694   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14695
14696   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14697     return SDValue();
14698   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14699     return SDValue();
14700
14701   SDLoc dl(Op);
14702
14703   // SSE41 targets can use the pmovsx* instructions directly.
14704   if (Subtarget->hasSSE41())
14705     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14706
14707   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14708   SDValue Curr = In;
14709   MVT CurrVT = InVT;
14710
14711   // As SRAI is only available on i16/i32 types, we expand only up to i32
14712   // and handle i64 separately.
14713   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14714     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14715     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14716     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14717     Curr = DAG.getBitcast(CurrVT, Curr);
14718   }
14719
14720   SDValue SignExt = Curr;
14721   if (CurrVT != InVT) {
14722     unsigned SignExtShift =
14723         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14724     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14725                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14726   }
14727
14728   if (CurrVT == VT)
14729     return SignExt;
14730
14731   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14732     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14733                                DAG.getConstant(31, dl, MVT::i8));
14734     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14735     return DAG.getBitcast(VT, Ext);
14736   }
14737
14738   return SDValue();
14739 }
14740
14741 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14742                                 SelectionDAG &DAG) {
14743   MVT VT = Op->getSimpleValueType(0);
14744   SDValue In = Op->getOperand(0);
14745   MVT InVT = In.getSimpleValueType();
14746   SDLoc dl(Op);
14747
14748   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14749     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14750
14751   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14752       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14753       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14754     return SDValue();
14755
14756   if (Subtarget->hasInt256())
14757     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14758
14759   // Optimize vectors in AVX mode
14760   // Sign extend  v8i16 to v8i32 and
14761   //              v4i32 to v4i64
14762   //
14763   // Divide input vector into two parts
14764   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14765   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14766   // concat the vectors to original VT
14767
14768   unsigned NumElems = InVT.getVectorNumElements();
14769   SDValue Undef = DAG.getUNDEF(InVT);
14770
14771   SmallVector<int,8> ShufMask1(NumElems, -1);
14772   for (unsigned i = 0; i != NumElems/2; ++i)
14773     ShufMask1[i] = i;
14774
14775   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14776
14777   SmallVector<int,8> ShufMask2(NumElems, -1);
14778   for (unsigned i = 0; i != NumElems/2; ++i)
14779     ShufMask2[i] = i + NumElems/2;
14780
14781   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14782
14783   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14784                                 VT.getVectorNumElements()/2);
14785
14786   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14787   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14788
14789   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14790 }
14791
14792 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14793 // may emit an illegal shuffle but the expansion is still better than scalar
14794 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14795 // we'll emit a shuffle and a arithmetic shift.
14796 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14797 // TODO: It is possible to support ZExt by zeroing the undef values during
14798 // the shuffle phase or after the shuffle.
14799 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14800                                  SelectionDAG &DAG) {
14801   MVT RegVT = Op.getSimpleValueType();
14802   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14803   assert(RegVT.isInteger() &&
14804          "We only custom lower integer vector sext loads.");
14805
14806   // Nothing useful we can do without SSE2 shuffles.
14807   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14808
14809   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14810   SDLoc dl(Ld);
14811   EVT MemVT = Ld->getMemoryVT();
14812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14813   unsigned RegSz = RegVT.getSizeInBits();
14814
14815   ISD::LoadExtType Ext = Ld->getExtensionType();
14816
14817   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14818          && "Only anyext and sext are currently implemented.");
14819   assert(MemVT != RegVT && "Cannot extend to the same type");
14820   assert(MemVT.isVector() && "Must load a vector from memory");
14821
14822   unsigned NumElems = RegVT.getVectorNumElements();
14823   unsigned MemSz = MemVT.getSizeInBits();
14824   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14825
14826   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14827     // The only way in which we have a legal 256-bit vector result but not the
14828     // integer 256-bit operations needed to directly lower a sextload is if we
14829     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14830     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14831     // correctly legalized. We do this late to allow the canonical form of
14832     // sextload to persist throughout the rest of the DAG combiner -- it wants
14833     // to fold together any extensions it can, and so will fuse a sign_extend
14834     // of an sextload into a sextload targeting a wider value.
14835     SDValue Load;
14836     if (MemSz == 128) {
14837       // Just switch this to a normal load.
14838       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14839                                        "it must be a legal 128-bit vector "
14840                                        "type!");
14841       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14842                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14843                   Ld->isInvariant(), Ld->getAlignment());
14844     } else {
14845       assert(MemSz < 128 &&
14846              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14847       // Do an sext load to a 128-bit vector type. We want to use the same
14848       // number of elements, but elements half as wide. This will end up being
14849       // recursively lowered by this routine, but will succeed as we definitely
14850       // have all the necessary features if we're using AVX1.
14851       EVT HalfEltVT =
14852           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14853       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14854       Load =
14855           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14856                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14857                          Ld->isNonTemporal(), Ld->isInvariant(),
14858                          Ld->getAlignment());
14859     }
14860
14861     // Replace chain users with the new chain.
14862     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14863     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14864
14865     // Finally, do a normal sign-extend to the desired register.
14866     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14867   }
14868
14869   // All sizes must be a power of two.
14870   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14871          "Non-power-of-two elements are not custom lowered!");
14872
14873   // Attempt to load the original value using scalar loads.
14874   // Find the largest scalar type that divides the total loaded size.
14875   MVT SclrLoadTy = MVT::i8;
14876   for (MVT Tp : MVT::integer_valuetypes()) {
14877     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14878       SclrLoadTy = Tp;
14879     }
14880   }
14881
14882   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14883   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14884       (64 <= MemSz))
14885     SclrLoadTy = MVT::f64;
14886
14887   // Calculate the number of scalar loads that we need to perform
14888   // in order to load our vector from memory.
14889   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14890
14891   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14892          "Can only lower sext loads with a single scalar load!");
14893
14894   unsigned loadRegZize = RegSz;
14895   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14896     loadRegZize = 128;
14897
14898   // Represent our vector as a sequence of elements which are the
14899   // largest scalar that we can load.
14900   EVT LoadUnitVecVT = EVT::getVectorVT(
14901       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14902
14903   // Represent the data using the same element type that is stored in
14904   // memory. In practice, we ''widen'' MemVT.
14905   EVT WideVecVT =
14906       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14907                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14908
14909   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14910          "Invalid vector type");
14911
14912   // We can't shuffle using an illegal type.
14913   assert(TLI.isTypeLegal(WideVecVT) &&
14914          "We only lower types that form legal widened vector types");
14915
14916   SmallVector<SDValue, 8> Chains;
14917   SDValue Ptr = Ld->getBasePtr();
14918   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14919                                       TLI.getPointerTy(DAG.getDataLayout()));
14920   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14921
14922   for (unsigned i = 0; i < NumLoads; ++i) {
14923     // Perform a single load.
14924     SDValue ScalarLoad =
14925         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14926                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14927                     Ld->getAlignment());
14928     Chains.push_back(ScalarLoad.getValue(1));
14929     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14930     // another round of DAGCombining.
14931     if (i == 0)
14932       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14933     else
14934       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14935                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14936
14937     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14938   }
14939
14940   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14941
14942   // Bitcast the loaded value to a vector of the original element type, in
14943   // the size of the target vector type.
14944   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14945   unsigned SizeRatio = RegSz / MemSz;
14946
14947   if (Ext == ISD::SEXTLOAD) {
14948     // If we have SSE4.1, we can directly emit a VSEXT node.
14949     if (Subtarget->hasSSE41()) {
14950       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14951       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14952       return Sext;
14953     }
14954
14955     // Otherwise we'll shuffle the small elements in the high bits of the
14956     // larger type and perform an arithmetic shift. If the shift is not legal
14957     // it's better to scalarize.
14958     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14959            "We can't implement a sext load without an arithmetic right shift!");
14960
14961     // Redistribute the loaded elements into the different locations.
14962     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14963     for (unsigned i = 0; i != NumElems; ++i)
14964       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14965
14966     SDValue Shuff = DAG.getVectorShuffle(
14967         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14968
14969     Shuff = DAG.getBitcast(RegVT, Shuff);
14970
14971     // Build the arithmetic shift.
14972     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14973                    MemVT.getVectorElementType().getSizeInBits();
14974     Shuff =
14975         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14976                     DAG.getConstant(Amt, dl, RegVT));
14977
14978     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14979     return Shuff;
14980   }
14981
14982   // Redistribute the loaded elements into the different locations.
14983   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14984   for (unsigned i = 0; i != NumElems; ++i)
14985     ShuffleVec[i * SizeRatio] = i;
14986
14987   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14988                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14989
14990   // Bitcast to the requested type.
14991   Shuff = DAG.getBitcast(RegVT, Shuff);
14992   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14993   return Shuff;
14994 }
14995
14996 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14997 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14998 // from the AND / OR.
14999 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15000   Opc = Op.getOpcode();
15001   if (Opc != ISD::OR && Opc != ISD::AND)
15002     return false;
15003   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15004           Op.getOperand(0).hasOneUse() &&
15005           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15006           Op.getOperand(1).hasOneUse());
15007 }
15008
15009 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15010 // 1 and that the SETCC node has a single use.
15011 static bool isXor1OfSetCC(SDValue Op) {
15012   if (Op.getOpcode() != ISD::XOR)
15013     return false;
15014   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15015   if (N1C && N1C->getAPIntValue() == 1) {
15016     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15017       Op.getOperand(0).hasOneUse();
15018   }
15019   return false;
15020 }
15021
15022 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15023   bool addTest = true;
15024   SDValue Chain = Op.getOperand(0);
15025   SDValue Cond  = Op.getOperand(1);
15026   SDValue Dest  = Op.getOperand(2);
15027   SDLoc dl(Op);
15028   SDValue CC;
15029   bool Inverted = false;
15030
15031   if (Cond.getOpcode() == ISD::SETCC) {
15032     // Check for setcc([su]{add,sub,mul}o == 0).
15033     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15034         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15035         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15036         Cond.getOperand(0).getResNo() == 1 &&
15037         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15038          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15039          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15040          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15041          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15042          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15043       Inverted = true;
15044       Cond = Cond.getOperand(0);
15045     } else {
15046       SDValue NewCond = LowerSETCC(Cond, DAG);
15047       if (NewCond.getNode())
15048         Cond = NewCond;
15049     }
15050   }
15051 #if 0
15052   // FIXME: LowerXALUO doesn't handle these!!
15053   else if (Cond.getOpcode() == X86ISD::ADD  ||
15054            Cond.getOpcode() == X86ISD::SUB  ||
15055            Cond.getOpcode() == X86ISD::SMUL ||
15056            Cond.getOpcode() == X86ISD::UMUL)
15057     Cond = LowerXALUO(Cond, DAG);
15058 #endif
15059
15060   // Look pass (and (setcc_carry (cmp ...)), 1).
15061   if (Cond.getOpcode() == ISD::AND &&
15062       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15063     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15064     if (C && C->getAPIntValue() == 1)
15065       Cond = Cond.getOperand(0);
15066   }
15067
15068   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15069   // setting operand in place of the X86ISD::SETCC.
15070   unsigned CondOpcode = Cond.getOpcode();
15071   if (CondOpcode == X86ISD::SETCC ||
15072       CondOpcode == X86ISD::SETCC_CARRY) {
15073     CC = Cond.getOperand(0);
15074
15075     SDValue Cmp = Cond.getOperand(1);
15076     unsigned Opc = Cmp.getOpcode();
15077     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15078     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15079       Cond = Cmp;
15080       addTest = false;
15081     } else {
15082       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15083       default: break;
15084       case X86::COND_O:
15085       case X86::COND_B:
15086         // These can only come from an arithmetic instruction with overflow,
15087         // e.g. SADDO, UADDO.
15088         Cond = Cond.getNode()->getOperand(1);
15089         addTest = false;
15090         break;
15091       }
15092     }
15093   }
15094   CondOpcode = Cond.getOpcode();
15095   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15096       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15097       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15098        Cond.getOperand(0).getValueType() != MVT::i8)) {
15099     SDValue LHS = Cond.getOperand(0);
15100     SDValue RHS = Cond.getOperand(1);
15101     unsigned X86Opcode;
15102     unsigned X86Cond;
15103     SDVTList VTs;
15104     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15105     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15106     // X86ISD::INC).
15107     switch (CondOpcode) {
15108     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15109     case ISD::SADDO:
15110       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15111         if (C->isOne()) {
15112           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15113           break;
15114         }
15115       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15116     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15117     case ISD::SSUBO:
15118       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15119         if (C->isOne()) {
15120           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15121           break;
15122         }
15123       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15124     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15125     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15126     default: llvm_unreachable("unexpected overflowing operator");
15127     }
15128     if (Inverted)
15129       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15130     if (CondOpcode == ISD::UMULO)
15131       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15132                           MVT::i32);
15133     else
15134       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15135
15136     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15137
15138     if (CondOpcode == ISD::UMULO)
15139       Cond = X86Op.getValue(2);
15140     else
15141       Cond = X86Op.getValue(1);
15142
15143     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15144     addTest = false;
15145   } else {
15146     unsigned CondOpc;
15147     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15148       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15149       if (CondOpc == ISD::OR) {
15150         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15151         // two branches instead of an explicit OR instruction with a
15152         // separate test.
15153         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15154             isX86LogicalCmp(Cmp)) {
15155           CC = Cond.getOperand(0).getOperand(0);
15156           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15157                               Chain, Dest, CC, Cmp);
15158           CC = Cond.getOperand(1).getOperand(0);
15159           Cond = Cmp;
15160           addTest = false;
15161         }
15162       } else { // ISD::AND
15163         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15164         // two branches instead of an explicit AND instruction with a
15165         // separate test. However, we only do this if this block doesn't
15166         // have a fall-through edge, because this requires an explicit
15167         // jmp when the condition is false.
15168         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15169             isX86LogicalCmp(Cmp) &&
15170             Op.getNode()->hasOneUse()) {
15171           X86::CondCode CCode =
15172             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15173           CCode = X86::GetOppositeBranchCondition(CCode);
15174           CC = DAG.getConstant(CCode, dl, MVT::i8);
15175           SDNode *User = *Op.getNode()->use_begin();
15176           // Look for an unconditional branch following this conditional branch.
15177           // We need this because we need to reverse the successors in order
15178           // to implement FCMP_OEQ.
15179           if (User->getOpcode() == ISD::BR) {
15180             SDValue FalseBB = User->getOperand(1);
15181             SDNode *NewBR =
15182               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15183             assert(NewBR == User);
15184             (void)NewBR;
15185             Dest = FalseBB;
15186
15187             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15188                                 Chain, Dest, CC, Cmp);
15189             X86::CondCode CCode =
15190               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15191             CCode = X86::GetOppositeBranchCondition(CCode);
15192             CC = DAG.getConstant(CCode, dl, MVT::i8);
15193             Cond = Cmp;
15194             addTest = false;
15195           }
15196         }
15197       }
15198     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15199       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15200       // It should be transformed during dag combiner except when the condition
15201       // is set by a arithmetics with overflow node.
15202       X86::CondCode CCode =
15203         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15204       CCode = X86::GetOppositeBranchCondition(CCode);
15205       CC = DAG.getConstant(CCode, dl, MVT::i8);
15206       Cond = Cond.getOperand(0).getOperand(1);
15207       addTest = false;
15208     } else if (Cond.getOpcode() == ISD::SETCC &&
15209                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15210       // For FCMP_OEQ, we can emit
15211       // two branches instead of an explicit AND instruction with a
15212       // separate test. However, we only do this if this block doesn't
15213       // have a fall-through edge, because this requires an explicit
15214       // jmp when the condition is false.
15215       if (Op.getNode()->hasOneUse()) {
15216         SDNode *User = *Op.getNode()->use_begin();
15217         // Look for an unconditional branch following this conditional branch.
15218         // We need this because we need to reverse the successors in order
15219         // to implement FCMP_OEQ.
15220         if (User->getOpcode() == ISD::BR) {
15221           SDValue FalseBB = User->getOperand(1);
15222           SDNode *NewBR =
15223             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15224           assert(NewBR == User);
15225           (void)NewBR;
15226           Dest = FalseBB;
15227
15228           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15229                                     Cond.getOperand(0), Cond.getOperand(1));
15230           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15231           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15232           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15233                               Chain, Dest, CC, Cmp);
15234           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15235           Cond = Cmp;
15236           addTest = false;
15237         }
15238       }
15239     } else if (Cond.getOpcode() == ISD::SETCC &&
15240                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15241       // For FCMP_UNE, we can emit
15242       // two branches instead of an explicit AND instruction with a
15243       // separate test. However, we only do this if this block doesn't
15244       // have a fall-through edge, because this requires an explicit
15245       // jmp when the condition is false.
15246       if (Op.getNode()->hasOneUse()) {
15247         SDNode *User = *Op.getNode()->use_begin();
15248         // Look for an unconditional branch following this conditional branch.
15249         // We need this because we need to reverse the successors in order
15250         // to implement FCMP_UNE.
15251         if (User->getOpcode() == ISD::BR) {
15252           SDValue FalseBB = User->getOperand(1);
15253           SDNode *NewBR =
15254             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15255           assert(NewBR == User);
15256           (void)NewBR;
15257
15258           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15259                                     Cond.getOperand(0), Cond.getOperand(1));
15260           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15261           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15262           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15263                               Chain, Dest, CC, Cmp);
15264           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15265           Cond = Cmp;
15266           addTest = false;
15267           Dest = FalseBB;
15268         }
15269       }
15270     }
15271   }
15272
15273   if (addTest) {
15274     // Look pass the truncate if the high bits are known zero.
15275     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15276         Cond = Cond.getOperand(0);
15277
15278     // We know the result of AND is compared against zero. Try to match
15279     // it to BT.
15280     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15281       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15282       if (NewSetCC.getNode()) {
15283         CC = NewSetCC.getOperand(0);
15284         Cond = NewSetCC.getOperand(1);
15285         addTest = false;
15286       }
15287     }
15288   }
15289
15290   if (addTest) {
15291     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15292     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15293     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15294   }
15295   Cond = ConvertCmpIfNecessary(Cond, DAG);
15296   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15297                      Chain, Dest, CC, Cond);
15298 }
15299
15300 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15301 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15302 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15303 // that the guard pages used by the OS virtual memory manager are allocated in
15304 // correct sequence.
15305 SDValue
15306 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15307                                            SelectionDAG &DAG) const {
15308   MachineFunction &MF = DAG.getMachineFunction();
15309   bool SplitStack = MF.shouldSplitStack();
15310   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15311                SplitStack;
15312   SDLoc dl(Op);
15313
15314   if (!Lower) {
15315     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15316     SDNode* Node = Op.getNode();
15317
15318     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15319     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15320         " not tell us which reg is the stack pointer!");
15321     EVT VT = Node->getValueType(0);
15322     SDValue Tmp1 = SDValue(Node, 0);
15323     SDValue Tmp2 = SDValue(Node, 1);
15324     SDValue Tmp3 = Node->getOperand(2);
15325     SDValue Chain = Tmp1.getOperand(0);
15326
15327     // Chain the dynamic stack allocation so that it doesn't modify the stack
15328     // pointer when other instructions are using the stack.
15329     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15330         SDLoc(Node));
15331
15332     SDValue Size = Tmp2.getOperand(1);
15333     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15334     Chain = SP.getValue(1);
15335     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15336     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15337     unsigned StackAlign = TFI.getStackAlignment();
15338     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15339     if (Align > StackAlign)
15340       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15341           DAG.getConstant(-(uint64_t)Align, dl, VT));
15342     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15343
15344     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15345         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15346         SDLoc(Node));
15347
15348     SDValue Ops[2] = { Tmp1, Tmp2 };
15349     return DAG.getMergeValues(Ops, dl);
15350   }
15351
15352   // Get the inputs.
15353   SDValue Chain = Op.getOperand(0);
15354   SDValue Size  = Op.getOperand(1);
15355   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15356   EVT VT = Op.getNode()->getValueType(0);
15357
15358   bool Is64Bit = Subtarget->is64Bit();
15359   MVT SPTy = getPointerTy(DAG.getDataLayout());
15360
15361   if (SplitStack) {
15362     MachineRegisterInfo &MRI = MF.getRegInfo();
15363
15364     if (Is64Bit) {
15365       // The 64 bit implementation of segmented stacks needs to clobber both r10
15366       // r11. This makes it impossible to use it along with nested parameters.
15367       const Function *F = MF.getFunction();
15368
15369       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15370            I != E; ++I)
15371         if (I->hasNestAttr())
15372           report_fatal_error("Cannot use segmented stacks with functions that "
15373                              "have nested arguments.");
15374     }
15375
15376     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15377     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15378     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15379     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15380                                 DAG.getRegister(Vreg, SPTy));
15381     SDValue Ops1[2] = { Value, Chain };
15382     return DAG.getMergeValues(Ops1, dl);
15383   } else {
15384     SDValue Flag;
15385     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15386
15387     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15388     Flag = Chain.getValue(1);
15389     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15390
15391     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15392
15393     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15394     unsigned SPReg = RegInfo->getStackRegister();
15395     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15396     Chain = SP.getValue(1);
15397
15398     if (Align) {
15399       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15400                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15401       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15402     }
15403
15404     SDValue Ops1[2] = { SP, Chain };
15405     return DAG.getMergeValues(Ops1, dl);
15406   }
15407 }
15408
15409 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15410   MachineFunction &MF = DAG.getMachineFunction();
15411   auto PtrVT = getPointerTy(MF.getDataLayout());
15412   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15413
15414   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15415   SDLoc DL(Op);
15416
15417   if (!Subtarget->is64Bit() ||
15418       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15419     // vastart just stores the address of the VarArgsFrameIndex slot into the
15420     // memory location argument.
15421     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15422     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15423                         MachinePointerInfo(SV), false, false, 0);
15424   }
15425
15426   // __va_list_tag:
15427   //   gp_offset         (0 - 6 * 8)
15428   //   fp_offset         (48 - 48 + 8 * 16)
15429   //   overflow_arg_area (point to parameters coming in memory).
15430   //   reg_save_area
15431   SmallVector<SDValue, 8> MemOps;
15432   SDValue FIN = Op.getOperand(1);
15433   // Store gp_offset
15434   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15435                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15436                                                DL, MVT::i32),
15437                                FIN, MachinePointerInfo(SV), false, false, 0);
15438   MemOps.push_back(Store);
15439
15440   // Store fp_offset
15441   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15442   Store = DAG.getStore(Op.getOperand(0), DL,
15443                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15444                                        MVT::i32),
15445                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15446   MemOps.push_back(Store);
15447
15448   // Store ptr to overflow_arg_area
15449   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15450   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15451   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15452                        MachinePointerInfo(SV, 8),
15453                        false, false, 0);
15454   MemOps.push_back(Store);
15455
15456   // Store ptr to reg_save_area.
15457   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15458       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15459   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15460   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15461       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15462   MemOps.push_back(Store);
15463   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15464 }
15465
15466 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15467   assert(Subtarget->is64Bit() &&
15468          "LowerVAARG only handles 64-bit va_arg!");
15469   assert(Op.getNode()->getNumOperands() == 4);
15470
15471   MachineFunction &MF = DAG.getMachineFunction();
15472   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15473     // The Win64 ABI uses char* instead of a structure.
15474     return DAG.expandVAArg(Op.getNode());
15475
15476   SDValue Chain = Op.getOperand(0);
15477   SDValue SrcPtr = Op.getOperand(1);
15478   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15479   unsigned Align = Op.getConstantOperandVal(3);
15480   SDLoc dl(Op);
15481
15482   EVT ArgVT = Op.getNode()->getValueType(0);
15483   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15484   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15485   uint8_t ArgMode;
15486
15487   // Decide which area this value should be read from.
15488   // TODO: Implement the AMD64 ABI in its entirety. This simple
15489   // selection mechanism works only for the basic types.
15490   if (ArgVT == MVT::f80) {
15491     llvm_unreachable("va_arg for f80 not yet implemented");
15492   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15493     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15494   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15495     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15496   } else {
15497     llvm_unreachable("Unhandled argument type in LowerVAARG");
15498   }
15499
15500   if (ArgMode == 2) {
15501     // Sanity Check: Make sure using fp_offset makes sense.
15502     assert(!Subtarget->useSoftFloat() &&
15503            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15504            Subtarget->hasSSE1());
15505   }
15506
15507   // Insert VAARG_64 node into the DAG
15508   // VAARG_64 returns two values: Variable Argument Address, Chain
15509   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15510                        DAG.getConstant(ArgMode, dl, MVT::i8),
15511                        DAG.getConstant(Align, dl, MVT::i32)};
15512   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15513   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15514                                           VTs, InstOps, MVT::i64,
15515                                           MachinePointerInfo(SV),
15516                                           /*Align=*/0,
15517                                           /*Volatile=*/false,
15518                                           /*ReadMem=*/true,
15519                                           /*WriteMem=*/true);
15520   Chain = VAARG.getValue(1);
15521
15522   // Load the next argument and return it
15523   return DAG.getLoad(ArgVT, dl,
15524                      Chain,
15525                      VAARG,
15526                      MachinePointerInfo(),
15527                      false, false, false, 0);
15528 }
15529
15530 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15531                            SelectionDAG &DAG) {
15532   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15533   // where a va_list is still an i8*.
15534   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15535   if (Subtarget->isCallingConvWin64(
15536         DAG.getMachineFunction().getFunction()->getCallingConv()))
15537     // Probably a Win64 va_copy.
15538     return DAG.expandVACopy(Op.getNode());
15539
15540   SDValue Chain = Op.getOperand(0);
15541   SDValue DstPtr = Op.getOperand(1);
15542   SDValue SrcPtr = Op.getOperand(2);
15543   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15544   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15545   SDLoc DL(Op);
15546
15547   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15548                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15549                        false, false,
15550                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15551 }
15552
15553 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15554 // amount is a constant. Takes immediate version of shift as input.
15555 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15556                                           SDValue SrcOp, uint64_t ShiftAmt,
15557                                           SelectionDAG &DAG) {
15558   MVT ElementType = VT.getVectorElementType();
15559
15560   // Fold this packed shift into its first operand if ShiftAmt is 0.
15561   if (ShiftAmt == 0)
15562     return SrcOp;
15563
15564   // Check for ShiftAmt >= element width
15565   if (ShiftAmt >= ElementType.getSizeInBits()) {
15566     if (Opc == X86ISD::VSRAI)
15567       ShiftAmt = ElementType.getSizeInBits() - 1;
15568     else
15569       return DAG.getConstant(0, dl, VT);
15570   }
15571
15572   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15573          && "Unknown target vector shift-by-constant node");
15574
15575   // Fold this packed vector shift into a build vector if SrcOp is a
15576   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15577   if (VT == SrcOp.getSimpleValueType() &&
15578       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15579     SmallVector<SDValue, 8> Elts;
15580     unsigned NumElts = SrcOp->getNumOperands();
15581     ConstantSDNode *ND;
15582
15583     switch(Opc) {
15584     default: llvm_unreachable(nullptr);
15585     case X86ISD::VSHLI:
15586       for (unsigned i=0; i!=NumElts; ++i) {
15587         SDValue CurrentOp = SrcOp->getOperand(i);
15588         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15589           Elts.push_back(CurrentOp);
15590           continue;
15591         }
15592         ND = cast<ConstantSDNode>(CurrentOp);
15593         const APInt &C = ND->getAPIntValue();
15594         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15595       }
15596       break;
15597     case X86ISD::VSRLI:
15598       for (unsigned i=0; i!=NumElts; ++i) {
15599         SDValue CurrentOp = SrcOp->getOperand(i);
15600         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15601           Elts.push_back(CurrentOp);
15602           continue;
15603         }
15604         ND = cast<ConstantSDNode>(CurrentOp);
15605         const APInt &C = ND->getAPIntValue();
15606         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15607       }
15608       break;
15609     case X86ISD::VSRAI:
15610       for (unsigned i=0; i!=NumElts; ++i) {
15611         SDValue CurrentOp = SrcOp->getOperand(i);
15612         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15613           Elts.push_back(CurrentOp);
15614           continue;
15615         }
15616         ND = cast<ConstantSDNode>(CurrentOp);
15617         const APInt &C = ND->getAPIntValue();
15618         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15619       }
15620       break;
15621     }
15622
15623     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15624   }
15625
15626   return DAG.getNode(Opc, dl, VT, SrcOp,
15627                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15628 }
15629
15630 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15631 // may or may not be a constant. Takes immediate version of shift as input.
15632 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15633                                    SDValue SrcOp, SDValue ShAmt,
15634                                    SelectionDAG &DAG) {
15635   MVT SVT = ShAmt.getSimpleValueType();
15636   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15637
15638   // Catch shift-by-constant.
15639   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15640     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15641                                       CShAmt->getZExtValue(), DAG);
15642
15643   // Change opcode to non-immediate version
15644   switch (Opc) {
15645     default: llvm_unreachable("Unknown target vector shift node");
15646     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15647     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15648     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15649   }
15650
15651   const X86Subtarget &Subtarget =
15652       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15653   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15654       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15655     // Let the shuffle legalizer expand this shift amount node.
15656     SDValue Op0 = ShAmt.getOperand(0);
15657     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15658     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15659   } else {
15660     // Need to build a vector containing shift amount.
15661     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15662     SmallVector<SDValue, 4> ShOps;
15663     ShOps.push_back(ShAmt);
15664     if (SVT == MVT::i32) {
15665       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15666       ShOps.push_back(DAG.getUNDEF(SVT));
15667     }
15668     ShOps.push_back(DAG.getUNDEF(SVT));
15669
15670     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15671     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15672   }
15673
15674   // The return type has to be a 128-bit type with the same element
15675   // type as the input type.
15676   MVT EltVT = VT.getVectorElementType();
15677   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15678
15679   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15680   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15681 }
15682
15683 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15684 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15685 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15686 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15687                                     SDValue PreservedSrc,
15688                                     const X86Subtarget *Subtarget,
15689                                     SelectionDAG &DAG) {
15690     EVT VT = Op.getValueType();
15691     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15692                                   MVT::i1, VT.getVectorNumElements());
15693     SDValue VMask = SDValue();
15694     unsigned OpcodeSelect = ISD::VSELECT;
15695     SDLoc dl(Op);
15696
15697     assert(MaskVT.isSimple() && "invalid mask type");
15698
15699     if (isAllOnes(Mask))
15700       return Op;
15701
15702     if (MaskVT.bitsGT(Mask.getValueType())) {
15703       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15704                                          MaskVT.getSizeInBits());
15705       VMask = DAG.getBitcast(MaskVT,
15706                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15707     } else {
15708       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15709                                        Mask.getValueType().getSizeInBits());
15710       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15711       // are extracted by EXTRACT_SUBVECTOR.
15712       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15713                           DAG.getBitcast(BitcastVT, Mask),
15714                           DAG.getIntPtrConstant(0, dl));
15715     }
15716
15717     switch (Op.getOpcode()) {
15718       default: break;
15719       case X86ISD::PCMPEQM:
15720       case X86ISD::PCMPGTM:
15721       case X86ISD::CMPM:
15722       case X86ISD::CMPMU:
15723         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15724       case X86ISD::VTRUNC:
15725       case X86ISD::VTRUNCS:
15726       case X86ISD::VTRUNCUS:
15727         // We can't use ISD::VSELECT here because it is not always "Legal"
15728         // for the destination type. For example vpmovqb require only AVX512
15729         // and vselect that can operate on byte element type require BWI
15730         OpcodeSelect = X86ISD::SELECT;
15731         break;
15732     }
15733     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15734       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15735     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15736 }
15737
15738 /// \brief Creates an SDNode for a predicated scalar operation.
15739 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15740 /// The mask is coming as MVT::i8 and it should be truncated
15741 /// to MVT::i1 while lowering masking intrinsics.
15742 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15743 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15744 /// for a scalar instruction.
15745 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15746                                     SDValue PreservedSrc,
15747                                     const X86Subtarget *Subtarget,
15748                                     SelectionDAG &DAG) {
15749     if (isAllOnes(Mask))
15750       return Op;
15751
15752     EVT VT = Op.getValueType();
15753     SDLoc dl(Op);
15754     // The mask should be of type MVT::i1
15755     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15756
15757     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15758       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15759     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15760 }
15761
15762 static int getSEHRegistrationNodeSize(const Function *Fn) {
15763   if (!Fn->hasPersonalityFn())
15764     report_fatal_error(
15765         "querying registration node size for function without personality");
15766   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15767   // WinEHStatePass for the full struct definition.
15768   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15769   case EHPersonality::MSVC_X86SEH: return 24;
15770   case EHPersonality::MSVC_CXX: return 16;
15771   default: break;
15772   }
15773   report_fatal_error("can only recover FP for MSVC EH personality functions");
15774 }
15775
15776 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15777 /// function or when returning to a parent frame after catching an exception, we
15778 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15779 /// Here's the math:
15780 ///   RegNodeBase = EntryEBP - RegNodeSize
15781 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15782 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15783 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15784 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15785                                    SDValue EntryEBP) {
15786   MachineFunction &MF = DAG.getMachineFunction();
15787   SDLoc dl;
15788
15789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15790   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15791
15792   // It's possible that the parent function no longer has a personality function
15793   // if the exceptional code was optimized away, in which case we just return
15794   // the incoming EBP.
15795   if (!Fn->hasPersonalityFn())
15796     return EntryEBP;
15797
15798   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15799
15800   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15801   // registration.
15802   MCSymbol *OffsetSym =
15803       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15804           GlobalValue::getRealLinkageName(Fn->getName()));
15805   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15806   SDValue RegNodeFrameOffset =
15807       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15808
15809   // RegNodeBase = EntryEBP - RegNodeSize
15810   // ParentFP = RegNodeBase - RegNodeFrameOffset
15811   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15812                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15813   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15814 }
15815
15816 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15817                                        SelectionDAG &DAG) {
15818   SDLoc dl(Op);
15819   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15820   EVT VT = Op.getValueType();
15821   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15822   if (IntrData) {
15823     switch(IntrData->Type) {
15824     case INTR_TYPE_1OP:
15825       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15826     case INTR_TYPE_2OP:
15827       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15828         Op.getOperand(2));
15829     case INTR_TYPE_2OP_IMM8:
15830       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15831                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15832     case INTR_TYPE_3OP:
15833       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15834         Op.getOperand(2), Op.getOperand(3));
15835     case INTR_TYPE_4OP:
15836       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15837         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15838     case INTR_TYPE_1OP_MASK_RM: {
15839       SDValue Src = Op.getOperand(1);
15840       SDValue PassThru = Op.getOperand(2);
15841       SDValue Mask = Op.getOperand(3);
15842       SDValue RoundingMode;
15843       // We allways add rounding mode to the Node.
15844       // If the rounding mode is not specified, we add the
15845       // "current direction" mode.
15846       if (Op.getNumOperands() == 4)
15847         RoundingMode =
15848           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15849       else
15850         RoundingMode = Op.getOperand(4);
15851       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15852       if (IntrWithRoundingModeOpcode != 0)
15853         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15854             X86::STATIC_ROUNDING::CUR_DIRECTION)
15855           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15856                                       dl, Op.getValueType(), Src, RoundingMode),
15857                                       Mask, PassThru, Subtarget, DAG);
15858       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15859                                               RoundingMode),
15860                                   Mask, PassThru, Subtarget, DAG);
15861     }
15862     case INTR_TYPE_1OP_MASK: {
15863       SDValue Src = Op.getOperand(1);
15864       SDValue PassThru = Op.getOperand(2);
15865       SDValue Mask = Op.getOperand(3);
15866       // We add rounding mode to the Node when
15867       //   - RM Opcode is specified and
15868       //   - RM is not "current direction".
15869       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15870       if (IntrWithRoundingModeOpcode != 0) {
15871         SDValue Rnd = Op.getOperand(4);
15872         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15873         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15874           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15875                                       dl, Op.getValueType(),
15876                                       Src, Rnd),
15877                                       Mask, PassThru, Subtarget, DAG);
15878         }
15879       }
15880       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15881                                   Mask, PassThru, Subtarget, DAG);
15882     }
15883     case INTR_TYPE_SCALAR_MASK_RM: {
15884       SDValue Src1 = Op.getOperand(1);
15885       SDValue Src2 = Op.getOperand(2);
15886       SDValue Src0 = Op.getOperand(3);
15887       SDValue Mask = Op.getOperand(4);
15888       // There are 2 kinds of intrinsics in this group:
15889       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15890       // (2) With rounding mode and sae - 7 operands.
15891       if (Op.getNumOperands() == 6) {
15892         SDValue Sae  = Op.getOperand(5);
15893         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15894         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15895                                                 Sae),
15896                                     Mask, Src0, Subtarget, DAG);
15897       }
15898       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15899       SDValue RoundingMode  = Op.getOperand(5);
15900       SDValue Sae  = Op.getOperand(6);
15901       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15902                                               RoundingMode, Sae),
15903                                   Mask, Src0, Subtarget, DAG);
15904     }
15905     case INTR_TYPE_2OP_MASK: {
15906       SDValue Src1 = Op.getOperand(1);
15907       SDValue Src2 = Op.getOperand(2);
15908       SDValue PassThru = Op.getOperand(3);
15909       SDValue Mask = Op.getOperand(4);
15910       // We specify 2 possible opcodes for intrinsics with rounding modes.
15911       // First, we check if the intrinsic may have non-default rounding mode,
15912       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15913       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15914       if (IntrWithRoundingModeOpcode != 0) {
15915         SDValue Rnd = Op.getOperand(5);
15916         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15917         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15918           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15919                                       dl, Op.getValueType(),
15920                                       Src1, Src2, Rnd),
15921                                       Mask, PassThru, Subtarget, DAG);
15922         }
15923       }
15924       // TODO: Intrinsics should have fast-math-flags to propagate.
15925       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
15926                                   Mask, PassThru, Subtarget, DAG);
15927     }
15928     case INTR_TYPE_2OP_MASK_RM: {
15929       SDValue Src1 = Op.getOperand(1);
15930       SDValue Src2 = Op.getOperand(2);
15931       SDValue PassThru = Op.getOperand(3);
15932       SDValue Mask = Op.getOperand(4);
15933       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15934       // First, we check if the intrinsic have rounding mode (6 operands),
15935       // if not, we set rounding mode to "current".
15936       SDValue Rnd;
15937       if (Op.getNumOperands() == 6)
15938         Rnd = Op.getOperand(5);
15939       else
15940         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15941       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15942                                               Src1, Src2, Rnd),
15943                                   Mask, PassThru, Subtarget, DAG);
15944     }
15945     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15946       SDValue Src1 = Op.getOperand(1);
15947       SDValue Src2 = Op.getOperand(2);
15948       SDValue Src3 = Op.getOperand(3);
15949       SDValue PassThru = Op.getOperand(4);
15950       SDValue Mask = Op.getOperand(5);
15951       SDValue Sae  = Op.getOperand(6);
15952
15953       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15954                                               Src2, Src3, Sae),
15955                                   Mask, PassThru, Subtarget, DAG);
15956     }
15957     case INTR_TYPE_3OP_MASK_RM: {
15958       SDValue Src1 = Op.getOperand(1);
15959       SDValue Src2 = Op.getOperand(2);
15960       SDValue Imm = Op.getOperand(3);
15961       SDValue PassThru = Op.getOperand(4);
15962       SDValue Mask = Op.getOperand(5);
15963       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15964       // First, we check if the intrinsic have rounding mode (7 operands),
15965       // if not, we set rounding mode to "current".
15966       SDValue Rnd;
15967       if (Op.getNumOperands() == 7)
15968         Rnd = Op.getOperand(6);
15969       else
15970         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15971       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15972         Src1, Src2, Imm, Rnd),
15973         Mask, PassThru, Subtarget, DAG);
15974     }
15975     case INTR_TYPE_3OP_IMM8_MASK:
15976     case INTR_TYPE_3OP_MASK:
15977     case INSERT_SUBVEC: {
15978       SDValue Src1 = Op.getOperand(1);
15979       SDValue Src2 = Op.getOperand(2);
15980       SDValue Src3 = Op.getOperand(3);
15981       SDValue PassThru = Op.getOperand(4);
15982       SDValue Mask = Op.getOperand(5);
15983
15984       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15985         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15986       else if (IntrData->Type == INSERT_SUBVEC) {
15987         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
15988         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
15989         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
15990         Imm *= Src2.getValueType().getVectorNumElements();
15991         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
15992       }
15993
15994       // We specify 2 possible opcodes for intrinsics with rounding modes.
15995       // First, we check if the intrinsic may have non-default rounding mode,
15996       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15997       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15998       if (IntrWithRoundingModeOpcode != 0) {
15999         SDValue Rnd = Op.getOperand(6);
16000         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16001         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16002           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16003                                       dl, Op.getValueType(),
16004                                       Src1, Src2, Src3, Rnd),
16005                                       Mask, PassThru, Subtarget, DAG);
16006         }
16007       }
16008       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16009                                               Src1, Src2, Src3),
16010                                   Mask, PassThru, Subtarget, DAG);
16011     }
16012     case VPERM_3OP_MASKZ:
16013     case VPERM_3OP_MASK:
16014     case FMA_OP_MASK3:
16015     case FMA_OP_MASKZ:
16016     case FMA_OP_MASK: {
16017       SDValue Src1 = Op.getOperand(1);
16018       SDValue Src2 = Op.getOperand(2);
16019       SDValue Src3 = Op.getOperand(3);
16020       SDValue Mask = Op.getOperand(4);
16021       EVT VT = Op.getValueType();
16022       SDValue PassThru = SDValue();
16023
16024       // set PassThru element
16025       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16026         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16027       else if (IntrData->Type == FMA_OP_MASK3)
16028         PassThru = Src3;
16029       else
16030         PassThru = Src1;
16031
16032       // We specify 2 possible opcodes for intrinsics with rounding modes.
16033       // First, we check if the intrinsic may have non-default rounding mode,
16034       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16035       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16036       if (IntrWithRoundingModeOpcode != 0) {
16037         SDValue Rnd = Op.getOperand(5);
16038         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16039             X86::STATIC_ROUNDING::CUR_DIRECTION)
16040           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16041                                                   dl, Op.getValueType(),
16042                                                   Src1, Src2, Src3, Rnd),
16043                                       Mask, PassThru, Subtarget, DAG);
16044       }
16045       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16046                                               dl, Op.getValueType(),
16047                                               Src1, Src2, Src3),
16048                                   Mask, PassThru, Subtarget, DAG);
16049     }
16050     case CMP_MASK:
16051     case CMP_MASK_CC: {
16052       // Comparison intrinsics with masks.
16053       // Example of transformation:
16054       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16055       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16056       // (i8 (bitcast
16057       //   (v8i1 (insert_subvector undef,
16058       //           (v2i1 (and (PCMPEQM %a, %b),
16059       //                      (extract_subvector
16060       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16061       EVT VT = Op.getOperand(1).getValueType();
16062       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16063                                     VT.getVectorNumElements());
16064       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16065       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16066                                        Mask.getValueType().getSizeInBits());
16067       SDValue Cmp;
16068       if (IntrData->Type == CMP_MASK_CC) {
16069         SDValue CC = Op.getOperand(3);
16070         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16071         // We specify 2 possible opcodes for intrinsics with rounding modes.
16072         // First, we check if the intrinsic may have non-default rounding mode,
16073         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16074         if (IntrData->Opc1 != 0) {
16075           SDValue Rnd = Op.getOperand(5);
16076           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16077               X86::STATIC_ROUNDING::CUR_DIRECTION)
16078             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16079                               Op.getOperand(2), CC, Rnd);
16080         }
16081         //default rounding mode
16082         if(!Cmp.getNode())
16083             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16084                               Op.getOperand(2), CC);
16085
16086       } else {
16087         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16088         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16089                           Op.getOperand(2));
16090       }
16091       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16092                                              DAG.getTargetConstant(0, dl,
16093                                                                    MaskVT),
16094                                              Subtarget, DAG);
16095       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16096                                 DAG.getUNDEF(BitcastVT), CmpMask,
16097                                 DAG.getIntPtrConstant(0, dl));
16098       return DAG.getBitcast(Op.getValueType(), Res);
16099     }
16100     case COMI: { // Comparison intrinsics
16101       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16102       SDValue LHS = Op.getOperand(1);
16103       SDValue RHS = Op.getOperand(2);
16104       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16105       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16106       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16107       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16108                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16109       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16110     }
16111     case VSHIFT:
16112       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16113                                  Op.getOperand(1), Op.getOperand(2), DAG);
16114     case VSHIFT_MASK:
16115       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16116                                                       Op.getSimpleValueType(),
16117                                                       Op.getOperand(1),
16118                                                       Op.getOperand(2), DAG),
16119                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16120                                   DAG);
16121     case COMPRESS_EXPAND_IN_REG: {
16122       SDValue Mask = Op.getOperand(3);
16123       SDValue DataToCompress = Op.getOperand(1);
16124       SDValue PassThru = Op.getOperand(2);
16125       if (isAllOnes(Mask)) // return data as is
16126         return Op.getOperand(1);
16127
16128       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16129                                               DataToCompress),
16130                                   Mask, PassThru, Subtarget, DAG);
16131     }
16132     case BLEND: {
16133       SDValue Mask = Op.getOperand(3);
16134       EVT VT = Op.getValueType();
16135       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16136                                     VT.getVectorNumElements());
16137       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16138                                        Mask.getValueType().getSizeInBits());
16139       SDLoc dl(Op);
16140       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16141                                   DAG.getBitcast(BitcastVT, Mask),
16142                                   DAG.getIntPtrConstant(0, dl));
16143       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16144                          Op.getOperand(2));
16145     }
16146     default:
16147       break;
16148     }
16149   }
16150
16151   switch (IntNo) {
16152   default: return SDValue();    // Don't custom lower most intrinsics.
16153
16154   case Intrinsic::x86_avx2_permd:
16155   case Intrinsic::x86_avx2_permps:
16156     // Operands intentionally swapped. Mask is last operand to intrinsic,
16157     // but second operand for node/instruction.
16158     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16159                        Op.getOperand(2), Op.getOperand(1));
16160
16161   // ptest and testp intrinsics. The intrinsic these come from are designed to
16162   // return an integer value, not just an instruction so lower it to the ptest
16163   // or testp pattern and a setcc for the result.
16164   case Intrinsic::x86_sse41_ptestz:
16165   case Intrinsic::x86_sse41_ptestc:
16166   case Intrinsic::x86_sse41_ptestnzc:
16167   case Intrinsic::x86_avx_ptestz_256:
16168   case Intrinsic::x86_avx_ptestc_256:
16169   case Intrinsic::x86_avx_ptestnzc_256:
16170   case Intrinsic::x86_avx_vtestz_ps:
16171   case Intrinsic::x86_avx_vtestc_ps:
16172   case Intrinsic::x86_avx_vtestnzc_ps:
16173   case Intrinsic::x86_avx_vtestz_pd:
16174   case Intrinsic::x86_avx_vtestc_pd:
16175   case Intrinsic::x86_avx_vtestnzc_pd:
16176   case Intrinsic::x86_avx_vtestz_ps_256:
16177   case Intrinsic::x86_avx_vtestc_ps_256:
16178   case Intrinsic::x86_avx_vtestnzc_ps_256:
16179   case Intrinsic::x86_avx_vtestz_pd_256:
16180   case Intrinsic::x86_avx_vtestc_pd_256:
16181   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16182     bool IsTestPacked = false;
16183     unsigned X86CC;
16184     switch (IntNo) {
16185     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16186     case Intrinsic::x86_avx_vtestz_ps:
16187     case Intrinsic::x86_avx_vtestz_pd:
16188     case Intrinsic::x86_avx_vtestz_ps_256:
16189     case Intrinsic::x86_avx_vtestz_pd_256:
16190       IsTestPacked = true; // Fallthrough
16191     case Intrinsic::x86_sse41_ptestz:
16192     case Intrinsic::x86_avx_ptestz_256:
16193       // ZF = 1
16194       X86CC = X86::COND_E;
16195       break;
16196     case Intrinsic::x86_avx_vtestc_ps:
16197     case Intrinsic::x86_avx_vtestc_pd:
16198     case Intrinsic::x86_avx_vtestc_ps_256:
16199     case Intrinsic::x86_avx_vtestc_pd_256:
16200       IsTestPacked = true; // Fallthrough
16201     case Intrinsic::x86_sse41_ptestc:
16202     case Intrinsic::x86_avx_ptestc_256:
16203       // CF = 1
16204       X86CC = X86::COND_B;
16205       break;
16206     case Intrinsic::x86_avx_vtestnzc_ps:
16207     case Intrinsic::x86_avx_vtestnzc_pd:
16208     case Intrinsic::x86_avx_vtestnzc_ps_256:
16209     case Intrinsic::x86_avx_vtestnzc_pd_256:
16210       IsTestPacked = true; // Fallthrough
16211     case Intrinsic::x86_sse41_ptestnzc:
16212     case Intrinsic::x86_avx_ptestnzc_256:
16213       // ZF and CF = 0
16214       X86CC = X86::COND_A;
16215       break;
16216     }
16217
16218     SDValue LHS = Op.getOperand(1);
16219     SDValue RHS = Op.getOperand(2);
16220     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16221     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16222     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16223     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16224     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16225   }
16226   case Intrinsic::x86_avx512_kortestz_w:
16227   case Intrinsic::x86_avx512_kortestc_w: {
16228     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16229     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16230     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16231     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16232     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16233     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16234     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16235   }
16236
16237   case Intrinsic::x86_sse42_pcmpistria128:
16238   case Intrinsic::x86_sse42_pcmpestria128:
16239   case Intrinsic::x86_sse42_pcmpistric128:
16240   case Intrinsic::x86_sse42_pcmpestric128:
16241   case Intrinsic::x86_sse42_pcmpistrio128:
16242   case Intrinsic::x86_sse42_pcmpestrio128:
16243   case Intrinsic::x86_sse42_pcmpistris128:
16244   case Intrinsic::x86_sse42_pcmpestris128:
16245   case Intrinsic::x86_sse42_pcmpistriz128:
16246   case Intrinsic::x86_sse42_pcmpestriz128: {
16247     unsigned Opcode;
16248     unsigned X86CC;
16249     switch (IntNo) {
16250     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16251     case Intrinsic::x86_sse42_pcmpistria128:
16252       Opcode = X86ISD::PCMPISTRI;
16253       X86CC = X86::COND_A;
16254       break;
16255     case Intrinsic::x86_sse42_pcmpestria128:
16256       Opcode = X86ISD::PCMPESTRI;
16257       X86CC = X86::COND_A;
16258       break;
16259     case Intrinsic::x86_sse42_pcmpistric128:
16260       Opcode = X86ISD::PCMPISTRI;
16261       X86CC = X86::COND_B;
16262       break;
16263     case Intrinsic::x86_sse42_pcmpestric128:
16264       Opcode = X86ISD::PCMPESTRI;
16265       X86CC = X86::COND_B;
16266       break;
16267     case Intrinsic::x86_sse42_pcmpistrio128:
16268       Opcode = X86ISD::PCMPISTRI;
16269       X86CC = X86::COND_O;
16270       break;
16271     case Intrinsic::x86_sse42_pcmpestrio128:
16272       Opcode = X86ISD::PCMPESTRI;
16273       X86CC = X86::COND_O;
16274       break;
16275     case Intrinsic::x86_sse42_pcmpistris128:
16276       Opcode = X86ISD::PCMPISTRI;
16277       X86CC = X86::COND_S;
16278       break;
16279     case Intrinsic::x86_sse42_pcmpestris128:
16280       Opcode = X86ISD::PCMPESTRI;
16281       X86CC = X86::COND_S;
16282       break;
16283     case Intrinsic::x86_sse42_pcmpistriz128:
16284       Opcode = X86ISD::PCMPISTRI;
16285       X86CC = X86::COND_E;
16286       break;
16287     case Intrinsic::x86_sse42_pcmpestriz128:
16288       Opcode = X86ISD::PCMPESTRI;
16289       X86CC = X86::COND_E;
16290       break;
16291     }
16292     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16293     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16294     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16295     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16296                                 DAG.getConstant(X86CC, dl, MVT::i8),
16297                                 SDValue(PCMP.getNode(), 1));
16298     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16299   }
16300
16301   case Intrinsic::x86_sse42_pcmpistri128:
16302   case Intrinsic::x86_sse42_pcmpestri128: {
16303     unsigned Opcode;
16304     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16305       Opcode = X86ISD::PCMPISTRI;
16306     else
16307       Opcode = X86ISD::PCMPESTRI;
16308
16309     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16310     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16311     return DAG.getNode(Opcode, dl, VTs, NewOps);
16312   }
16313
16314   case Intrinsic::x86_seh_lsda: {
16315     // Compute the symbol for the LSDA. We know it'll get emitted later.
16316     MachineFunction &MF = DAG.getMachineFunction();
16317     SDValue Op1 = Op.getOperand(1);
16318     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16319     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16320         GlobalValue::getRealLinkageName(Fn->getName()));
16321
16322     // Generate a simple absolute symbol reference. This intrinsic is only
16323     // supported on 32-bit Windows, which isn't PIC.
16324     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16325     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16326   }
16327
16328   case Intrinsic::x86_seh_recoverfp: {
16329     SDValue FnOp = Op.getOperand(1);
16330     SDValue IncomingFPOp = Op.getOperand(2);
16331     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16332     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16333     if (!Fn)
16334       report_fatal_error(
16335           "llvm.x86.seh.recoverfp must take a function as the first argument");
16336     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16337   }
16338
16339   case Intrinsic::localaddress: {
16340     // Returns one of the stack, base, or frame pointer registers, depending on
16341     // which is used to reference local variables.
16342     MachineFunction &MF = DAG.getMachineFunction();
16343     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16344     unsigned Reg;
16345     if (RegInfo->hasBasePointer(MF))
16346       Reg = RegInfo->getBaseRegister();
16347     else // This function handles the SP or FP case.
16348       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16349     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16350   }
16351   }
16352 }
16353
16354 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16355                               SDValue Src, SDValue Mask, SDValue Base,
16356                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16357                               const X86Subtarget * Subtarget) {
16358   SDLoc dl(Op);
16359   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16360   if (!C)
16361     llvm_unreachable("Invalid scale type");
16362   unsigned ScaleVal = C->getZExtValue();
16363   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16364     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16365
16366   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16367   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16368                              Index.getSimpleValueType().getVectorNumElements());
16369   SDValue MaskInReg;
16370   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16371   if (MaskC)
16372     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16373   else {
16374     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16375                                      Mask.getValueType().getSizeInBits());
16376
16377     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16378     // are extracted by EXTRACT_SUBVECTOR.
16379     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16380                             DAG.getBitcast(BitcastVT, Mask),
16381                             DAG.getIntPtrConstant(0, dl));
16382   }
16383   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16384   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16385   SDValue Segment = DAG.getRegister(0, MVT::i32);
16386   if (Src.getOpcode() == ISD::UNDEF)
16387     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16388   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16389   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16390   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16391   return DAG.getMergeValues(RetOps, dl);
16392 }
16393
16394 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16395                                SDValue Src, SDValue Mask, SDValue Base,
16396                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16397   SDLoc dl(Op);
16398   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16399   if (!C)
16400     llvm_unreachable("Invalid scale type");
16401   unsigned ScaleVal = C->getZExtValue();
16402   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16403     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16404
16405   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16406   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16407   SDValue Segment = DAG.getRegister(0, MVT::i32);
16408   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16409                              Index.getSimpleValueType().getVectorNumElements());
16410   SDValue MaskInReg;
16411   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16412   if (MaskC)
16413     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16414   else {
16415     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16416                                      Mask.getValueType().getSizeInBits());
16417
16418     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16419     // are extracted by EXTRACT_SUBVECTOR.
16420     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16421                             DAG.getBitcast(BitcastVT, Mask),
16422                             DAG.getIntPtrConstant(0, dl));
16423   }
16424   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16425   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16426   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16427   return SDValue(Res, 1);
16428 }
16429
16430 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16431                                SDValue Mask, SDValue Base, SDValue Index,
16432                                SDValue ScaleOp, SDValue Chain) {
16433   SDLoc dl(Op);
16434   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16435   assert(C && "Invalid scale type");
16436   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16437   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16438   SDValue Segment = DAG.getRegister(0, MVT::i32);
16439   EVT MaskVT =
16440     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16441   SDValue MaskInReg;
16442   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16443   if (MaskC)
16444     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16445   else
16446     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16447   //SDVTList VTs = DAG.getVTList(MVT::Other);
16448   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16449   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16450   return SDValue(Res, 0);
16451 }
16452
16453 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16454 // read performance monitor counters (x86_rdpmc).
16455 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16456                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16457                               SmallVectorImpl<SDValue> &Results) {
16458   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16459   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16460   SDValue LO, HI;
16461
16462   // The ECX register is used to select the index of the performance counter
16463   // to read.
16464   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16465                                    N->getOperand(2));
16466   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16467
16468   // Reads the content of a 64-bit performance counter and returns it in the
16469   // registers EDX:EAX.
16470   if (Subtarget->is64Bit()) {
16471     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16472     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16473                             LO.getValue(2));
16474   } else {
16475     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16476     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16477                             LO.getValue(2));
16478   }
16479   Chain = HI.getValue(1);
16480
16481   if (Subtarget->is64Bit()) {
16482     // The EAX register is loaded with the low-order 32 bits. The EDX register
16483     // is loaded with the supported high-order bits of the counter.
16484     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16485                               DAG.getConstant(32, DL, MVT::i8));
16486     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16487     Results.push_back(Chain);
16488     return;
16489   }
16490
16491   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16492   SDValue Ops[] = { LO, HI };
16493   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16494   Results.push_back(Pair);
16495   Results.push_back(Chain);
16496 }
16497
16498 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16499 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16500 // also used to custom lower READCYCLECOUNTER nodes.
16501 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16502                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16503                               SmallVectorImpl<SDValue> &Results) {
16504   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16505   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16506   SDValue LO, HI;
16507
16508   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16509   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16510   // and the EAX register is loaded with the low-order 32 bits.
16511   if (Subtarget->is64Bit()) {
16512     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16513     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16514                             LO.getValue(2));
16515   } else {
16516     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16517     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16518                             LO.getValue(2));
16519   }
16520   SDValue Chain = HI.getValue(1);
16521
16522   if (Opcode == X86ISD::RDTSCP_DAG) {
16523     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16524
16525     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16526     // the ECX register. Add 'ecx' explicitly to the chain.
16527     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16528                                      HI.getValue(2));
16529     // Explicitly store the content of ECX at the location passed in input
16530     // to the 'rdtscp' intrinsic.
16531     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16532                          MachinePointerInfo(), false, false, 0);
16533   }
16534
16535   if (Subtarget->is64Bit()) {
16536     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16537     // the EAX register is loaded with the low-order 32 bits.
16538     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16539                               DAG.getConstant(32, DL, MVT::i8));
16540     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16541     Results.push_back(Chain);
16542     return;
16543   }
16544
16545   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16546   SDValue Ops[] = { LO, HI };
16547   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16548   Results.push_back(Pair);
16549   Results.push_back(Chain);
16550 }
16551
16552 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16553                                      SelectionDAG &DAG) {
16554   SmallVector<SDValue, 2> Results;
16555   SDLoc DL(Op);
16556   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16557                           Results);
16558   return DAG.getMergeValues(Results, DL);
16559 }
16560
16561 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16562                                     SelectionDAG &DAG) {
16563   MachineFunction &MF = DAG.getMachineFunction();
16564   const Function *Fn = MF.getFunction();
16565   SDLoc dl(Op);
16566   SDValue Chain = Op.getOperand(0);
16567
16568   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16569          "using llvm.x86.seh.restoreframe requires a frame pointer");
16570
16571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16572   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16573
16574   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16575   unsigned FrameReg =
16576       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16577   unsigned SPReg = RegInfo->getStackRegister();
16578   unsigned SlotSize = RegInfo->getSlotSize();
16579
16580   // Get incoming EBP.
16581   SDValue IncomingEBP =
16582       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16583
16584   // SP is saved in the first field of every registration node, so load
16585   // [EBP-RegNodeSize] into SP.
16586   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16587   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16588                                DAG.getConstant(-RegNodeSize, dl, VT));
16589   SDValue NewSP =
16590       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16591                   false, VT.getScalarSizeInBits() / 8);
16592   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16593
16594   if (!RegInfo->needsStackRealignment(MF)) {
16595     // Adjust EBP to point back to the original frame position.
16596     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16597     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16598   } else {
16599     assert(RegInfo->hasBasePointer(MF) &&
16600            "functions with Win32 EH must use frame or base pointer register");
16601
16602     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16603     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16604     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16605
16606     // Reload the spilled EBP value, now that the stack and base pointers are
16607     // set up.
16608     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16609     X86FI->setHasSEHFramePtrSave(true);
16610     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16611     X86FI->setSEHFramePtrSaveIndex(FI);
16612     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16613                                 MachinePointerInfo(), false, false, false,
16614                                 VT.getScalarSizeInBits() / 8);
16615     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16616   }
16617
16618   return Chain;
16619 }
16620
16621 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16622 /// return truncate Store/MaskedStore Node
16623 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16624                                                SelectionDAG &DAG,
16625                                                MVT ElementType) {
16626   SDLoc dl(Op);
16627   SDValue Mask = Op.getOperand(4);
16628   SDValue DataToTruncate = Op.getOperand(3);
16629   SDValue Addr = Op.getOperand(2);
16630   SDValue Chain = Op.getOperand(0);
16631
16632   EVT VT  = DataToTruncate.getValueType();
16633   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16634                              ElementType, VT.getVectorNumElements());
16635
16636   if (isAllOnes(Mask)) // return just a truncate store
16637     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16638                              MachinePointerInfo(), SVT, false, false,
16639                              SVT.getScalarSizeInBits()/8);
16640
16641   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16642                                 MVT::i1, VT.getVectorNumElements());
16643   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16644                                    Mask.getValueType().getSizeInBits());
16645   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16646   // are extracted by EXTRACT_SUBVECTOR.
16647   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16648                               DAG.getBitcast(BitcastVT, Mask),
16649                               DAG.getIntPtrConstant(0, dl));
16650
16651   MachineMemOperand *MMO = DAG.getMachineFunction().
16652     getMachineMemOperand(MachinePointerInfo(),
16653                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16654                          SVT.getScalarSizeInBits()/8);
16655
16656   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16657                             VMask, SVT, MMO, true);
16658 }
16659
16660 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16661                                       SelectionDAG &DAG) {
16662   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16663
16664   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16665   if (!IntrData) {
16666     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16667       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16668     return SDValue();
16669   }
16670
16671   SDLoc dl(Op);
16672   switch(IntrData->Type) {
16673   default:
16674     llvm_unreachable("Unknown Intrinsic Type");
16675     break;
16676   case RDSEED:
16677   case RDRAND: {
16678     // Emit the node with the right value type.
16679     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16680     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16681
16682     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16683     // Otherwise return the value from Rand, which is always 0, casted to i32.
16684     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16685                       DAG.getConstant(1, dl, Op->getValueType(1)),
16686                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16687                       SDValue(Result.getNode(), 1) };
16688     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16689                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16690                                   Ops);
16691
16692     // Return { result, isValid, chain }.
16693     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16694                        SDValue(Result.getNode(), 2));
16695   }
16696   case GATHER: {
16697   //gather(v1, mask, index, base, scale);
16698     SDValue Chain = Op.getOperand(0);
16699     SDValue Src   = Op.getOperand(2);
16700     SDValue Base  = Op.getOperand(3);
16701     SDValue Index = Op.getOperand(4);
16702     SDValue Mask  = Op.getOperand(5);
16703     SDValue Scale = Op.getOperand(6);
16704     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16705                          Chain, Subtarget);
16706   }
16707   case SCATTER: {
16708   //scatter(base, mask, index, v1, scale);
16709     SDValue Chain = Op.getOperand(0);
16710     SDValue Base  = Op.getOperand(2);
16711     SDValue Mask  = Op.getOperand(3);
16712     SDValue Index = Op.getOperand(4);
16713     SDValue Src   = Op.getOperand(5);
16714     SDValue Scale = Op.getOperand(6);
16715     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16716                           Scale, Chain);
16717   }
16718   case PREFETCH: {
16719     SDValue Hint = Op.getOperand(6);
16720     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16721     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16722     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16723     SDValue Chain = Op.getOperand(0);
16724     SDValue Mask  = Op.getOperand(2);
16725     SDValue Index = Op.getOperand(3);
16726     SDValue Base  = Op.getOperand(4);
16727     SDValue Scale = Op.getOperand(5);
16728     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16729   }
16730   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16731   case RDTSC: {
16732     SmallVector<SDValue, 2> Results;
16733     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16734                             Results);
16735     return DAG.getMergeValues(Results, dl);
16736   }
16737   // Read Performance Monitoring Counters.
16738   case RDPMC: {
16739     SmallVector<SDValue, 2> Results;
16740     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16741     return DAG.getMergeValues(Results, dl);
16742   }
16743   // XTEST intrinsics.
16744   case XTEST: {
16745     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16746     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16747     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16748                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16749                                 InTrans);
16750     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16751     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16752                        Ret, SDValue(InTrans.getNode(), 1));
16753   }
16754   // ADC/ADCX/SBB
16755   case ADX: {
16756     SmallVector<SDValue, 2> Results;
16757     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16758     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16759     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16760                                 DAG.getConstant(-1, dl, MVT::i8));
16761     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16762                               Op.getOperand(4), GenCF.getValue(1));
16763     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16764                                  Op.getOperand(5), MachinePointerInfo(),
16765                                  false, false, 0);
16766     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16767                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16768                                 Res.getValue(1));
16769     Results.push_back(SetCC);
16770     Results.push_back(Store);
16771     return DAG.getMergeValues(Results, dl);
16772   }
16773   case COMPRESS_TO_MEM: {
16774     SDLoc dl(Op);
16775     SDValue Mask = Op.getOperand(4);
16776     SDValue DataToCompress = Op.getOperand(3);
16777     SDValue Addr = Op.getOperand(2);
16778     SDValue Chain = Op.getOperand(0);
16779
16780     EVT VT = DataToCompress.getValueType();
16781     if (isAllOnes(Mask)) // return just a store
16782       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16783                           MachinePointerInfo(), false, false,
16784                           VT.getScalarSizeInBits()/8);
16785
16786     SDValue Compressed =
16787       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16788                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16789     return DAG.getStore(Chain, dl, Compressed, Addr,
16790                         MachinePointerInfo(), false, false,
16791                         VT.getScalarSizeInBits()/8);
16792   }
16793   case TRUNCATE_TO_MEM_VI8:
16794     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16795   case TRUNCATE_TO_MEM_VI16:
16796     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16797   case TRUNCATE_TO_MEM_VI32:
16798     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16799   case EXPAND_FROM_MEM: {
16800     SDLoc dl(Op);
16801     SDValue Mask = Op.getOperand(4);
16802     SDValue PassThru = Op.getOperand(3);
16803     SDValue Addr = Op.getOperand(2);
16804     SDValue Chain = Op.getOperand(0);
16805     EVT VT = Op.getValueType();
16806
16807     if (isAllOnes(Mask)) // return just a load
16808       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16809                          false, VT.getScalarSizeInBits()/8);
16810
16811     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16812                                        false, false, false,
16813                                        VT.getScalarSizeInBits()/8);
16814
16815     SDValue Results[] = {
16816       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16817                            Mask, PassThru, Subtarget, DAG), Chain};
16818     return DAG.getMergeValues(Results, dl);
16819   }
16820   }
16821 }
16822
16823 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16824                                            SelectionDAG &DAG) const {
16825   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16826   MFI->setReturnAddressIsTaken(true);
16827
16828   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16829     return SDValue();
16830
16831   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16832   SDLoc dl(Op);
16833   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16834
16835   if (Depth > 0) {
16836     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16837     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16838     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16839     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16840                        DAG.getNode(ISD::ADD, dl, PtrVT,
16841                                    FrameAddr, Offset),
16842                        MachinePointerInfo(), false, false, false, 0);
16843   }
16844
16845   // Just load the return address.
16846   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16847   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16848                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16849 }
16850
16851 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16852   MachineFunction &MF = DAG.getMachineFunction();
16853   MachineFrameInfo *MFI = MF.getFrameInfo();
16854   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16855   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16856   EVT VT = Op.getValueType();
16857
16858   MFI->setFrameAddressIsTaken(true);
16859
16860   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16861     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16862     // is not possible to crawl up the stack without looking at the unwind codes
16863     // simultaneously.
16864     int FrameAddrIndex = FuncInfo->getFAIndex();
16865     if (!FrameAddrIndex) {
16866       // Set up a frame object for the return address.
16867       unsigned SlotSize = RegInfo->getSlotSize();
16868       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16869           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16870       FuncInfo->setFAIndex(FrameAddrIndex);
16871     }
16872     return DAG.getFrameIndex(FrameAddrIndex, VT);
16873   }
16874
16875   unsigned FrameReg =
16876       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16877   SDLoc dl(Op);  // FIXME probably not meaningful
16878   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16879   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16880           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16881          "Invalid Frame Register!");
16882   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16883   while (Depth--)
16884     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16885                             MachinePointerInfo(),
16886                             false, false, false, 0);
16887   return FrameAddr;
16888 }
16889
16890 // FIXME? Maybe this could be a TableGen attribute on some registers and
16891 // this table could be generated automatically from RegInfo.
16892 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16893                                               SelectionDAG &DAG) const {
16894   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16895   const MachineFunction &MF = DAG.getMachineFunction();
16896
16897   unsigned Reg = StringSwitch<unsigned>(RegName)
16898                        .Case("esp", X86::ESP)
16899                        .Case("rsp", X86::RSP)
16900                        .Case("ebp", X86::EBP)
16901                        .Case("rbp", X86::RBP)
16902                        .Default(0);
16903
16904   if (Reg == X86::EBP || Reg == X86::RBP) {
16905     if (!TFI.hasFP(MF))
16906       report_fatal_error("register " + StringRef(RegName) +
16907                          " is allocatable: function has no frame pointer");
16908 #ifndef NDEBUG
16909     else {
16910       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16911       unsigned FrameReg =
16912           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16913       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16914              "Invalid Frame Register!");
16915     }
16916 #endif
16917   }
16918
16919   if (Reg)
16920     return Reg;
16921
16922   report_fatal_error("Invalid register name global variable");
16923 }
16924
16925 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16926                                                      SelectionDAG &DAG) const {
16927   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16928   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16929 }
16930
16931 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16932   SDValue Chain     = Op.getOperand(0);
16933   SDValue Offset    = Op.getOperand(1);
16934   SDValue Handler   = Op.getOperand(2);
16935   SDLoc dl      (Op);
16936
16937   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16938   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16939   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16940   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16941           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16942          "Invalid Frame Register!");
16943   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16944   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16945
16946   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16947                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16948                                                        dl));
16949   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16950   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16951                        false, false, 0);
16952   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16953
16954   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16955                      DAG.getRegister(StoreAddrReg, PtrVT));
16956 }
16957
16958 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16959                                                SelectionDAG &DAG) const {
16960   SDLoc DL(Op);
16961   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16962                      DAG.getVTList(MVT::i32, MVT::Other),
16963                      Op.getOperand(0), Op.getOperand(1));
16964 }
16965
16966 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16967                                                 SelectionDAG &DAG) const {
16968   SDLoc DL(Op);
16969   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16970                      Op.getOperand(0), Op.getOperand(1));
16971 }
16972
16973 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16974   return Op.getOperand(0);
16975 }
16976
16977 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16978                                                 SelectionDAG &DAG) const {
16979   SDValue Root = Op.getOperand(0);
16980   SDValue Trmp = Op.getOperand(1); // trampoline
16981   SDValue FPtr = Op.getOperand(2); // nested function
16982   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16983   SDLoc dl (Op);
16984
16985   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16986   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16987
16988   if (Subtarget->is64Bit()) {
16989     SDValue OutChains[6];
16990
16991     // Large code-model.
16992     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16993     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16994
16995     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16996     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16997
16998     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16999
17000     // Load the pointer to the nested function into R11.
17001     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17002     SDValue Addr = Trmp;
17003     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17004                                 Addr, MachinePointerInfo(TrmpAddr),
17005                                 false, false, 0);
17006
17007     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17008                        DAG.getConstant(2, dl, MVT::i64));
17009     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17010                                 MachinePointerInfo(TrmpAddr, 2),
17011                                 false, false, 2);
17012
17013     // Load the 'nest' parameter value into R10.
17014     // R10 is specified in X86CallingConv.td
17015     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17016     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17017                        DAG.getConstant(10, dl, MVT::i64));
17018     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17019                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17020                                 false, false, 0);
17021
17022     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17023                        DAG.getConstant(12, dl, MVT::i64));
17024     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17025                                 MachinePointerInfo(TrmpAddr, 12),
17026                                 false, false, 2);
17027
17028     // Jump to the nested function.
17029     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17030     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17031                        DAG.getConstant(20, dl, MVT::i64));
17032     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17033                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17034                                 false, false, 0);
17035
17036     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17037     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17038                        DAG.getConstant(22, dl, MVT::i64));
17039     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17040                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17041                                 false, false, 0);
17042
17043     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17044   } else {
17045     const Function *Func =
17046       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17047     CallingConv::ID CC = Func->getCallingConv();
17048     unsigned NestReg;
17049
17050     switch (CC) {
17051     default:
17052       llvm_unreachable("Unsupported calling convention");
17053     case CallingConv::C:
17054     case CallingConv::X86_StdCall: {
17055       // Pass 'nest' parameter in ECX.
17056       // Must be kept in sync with X86CallingConv.td
17057       NestReg = X86::ECX;
17058
17059       // Check that ECX wasn't needed by an 'inreg' parameter.
17060       FunctionType *FTy = Func->getFunctionType();
17061       const AttributeSet &Attrs = Func->getAttributes();
17062
17063       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17064         unsigned InRegCount = 0;
17065         unsigned Idx = 1;
17066
17067         for (FunctionType::param_iterator I = FTy->param_begin(),
17068              E = FTy->param_end(); I != E; ++I, ++Idx)
17069           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17070             auto &DL = DAG.getDataLayout();
17071             // FIXME: should only count parameters that are lowered to integers.
17072             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17073           }
17074
17075         if (InRegCount > 2) {
17076           report_fatal_error("Nest register in use - reduce number of inreg"
17077                              " parameters!");
17078         }
17079       }
17080       break;
17081     }
17082     case CallingConv::X86_FastCall:
17083     case CallingConv::X86_ThisCall:
17084     case CallingConv::Fast:
17085       // Pass 'nest' parameter in EAX.
17086       // Must be kept in sync with X86CallingConv.td
17087       NestReg = X86::EAX;
17088       break;
17089     }
17090
17091     SDValue OutChains[4];
17092     SDValue Addr, Disp;
17093
17094     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17095                        DAG.getConstant(10, dl, MVT::i32));
17096     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17097
17098     // This is storing the opcode for MOV32ri.
17099     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17100     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17101     OutChains[0] = DAG.getStore(Root, dl,
17102                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17103                                 Trmp, MachinePointerInfo(TrmpAddr),
17104                                 false, false, 0);
17105
17106     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17107                        DAG.getConstant(1, dl, MVT::i32));
17108     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17109                                 MachinePointerInfo(TrmpAddr, 1),
17110                                 false, false, 1);
17111
17112     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17113     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17114                        DAG.getConstant(5, dl, MVT::i32));
17115     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17116                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17117                                 false, false, 1);
17118
17119     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17120                        DAG.getConstant(6, dl, MVT::i32));
17121     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17122                                 MachinePointerInfo(TrmpAddr, 6),
17123                                 false, false, 1);
17124
17125     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17126   }
17127 }
17128
17129 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17130                                             SelectionDAG &DAG) const {
17131   /*
17132    The rounding mode is in bits 11:10 of FPSR, and has the following
17133    settings:
17134      00 Round to nearest
17135      01 Round to -inf
17136      10 Round to +inf
17137      11 Round to 0
17138
17139   FLT_ROUNDS, on the other hand, expects the following:
17140     -1 Undefined
17141      0 Round to 0
17142      1 Round to nearest
17143      2 Round to +inf
17144      3 Round to -inf
17145
17146   To perform the conversion, we do:
17147     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17148   */
17149
17150   MachineFunction &MF = DAG.getMachineFunction();
17151   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17152   unsigned StackAlignment = TFI.getStackAlignment();
17153   MVT VT = Op.getSimpleValueType();
17154   SDLoc DL(Op);
17155
17156   // Save FP Control Word to stack slot
17157   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17158   SDValue StackSlot =
17159       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17160
17161   MachineMemOperand *MMO =
17162       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17163                               MachineMemOperand::MOStore, 2, 2);
17164
17165   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17166   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17167                                           DAG.getVTList(MVT::Other),
17168                                           Ops, MVT::i16, MMO);
17169
17170   // Load FP Control Word from stack slot
17171   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17172                             MachinePointerInfo(), false, false, false, 0);
17173
17174   // Transform as necessary
17175   SDValue CWD1 =
17176     DAG.getNode(ISD::SRL, DL, MVT::i16,
17177                 DAG.getNode(ISD::AND, DL, MVT::i16,
17178                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17179                 DAG.getConstant(11, DL, MVT::i8));
17180   SDValue CWD2 =
17181     DAG.getNode(ISD::SRL, DL, MVT::i16,
17182                 DAG.getNode(ISD::AND, DL, MVT::i16,
17183                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17184                 DAG.getConstant(9, DL, MVT::i8));
17185
17186   SDValue RetVal =
17187     DAG.getNode(ISD::AND, DL, MVT::i16,
17188                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17189                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17190                             DAG.getConstant(1, DL, MVT::i16)),
17191                 DAG.getConstant(3, DL, MVT::i16));
17192
17193   return DAG.getNode((VT.getSizeInBits() < 16 ?
17194                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17195 }
17196
17197 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17198   MVT VT = Op.getSimpleValueType();
17199   EVT OpVT = VT;
17200   unsigned NumBits = VT.getSizeInBits();
17201   SDLoc dl(Op);
17202
17203   Op = Op.getOperand(0);
17204   if (VT == MVT::i8) {
17205     // Zero extend to i32 since there is not an i8 bsr.
17206     OpVT = MVT::i32;
17207     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17208   }
17209
17210   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17211   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17212   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17213
17214   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17215   SDValue Ops[] = {
17216     Op,
17217     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17218     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17219     Op.getValue(1)
17220   };
17221   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17222
17223   // Finally xor with NumBits-1.
17224   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17225                    DAG.getConstant(NumBits - 1, dl, OpVT));
17226
17227   if (VT == MVT::i8)
17228     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17229   return Op;
17230 }
17231
17232 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17233   MVT VT = Op.getSimpleValueType();
17234   EVT OpVT = VT;
17235   unsigned NumBits = VT.getSizeInBits();
17236   SDLoc dl(Op);
17237
17238   Op = Op.getOperand(0);
17239   if (VT == MVT::i8) {
17240     // Zero extend to i32 since there is not an i8 bsr.
17241     OpVT = MVT::i32;
17242     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17243   }
17244
17245   // Issue a bsr (scan bits in reverse).
17246   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17247   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17248
17249   // And xor with NumBits-1.
17250   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17251                    DAG.getConstant(NumBits - 1, dl, OpVT));
17252
17253   if (VT == MVT::i8)
17254     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17255   return Op;
17256 }
17257
17258 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17259   MVT VT = Op.getSimpleValueType();
17260   unsigned NumBits = VT.getScalarSizeInBits();
17261   SDLoc dl(Op);
17262
17263   if (VT.isVector()) {
17264     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17265
17266     SDValue N0 = Op.getOperand(0);
17267     SDValue Zero = DAG.getConstant(0, dl, VT);
17268
17269     // lsb(x) = (x & -x)
17270     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17271                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17272
17273     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17274     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17275         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17276       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17277       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17278                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17279     }
17280
17281     // cttz(x) = ctpop(lsb - 1)
17282     SDValue One = DAG.getConstant(1, dl, VT);
17283     return DAG.getNode(ISD::CTPOP, dl, VT,
17284                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17285   }
17286
17287   assert(Op.getOpcode() == ISD::CTTZ &&
17288          "Only scalar CTTZ requires custom lowering");
17289
17290   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17291   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17292   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17293
17294   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17295   SDValue Ops[] = {
17296     Op,
17297     DAG.getConstant(NumBits, dl, VT),
17298     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17299     Op.getValue(1)
17300   };
17301   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17302 }
17303
17304 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17305 // ones, and then concatenate the result back.
17306 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17307   MVT VT = Op.getSimpleValueType();
17308
17309   assert(VT.is256BitVector() && VT.isInteger() &&
17310          "Unsupported value type for operation");
17311
17312   unsigned NumElems = VT.getVectorNumElements();
17313   SDLoc dl(Op);
17314
17315   // Extract the LHS vectors
17316   SDValue LHS = Op.getOperand(0);
17317   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17318   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17319
17320   // Extract the RHS vectors
17321   SDValue RHS = Op.getOperand(1);
17322   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17323   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17324
17325   MVT EltVT = VT.getVectorElementType();
17326   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17327
17328   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17329                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17330                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17331 }
17332
17333 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17334   if (Op.getValueType() == MVT::i1)
17335     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17336                        Op.getOperand(0), Op.getOperand(1));
17337   assert(Op.getSimpleValueType().is256BitVector() &&
17338          Op.getSimpleValueType().isInteger() &&
17339          "Only handle AVX 256-bit vector integer operation");
17340   return Lower256IntArith(Op, DAG);
17341 }
17342
17343 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17344   if (Op.getValueType() == MVT::i1)
17345     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17346                        Op.getOperand(0), Op.getOperand(1));
17347   assert(Op.getSimpleValueType().is256BitVector() &&
17348          Op.getSimpleValueType().isInteger() &&
17349          "Only handle AVX 256-bit vector integer operation");
17350   return Lower256IntArith(Op, DAG);
17351 }
17352
17353 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17354   assert(Op.getSimpleValueType().is256BitVector() &&
17355          Op.getSimpleValueType().isInteger() &&
17356          "Only handle AVX 256-bit vector integer operation");
17357   return Lower256IntArith(Op, DAG);
17358 }
17359
17360 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17361                         SelectionDAG &DAG) {
17362   SDLoc dl(Op);
17363   MVT VT = Op.getSimpleValueType();
17364
17365   if (VT == MVT::i1)
17366     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17367
17368   // Decompose 256-bit ops into smaller 128-bit ops.
17369   if (VT.is256BitVector() && !Subtarget->hasInt256())
17370     return Lower256IntArith(Op, DAG);
17371
17372   SDValue A = Op.getOperand(0);
17373   SDValue B = Op.getOperand(1);
17374
17375   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17376   // pairs, multiply and truncate.
17377   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17378     if (Subtarget->hasInt256()) {
17379       if (VT == MVT::v32i8) {
17380         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17381         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17382         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17383         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17384         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17385         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17386         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17387         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17388                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17389                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17390       }
17391
17392       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17393       return DAG.getNode(
17394           ISD::TRUNCATE, dl, VT,
17395           DAG.getNode(ISD::MUL, dl, ExVT,
17396                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17397                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17398     }
17399
17400     assert(VT == MVT::v16i8 &&
17401            "Pre-AVX2 support only supports v16i8 multiplication");
17402     MVT ExVT = MVT::v8i16;
17403
17404     // Extract the lo parts and sign extend to i16
17405     SDValue ALo, BLo;
17406     if (Subtarget->hasSSE41()) {
17407       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17408       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17409     } else {
17410       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17411                               -1, 4, -1, 5, -1, 6, -1, 7};
17412       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17413       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17414       ALo = DAG.getBitcast(ExVT, ALo);
17415       BLo = DAG.getBitcast(ExVT, BLo);
17416       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17417       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17418     }
17419
17420     // Extract the hi parts and sign extend to i16
17421     SDValue AHi, BHi;
17422     if (Subtarget->hasSSE41()) {
17423       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17424                               -1, -1, -1, -1, -1, -1, -1, -1};
17425       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17426       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17427       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17428       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17429     } else {
17430       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17431                               -1, 12, -1, 13, -1, 14, -1, 15};
17432       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17433       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17434       AHi = DAG.getBitcast(ExVT, AHi);
17435       BHi = DAG.getBitcast(ExVT, BHi);
17436       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17437       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17438     }
17439
17440     // Multiply, mask the lower 8bits of the lo/hi results and pack
17441     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17442     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17443     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17444     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17445     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17446   }
17447
17448   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17449   if (VT == MVT::v4i32) {
17450     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17451            "Should not custom lower when pmuldq is available!");
17452
17453     // Extract the odd parts.
17454     static const int UnpackMask[] = { 1, -1, 3, -1 };
17455     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17456     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17457
17458     // Multiply the even parts.
17459     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17460     // Now multiply odd parts.
17461     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17462
17463     Evens = DAG.getBitcast(VT, Evens);
17464     Odds = DAG.getBitcast(VT, Odds);
17465
17466     // Merge the two vectors back together with a shuffle. This expands into 2
17467     // shuffles.
17468     static const int ShufMask[] = { 0, 4, 2, 6 };
17469     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17470   }
17471
17472   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17473          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17474
17475   //  Ahi = psrlqi(a, 32);
17476   //  Bhi = psrlqi(b, 32);
17477   //
17478   //  AloBlo = pmuludq(a, b);
17479   //  AloBhi = pmuludq(a, Bhi);
17480   //  AhiBlo = pmuludq(Ahi, b);
17481
17482   //  AloBhi = psllqi(AloBhi, 32);
17483   //  AhiBlo = psllqi(AhiBlo, 32);
17484   //  return AloBlo + AloBhi + AhiBlo;
17485
17486   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17487   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17488
17489   SDValue AhiBlo = Ahi;
17490   SDValue AloBhi = Bhi;
17491   // Bit cast to 32-bit vectors for MULUDQ
17492   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17493                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17494   A = DAG.getBitcast(MulVT, A);
17495   B = DAG.getBitcast(MulVT, B);
17496   Ahi = DAG.getBitcast(MulVT, Ahi);
17497   Bhi = DAG.getBitcast(MulVT, Bhi);
17498
17499   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17500   // After shifting right const values the result may be all-zero.
17501   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17502     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17503     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17504   }
17505   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17506     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17507     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17508   }
17509
17510   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17511   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17512 }
17513
17514 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17515   assert(Subtarget->isTargetWin64() && "Unexpected target");
17516   EVT VT = Op.getValueType();
17517   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17518          "Unexpected return type for lowering");
17519
17520   RTLIB::Libcall LC;
17521   bool isSigned;
17522   switch (Op->getOpcode()) {
17523   default: llvm_unreachable("Unexpected request for libcall!");
17524   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17525   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17526   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17527   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17528   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17529   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17530   }
17531
17532   SDLoc dl(Op);
17533   SDValue InChain = DAG.getEntryNode();
17534
17535   TargetLowering::ArgListTy Args;
17536   TargetLowering::ArgListEntry Entry;
17537   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17538     EVT ArgVT = Op->getOperand(i).getValueType();
17539     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17540            "Unexpected argument type for lowering");
17541     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17542     Entry.Node = StackPtr;
17543     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17544                            false, false, 16);
17545     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17546     Entry.Ty = PointerType::get(ArgTy,0);
17547     Entry.isSExt = false;
17548     Entry.isZExt = false;
17549     Args.push_back(Entry);
17550   }
17551
17552   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17553                                          getPointerTy(DAG.getDataLayout()));
17554
17555   TargetLowering::CallLoweringInfo CLI(DAG);
17556   CLI.setDebugLoc(dl).setChain(InChain)
17557     .setCallee(getLibcallCallingConv(LC),
17558                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17559                Callee, std::move(Args), 0)
17560     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17561
17562   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17563   return DAG.getBitcast(VT, CallInfo.first);
17564 }
17565
17566 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17567                              SelectionDAG &DAG) {
17568   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17569   EVT VT = Op0.getValueType();
17570   SDLoc dl(Op);
17571
17572   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17573          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17574
17575   // PMULxD operations multiply each even value (starting at 0) of LHS with
17576   // the related value of RHS and produce a widen result.
17577   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17578   // => <2 x i64> <ae|cg>
17579   //
17580   // In other word, to have all the results, we need to perform two PMULxD:
17581   // 1. one with the even values.
17582   // 2. one with the odd values.
17583   // To achieve #2, with need to place the odd values at an even position.
17584   //
17585   // Place the odd value at an even position (basically, shift all values 1
17586   // step to the left):
17587   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17588   // <a|b|c|d> => <b|undef|d|undef>
17589   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17590   // <e|f|g|h> => <f|undef|h|undef>
17591   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17592
17593   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17594   // ints.
17595   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17596   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17597   unsigned Opcode =
17598       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17599   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17600   // => <2 x i64> <ae|cg>
17601   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17602   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17603   // => <2 x i64> <bf|dh>
17604   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17605
17606   // Shuffle it back into the right order.
17607   SDValue Highs, Lows;
17608   if (VT == MVT::v8i32) {
17609     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17610     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17611     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17612     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17613   } else {
17614     const int HighMask[] = {1, 5, 3, 7};
17615     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17616     const int LowMask[] = {0, 4, 2, 6};
17617     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17618   }
17619
17620   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17621   // unsigned multiply.
17622   if (IsSigned && !Subtarget->hasSSE41()) {
17623     SDValue ShAmt = DAG.getConstant(
17624         31, dl,
17625         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17626     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17627                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17628     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17629                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17630
17631     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17632     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17633   }
17634
17635   // The first result of MUL_LOHI is actually the low value, followed by the
17636   // high value.
17637   SDValue Ops[] = {Lows, Highs};
17638   return DAG.getMergeValues(Ops, dl);
17639 }
17640
17641 // Return true if the required (according to Opcode) shift-imm form is natively
17642 // supported by the Subtarget
17643 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17644                                         unsigned Opcode) {
17645   if (VT.getScalarSizeInBits() < 16)
17646     return false;
17647
17648   if (VT.is512BitVector() &&
17649       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17650     return true;
17651
17652   bool LShift = VT.is128BitVector() ||
17653     (VT.is256BitVector() && Subtarget->hasInt256());
17654
17655   bool AShift = LShift && (Subtarget->hasVLX() ||
17656     (VT != MVT::v2i64 && VT != MVT::v4i64));
17657   return (Opcode == ISD::SRA) ? AShift : LShift;
17658 }
17659
17660 // The shift amount is a variable, but it is the same for all vector lanes.
17661 // These instructions are defined together with shift-immediate.
17662 static
17663 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17664                                       unsigned Opcode) {
17665   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17666 }
17667
17668 // Return true if the required (according to Opcode) variable-shift form is
17669 // natively supported by the Subtarget
17670 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17671                                     unsigned Opcode) {
17672
17673   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17674     return false;
17675
17676   // vXi16 supported only on AVX-512, BWI
17677   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17678     return false;
17679
17680   if (VT.is512BitVector() || Subtarget->hasVLX())
17681     return true;
17682
17683   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17684   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17685   return (Opcode == ISD::SRA) ? AShift : LShift;
17686 }
17687
17688 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17689                                          const X86Subtarget *Subtarget) {
17690   MVT VT = Op.getSimpleValueType();
17691   SDLoc dl(Op);
17692   SDValue R = Op.getOperand(0);
17693   SDValue Amt = Op.getOperand(1);
17694
17695   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17696     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17697
17698   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17699     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17700     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17701     SDValue Ex = DAG.getBitcast(ExVT, R);
17702
17703     if (ShiftAmt >= 32) {
17704       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17705       SDValue Upper =
17706           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17707       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17708                                                  ShiftAmt - 32, DAG);
17709       if (VT == MVT::v2i64)
17710         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17711       if (VT == MVT::v4i64)
17712         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17713                                   {9, 1, 11, 3, 13, 5, 15, 7});
17714     } else {
17715       // SRA upper i32, SHL whole i64 and select lower i32.
17716       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17717                                                  ShiftAmt, DAG);
17718       SDValue Lower =
17719           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17720       Lower = DAG.getBitcast(ExVT, Lower);
17721       if (VT == MVT::v2i64)
17722         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17723       if (VT == MVT::v4i64)
17724         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17725                                   {8, 1, 10, 3, 12, 5, 14, 7});
17726     }
17727     return DAG.getBitcast(VT, Ex);
17728   };
17729
17730   // Optimize shl/srl/sra with constant shift amount.
17731   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17732     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17733       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17734
17735       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17736         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17737
17738       // i64 SRA needs to be performed as partial shifts.
17739       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17740           Op.getOpcode() == ISD::SRA)
17741         return ArithmeticShiftRight64(ShiftAmt);
17742
17743       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17744         unsigned NumElts = VT.getVectorNumElements();
17745         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17746
17747         if (Op.getOpcode() == ISD::SHL) {
17748           // Simple i8 add case
17749           if (ShiftAmt == 1)
17750             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17751
17752           // Make a large shift.
17753           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17754                                                    R, ShiftAmt, DAG);
17755           SHL = DAG.getBitcast(VT, SHL);
17756           // Zero out the rightmost bits.
17757           SmallVector<SDValue, 32> V(
17758               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17759           return DAG.getNode(ISD::AND, dl, VT, SHL,
17760                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17761         }
17762         if (Op.getOpcode() == ISD::SRL) {
17763           // Make a large shift.
17764           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17765                                                    R, ShiftAmt, DAG);
17766           SRL = DAG.getBitcast(VT, SRL);
17767           // Zero out the leftmost bits.
17768           SmallVector<SDValue, 32> V(
17769               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17770           return DAG.getNode(ISD::AND, dl, VT, SRL,
17771                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17772         }
17773         if (Op.getOpcode() == ISD::SRA) {
17774           if (ShiftAmt == 7) {
17775             // ashr(R, 7)  === cmp_slt(R, 0)
17776             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17777             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17778           }
17779
17780           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17781           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17782           SmallVector<SDValue, 32> V(NumElts,
17783                                      DAG.getConstant(128 >> ShiftAmt, dl,
17784                                                      MVT::i8));
17785           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17786           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17787           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17788           return Res;
17789         }
17790         llvm_unreachable("Unknown shift opcode.");
17791       }
17792     }
17793   }
17794
17795   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17796   if (!Subtarget->is64Bit() &&
17797       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17798
17799     // Peek through any splat that was introduced for i64 shift vectorization.
17800     int SplatIndex = -1;
17801     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17802       if (SVN->isSplat()) {
17803         SplatIndex = SVN->getSplatIndex();
17804         Amt = Amt.getOperand(0);
17805         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17806                "Splat shuffle referencing second operand");
17807       }
17808
17809     if (Amt.getOpcode() != ISD::BITCAST ||
17810         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17811       return SDValue();
17812
17813     Amt = Amt.getOperand(0);
17814     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17815                      VT.getVectorNumElements();
17816     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17817     uint64_t ShiftAmt = 0;
17818     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17819     for (unsigned i = 0; i != Ratio; ++i) {
17820       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17821       if (!C)
17822         return SDValue();
17823       // 6 == Log2(64)
17824       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17825     }
17826
17827     // Check remaining shift amounts (if not a splat).
17828     if (SplatIndex < 0) {
17829       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17830         uint64_t ShAmt = 0;
17831         for (unsigned j = 0; j != Ratio; ++j) {
17832           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17833           if (!C)
17834             return SDValue();
17835           // 6 == Log2(64)
17836           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17837         }
17838         if (ShAmt != ShiftAmt)
17839           return SDValue();
17840       }
17841     }
17842
17843     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17844       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17845
17846     if (Op.getOpcode() == ISD::SRA)
17847       return ArithmeticShiftRight64(ShiftAmt);
17848   }
17849
17850   return SDValue();
17851 }
17852
17853 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17854                                         const X86Subtarget* Subtarget) {
17855   MVT VT = Op.getSimpleValueType();
17856   SDLoc dl(Op);
17857   SDValue R = Op.getOperand(0);
17858   SDValue Amt = Op.getOperand(1);
17859
17860   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17861     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17862
17863   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17864     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17865
17866   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17867     SDValue BaseShAmt;
17868     EVT EltVT = VT.getVectorElementType();
17869
17870     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17871       // Check if this build_vector node is doing a splat.
17872       // If so, then set BaseShAmt equal to the splat value.
17873       BaseShAmt = BV->getSplatValue();
17874       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17875         BaseShAmt = SDValue();
17876     } else {
17877       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17878         Amt = Amt.getOperand(0);
17879
17880       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17881       if (SVN && SVN->isSplat()) {
17882         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17883         SDValue InVec = Amt.getOperand(0);
17884         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17885           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17886                  "Unexpected shuffle index found!");
17887           BaseShAmt = InVec.getOperand(SplatIdx);
17888         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17889            if (ConstantSDNode *C =
17890                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17891              if (C->getZExtValue() == SplatIdx)
17892                BaseShAmt = InVec.getOperand(1);
17893            }
17894         }
17895
17896         if (!BaseShAmt)
17897           // Avoid introducing an extract element from a shuffle.
17898           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17899                                   DAG.getIntPtrConstant(SplatIdx, dl));
17900       }
17901     }
17902
17903     if (BaseShAmt.getNode()) {
17904       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17905       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17906         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17907       else if (EltVT.bitsLT(MVT::i32))
17908         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17909
17910       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17911     }
17912   }
17913
17914   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17915   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17916       Amt.getOpcode() == ISD::BITCAST &&
17917       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17918     Amt = Amt.getOperand(0);
17919     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17920                      VT.getVectorNumElements();
17921     std::vector<SDValue> Vals(Ratio);
17922     for (unsigned i = 0; i != Ratio; ++i)
17923       Vals[i] = Amt.getOperand(i);
17924     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17925       for (unsigned j = 0; j != Ratio; ++j)
17926         if (Vals[j] != Amt.getOperand(i + j))
17927           return SDValue();
17928     }
17929
17930     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17931       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17932   }
17933   return SDValue();
17934 }
17935
17936 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17937                           SelectionDAG &DAG) {
17938   MVT VT = Op.getSimpleValueType();
17939   SDLoc dl(Op);
17940   SDValue R = Op.getOperand(0);
17941   SDValue Amt = Op.getOperand(1);
17942
17943   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17944   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17945
17946   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17947     return V;
17948
17949   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17950       return V;
17951
17952   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17953     return Op;
17954
17955   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17956   // shifts per-lane and then shuffle the partial results back together.
17957   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17958     // Splat the shift amounts so the scalar shifts above will catch it.
17959     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17960     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17961     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17962     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17963     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17964   }
17965
17966   // i64 vector arithmetic shift can be emulated with the transform:
17967   // M = lshr(SIGN_BIT, Amt)
17968   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17969   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17970       Op.getOpcode() == ISD::SRA) {
17971     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17972     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17973     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17974     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17975     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17976     return R;
17977   }
17978
17979   // If possible, lower this packed shift into a vector multiply instead of
17980   // expanding it into a sequence of scalar shifts.
17981   // Do this only if the vector shift count is a constant build_vector.
17982   if (Op.getOpcode() == ISD::SHL &&
17983       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17984        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17985       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17986     SmallVector<SDValue, 8> Elts;
17987     EVT SVT = VT.getScalarType();
17988     unsigned SVTBits = SVT.getSizeInBits();
17989     const APInt &One = APInt(SVTBits, 1);
17990     unsigned NumElems = VT.getVectorNumElements();
17991
17992     for (unsigned i=0; i !=NumElems; ++i) {
17993       SDValue Op = Amt->getOperand(i);
17994       if (Op->getOpcode() == ISD::UNDEF) {
17995         Elts.push_back(Op);
17996         continue;
17997       }
17998
17999       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18000       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18001       uint64_t ShAmt = C.getZExtValue();
18002       if (ShAmt >= SVTBits) {
18003         Elts.push_back(DAG.getUNDEF(SVT));
18004         continue;
18005       }
18006       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18007     }
18008     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18009     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18010   }
18011
18012   // Lower SHL with variable shift amount.
18013   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18014     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18015
18016     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18017                      DAG.getConstant(0x3f800000U, dl, VT));
18018     Op = DAG.getBitcast(MVT::v4f32, Op);
18019     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18020     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18021   }
18022
18023   // If possible, lower this shift as a sequence of two shifts by
18024   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18025   // Example:
18026   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18027   //
18028   // Could be rewritten as:
18029   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18030   //
18031   // The advantage is that the two shifts from the example would be
18032   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18033   // the vector shift into four scalar shifts plus four pairs of vector
18034   // insert/extract.
18035   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18036       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18037     unsigned TargetOpcode = X86ISD::MOVSS;
18038     bool CanBeSimplified;
18039     // The splat value for the first packed shift (the 'X' from the example).
18040     SDValue Amt1 = Amt->getOperand(0);
18041     // The splat value for the second packed shift (the 'Y' from the example).
18042     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18043                                         Amt->getOperand(2);
18044
18045     // See if it is possible to replace this node with a sequence of
18046     // two shifts followed by a MOVSS/MOVSD
18047     if (VT == MVT::v4i32) {
18048       // Check if it is legal to use a MOVSS.
18049       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18050                         Amt2 == Amt->getOperand(3);
18051       if (!CanBeSimplified) {
18052         // Otherwise, check if we can still simplify this node using a MOVSD.
18053         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18054                           Amt->getOperand(2) == Amt->getOperand(3);
18055         TargetOpcode = X86ISD::MOVSD;
18056         Amt2 = Amt->getOperand(2);
18057       }
18058     } else {
18059       // Do similar checks for the case where the machine value type
18060       // is MVT::v8i16.
18061       CanBeSimplified = Amt1 == Amt->getOperand(1);
18062       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18063         CanBeSimplified = Amt2 == Amt->getOperand(i);
18064
18065       if (!CanBeSimplified) {
18066         TargetOpcode = X86ISD::MOVSD;
18067         CanBeSimplified = true;
18068         Amt2 = Amt->getOperand(4);
18069         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18070           CanBeSimplified = Amt1 == Amt->getOperand(i);
18071         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18072           CanBeSimplified = Amt2 == Amt->getOperand(j);
18073       }
18074     }
18075
18076     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18077         isa<ConstantSDNode>(Amt2)) {
18078       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18079       EVT CastVT = MVT::v4i32;
18080       SDValue Splat1 =
18081         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18082       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18083       SDValue Splat2 =
18084         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18085       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18086       if (TargetOpcode == X86ISD::MOVSD)
18087         CastVT = MVT::v2i64;
18088       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18089       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18090       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18091                                             BitCast1, DAG);
18092       return DAG.getBitcast(VT, Result);
18093     }
18094   }
18095
18096   // v4i32 Non Uniform Shifts.
18097   // If the shift amount is constant we can shift each lane using the SSE2
18098   // immediate shifts, else we need to zero-extend each lane to the lower i64
18099   // and shift using the SSE2 variable shifts.
18100   // The separate results can then be blended together.
18101   if (VT == MVT::v4i32) {
18102     unsigned Opc = Op.getOpcode();
18103     SDValue Amt0, Amt1, Amt2, Amt3;
18104     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18105       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18106       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18107       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18108       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18109     } else {
18110       // ISD::SHL is handled above but we include it here for completeness.
18111       switch (Opc) {
18112       default:
18113         llvm_unreachable("Unknown target vector shift node");
18114       case ISD::SHL:
18115         Opc = X86ISD::VSHL;
18116         break;
18117       case ISD::SRL:
18118         Opc = X86ISD::VSRL;
18119         break;
18120       case ISD::SRA:
18121         Opc = X86ISD::VSRA;
18122         break;
18123       }
18124       // The SSE2 shifts use the lower i64 as the same shift amount for
18125       // all lanes and the upper i64 is ignored. These shuffle masks
18126       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18127       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18128       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18129       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18130       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18131       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18132     }
18133
18134     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18135     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18136     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18137     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18138     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18139     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18140     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18141   }
18142
18143   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18144     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18145     unsigned ShiftOpcode = Op->getOpcode();
18146
18147     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18148       // On SSE41 targets we make use of the fact that VSELECT lowers
18149       // to PBLENDVB which selects bytes based just on the sign bit.
18150       if (Subtarget->hasSSE41()) {
18151         V0 = DAG.getBitcast(VT, V0);
18152         V1 = DAG.getBitcast(VT, V1);
18153         Sel = DAG.getBitcast(VT, Sel);
18154         return DAG.getBitcast(SelVT,
18155                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18156       }
18157       // On pre-SSE41 targets we test for the sign bit by comparing to
18158       // zero - a negative value will set all bits of the lanes to true
18159       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18160       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18161       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18162       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18163     };
18164
18165     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18166     // We can safely do this using i16 shifts as we're only interested in
18167     // the 3 lower bits of each byte.
18168     Amt = DAG.getBitcast(ExtVT, Amt);
18169     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18170     Amt = DAG.getBitcast(VT, Amt);
18171
18172     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18173       // r = VSELECT(r, shift(r, 4), a);
18174       SDValue M =
18175           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18176       R = SignBitSelect(VT, Amt, M, R);
18177
18178       // a += a
18179       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18180
18181       // r = VSELECT(r, shift(r, 2), a);
18182       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18183       R = SignBitSelect(VT, Amt, M, R);
18184
18185       // a += a
18186       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18187
18188       // return VSELECT(r, shift(r, 1), a);
18189       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18190       R = SignBitSelect(VT, Amt, M, R);
18191       return R;
18192     }
18193
18194     if (Op->getOpcode() == ISD::SRA) {
18195       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18196       // so we can correctly sign extend. We don't care what happens to the
18197       // lower byte.
18198       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18199       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18200       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18201       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18202       ALo = DAG.getBitcast(ExtVT, ALo);
18203       AHi = DAG.getBitcast(ExtVT, AHi);
18204       RLo = DAG.getBitcast(ExtVT, RLo);
18205       RHi = DAG.getBitcast(ExtVT, RHi);
18206
18207       // r = VSELECT(r, shift(r, 4), a);
18208       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18209                                 DAG.getConstant(4, dl, ExtVT));
18210       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18211                                 DAG.getConstant(4, dl, ExtVT));
18212       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18213       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18214
18215       // a += a
18216       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18217       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18218
18219       // r = VSELECT(r, shift(r, 2), a);
18220       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18221                         DAG.getConstant(2, dl, ExtVT));
18222       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18223                         DAG.getConstant(2, dl, ExtVT));
18224       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18225       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18226
18227       // a += a
18228       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18229       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18230
18231       // r = VSELECT(r, shift(r, 1), a);
18232       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18233                         DAG.getConstant(1, dl, ExtVT));
18234       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18235                         DAG.getConstant(1, dl, ExtVT));
18236       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18237       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18238
18239       // Logical shift the result back to the lower byte, leaving a zero upper
18240       // byte
18241       // meaning that we can safely pack with PACKUSWB.
18242       RLo =
18243           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18244       RHi =
18245           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18246       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18247     }
18248   }
18249
18250   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18251   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18252   // solution better.
18253   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18254     MVT ExtVT = MVT::v8i32;
18255     unsigned ExtOpc =
18256         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18257     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18258     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18259     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18260                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18261   }
18262
18263   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18264     MVT ExtVT = MVT::v8i32;
18265     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18266     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18267     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18268     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18269     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18270     ALo = DAG.getBitcast(ExtVT, ALo);
18271     AHi = DAG.getBitcast(ExtVT, AHi);
18272     RLo = DAG.getBitcast(ExtVT, RLo);
18273     RHi = DAG.getBitcast(ExtVT, RHi);
18274     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18275     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18276     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18277     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18278     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18279   }
18280
18281   if (VT == MVT::v8i16) {
18282     unsigned ShiftOpcode = Op->getOpcode();
18283
18284     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18285       // On SSE41 targets we make use of the fact that VSELECT lowers
18286       // to PBLENDVB which selects bytes based just on the sign bit.
18287       if (Subtarget->hasSSE41()) {
18288         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18289         V0 = DAG.getBitcast(ExtVT, V0);
18290         V1 = DAG.getBitcast(ExtVT, V1);
18291         Sel = DAG.getBitcast(ExtVT, Sel);
18292         return DAG.getBitcast(
18293             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18294       }
18295       // On pre-SSE41 targets we splat the sign bit - a negative value will
18296       // set all bits of the lanes to true and VSELECT uses that in
18297       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18298       SDValue C =
18299           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18300       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18301     };
18302
18303     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18304     if (Subtarget->hasSSE41()) {
18305       // On SSE41 targets we need to replicate the shift mask in both
18306       // bytes for PBLENDVB.
18307       Amt = DAG.getNode(
18308           ISD::OR, dl, VT,
18309           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18310           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18311     } else {
18312       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18313     }
18314
18315     // r = VSELECT(r, shift(r, 8), a);
18316     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18317     R = SignBitSelect(Amt, M, R);
18318
18319     // a += a
18320     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18321
18322     // r = VSELECT(r, shift(r, 4), a);
18323     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18324     R = SignBitSelect(Amt, M, R);
18325
18326     // a += a
18327     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18328
18329     // r = VSELECT(r, shift(r, 2), a);
18330     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18331     R = SignBitSelect(Amt, M, R);
18332
18333     // a += a
18334     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18335
18336     // return VSELECT(r, shift(r, 1), a);
18337     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18338     R = SignBitSelect(Amt, M, R);
18339     return R;
18340   }
18341
18342   // Decompose 256-bit shifts into smaller 128-bit shifts.
18343   if (VT.is256BitVector()) {
18344     unsigned NumElems = VT.getVectorNumElements();
18345     MVT EltVT = VT.getVectorElementType();
18346     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18347
18348     // Extract the two vectors
18349     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18350     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18351
18352     // Recreate the shift amount vectors
18353     SDValue Amt1, Amt2;
18354     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18355       // Constant shift amount
18356       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18357       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18358       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18359
18360       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18361       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18362     } else {
18363       // Variable shift amount
18364       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18365       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18366     }
18367
18368     // Issue new vector shifts for the smaller types
18369     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18370     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18371
18372     // Concatenate the result back
18373     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18374   }
18375
18376   return SDValue();
18377 }
18378
18379 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18380   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18381   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18382   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18383   // has only one use.
18384   SDNode *N = Op.getNode();
18385   SDValue LHS = N->getOperand(0);
18386   SDValue RHS = N->getOperand(1);
18387   unsigned BaseOp = 0;
18388   unsigned Cond = 0;
18389   SDLoc DL(Op);
18390   switch (Op.getOpcode()) {
18391   default: llvm_unreachable("Unknown ovf instruction!");
18392   case ISD::SADDO:
18393     // A subtract of one will be selected as a INC. Note that INC doesn't
18394     // set CF, so we can't do this for UADDO.
18395     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18396       if (C->isOne()) {
18397         BaseOp = X86ISD::INC;
18398         Cond = X86::COND_O;
18399         break;
18400       }
18401     BaseOp = X86ISD::ADD;
18402     Cond = X86::COND_O;
18403     break;
18404   case ISD::UADDO:
18405     BaseOp = X86ISD::ADD;
18406     Cond = X86::COND_B;
18407     break;
18408   case ISD::SSUBO:
18409     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18410     // set CF, so we can't do this for USUBO.
18411     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18412       if (C->isOne()) {
18413         BaseOp = X86ISD::DEC;
18414         Cond = X86::COND_O;
18415         break;
18416       }
18417     BaseOp = X86ISD::SUB;
18418     Cond = X86::COND_O;
18419     break;
18420   case ISD::USUBO:
18421     BaseOp = X86ISD::SUB;
18422     Cond = X86::COND_B;
18423     break;
18424   case ISD::SMULO:
18425     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18426     Cond = X86::COND_O;
18427     break;
18428   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18429     if (N->getValueType(0) == MVT::i8) {
18430       BaseOp = X86ISD::UMUL8;
18431       Cond = X86::COND_O;
18432       break;
18433     }
18434     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18435                                  MVT::i32);
18436     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18437
18438     SDValue SetCC =
18439       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18440                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18441                   SDValue(Sum.getNode(), 2));
18442
18443     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18444   }
18445   }
18446
18447   // Also sets EFLAGS.
18448   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18449   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18450
18451   SDValue SetCC =
18452     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18453                 DAG.getConstant(Cond, DL, MVT::i32),
18454                 SDValue(Sum.getNode(), 1));
18455
18456   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18457 }
18458
18459 /// Returns true if the operand type is exactly twice the native width, and
18460 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18461 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18462 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18463 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18464   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18465
18466   if (OpWidth == 64)
18467     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18468   else if (OpWidth == 128)
18469     return Subtarget->hasCmpxchg16b();
18470   else
18471     return false;
18472 }
18473
18474 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18475   return needsCmpXchgNb(SI->getValueOperand()->getType());
18476 }
18477
18478 // Note: this turns large loads into lock cmpxchg8b/16b.
18479 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18480 TargetLowering::AtomicExpansionKind
18481 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18482   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18483   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18484                                                : AtomicExpansionKind::None;
18485 }
18486
18487 TargetLowering::AtomicExpansionKind
18488 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18489   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18490   Type *MemType = AI->getType();
18491
18492   // If the operand is too big, we must see if cmpxchg8/16b is available
18493   // and default to library calls otherwise.
18494   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18495     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18496                                    : AtomicExpansionKind::None;
18497   }
18498
18499   AtomicRMWInst::BinOp Op = AI->getOperation();
18500   switch (Op) {
18501   default:
18502     llvm_unreachable("Unknown atomic operation");
18503   case AtomicRMWInst::Xchg:
18504   case AtomicRMWInst::Add:
18505   case AtomicRMWInst::Sub:
18506     // It's better to use xadd, xsub or xchg for these in all cases.
18507     return AtomicExpansionKind::None;
18508   case AtomicRMWInst::Or:
18509   case AtomicRMWInst::And:
18510   case AtomicRMWInst::Xor:
18511     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18512     // prefix to a normal instruction for these operations.
18513     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18514                             : AtomicExpansionKind::None;
18515   case AtomicRMWInst::Nand:
18516   case AtomicRMWInst::Max:
18517   case AtomicRMWInst::Min:
18518   case AtomicRMWInst::UMax:
18519   case AtomicRMWInst::UMin:
18520     // These always require a non-trivial set of data operations on x86. We must
18521     // use a cmpxchg loop.
18522     return AtomicExpansionKind::CmpXChg;
18523   }
18524 }
18525
18526 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18527   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18528   // no-sse2). There isn't any reason to disable it if the target processor
18529   // supports it.
18530   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18531 }
18532
18533 LoadInst *
18534 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18535   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18536   Type *MemType = AI->getType();
18537   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18538   // there is no benefit in turning such RMWs into loads, and it is actually
18539   // harmful as it introduces a mfence.
18540   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18541     return nullptr;
18542
18543   auto Builder = IRBuilder<>(AI);
18544   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18545   auto SynchScope = AI->getSynchScope();
18546   // We must restrict the ordering to avoid generating loads with Release or
18547   // ReleaseAcquire orderings.
18548   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18549   auto Ptr = AI->getPointerOperand();
18550
18551   // Before the load we need a fence. Here is an example lifted from
18552   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18553   // is required:
18554   // Thread 0:
18555   //   x.store(1, relaxed);
18556   //   r1 = y.fetch_add(0, release);
18557   // Thread 1:
18558   //   y.fetch_add(42, acquire);
18559   //   r2 = x.load(relaxed);
18560   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18561   // lowered to just a load without a fence. A mfence flushes the store buffer,
18562   // making the optimization clearly correct.
18563   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18564   // otherwise, we might be able to be more aggressive on relaxed idempotent
18565   // rmw. In practice, they do not look useful, so we don't try to be
18566   // especially clever.
18567   if (SynchScope == SingleThread)
18568     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18569     // the IR level, so we must wrap it in an intrinsic.
18570     return nullptr;
18571
18572   if (!hasMFENCE(*Subtarget))
18573     // FIXME: it might make sense to use a locked operation here but on a
18574     // different cache-line to prevent cache-line bouncing. In practice it
18575     // is probably a small win, and x86 processors without mfence are rare
18576     // enough that we do not bother.
18577     return nullptr;
18578
18579   Function *MFence =
18580       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18581   Builder.CreateCall(MFence, {});
18582
18583   // Finally we can emit the atomic load.
18584   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18585           AI->getType()->getPrimitiveSizeInBits());
18586   Loaded->setAtomic(Order, SynchScope);
18587   AI->replaceAllUsesWith(Loaded);
18588   AI->eraseFromParent();
18589   return Loaded;
18590 }
18591
18592 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18593                                  SelectionDAG &DAG) {
18594   SDLoc dl(Op);
18595   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18596     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18597   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18598     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18599
18600   // The only fence that needs an instruction is a sequentially-consistent
18601   // cross-thread fence.
18602   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18603     if (hasMFENCE(*Subtarget))
18604       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18605
18606     SDValue Chain = Op.getOperand(0);
18607     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18608     SDValue Ops[] = {
18609       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18610       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18611       DAG.getRegister(0, MVT::i32),            // Index
18612       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18613       DAG.getRegister(0, MVT::i32),            // Segment.
18614       Zero,
18615       Chain
18616     };
18617     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18618     return SDValue(Res, 0);
18619   }
18620
18621   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18622   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18623 }
18624
18625 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18626                              SelectionDAG &DAG) {
18627   MVT T = Op.getSimpleValueType();
18628   SDLoc DL(Op);
18629   unsigned Reg = 0;
18630   unsigned size = 0;
18631   switch(T.SimpleTy) {
18632   default: llvm_unreachable("Invalid value type!");
18633   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18634   case MVT::i16: Reg = X86::AX;  size = 2; break;
18635   case MVT::i32: Reg = X86::EAX; size = 4; break;
18636   case MVT::i64:
18637     assert(Subtarget->is64Bit() && "Node not type legal!");
18638     Reg = X86::RAX; size = 8;
18639     break;
18640   }
18641   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18642                                   Op.getOperand(2), SDValue());
18643   SDValue Ops[] = { cpIn.getValue(0),
18644                     Op.getOperand(1),
18645                     Op.getOperand(3),
18646                     DAG.getTargetConstant(size, DL, MVT::i8),
18647                     cpIn.getValue(1) };
18648   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18649   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18650   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18651                                            Ops, T, MMO);
18652
18653   SDValue cpOut =
18654     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18655   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18656                                       MVT::i32, cpOut.getValue(2));
18657   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18658                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18659                                 EFLAGS);
18660
18661   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18662   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18663   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18664   return SDValue();
18665 }
18666
18667 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18668                             SelectionDAG &DAG) {
18669   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18670   MVT DstVT = Op.getSimpleValueType();
18671
18672   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18673     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18674     if (DstVT != MVT::f64)
18675       // This conversion needs to be expanded.
18676       return SDValue();
18677
18678     SDValue InVec = Op->getOperand(0);
18679     SDLoc dl(Op);
18680     unsigned NumElts = SrcVT.getVectorNumElements();
18681     EVT SVT = SrcVT.getVectorElementType();
18682
18683     // Widen the vector in input in the case of MVT::v2i32.
18684     // Example: from MVT::v2i32 to MVT::v4i32.
18685     SmallVector<SDValue, 16> Elts;
18686     for (unsigned i = 0, e = NumElts; i != e; ++i)
18687       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18688                                  DAG.getIntPtrConstant(i, dl)));
18689
18690     // Explicitly mark the extra elements as Undef.
18691     Elts.append(NumElts, DAG.getUNDEF(SVT));
18692
18693     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18694     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18695     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18696     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18697                        DAG.getIntPtrConstant(0, dl));
18698   }
18699
18700   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18701          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18702   assert((DstVT == MVT::i64 ||
18703           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18704          "Unexpected custom BITCAST");
18705   // i64 <=> MMX conversions are Legal.
18706   if (SrcVT==MVT::i64 && DstVT.isVector())
18707     return Op;
18708   if (DstVT==MVT::i64 && SrcVT.isVector())
18709     return Op;
18710   // MMX <=> MMX conversions are Legal.
18711   if (SrcVT.isVector() && DstVT.isVector())
18712     return Op;
18713   // All other conversions need to be expanded.
18714   return SDValue();
18715 }
18716
18717 /// Compute the horizontal sum of bytes in V for the elements of VT.
18718 ///
18719 /// Requires V to be a byte vector and VT to be an integer vector type with
18720 /// wider elements than V's type. The width of the elements of VT determines
18721 /// how many bytes of V are summed horizontally to produce each element of the
18722 /// result.
18723 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18724                                       const X86Subtarget *Subtarget,
18725                                       SelectionDAG &DAG) {
18726   SDLoc DL(V);
18727   MVT ByteVecVT = V.getSimpleValueType();
18728   MVT EltVT = VT.getVectorElementType();
18729   int NumElts = VT.getVectorNumElements();
18730   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18731          "Expected value to have byte element type.");
18732   assert(EltVT != MVT::i8 &&
18733          "Horizontal byte sum only makes sense for wider elements!");
18734   unsigned VecSize = VT.getSizeInBits();
18735   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18736
18737   // PSADBW instruction horizontally add all bytes and leave the result in i64
18738   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18739   if (EltVT == MVT::i64) {
18740     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18741     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18742     return DAG.getBitcast(VT, V);
18743   }
18744
18745   if (EltVT == MVT::i32) {
18746     // We unpack the low half and high half into i32s interleaved with zeros so
18747     // that we can use PSADBW to horizontally sum them. The most useful part of
18748     // this is that it lines up the results of two PSADBW instructions to be
18749     // two v2i64 vectors which concatenated are the 4 population counts. We can
18750     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18751     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18752     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18753     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18754
18755     // Do the horizontal sums into two v2i64s.
18756     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18757     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18758                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18759     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18760                        DAG.getBitcast(ByteVecVT, High), Zeros);
18761
18762     // Merge them together.
18763     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18764     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18765                     DAG.getBitcast(ShortVecVT, Low),
18766                     DAG.getBitcast(ShortVecVT, High));
18767
18768     return DAG.getBitcast(VT, V);
18769   }
18770
18771   // The only element type left is i16.
18772   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18773
18774   // To obtain pop count for each i16 element starting from the pop count for
18775   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18776   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18777   // directly supported.
18778   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18779   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18780   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18781   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18782                   DAG.getBitcast(ByteVecVT, V));
18783   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18784 }
18785
18786 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18787                                         const X86Subtarget *Subtarget,
18788                                         SelectionDAG &DAG) {
18789   MVT VT = Op.getSimpleValueType();
18790   MVT EltVT = VT.getVectorElementType();
18791   unsigned VecSize = VT.getSizeInBits();
18792
18793   // Implement a lookup table in register by using an algorithm based on:
18794   // http://wm.ite.pl/articles/sse-popcount.html
18795   //
18796   // The general idea is that every lower byte nibble in the input vector is an
18797   // index into a in-register pre-computed pop count table. We then split up the
18798   // input vector in two new ones: (1) a vector with only the shifted-right
18799   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18800   // masked out higher ones) for each byte. PSHUB is used separately with both
18801   // to index the in-register table. Next, both are added and the result is a
18802   // i8 vector where each element contains the pop count for input byte.
18803   //
18804   // To obtain the pop count for elements != i8, we follow up with the same
18805   // approach and use additional tricks as described below.
18806   //
18807   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18808                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18809                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18810                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18811
18812   int NumByteElts = VecSize / 8;
18813   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18814   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18815   SmallVector<SDValue, 16> LUTVec;
18816   for (int i = 0; i < NumByteElts; ++i)
18817     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18818   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18819   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18820                                   DAG.getConstant(0x0F, DL, MVT::i8));
18821   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18822
18823   // High nibbles
18824   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18825   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18826   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18827
18828   // Low nibbles
18829   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18830
18831   // The input vector is used as the shuffle mask that index elements into the
18832   // LUT. After counting low and high nibbles, add the vector to obtain the
18833   // final pop count per i8 element.
18834   SDValue HighPopCnt =
18835       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18836   SDValue LowPopCnt =
18837       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18838   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18839
18840   if (EltVT == MVT::i8)
18841     return PopCnt;
18842
18843   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18844 }
18845
18846 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18847                                        const X86Subtarget *Subtarget,
18848                                        SelectionDAG &DAG) {
18849   MVT VT = Op.getSimpleValueType();
18850   assert(VT.is128BitVector() &&
18851          "Only 128-bit vector bitmath lowering supported.");
18852
18853   int VecSize = VT.getSizeInBits();
18854   MVT EltVT = VT.getVectorElementType();
18855   int Len = EltVT.getSizeInBits();
18856
18857   // This is the vectorized version of the "best" algorithm from
18858   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18859   // with a minor tweak to use a series of adds + shifts instead of vector
18860   // multiplications. Implemented for all integer vector types. We only use
18861   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18862   // much faster, even faster than using native popcnt instructions.
18863
18864   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18865     MVT VT = V.getSimpleValueType();
18866     SmallVector<SDValue, 32> Shifters(
18867         VT.getVectorNumElements(),
18868         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18869     return DAG.getNode(OpCode, DL, VT, V,
18870                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18871   };
18872   auto GetMask = [&](SDValue V, APInt Mask) {
18873     MVT VT = V.getSimpleValueType();
18874     SmallVector<SDValue, 32> Masks(
18875         VT.getVectorNumElements(),
18876         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18877     return DAG.getNode(ISD::AND, DL, VT, V,
18878                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18879   };
18880
18881   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18882   // x86, so set the SRL type to have elements at least i16 wide. This is
18883   // correct because all of our SRLs are followed immediately by a mask anyways
18884   // that handles any bits that sneak into the high bits of the byte elements.
18885   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18886
18887   SDValue V = Op;
18888
18889   // v = v - ((v >> 1) & 0x55555555...)
18890   SDValue Srl =
18891       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18892   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18893   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18894
18895   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18896   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18897   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18898   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18899   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18900
18901   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18902   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18903   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18904   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18905
18906   // At this point, V contains the byte-wise population count, and we are
18907   // merely doing a horizontal sum if necessary to get the wider element
18908   // counts.
18909   if (EltVT == MVT::i8)
18910     return V;
18911
18912   return LowerHorizontalByteSum(
18913       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18914       DAG);
18915 }
18916
18917 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18918                                 SelectionDAG &DAG) {
18919   MVT VT = Op.getSimpleValueType();
18920   // FIXME: Need to add AVX-512 support here!
18921   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18922          "Unknown CTPOP type to handle");
18923   SDLoc DL(Op.getNode());
18924   SDValue Op0 = Op.getOperand(0);
18925
18926   if (!Subtarget->hasSSSE3()) {
18927     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18928     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18929     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18930   }
18931
18932   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18933     unsigned NumElems = VT.getVectorNumElements();
18934
18935     // Extract each 128-bit vector, compute pop count and concat the result.
18936     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18937     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18938
18939     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18940                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18941                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18942   }
18943
18944   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18945 }
18946
18947 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18948                           SelectionDAG &DAG) {
18949   assert(Op.getValueType().isVector() &&
18950          "We only do custom lowering for vector population count.");
18951   return LowerVectorCTPOP(Op, Subtarget, DAG);
18952 }
18953
18954 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18955   SDNode *Node = Op.getNode();
18956   SDLoc dl(Node);
18957   EVT T = Node->getValueType(0);
18958   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18959                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18960   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18961                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18962                        Node->getOperand(0),
18963                        Node->getOperand(1), negOp,
18964                        cast<AtomicSDNode>(Node)->getMemOperand(),
18965                        cast<AtomicSDNode>(Node)->getOrdering(),
18966                        cast<AtomicSDNode>(Node)->getSynchScope());
18967 }
18968
18969 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18970   SDNode *Node = Op.getNode();
18971   SDLoc dl(Node);
18972   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18973
18974   // Convert seq_cst store -> xchg
18975   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18976   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18977   //        (The only way to get a 16-byte store is cmpxchg16b)
18978   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18979   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18980       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18981     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18982                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18983                                  Node->getOperand(0),
18984                                  Node->getOperand(1), Node->getOperand(2),
18985                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18986                                  cast<AtomicSDNode>(Node)->getOrdering(),
18987                                  cast<AtomicSDNode>(Node)->getSynchScope());
18988     return Swap.getValue(1);
18989   }
18990   // Other atomic stores have a simple pattern.
18991   return Op;
18992 }
18993
18994 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18995   EVT VT = Op.getNode()->getSimpleValueType(0);
18996
18997   // Let legalize expand this if it isn't a legal type yet.
18998   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18999     return SDValue();
19000
19001   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19002
19003   unsigned Opc;
19004   bool ExtraOp = false;
19005   switch (Op.getOpcode()) {
19006   default: llvm_unreachable("Invalid code");
19007   case ISD::ADDC: Opc = X86ISD::ADD; break;
19008   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19009   case ISD::SUBC: Opc = X86ISD::SUB; break;
19010   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19011   }
19012
19013   if (!ExtraOp)
19014     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19015                        Op.getOperand(1));
19016   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19017                      Op.getOperand(1), Op.getOperand(2));
19018 }
19019
19020 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19021                             SelectionDAG &DAG) {
19022   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19023
19024   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19025   // which returns the values as { float, float } (in XMM0) or
19026   // { double, double } (which is returned in XMM0, XMM1).
19027   SDLoc dl(Op);
19028   SDValue Arg = Op.getOperand(0);
19029   EVT ArgVT = Arg.getValueType();
19030   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19031
19032   TargetLowering::ArgListTy Args;
19033   TargetLowering::ArgListEntry Entry;
19034
19035   Entry.Node = Arg;
19036   Entry.Ty = ArgTy;
19037   Entry.isSExt = false;
19038   Entry.isZExt = false;
19039   Args.push_back(Entry);
19040
19041   bool isF64 = ArgVT == MVT::f64;
19042   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19043   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19044   // the results are returned via SRet in memory.
19045   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19046   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19047   SDValue Callee =
19048       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19049
19050   Type *RetTy = isF64
19051     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19052     : (Type*)VectorType::get(ArgTy, 4);
19053
19054   TargetLowering::CallLoweringInfo CLI(DAG);
19055   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19056     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19057
19058   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19059
19060   if (isF64)
19061     // Returned in xmm0 and xmm1.
19062     return CallResult.first;
19063
19064   // Returned in bits 0:31 and 32:64 xmm0.
19065   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19066                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19067   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19068                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19069   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19070   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19071 }
19072
19073 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19074                              SelectionDAG &DAG) {
19075   assert(Subtarget->hasAVX512() &&
19076          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19077
19078   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19079   EVT VT = N->getValue().getValueType();
19080   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19081   SDLoc dl(Op);
19082
19083   // X86 scatter kills mask register, so its type should be added to
19084   // the list of return values
19085   if (N->getNumValues() == 1) {
19086     SDValue Index = N->getIndex();
19087     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19088         !Index.getValueType().is512BitVector())
19089       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19090
19091     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19092     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19093                       N->getOperand(3), Index };
19094
19095     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19096     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19097     return SDValue(NewScatter.getNode(), 0);
19098   }
19099   return Op;
19100 }
19101
19102 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19103                             SelectionDAG &DAG) {
19104   assert(Subtarget->hasAVX512() &&
19105          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19106
19107   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19108   EVT VT = Op.getValueType();
19109   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19110   SDLoc dl(Op);
19111
19112   SDValue Index = N->getIndex();
19113   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19114       !Index.getValueType().is512BitVector()) {
19115     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19116     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19117                       N->getOperand(3), Index };
19118     DAG.UpdateNodeOperands(N, Ops);
19119   }
19120   return Op;
19121 }
19122
19123 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19124                                                     SelectionDAG &DAG) const {
19125   // TODO: Eventually, the lowering of these nodes should be informed by or
19126   // deferred to the GC strategy for the function in which they appear. For
19127   // now, however, they must be lowered to something. Since they are logically
19128   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19129   // require special handling for these nodes), lower them as literal NOOPs for
19130   // the time being.
19131   SmallVector<SDValue, 2> Ops;
19132
19133   Ops.push_back(Op.getOperand(0));
19134   if (Op->getGluedNode())
19135     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19136
19137   SDLoc OpDL(Op);
19138   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19139   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19140
19141   return NOOP;
19142 }
19143
19144 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19145                                                   SelectionDAG &DAG) const {
19146   // TODO: Eventually, the lowering of these nodes should be informed by or
19147   // deferred to the GC strategy for the function in which they appear. For
19148   // now, however, they must be lowered to something. Since they are logically
19149   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19150   // require special handling for these nodes), lower them as literal NOOPs for
19151   // the time being.
19152   SmallVector<SDValue, 2> Ops;
19153
19154   Ops.push_back(Op.getOperand(0));
19155   if (Op->getGluedNode())
19156     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19157
19158   SDLoc OpDL(Op);
19159   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19160   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19161
19162   return NOOP;
19163 }
19164
19165 /// LowerOperation - Provide custom lowering hooks for some operations.
19166 ///
19167 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19168   switch (Op.getOpcode()) {
19169   default: llvm_unreachable("Should not custom lower this!");
19170   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19171   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19172     return LowerCMP_SWAP(Op, Subtarget, DAG);
19173   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19174   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19175   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19176   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19177   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19178   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19179   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19180   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19181   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19182   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19183   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19184   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19185   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19186   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19187   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19188   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19189   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19190   case ISD::SHL_PARTS:
19191   case ISD::SRA_PARTS:
19192   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19193   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19194   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19195   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19196   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19197   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19198   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19199   case ISD::SIGN_EXTEND_VECTOR_INREG:
19200     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19201   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19202   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19203   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19204   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19205   case ISD::FABS:
19206   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19207   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19208   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19209   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19210   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19211   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19212   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19213   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19214   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19215   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19216   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19217   case ISD::INTRINSIC_VOID:
19218   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19219   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19220   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19221   case ISD::FRAME_TO_ARGS_OFFSET:
19222                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19223   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19224   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19225   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19226   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19227   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19228   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19229   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19230   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19231   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19232   case ISD::CTTZ:
19233   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19234   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19235   case ISD::UMUL_LOHI:
19236   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19237   case ISD::SRA:
19238   case ISD::SRL:
19239   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19240   case ISD::SADDO:
19241   case ISD::UADDO:
19242   case ISD::SSUBO:
19243   case ISD::USUBO:
19244   case ISD::SMULO:
19245   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19246   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19247   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19248   case ISD::ADDC:
19249   case ISD::ADDE:
19250   case ISD::SUBC:
19251   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19252   case ISD::ADD:                return LowerADD(Op, DAG);
19253   case ISD::SUB:                return LowerSUB(Op, DAG);
19254   case ISD::SMAX:
19255   case ISD::SMIN:
19256   case ISD::UMAX:
19257   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19258   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19259   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19260   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19261   case ISD::GC_TRANSITION_START:
19262                                 return LowerGC_TRANSITION_START(Op, DAG);
19263   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19264   }
19265 }
19266
19267 /// ReplaceNodeResults - Replace a node with an illegal result type
19268 /// with a new node built out of custom code.
19269 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19270                                            SmallVectorImpl<SDValue>&Results,
19271                                            SelectionDAG &DAG) const {
19272   SDLoc dl(N);
19273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19274   switch (N->getOpcode()) {
19275   default:
19276     llvm_unreachable("Do not know how to custom type legalize this operation!");
19277   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19278   case X86ISD::FMINC:
19279   case X86ISD::FMIN:
19280   case X86ISD::FMAXC:
19281   case X86ISD::FMAX: {
19282     EVT VT = N->getValueType(0);
19283     if (VT != MVT::v2f32)
19284       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19285     SDValue UNDEF = DAG.getUNDEF(VT);
19286     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19287                               N->getOperand(0), UNDEF);
19288     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19289                               N->getOperand(1), UNDEF);
19290     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19291     return;
19292   }
19293   case ISD::SIGN_EXTEND_INREG:
19294   case ISD::ADDC:
19295   case ISD::ADDE:
19296   case ISD::SUBC:
19297   case ISD::SUBE:
19298     // We don't want to expand or promote these.
19299     return;
19300   case ISD::SDIV:
19301   case ISD::UDIV:
19302   case ISD::SREM:
19303   case ISD::UREM:
19304   case ISD::SDIVREM:
19305   case ISD::UDIVREM: {
19306     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19307     Results.push_back(V);
19308     return;
19309   }
19310   case ISD::FP_TO_SINT:
19311   case ISD::FP_TO_UINT: {
19312     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19313
19314     std::pair<SDValue,SDValue> Vals =
19315         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19316     SDValue FIST = Vals.first, StackSlot = Vals.second;
19317     if (FIST.getNode()) {
19318       EVT VT = N->getValueType(0);
19319       // Return a load from the stack slot.
19320       if (StackSlot.getNode())
19321         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19322                                       MachinePointerInfo(),
19323                                       false, false, false, 0));
19324       else
19325         Results.push_back(FIST);
19326     }
19327     return;
19328   }
19329   case ISD::UINT_TO_FP: {
19330     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19331     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19332         N->getValueType(0) != MVT::v2f32)
19333       return;
19334     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19335                                  N->getOperand(0));
19336     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19337                                      MVT::f64);
19338     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19339     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19340                              DAG.getBitcast(MVT::v2i64, VBias));
19341     Or = DAG.getBitcast(MVT::v2f64, Or);
19342     // TODO: Are there any fast-math-flags to propagate here?
19343     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19344     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19345     return;
19346   }
19347   case ISD::FP_ROUND: {
19348     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19349         return;
19350     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19351     Results.push_back(V);
19352     return;
19353   }
19354   case ISD::FP_EXTEND: {
19355     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19356     // No other ValueType for FP_EXTEND should reach this point.
19357     assert(N->getValueType(0) == MVT::v2f32 &&
19358            "Do not know how to legalize this Node");
19359     return;
19360   }
19361   case ISD::INTRINSIC_W_CHAIN: {
19362     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19363     switch (IntNo) {
19364     default : llvm_unreachable("Do not know how to custom type "
19365                                "legalize this intrinsic operation!");
19366     case Intrinsic::x86_rdtsc:
19367       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19368                                      Results);
19369     case Intrinsic::x86_rdtscp:
19370       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19371                                      Results);
19372     case Intrinsic::x86_rdpmc:
19373       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19374     }
19375   }
19376   case ISD::READCYCLECOUNTER: {
19377     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19378                                    Results);
19379   }
19380   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19381     EVT T = N->getValueType(0);
19382     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19383     bool Regs64bit = T == MVT::i128;
19384     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19385     SDValue cpInL, cpInH;
19386     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19387                         DAG.getConstant(0, dl, HalfT));
19388     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19389                         DAG.getConstant(1, dl, HalfT));
19390     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19391                              Regs64bit ? X86::RAX : X86::EAX,
19392                              cpInL, SDValue());
19393     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19394                              Regs64bit ? X86::RDX : X86::EDX,
19395                              cpInH, cpInL.getValue(1));
19396     SDValue swapInL, swapInH;
19397     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19398                           DAG.getConstant(0, dl, HalfT));
19399     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19400                           DAG.getConstant(1, dl, HalfT));
19401     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19402                                Regs64bit ? X86::RBX : X86::EBX,
19403                                swapInL, cpInH.getValue(1));
19404     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19405                                Regs64bit ? X86::RCX : X86::ECX,
19406                                swapInH, swapInL.getValue(1));
19407     SDValue Ops[] = { swapInH.getValue(0),
19408                       N->getOperand(1),
19409                       swapInH.getValue(1) };
19410     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19411     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19412     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19413                                   X86ISD::LCMPXCHG8_DAG;
19414     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19415     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19416                                         Regs64bit ? X86::RAX : X86::EAX,
19417                                         HalfT, Result.getValue(1));
19418     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19419                                         Regs64bit ? X86::RDX : X86::EDX,
19420                                         HalfT, cpOutL.getValue(2));
19421     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19422
19423     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19424                                         MVT::i32, cpOutH.getValue(2));
19425     SDValue Success =
19426         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19427                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19428     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19429
19430     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19431     Results.push_back(Success);
19432     Results.push_back(EFLAGS.getValue(1));
19433     return;
19434   }
19435   case ISD::ATOMIC_SWAP:
19436   case ISD::ATOMIC_LOAD_ADD:
19437   case ISD::ATOMIC_LOAD_SUB:
19438   case ISD::ATOMIC_LOAD_AND:
19439   case ISD::ATOMIC_LOAD_OR:
19440   case ISD::ATOMIC_LOAD_XOR:
19441   case ISD::ATOMIC_LOAD_NAND:
19442   case ISD::ATOMIC_LOAD_MIN:
19443   case ISD::ATOMIC_LOAD_MAX:
19444   case ISD::ATOMIC_LOAD_UMIN:
19445   case ISD::ATOMIC_LOAD_UMAX:
19446   case ISD::ATOMIC_LOAD: {
19447     // Delegate to generic TypeLegalization. Situations we can really handle
19448     // should have already been dealt with by AtomicExpandPass.cpp.
19449     break;
19450   }
19451   case ISD::BITCAST: {
19452     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19453     EVT DstVT = N->getValueType(0);
19454     EVT SrcVT = N->getOperand(0)->getValueType(0);
19455
19456     if (SrcVT != MVT::f64 ||
19457         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19458       return;
19459
19460     unsigned NumElts = DstVT.getVectorNumElements();
19461     EVT SVT = DstVT.getVectorElementType();
19462     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19463     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19464                                    MVT::v2f64, N->getOperand(0));
19465     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19466
19467     if (ExperimentalVectorWideningLegalization) {
19468       // If we are legalizing vectors by widening, we already have the desired
19469       // legal vector type, just return it.
19470       Results.push_back(ToVecInt);
19471       return;
19472     }
19473
19474     SmallVector<SDValue, 8> Elts;
19475     for (unsigned i = 0, e = NumElts; i != e; ++i)
19476       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19477                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19478
19479     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19480   }
19481   }
19482 }
19483
19484 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19485   switch ((X86ISD::NodeType)Opcode) {
19486   case X86ISD::FIRST_NUMBER:       break;
19487   case X86ISD::BSF:                return "X86ISD::BSF";
19488   case X86ISD::BSR:                return "X86ISD::BSR";
19489   case X86ISD::SHLD:               return "X86ISD::SHLD";
19490   case X86ISD::SHRD:               return "X86ISD::SHRD";
19491   case X86ISD::FAND:               return "X86ISD::FAND";
19492   case X86ISD::FANDN:              return "X86ISD::FANDN";
19493   case X86ISD::FOR:                return "X86ISD::FOR";
19494   case X86ISD::FXOR:               return "X86ISD::FXOR";
19495   case X86ISD::FILD:               return "X86ISD::FILD";
19496   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19497   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19498   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19499   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19500   case X86ISD::FLD:                return "X86ISD::FLD";
19501   case X86ISD::FST:                return "X86ISD::FST";
19502   case X86ISD::CALL:               return "X86ISD::CALL";
19503   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19504   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19505   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19506   case X86ISD::BT:                 return "X86ISD::BT";
19507   case X86ISD::CMP:                return "X86ISD::CMP";
19508   case X86ISD::COMI:               return "X86ISD::COMI";
19509   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19510   case X86ISD::CMPM:               return "X86ISD::CMPM";
19511   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19512   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19513   case X86ISD::SETCC:              return "X86ISD::SETCC";
19514   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19515   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19516   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19517   case X86ISD::CMOV:               return "X86ISD::CMOV";
19518   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19519   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19520   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19521   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19522   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19523   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19524   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19525   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19526   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19527   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19528   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19529   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19530   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19531   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19532   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19533   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19534   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19535   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19536   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19537   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19538   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19539   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19540   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19541   case X86ISD::HADD:               return "X86ISD::HADD";
19542   case X86ISD::HSUB:               return "X86ISD::HSUB";
19543   case X86ISD::FHADD:              return "X86ISD::FHADD";
19544   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19545   case X86ISD::ABS:                return "X86ISD::ABS";
19546   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19547   case X86ISD::FMAX:               return "X86ISD::FMAX";
19548   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19549   case X86ISD::FMIN:               return "X86ISD::FMIN";
19550   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19551   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19552   case X86ISD::FMINC:              return "X86ISD::FMINC";
19553   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19554   case X86ISD::FRCP:               return "X86ISD::FRCP";
19555   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19556   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19557   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19558   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19559   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19560   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19561   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19562   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19563   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19564   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19565   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19566   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19567   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19568   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19569   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19570   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19571   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19572   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19573   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19574   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19575   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19576   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19577   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19578   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19579   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19580   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19581   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19582   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19583   case X86ISD::VSHL:               return "X86ISD::VSHL";
19584   case X86ISD::VSRL:               return "X86ISD::VSRL";
19585   case X86ISD::VSRA:               return "X86ISD::VSRA";
19586   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19587   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19588   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19589   case X86ISD::CMPP:               return "X86ISD::CMPP";
19590   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19591   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19592   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19593   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19594   case X86ISD::ADD:                return "X86ISD::ADD";
19595   case X86ISD::SUB:                return "X86ISD::SUB";
19596   case X86ISD::ADC:                return "X86ISD::ADC";
19597   case X86ISD::SBB:                return "X86ISD::SBB";
19598   case X86ISD::SMUL:               return "X86ISD::SMUL";
19599   case X86ISD::UMUL:               return "X86ISD::UMUL";
19600   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19601   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19602   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19603   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19604   case X86ISD::INC:                return "X86ISD::INC";
19605   case X86ISD::DEC:                return "X86ISD::DEC";
19606   case X86ISD::OR:                 return "X86ISD::OR";
19607   case X86ISD::XOR:                return "X86ISD::XOR";
19608   case X86ISD::AND:                return "X86ISD::AND";
19609   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19610   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19611   case X86ISD::PTEST:              return "X86ISD::PTEST";
19612   case X86ISD::TESTP:              return "X86ISD::TESTP";
19613   case X86ISD::TESTM:              return "X86ISD::TESTM";
19614   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19615   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19616   case X86ISD::KTEST:              return "X86ISD::KTEST";
19617   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19618   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19619   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19620   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19621   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19622   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19623   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19624   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19625   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19626   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19627   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19628   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19629   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19630   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19631   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19632   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19633   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19634   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19635   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19636   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19637   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19638   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19639   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19640   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19641   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19642   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19643   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19644   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19645   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19646   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19647   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19648   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19649   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19650   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19651   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19652   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19653   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19654   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19655   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19656   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19657   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19658   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19659   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19660   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19661   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19662   case X86ISD::SAHF:               return "X86ISD::SAHF";
19663   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19664   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19665   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19666   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19667   case X86ISD::FMADD:              return "X86ISD::FMADD";
19668   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19669   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19670   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19671   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19672   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19673   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19674   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19675   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19676   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19677   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19678   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19679   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19680   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19681   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19682   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19683   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19684   case X86ISD::XTEST:              return "X86ISD::XTEST";
19685   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19686   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19687   case X86ISD::SELECT:             return "X86ISD::SELECT";
19688   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19689   case X86ISD::RCP28:              return "X86ISD::RCP28";
19690   case X86ISD::EXP2:               return "X86ISD::EXP2";
19691   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19692   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19693   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19694   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19695   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19696   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19697   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19698   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19699   case X86ISD::ADDS:               return "X86ISD::ADDS";
19700   case X86ISD::SUBS:               return "X86ISD::SUBS";
19701   case X86ISD::AVG:                return "X86ISD::AVG";
19702   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19703   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19704   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19705   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19706   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19707   }
19708   return nullptr;
19709 }
19710
19711 // isLegalAddressingMode - Return true if the addressing mode represented
19712 // by AM is legal for this target, for a load/store of the specified type.
19713 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19714                                               const AddrMode &AM, Type *Ty,
19715                                               unsigned AS) const {
19716   // X86 supports extremely general addressing modes.
19717   CodeModel::Model M = getTargetMachine().getCodeModel();
19718   Reloc::Model R = getTargetMachine().getRelocationModel();
19719
19720   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19721   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19722     return false;
19723
19724   if (AM.BaseGV) {
19725     unsigned GVFlags =
19726       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19727
19728     // If a reference to this global requires an extra load, we can't fold it.
19729     if (isGlobalStubReference(GVFlags))
19730       return false;
19731
19732     // If BaseGV requires a register for the PIC base, we cannot also have a
19733     // BaseReg specified.
19734     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19735       return false;
19736
19737     // If lower 4G is not available, then we must use rip-relative addressing.
19738     if ((M != CodeModel::Small || R != Reloc::Static) &&
19739         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19740       return false;
19741   }
19742
19743   switch (AM.Scale) {
19744   case 0:
19745   case 1:
19746   case 2:
19747   case 4:
19748   case 8:
19749     // These scales always work.
19750     break;
19751   case 3:
19752   case 5:
19753   case 9:
19754     // These scales are formed with basereg+scalereg.  Only accept if there is
19755     // no basereg yet.
19756     if (AM.HasBaseReg)
19757       return false;
19758     break;
19759   default:  // Other stuff never works.
19760     return false;
19761   }
19762
19763   return true;
19764 }
19765
19766 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19767   unsigned Bits = Ty->getScalarSizeInBits();
19768
19769   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19770   // particularly cheaper than those without.
19771   if (Bits == 8)
19772     return false;
19773
19774   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19775   // variable shifts just as cheap as scalar ones.
19776   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19777     return false;
19778
19779   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19780   // fully general vector.
19781   return true;
19782 }
19783
19784 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19785   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19786     return false;
19787   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19788   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19789   return NumBits1 > NumBits2;
19790 }
19791
19792 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19793   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19794     return false;
19795
19796   if (!isTypeLegal(EVT::getEVT(Ty1)))
19797     return false;
19798
19799   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19800
19801   // Assuming the caller doesn't have a zeroext or signext return parameter,
19802   // truncation all the way down to i1 is valid.
19803   return true;
19804 }
19805
19806 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19807   return isInt<32>(Imm);
19808 }
19809
19810 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19811   // Can also use sub to handle negated immediates.
19812   return isInt<32>(Imm);
19813 }
19814
19815 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19816   if (!VT1.isInteger() || !VT2.isInteger())
19817     return false;
19818   unsigned NumBits1 = VT1.getSizeInBits();
19819   unsigned NumBits2 = VT2.getSizeInBits();
19820   return NumBits1 > NumBits2;
19821 }
19822
19823 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19824   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19825   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19826 }
19827
19828 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19829   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19830   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19831 }
19832
19833 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19834   EVT VT1 = Val.getValueType();
19835   if (isZExtFree(VT1, VT2))
19836     return true;
19837
19838   if (Val.getOpcode() != ISD::LOAD)
19839     return false;
19840
19841   if (!VT1.isSimple() || !VT1.isInteger() ||
19842       !VT2.isSimple() || !VT2.isInteger())
19843     return false;
19844
19845   switch (VT1.getSimpleVT().SimpleTy) {
19846   default: break;
19847   case MVT::i8:
19848   case MVT::i16:
19849   case MVT::i32:
19850     // X86 has 8, 16, and 32-bit zero-extending loads.
19851     return true;
19852   }
19853
19854   return false;
19855 }
19856
19857 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19858
19859 bool
19860 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19861   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19862     return false;
19863
19864   VT = VT.getScalarType();
19865
19866   if (!VT.isSimple())
19867     return false;
19868
19869   switch (VT.getSimpleVT().SimpleTy) {
19870   case MVT::f32:
19871   case MVT::f64:
19872     return true;
19873   default:
19874     break;
19875   }
19876
19877   return false;
19878 }
19879
19880 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19881   // i16 instructions are longer (0x66 prefix) and potentially slower.
19882   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19883 }
19884
19885 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19886 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19887 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19888 /// are assumed to be legal.
19889 bool
19890 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19891                                       EVT VT) const {
19892   if (!VT.isSimple())
19893     return false;
19894
19895   // Not for i1 vectors
19896   if (VT.getScalarType() == MVT::i1)
19897     return false;
19898
19899   // Very little shuffling can be done for 64-bit vectors right now.
19900   if (VT.getSizeInBits() == 64)
19901     return false;
19902
19903   // We only care that the types being shuffled are legal. The lowering can
19904   // handle any possible shuffle mask that results.
19905   return isTypeLegal(VT.getSimpleVT());
19906 }
19907
19908 bool
19909 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19910                                           EVT VT) const {
19911   // Just delegate to the generic legality, clear masks aren't special.
19912   return isShuffleMaskLegal(Mask, VT);
19913 }
19914
19915 //===----------------------------------------------------------------------===//
19916 //                           X86 Scheduler Hooks
19917 //===----------------------------------------------------------------------===//
19918
19919 /// Utility function to emit xbegin specifying the start of an RTM region.
19920 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19921                                      const TargetInstrInfo *TII) {
19922   DebugLoc DL = MI->getDebugLoc();
19923
19924   const BasicBlock *BB = MBB->getBasicBlock();
19925   MachineFunction::iterator I = MBB;
19926   ++I;
19927
19928   // For the v = xbegin(), we generate
19929   //
19930   // thisMBB:
19931   //  xbegin sinkMBB
19932   //
19933   // mainMBB:
19934   //  eax = -1
19935   //
19936   // sinkMBB:
19937   //  v = eax
19938
19939   MachineBasicBlock *thisMBB = MBB;
19940   MachineFunction *MF = MBB->getParent();
19941   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19942   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19943   MF->insert(I, mainMBB);
19944   MF->insert(I, sinkMBB);
19945
19946   // Transfer the remainder of BB and its successor edges to sinkMBB.
19947   sinkMBB->splice(sinkMBB->begin(), MBB,
19948                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19949   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19950
19951   // thisMBB:
19952   //  xbegin sinkMBB
19953   //  # fallthrough to mainMBB
19954   //  # abortion to sinkMBB
19955   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19956   thisMBB->addSuccessor(mainMBB);
19957   thisMBB->addSuccessor(sinkMBB);
19958
19959   // mainMBB:
19960   //  EAX = -1
19961   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19962   mainMBB->addSuccessor(sinkMBB);
19963
19964   // sinkMBB:
19965   // EAX is live into the sinkMBB
19966   sinkMBB->addLiveIn(X86::EAX);
19967   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19968           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19969     .addReg(X86::EAX);
19970
19971   MI->eraseFromParent();
19972   return sinkMBB;
19973 }
19974
19975 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19976 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19977 // in the .td file.
19978 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19979                                        const TargetInstrInfo *TII) {
19980   unsigned Opc;
19981   switch (MI->getOpcode()) {
19982   default: llvm_unreachable("illegal opcode!");
19983   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19984   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19985   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19986   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19987   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19988   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19989   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19990   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19991   }
19992
19993   DebugLoc dl = MI->getDebugLoc();
19994   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19995
19996   unsigned NumArgs = MI->getNumOperands();
19997   for (unsigned i = 1; i < NumArgs; ++i) {
19998     MachineOperand &Op = MI->getOperand(i);
19999     if (!(Op.isReg() && Op.isImplicit()))
20000       MIB.addOperand(Op);
20001   }
20002   if (MI->hasOneMemOperand())
20003     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20004
20005   BuildMI(*BB, MI, dl,
20006     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20007     .addReg(X86::XMM0);
20008
20009   MI->eraseFromParent();
20010   return BB;
20011 }
20012
20013 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20014 // defs in an instruction pattern
20015 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20016                                        const TargetInstrInfo *TII) {
20017   unsigned Opc;
20018   switch (MI->getOpcode()) {
20019   default: llvm_unreachable("illegal opcode!");
20020   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20021   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20022   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20023   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20024   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20025   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20026   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20027   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20028   }
20029
20030   DebugLoc dl = MI->getDebugLoc();
20031   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20032
20033   unsigned NumArgs = MI->getNumOperands(); // remove the results
20034   for (unsigned i = 1; i < NumArgs; ++i) {
20035     MachineOperand &Op = MI->getOperand(i);
20036     if (!(Op.isReg() && Op.isImplicit()))
20037       MIB.addOperand(Op);
20038   }
20039   if (MI->hasOneMemOperand())
20040     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20041
20042   BuildMI(*BB, MI, dl,
20043     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20044     .addReg(X86::ECX);
20045
20046   MI->eraseFromParent();
20047   return BB;
20048 }
20049
20050 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20051                                       const X86Subtarget *Subtarget) {
20052   DebugLoc dl = MI->getDebugLoc();
20053   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20054   // Address into RAX/EAX, other two args into ECX, EDX.
20055   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20056   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20057   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20058   for (int i = 0; i < X86::AddrNumOperands; ++i)
20059     MIB.addOperand(MI->getOperand(i));
20060
20061   unsigned ValOps = X86::AddrNumOperands;
20062   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20063     .addReg(MI->getOperand(ValOps).getReg());
20064   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20065     .addReg(MI->getOperand(ValOps+1).getReg());
20066
20067   // The instruction doesn't actually take any operands though.
20068   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20069
20070   MI->eraseFromParent(); // The pseudo is gone now.
20071   return BB;
20072 }
20073
20074 MachineBasicBlock *
20075 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20076                                                  MachineBasicBlock *MBB) const {
20077   // Emit va_arg instruction on X86-64.
20078
20079   // Operands to this pseudo-instruction:
20080   // 0  ) Output        : destination address (reg)
20081   // 1-5) Input         : va_list address (addr, i64mem)
20082   // 6  ) ArgSize       : Size (in bytes) of vararg type
20083   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20084   // 8  ) Align         : Alignment of type
20085   // 9  ) EFLAGS (implicit-def)
20086
20087   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20088   static_assert(X86::AddrNumOperands == 5,
20089                 "VAARG_64 assumes 5 address operands");
20090
20091   unsigned DestReg = MI->getOperand(0).getReg();
20092   MachineOperand &Base = MI->getOperand(1);
20093   MachineOperand &Scale = MI->getOperand(2);
20094   MachineOperand &Index = MI->getOperand(3);
20095   MachineOperand &Disp = MI->getOperand(4);
20096   MachineOperand &Segment = MI->getOperand(5);
20097   unsigned ArgSize = MI->getOperand(6).getImm();
20098   unsigned ArgMode = MI->getOperand(7).getImm();
20099   unsigned Align = MI->getOperand(8).getImm();
20100
20101   // Memory Reference
20102   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20103   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20104   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20105
20106   // Machine Information
20107   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20108   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20109   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20110   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20111   DebugLoc DL = MI->getDebugLoc();
20112
20113   // struct va_list {
20114   //   i32   gp_offset
20115   //   i32   fp_offset
20116   //   i64   overflow_area (address)
20117   //   i64   reg_save_area (address)
20118   // }
20119   // sizeof(va_list) = 24
20120   // alignment(va_list) = 8
20121
20122   unsigned TotalNumIntRegs = 6;
20123   unsigned TotalNumXMMRegs = 8;
20124   bool UseGPOffset = (ArgMode == 1);
20125   bool UseFPOffset = (ArgMode == 2);
20126   unsigned MaxOffset = TotalNumIntRegs * 8 +
20127                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20128
20129   /* Align ArgSize to a multiple of 8 */
20130   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20131   bool NeedsAlign = (Align > 8);
20132
20133   MachineBasicBlock *thisMBB = MBB;
20134   MachineBasicBlock *overflowMBB;
20135   MachineBasicBlock *offsetMBB;
20136   MachineBasicBlock *endMBB;
20137
20138   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20139   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20140   unsigned OffsetReg = 0;
20141
20142   if (!UseGPOffset && !UseFPOffset) {
20143     // If we only pull from the overflow region, we don't create a branch.
20144     // We don't need to alter control flow.
20145     OffsetDestReg = 0; // unused
20146     OverflowDestReg = DestReg;
20147
20148     offsetMBB = nullptr;
20149     overflowMBB = thisMBB;
20150     endMBB = thisMBB;
20151   } else {
20152     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20153     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20154     // If not, pull from overflow_area. (branch to overflowMBB)
20155     //
20156     //       thisMBB
20157     //         |     .
20158     //         |        .
20159     //     offsetMBB   overflowMBB
20160     //         |        .
20161     //         |     .
20162     //        endMBB
20163
20164     // Registers for the PHI in endMBB
20165     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20166     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20167
20168     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20169     MachineFunction *MF = MBB->getParent();
20170     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20171     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20172     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20173
20174     MachineFunction::iterator MBBIter = MBB;
20175     ++MBBIter;
20176
20177     // Insert the new basic blocks
20178     MF->insert(MBBIter, offsetMBB);
20179     MF->insert(MBBIter, overflowMBB);
20180     MF->insert(MBBIter, endMBB);
20181
20182     // Transfer the remainder of MBB and its successor edges to endMBB.
20183     endMBB->splice(endMBB->begin(), thisMBB,
20184                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20185     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20186
20187     // Make offsetMBB and overflowMBB successors of thisMBB
20188     thisMBB->addSuccessor(offsetMBB);
20189     thisMBB->addSuccessor(overflowMBB);
20190
20191     // endMBB is a successor of both offsetMBB and overflowMBB
20192     offsetMBB->addSuccessor(endMBB);
20193     overflowMBB->addSuccessor(endMBB);
20194
20195     // Load the offset value into a register
20196     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20197     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20198       .addOperand(Base)
20199       .addOperand(Scale)
20200       .addOperand(Index)
20201       .addDisp(Disp, UseFPOffset ? 4 : 0)
20202       .addOperand(Segment)
20203       .setMemRefs(MMOBegin, MMOEnd);
20204
20205     // Check if there is enough room left to pull this argument.
20206     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20207       .addReg(OffsetReg)
20208       .addImm(MaxOffset + 8 - ArgSizeA8);
20209
20210     // Branch to "overflowMBB" if offset >= max
20211     // Fall through to "offsetMBB" otherwise
20212     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20213       .addMBB(overflowMBB);
20214   }
20215
20216   // In offsetMBB, emit code to use the reg_save_area.
20217   if (offsetMBB) {
20218     assert(OffsetReg != 0);
20219
20220     // Read the reg_save_area address.
20221     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20222     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20223       .addOperand(Base)
20224       .addOperand(Scale)
20225       .addOperand(Index)
20226       .addDisp(Disp, 16)
20227       .addOperand(Segment)
20228       .setMemRefs(MMOBegin, MMOEnd);
20229
20230     // Zero-extend the offset
20231     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20232       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20233         .addImm(0)
20234         .addReg(OffsetReg)
20235         .addImm(X86::sub_32bit);
20236
20237     // Add the offset to the reg_save_area to get the final address.
20238     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20239       .addReg(OffsetReg64)
20240       .addReg(RegSaveReg);
20241
20242     // Compute the offset for the next argument
20243     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20244     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20245       .addReg(OffsetReg)
20246       .addImm(UseFPOffset ? 16 : 8);
20247
20248     // Store it back into the va_list.
20249     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20250       .addOperand(Base)
20251       .addOperand(Scale)
20252       .addOperand(Index)
20253       .addDisp(Disp, UseFPOffset ? 4 : 0)
20254       .addOperand(Segment)
20255       .addReg(NextOffsetReg)
20256       .setMemRefs(MMOBegin, MMOEnd);
20257
20258     // Jump to endMBB
20259     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20260       .addMBB(endMBB);
20261   }
20262
20263   //
20264   // Emit code to use overflow area
20265   //
20266
20267   // Load the overflow_area address into a register.
20268   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20269   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20270     .addOperand(Base)
20271     .addOperand(Scale)
20272     .addOperand(Index)
20273     .addDisp(Disp, 8)
20274     .addOperand(Segment)
20275     .setMemRefs(MMOBegin, MMOEnd);
20276
20277   // If we need to align it, do so. Otherwise, just copy the address
20278   // to OverflowDestReg.
20279   if (NeedsAlign) {
20280     // Align the overflow address
20281     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20282     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20283
20284     // aligned_addr = (addr + (align-1)) & ~(align-1)
20285     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20286       .addReg(OverflowAddrReg)
20287       .addImm(Align-1);
20288
20289     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20290       .addReg(TmpReg)
20291       .addImm(~(uint64_t)(Align-1));
20292   } else {
20293     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20294       .addReg(OverflowAddrReg);
20295   }
20296
20297   // Compute the next overflow address after this argument.
20298   // (the overflow address should be kept 8-byte aligned)
20299   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20300   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20301     .addReg(OverflowDestReg)
20302     .addImm(ArgSizeA8);
20303
20304   // Store the new overflow address.
20305   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20306     .addOperand(Base)
20307     .addOperand(Scale)
20308     .addOperand(Index)
20309     .addDisp(Disp, 8)
20310     .addOperand(Segment)
20311     .addReg(NextAddrReg)
20312     .setMemRefs(MMOBegin, MMOEnd);
20313
20314   // If we branched, emit the PHI to the front of endMBB.
20315   if (offsetMBB) {
20316     BuildMI(*endMBB, endMBB->begin(), DL,
20317             TII->get(X86::PHI), DestReg)
20318       .addReg(OffsetDestReg).addMBB(offsetMBB)
20319       .addReg(OverflowDestReg).addMBB(overflowMBB);
20320   }
20321
20322   // Erase the pseudo instruction
20323   MI->eraseFromParent();
20324
20325   return endMBB;
20326 }
20327
20328 MachineBasicBlock *
20329 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20330                                                  MachineInstr *MI,
20331                                                  MachineBasicBlock *MBB) const {
20332   // Emit code to save XMM registers to the stack. The ABI says that the
20333   // number of registers to save is given in %al, so it's theoretically
20334   // possible to do an indirect jump trick to avoid saving all of them,
20335   // however this code takes a simpler approach and just executes all
20336   // of the stores if %al is non-zero. It's less code, and it's probably
20337   // easier on the hardware branch predictor, and stores aren't all that
20338   // expensive anyway.
20339
20340   // Create the new basic blocks. One block contains all the XMM stores,
20341   // and one block is the final destination regardless of whether any
20342   // stores were performed.
20343   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20344   MachineFunction *F = MBB->getParent();
20345   MachineFunction::iterator MBBIter = MBB;
20346   ++MBBIter;
20347   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20348   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20349   F->insert(MBBIter, XMMSaveMBB);
20350   F->insert(MBBIter, EndMBB);
20351
20352   // Transfer the remainder of MBB and its successor edges to EndMBB.
20353   EndMBB->splice(EndMBB->begin(), MBB,
20354                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20355   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20356
20357   // The original block will now fall through to the XMM save block.
20358   MBB->addSuccessor(XMMSaveMBB);
20359   // The XMMSaveMBB will fall through to the end block.
20360   XMMSaveMBB->addSuccessor(EndMBB);
20361
20362   // Now add the instructions.
20363   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20364   DebugLoc DL = MI->getDebugLoc();
20365
20366   unsigned CountReg = MI->getOperand(0).getReg();
20367   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20368   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20369
20370   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20371     // If %al is 0, branch around the XMM save block.
20372     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20373     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20374     MBB->addSuccessor(EndMBB);
20375   }
20376
20377   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20378   // that was just emitted, but clearly shouldn't be "saved".
20379   assert((MI->getNumOperands() <= 3 ||
20380           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20381           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20382          && "Expected last argument to be EFLAGS");
20383   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20384   // In the XMM save block, save all the XMM argument registers.
20385   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20386     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20387     MachineMemOperand *MMO = F->getMachineMemOperand(
20388         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20389         MachineMemOperand::MOStore,
20390         /*Size=*/16, /*Align=*/16);
20391     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20392       .addFrameIndex(RegSaveFrameIndex)
20393       .addImm(/*Scale=*/1)
20394       .addReg(/*IndexReg=*/0)
20395       .addImm(/*Disp=*/Offset)
20396       .addReg(/*Segment=*/0)
20397       .addReg(MI->getOperand(i).getReg())
20398       .addMemOperand(MMO);
20399   }
20400
20401   MI->eraseFromParent();   // The pseudo instruction is gone now.
20402
20403   return EndMBB;
20404 }
20405
20406 // The EFLAGS operand of SelectItr might be missing a kill marker
20407 // because there were multiple uses of EFLAGS, and ISel didn't know
20408 // which to mark. Figure out whether SelectItr should have had a
20409 // kill marker, and set it if it should. Returns the correct kill
20410 // marker value.
20411 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20412                                      MachineBasicBlock* BB,
20413                                      const TargetRegisterInfo* TRI) {
20414   // Scan forward through BB for a use/def of EFLAGS.
20415   MachineBasicBlock::iterator miI(std::next(SelectItr));
20416   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20417     const MachineInstr& mi = *miI;
20418     if (mi.readsRegister(X86::EFLAGS))
20419       return false;
20420     if (mi.definesRegister(X86::EFLAGS))
20421       break; // Should have kill-flag - update below.
20422   }
20423
20424   // If we hit the end of the block, check whether EFLAGS is live into a
20425   // successor.
20426   if (miI == BB->end()) {
20427     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20428                                           sEnd = BB->succ_end();
20429          sItr != sEnd; ++sItr) {
20430       MachineBasicBlock* succ = *sItr;
20431       if (succ->isLiveIn(X86::EFLAGS))
20432         return false;
20433     }
20434   }
20435
20436   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20437   // out. SelectMI should have a kill flag on EFLAGS.
20438   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20439   return true;
20440 }
20441
20442 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20443 // together with other CMOV pseudo-opcodes into a single basic-block with
20444 // conditional jump around it.
20445 static bool isCMOVPseudo(MachineInstr *MI) {
20446   switch (MI->getOpcode()) {
20447   case X86::CMOV_FR32:
20448   case X86::CMOV_FR64:
20449   case X86::CMOV_GR8:
20450   case X86::CMOV_GR16:
20451   case X86::CMOV_GR32:
20452   case X86::CMOV_RFP32:
20453   case X86::CMOV_RFP64:
20454   case X86::CMOV_RFP80:
20455   case X86::CMOV_V2F64:
20456   case X86::CMOV_V2I64:
20457   case X86::CMOV_V4F32:
20458   case X86::CMOV_V4F64:
20459   case X86::CMOV_V4I64:
20460   case X86::CMOV_V16F32:
20461   case X86::CMOV_V8F32:
20462   case X86::CMOV_V8F64:
20463   case X86::CMOV_V8I64:
20464   case X86::CMOV_V8I1:
20465   case X86::CMOV_V16I1:
20466   case X86::CMOV_V32I1:
20467   case X86::CMOV_V64I1:
20468     return true;
20469
20470   default:
20471     return false;
20472   }
20473 }
20474
20475 MachineBasicBlock *
20476 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20477                                      MachineBasicBlock *BB) const {
20478   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20479   DebugLoc DL = MI->getDebugLoc();
20480
20481   // To "insert" a SELECT_CC instruction, we actually have to insert the
20482   // diamond control-flow pattern.  The incoming instruction knows the
20483   // destination vreg to set, the condition code register to branch on, the
20484   // true/false values to select between, and a branch opcode to use.
20485   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20486   MachineFunction::iterator It = BB;
20487   ++It;
20488
20489   //  thisMBB:
20490   //  ...
20491   //   TrueVal = ...
20492   //   cmpTY ccX, r1, r2
20493   //   bCC copy1MBB
20494   //   fallthrough --> copy0MBB
20495   MachineBasicBlock *thisMBB = BB;
20496   MachineFunction *F = BB->getParent();
20497
20498   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20499   // as described above, by inserting a BB, and then making a PHI at the join
20500   // point to select the true and false operands of the CMOV in the PHI.
20501   //
20502   // The code also handles two different cases of multiple CMOV opcodes
20503   // in a row.
20504   //
20505   // Case 1:
20506   // In this case, there are multiple CMOVs in a row, all which are based on
20507   // the same condition setting (or the exact opposite condition setting).
20508   // In this case we can lower all the CMOVs using a single inserted BB, and
20509   // then make a number of PHIs at the join point to model the CMOVs. The only
20510   // trickiness here, is that in a case like:
20511   //
20512   // t2 = CMOV cond1 t1, f1
20513   // t3 = CMOV cond1 t2, f2
20514   //
20515   // when rewriting this into PHIs, we have to perform some renaming on the
20516   // temps since you cannot have a PHI operand refer to a PHI result earlier
20517   // in the same block.  The "simple" but wrong lowering would be:
20518   //
20519   // t2 = PHI t1(BB1), f1(BB2)
20520   // t3 = PHI t2(BB1), f2(BB2)
20521   //
20522   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20523   // renaming is to note that on the path through BB1, t2 is really just a
20524   // copy of t1, and do that renaming, properly generating:
20525   //
20526   // t2 = PHI t1(BB1), f1(BB2)
20527   // t3 = PHI t1(BB1), f2(BB2)
20528   //
20529   // Case 2, we lower cascaded CMOVs such as
20530   //
20531   //   (CMOV (CMOV F, T, cc1), T, cc2)
20532   //
20533   // to two successives branches.  For that, we look for another CMOV as the
20534   // following instruction.
20535   //
20536   // Without this, we would add a PHI between the two jumps, which ends up
20537   // creating a few copies all around. For instance, for
20538   //
20539   //    (sitofp (zext (fcmp une)))
20540   //
20541   // we would generate:
20542   //
20543   //         ucomiss %xmm1, %xmm0
20544   //         movss  <1.0f>, %xmm0
20545   //         movaps  %xmm0, %xmm1
20546   //         jne     .LBB5_2
20547   //         xorps   %xmm1, %xmm1
20548   // .LBB5_2:
20549   //         jp      .LBB5_4
20550   //         movaps  %xmm1, %xmm0
20551   // .LBB5_4:
20552   //         retq
20553   //
20554   // because this custom-inserter would have generated:
20555   //
20556   //   A
20557   //   | \
20558   //   |  B
20559   //   | /
20560   //   C
20561   //   | \
20562   //   |  D
20563   //   | /
20564   //   E
20565   //
20566   // A: X = ...; Y = ...
20567   // B: empty
20568   // C: Z = PHI [X, A], [Y, B]
20569   // D: empty
20570   // E: PHI [X, C], [Z, D]
20571   //
20572   // If we lower both CMOVs in a single step, we can instead generate:
20573   //
20574   //   A
20575   //   | \
20576   //   |  C
20577   //   | /|
20578   //   |/ |
20579   //   |  |
20580   //   |  D
20581   //   | /
20582   //   E
20583   //
20584   // A: X = ...; Y = ...
20585   // D: empty
20586   // E: PHI [X, A], [X, C], [Y, D]
20587   //
20588   // Which, in our sitofp/fcmp example, gives us something like:
20589   //
20590   //         ucomiss %xmm1, %xmm0
20591   //         movss  <1.0f>, %xmm0
20592   //         jne     .LBB5_4
20593   //         jp      .LBB5_4
20594   //         xorps   %xmm0, %xmm0
20595   // .LBB5_4:
20596   //         retq
20597   //
20598   MachineInstr *CascadedCMOV = nullptr;
20599   MachineInstr *LastCMOV = MI;
20600   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20601   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20602   MachineBasicBlock::iterator NextMIIt =
20603       std::next(MachineBasicBlock::iterator(MI));
20604
20605   // Check for case 1, where there are multiple CMOVs with the same condition
20606   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20607   // number of jumps the most.
20608
20609   if (isCMOVPseudo(MI)) {
20610     // See if we have a string of CMOVS with the same condition.
20611     while (NextMIIt != BB->end() &&
20612            isCMOVPseudo(NextMIIt) &&
20613            (NextMIIt->getOperand(3).getImm() == CC ||
20614             NextMIIt->getOperand(3).getImm() == OppCC)) {
20615       LastCMOV = &*NextMIIt;
20616       ++NextMIIt;
20617     }
20618   }
20619
20620   // This checks for case 2, but only do this if we didn't already find
20621   // case 1, as indicated by LastCMOV == MI.
20622   if (LastCMOV == MI &&
20623       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20624       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20625       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20626     CascadedCMOV = &*NextMIIt;
20627   }
20628
20629   MachineBasicBlock *jcc1MBB = nullptr;
20630
20631   // If we have a cascaded CMOV, we lower it to two successive branches to
20632   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20633   if (CascadedCMOV) {
20634     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20635     F->insert(It, jcc1MBB);
20636     jcc1MBB->addLiveIn(X86::EFLAGS);
20637   }
20638
20639   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20640   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20641   F->insert(It, copy0MBB);
20642   F->insert(It, sinkMBB);
20643
20644   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20645   // live into the sink and copy blocks.
20646   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20647
20648   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20649   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20650       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20651     copy0MBB->addLiveIn(X86::EFLAGS);
20652     sinkMBB->addLiveIn(X86::EFLAGS);
20653   }
20654
20655   // Transfer the remainder of BB and its successor edges to sinkMBB.
20656   sinkMBB->splice(sinkMBB->begin(), BB,
20657                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20658   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20659
20660   // Add the true and fallthrough blocks as its successors.
20661   if (CascadedCMOV) {
20662     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20663     BB->addSuccessor(jcc1MBB);
20664
20665     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20666     // jump to the sinkMBB.
20667     jcc1MBB->addSuccessor(copy0MBB);
20668     jcc1MBB->addSuccessor(sinkMBB);
20669   } else {
20670     BB->addSuccessor(copy0MBB);
20671   }
20672
20673   // The true block target of the first (or only) branch is always sinkMBB.
20674   BB->addSuccessor(sinkMBB);
20675
20676   // Create the conditional branch instruction.
20677   unsigned Opc = X86::GetCondBranchFromCond(CC);
20678   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20679
20680   if (CascadedCMOV) {
20681     unsigned Opc2 = X86::GetCondBranchFromCond(
20682         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20683     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20684   }
20685
20686   //  copy0MBB:
20687   //   %FalseValue = ...
20688   //   # fallthrough to sinkMBB
20689   copy0MBB->addSuccessor(sinkMBB);
20690
20691   //  sinkMBB:
20692   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20693   //  ...
20694   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20695   MachineBasicBlock::iterator MIItEnd =
20696     std::next(MachineBasicBlock::iterator(LastCMOV));
20697   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20698   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20699   MachineInstrBuilder MIB;
20700
20701   // As we are creating the PHIs, we have to be careful if there is more than
20702   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20703   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20704   // That also means that PHI construction must work forward from earlier to
20705   // later, and that the code must maintain a mapping from earlier PHI's
20706   // destination registers, and the registers that went into the PHI.
20707
20708   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20709     unsigned DestReg = MIIt->getOperand(0).getReg();
20710     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20711     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20712
20713     // If this CMOV we are generating is the opposite condition from
20714     // the jump we generated, then we have to swap the operands for the
20715     // PHI that is going to be generated.
20716     if (MIIt->getOperand(3).getImm() == OppCC)
20717         std::swap(Op1Reg, Op2Reg);
20718
20719     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20720       Op1Reg = RegRewriteTable[Op1Reg].first;
20721
20722     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20723       Op2Reg = RegRewriteTable[Op2Reg].second;
20724
20725     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20726                   TII->get(X86::PHI), DestReg)
20727           .addReg(Op1Reg).addMBB(copy0MBB)
20728           .addReg(Op2Reg).addMBB(thisMBB);
20729
20730     // Add this PHI to the rewrite table.
20731     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20732   }
20733
20734   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20735   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20736   if (CascadedCMOV) {
20737     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20738     // Copy the PHI result to the register defined by the second CMOV.
20739     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20740             DL, TII->get(TargetOpcode::COPY),
20741             CascadedCMOV->getOperand(0).getReg())
20742         .addReg(MI->getOperand(0).getReg());
20743     CascadedCMOV->eraseFromParent();
20744   }
20745
20746   // Now remove the CMOV(s).
20747   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20748     (MIIt++)->eraseFromParent();
20749
20750   return sinkMBB;
20751 }
20752
20753 MachineBasicBlock *
20754 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20755                                        MachineBasicBlock *BB) const {
20756   // Combine the following atomic floating-point modification pattern:
20757   //   a.store(reg OP a.load(acquire), release)
20758   // Transform them into:
20759   //   OPss (%gpr), %xmm
20760   //   movss %xmm, (%gpr)
20761   // Or sd equivalent for 64-bit operations.
20762   unsigned MOp, FOp;
20763   switch (MI->getOpcode()) {
20764   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20765   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20766   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20767   }
20768   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20769   DebugLoc DL = MI->getDebugLoc();
20770   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20771   unsigned MSrc = MI->getOperand(0).getReg();
20772   unsigned VSrc = MI->getOperand(5).getReg();
20773   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20774                                 .addReg(/*Base=*/MSrc)
20775                                 .addImm(/*Scale=*/1)
20776                                 .addReg(/*Index=*/0)
20777                                 .addImm(0)
20778                                 .addReg(0);
20779   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20780                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20781                           .addReg(VSrc)
20782                           .addReg(/*Base=*/MSrc)
20783                           .addImm(/*Scale=*/1)
20784                           .addReg(/*Index=*/0)
20785                           .addImm(/*Disp=*/0)
20786                           .addReg(/*Segment=*/0);
20787   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20788   MI->eraseFromParent(); // The pseudo instruction is gone now.
20789   return BB;
20790 }
20791
20792 MachineBasicBlock *
20793 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20794                                         MachineBasicBlock *BB) const {
20795   MachineFunction *MF = BB->getParent();
20796   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20797   DebugLoc DL = MI->getDebugLoc();
20798   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20799
20800   assert(MF->shouldSplitStack());
20801
20802   const bool Is64Bit = Subtarget->is64Bit();
20803   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20804
20805   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20806   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20807
20808   // BB:
20809   //  ... [Till the alloca]
20810   // If stacklet is not large enough, jump to mallocMBB
20811   //
20812   // bumpMBB:
20813   //  Allocate by subtracting from RSP
20814   //  Jump to continueMBB
20815   //
20816   // mallocMBB:
20817   //  Allocate by call to runtime
20818   //
20819   // continueMBB:
20820   //  ...
20821   //  [rest of original BB]
20822   //
20823
20824   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20825   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20826   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20827
20828   MachineRegisterInfo &MRI = MF->getRegInfo();
20829   const TargetRegisterClass *AddrRegClass =
20830       getRegClassFor(getPointerTy(MF->getDataLayout()));
20831
20832   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20833     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20834     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20835     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20836     sizeVReg = MI->getOperand(1).getReg(),
20837     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20838
20839   MachineFunction::iterator MBBIter = BB;
20840   ++MBBIter;
20841
20842   MF->insert(MBBIter, bumpMBB);
20843   MF->insert(MBBIter, mallocMBB);
20844   MF->insert(MBBIter, continueMBB);
20845
20846   continueMBB->splice(continueMBB->begin(), BB,
20847                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20848   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20849
20850   // Add code to the main basic block to check if the stack limit has been hit,
20851   // and if so, jump to mallocMBB otherwise to bumpMBB.
20852   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20853   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20854     .addReg(tmpSPVReg).addReg(sizeVReg);
20855   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20856     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20857     .addReg(SPLimitVReg);
20858   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20859
20860   // bumpMBB simply decreases the stack pointer, since we know the current
20861   // stacklet has enough space.
20862   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20863     .addReg(SPLimitVReg);
20864   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20865     .addReg(SPLimitVReg);
20866   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20867
20868   // Calls into a routine in libgcc to allocate more space from the heap.
20869   const uint32_t *RegMask =
20870       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20871   if (IsLP64) {
20872     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20873       .addReg(sizeVReg);
20874     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20875       .addExternalSymbol("__morestack_allocate_stack_space")
20876       .addRegMask(RegMask)
20877       .addReg(X86::RDI, RegState::Implicit)
20878       .addReg(X86::RAX, RegState::ImplicitDefine);
20879   } else if (Is64Bit) {
20880     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20881       .addReg(sizeVReg);
20882     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20883       .addExternalSymbol("__morestack_allocate_stack_space")
20884       .addRegMask(RegMask)
20885       .addReg(X86::EDI, RegState::Implicit)
20886       .addReg(X86::EAX, RegState::ImplicitDefine);
20887   } else {
20888     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20889       .addImm(12);
20890     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20891     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20892       .addExternalSymbol("__morestack_allocate_stack_space")
20893       .addRegMask(RegMask)
20894       .addReg(X86::EAX, RegState::ImplicitDefine);
20895   }
20896
20897   if (!Is64Bit)
20898     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20899       .addImm(16);
20900
20901   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20902     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20903   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20904
20905   // Set up the CFG correctly.
20906   BB->addSuccessor(bumpMBB);
20907   BB->addSuccessor(mallocMBB);
20908   mallocMBB->addSuccessor(continueMBB);
20909   bumpMBB->addSuccessor(continueMBB);
20910
20911   // Take care of the PHI nodes.
20912   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20913           MI->getOperand(0).getReg())
20914     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20915     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20916
20917   // Delete the original pseudo instruction.
20918   MI->eraseFromParent();
20919
20920   // And we're done.
20921   return continueMBB;
20922 }
20923
20924 MachineBasicBlock *
20925 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20926                                         MachineBasicBlock *BB) const {
20927   DebugLoc DL = MI->getDebugLoc();
20928
20929   assert(!Subtarget->isTargetMachO());
20930
20931   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20932                                                     DL);
20933
20934   MI->eraseFromParent();   // The pseudo instruction is gone now.
20935   return BB;
20936 }
20937
20938 MachineBasicBlock *
20939 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20940                                       MachineBasicBlock *BB) const {
20941   // This is pretty easy.  We're taking the value that we received from
20942   // our load from the relocation, sticking it in either RDI (x86-64)
20943   // or EAX and doing an indirect call.  The return value will then
20944   // be in the normal return register.
20945   MachineFunction *F = BB->getParent();
20946   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20947   DebugLoc DL = MI->getDebugLoc();
20948
20949   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20950   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20951
20952   // Get a register mask for the lowered call.
20953   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20954   // proper register mask.
20955   const uint32_t *RegMask =
20956       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20957   if (Subtarget->is64Bit()) {
20958     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20959                                       TII->get(X86::MOV64rm), X86::RDI)
20960     .addReg(X86::RIP)
20961     .addImm(0).addReg(0)
20962     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20963                       MI->getOperand(3).getTargetFlags())
20964     .addReg(0);
20965     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20966     addDirectMem(MIB, X86::RDI);
20967     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20968   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20969     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20970                                       TII->get(X86::MOV32rm), X86::EAX)
20971     .addReg(0)
20972     .addImm(0).addReg(0)
20973     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20974                       MI->getOperand(3).getTargetFlags())
20975     .addReg(0);
20976     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20977     addDirectMem(MIB, X86::EAX);
20978     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20979   } else {
20980     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20981                                       TII->get(X86::MOV32rm), X86::EAX)
20982     .addReg(TII->getGlobalBaseReg(F))
20983     .addImm(0).addReg(0)
20984     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20985                       MI->getOperand(3).getTargetFlags())
20986     .addReg(0);
20987     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20988     addDirectMem(MIB, X86::EAX);
20989     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20990   }
20991
20992   MI->eraseFromParent(); // The pseudo instruction is gone now.
20993   return BB;
20994 }
20995
20996 MachineBasicBlock *
20997 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20998                                     MachineBasicBlock *MBB) const {
20999   DebugLoc DL = MI->getDebugLoc();
21000   MachineFunction *MF = MBB->getParent();
21001   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21002   MachineRegisterInfo &MRI = MF->getRegInfo();
21003
21004   const BasicBlock *BB = MBB->getBasicBlock();
21005   MachineFunction::iterator I = MBB;
21006   ++I;
21007
21008   // Memory Reference
21009   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21010   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21011
21012   unsigned DstReg;
21013   unsigned MemOpndSlot = 0;
21014
21015   unsigned CurOp = 0;
21016
21017   DstReg = MI->getOperand(CurOp++).getReg();
21018   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21019   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21020   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21021   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21022
21023   MemOpndSlot = CurOp;
21024
21025   MVT PVT = getPointerTy(MF->getDataLayout());
21026   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21027          "Invalid Pointer Size!");
21028
21029   // For v = setjmp(buf), we generate
21030   //
21031   // thisMBB:
21032   //  buf[LabelOffset] = restoreMBB
21033   //  SjLjSetup restoreMBB
21034   //
21035   // mainMBB:
21036   //  v_main = 0
21037   //
21038   // sinkMBB:
21039   //  v = phi(main, restore)
21040   //
21041   // restoreMBB:
21042   //  if base pointer being used, load it from frame
21043   //  v_restore = 1
21044
21045   MachineBasicBlock *thisMBB = MBB;
21046   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21047   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21048   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21049   MF->insert(I, mainMBB);
21050   MF->insert(I, sinkMBB);
21051   MF->push_back(restoreMBB);
21052
21053   MachineInstrBuilder MIB;
21054
21055   // Transfer the remainder of BB and its successor edges to sinkMBB.
21056   sinkMBB->splice(sinkMBB->begin(), MBB,
21057                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21058   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21059
21060   // thisMBB:
21061   unsigned PtrStoreOpc = 0;
21062   unsigned LabelReg = 0;
21063   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21064   Reloc::Model RM = MF->getTarget().getRelocationModel();
21065   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21066                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21067
21068   // Prepare IP either in reg or imm.
21069   if (!UseImmLabel) {
21070     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21071     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21072     LabelReg = MRI.createVirtualRegister(PtrRC);
21073     if (Subtarget->is64Bit()) {
21074       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21075               .addReg(X86::RIP)
21076               .addImm(0)
21077               .addReg(0)
21078               .addMBB(restoreMBB)
21079               .addReg(0);
21080     } else {
21081       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21082       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21083               .addReg(XII->getGlobalBaseReg(MF))
21084               .addImm(0)
21085               .addReg(0)
21086               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21087               .addReg(0);
21088     }
21089   } else
21090     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21091   // Store IP
21092   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21093   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21094     if (i == X86::AddrDisp)
21095       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21096     else
21097       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21098   }
21099   if (!UseImmLabel)
21100     MIB.addReg(LabelReg);
21101   else
21102     MIB.addMBB(restoreMBB);
21103   MIB.setMemRefs(MMOBegin, MMOEnd);
21104   // Setup
21105   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21106           .addMBB(restoreMBB);
21107
21108   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21109   MIB.addRegMask(RegInfo->getNoPreservedMask());
21110   thisMBB->addSuccessor(mainMBB);
21111   thisMBB->addSuccessor(restoreMBB);
21112
21113   // mainMBB:
21114   //  EAX = 0
21115   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21116   mainMBB->addSuccessor(sinkMBB);
21117
21118   // sinkMBB:
21119   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21120           TII->get(X86::PHI), DstReg)
21121     .addReg(mainDstReg).addMBB(mainMBB)
21122     .addReg(restoreDstReg).addMBB(restoreMBB);
21123
21124   // restoreMBB:
21125   if (RegInfo->hasBasePointer(*MF)) {
21126     const bool Uses64BitFramePtr =
21127         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21128     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21129     X86FI->setRestoreBasePointer(MF);
21130     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21131     unsigned BasePtr = RegInfo->getBaseRegister();
21132     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21133     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21134                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21135       .setMIFlag(MachineInstr::FrameSetup);
21136   }
21137   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21138   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21139   restoreMBB->addSuccessor(sinkMBB);
21140
21141   MI->eraseFromParent();
21142   return sinkMBB;
21143 }
21144
21145 MachineBasicBlock *
21146 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21147                                      MachineBasicBlock *MBB) const {
21148   DebugLoc DL = MI->getDebugLoc();
21149   MachineFunction *MF = MBB->getParent();
21150   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21151   MachineRegisterInfo &MRI = MF->getRegInfo();
21152
21153   // Memory Reference
21154   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21155   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21156
21157   MVT PVT = getPointerTy(MF->getDataLayout());
21158   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21159          "Invalid Pointer Size!");
21160
21161   const TargetRegisterClass *RC =
21162     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21163   unsigned Tmp = MRI.createVirtualRegister(RC);
21164   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21165   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21166   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21167   unsigned SP = RegInfo->getStackRegister();
21168
21169   MachineInstrBuilder MIB;
21170
21171   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21172   const int64_t SPOffset = 2 * PVT.getStoreSize();
21173
21174   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21175   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21176
21177   // Reload FP
21178   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21179   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21180     MIB.addOperand(MI->getOperand(i));
21181   MIB.setMemRefs(MMOBegin, MMOEnd);
21182   // Reload IP
21183   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21184   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21185     if (i == X86::AddrDisp)
21186       MIB.addDisp(MI->getOperand(i), LabelOffset);
21187     else
21188       MIB.addOperand(MI->getOperand(i));
21189   }
21190   MIB.setMemRefs(MMOBegin, MMOEnd);
21191   // Reload SP
21192   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21193   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21194     if (i == X86::AddrDisp)
21195       MIB.addDisp(MI->getOperand(i), SPOffset);
21196     else
21197       MIB.addOperand(MI->getOperand(i));
21198   }
21199   MIB.setMemRefs(MMOBegin, MMOEnd);
21200   // Jump
21201   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21202
21203   MI->eraseFromParent();
21204   return MBB;
21205 }
21206
21207 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21208 // accumulator loops. Writing back to the accumulator allows the coalescer
21209 // to remove extra copies in the loop.
21210 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21211 MachineBasicBlock *
21212 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21213                                  MachineBasicBlock *MBB) const {
21214   MachineOperand &AddendOp = MI->getOperand(3);
21215
21216   // Bail out early if the addend isn't a register - we can't switch these.
21217   if (!AddendOp.isReg())
21218     return MBB;
21219
21220   MachineFunction &MF = *MBB->getParent();
21221   MachineRegisterInfo &MRI = MF.getRegInfo();
21222
21223   // Check whether the addend is defined by a PHI:
21224   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21225   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21226   if (!AddendDef.isPHI())
21227     return MBB;
21228
21229   // Look for the following pattern:
21230   // loop:
21231   //   %addend = phi [%entry, 0], [%loop, %result]
21232   //   ...
21233   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21234
21235   // Replace with:
21236   //   loop:
21237   //   %addend = phi [%entry, 0], [%loop, %result]
21238   //   ...
21239   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21240
21241   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21242     assert(AddendDef.getOperand(i).isReg());
21243     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21244     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21245     if (&PHISrcInst == MI) {
21246       // Found a matching instruction.
21247       unsigned NewFMAOpc = 0;
21248       switch (MI->getOpcode()) {
21249         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21250         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21251         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21252         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21253         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21254         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21255         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21256         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21257         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21258         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21259         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21260         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21261         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21262         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21263         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21264         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21265         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21266         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21267         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21268         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21269
21270         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21271         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21272         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21273         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21274         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21275         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21276         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21277         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21278         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21279         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21280         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21281         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21282         default: llvm_unreachable("Unrecognized FMA variant.");
21283       }
21284
21285       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21286       MachineInstrBuilder MIB =
21287         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21288         .addOperand(MI->getOperand(0))
21289         .addOperand(MI->getOperand(3))
21290         .addOperand(MI->getOperand(2))
21291         .addOperand(MI->getOperand(1));
21292       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21293       MI->eraseFromParent();
21294     }
21295   }
21296
21297   return MBB;
21298 }
21299
21300 MachineBasicBlock *
21301 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21302                                                MachineBasicBlock *BB) const {
21303   switch (MI->getOpcode()) {
21304   default: llvm_unreachable("Unexpected instr type to insert");
21305   case X86::TAILJMPd64:
21306   case X86::TAILJMPr64:
21307   case X86::TAILJMPm64:
21308   case X86::TAILJMPd64_REX:
21309   case X86::TAILJMPr64_REX:
21310   case X86::TAILJMPm64_REX:
21311     llvm_unreachable("TAILJMP64 would not be touched here.");
21312   case X86::TCRETURNdi64:
21313   case X86::TCRETURNri64:
21314   case X86::TCRETURNmi64:
21315     return BB;
21316   case X86::WIN_ALLOCA:
21317     return EmitLoweredWinAlloca(MI, BB);
21318   case X86::SEG_ALLOCA_32:
21319   case X86::SEG_ALLOCA_64:
21320     return EmitLoweredSegAlloca(MI, BB);
21321   case X86::TLSCall_32:
21322   case X86::TLSCall_64:
21323     return EmitLoweredTLSCall(MI, BB);
21324   case X86::CMOV_FR32:
21325   case X86::CMOV_FR64:
21326   case X86::CMOV_GR8:
21327   case X86::CMOV_GR16:
21328   case X86::CMOV_GR32:
21329   case X86::CMOV_RFP32:
21330   case X86::CMOV_RFP64:
21331   case X86::CMOV_RFP80:
21332   case X86::CMOV_V2F64:
21333   case X86::CMOV_V2I64:
21334   case X86::CMOV_V4F32:
21335   case X86::CMOV_V4F64:
21336   case X86::CMOV_V4I64:
21337   case X86::CMOV_V16F32:
21338   case X86::CMOV_V8F32:
21339   case X86::CMOV_V8F64:
21340   case X86::CMOV_V8I64:
21341   case X86::CMOV_V8I1:
21342   case X86::CMOV_V16I1:
21343   case X86::CMOV_V32I1:
21344   case X86::CMOV_V64I1:
21345     return EmitLoweredSelect(MI, BB);
21346
21347   case X86::RELEASE_FADD32mr:
21348   case X86::RELEASE_FADD64mr:
21349     return EmitLoweredAtomicFP(MI, BB);
21350
21351   case X86::FP32_TO_INT16_IN_MEM:
21352   case X86::FP32_TO_INT32_IN_MEM:
21353   case X86::FP32_TO_INT64_IN_MEM:
21354   case X86::FP64_TO_INT16_IN_MEM:
21355   case X86::FP64_TO_INT32_IN_MEM:
21356   case X86::FP64_TO_INT64_IN_MEM:
21357   case X86::FP80_TO_INT16_IN_MEM:
21358   case X86::FP80_TO_INT32_IN_MEM:
21359   case X86::FP80_TO_INT64_IN_MEM: {
21360     MachineFunction *F = BB->getParent();
21361     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21362     DebugLoc DL = MI->getDebugLoc();
21363
21364     // Change the floating point control register to use "round towards zero"
21365     // mode when truncating to an integer value.
21366     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21367     addFrameReference(BuildMI(*BB, MI, DL,
21368                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21369
21370     // Load the old value of the high byte of the control word...
21371     unsigned OldCW =
21372       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21373     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21374                       CWFrameIdx);
21375
21376     // Set the high part to be round to zero...
21377     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21378       .addImm(0xC7F);
21379
21380     // Reload the modified control word now...
21381     addFrameReference(BuildMI(*BB, MI, DL,
21382                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21383
21384     // Restore the memory image of control word to original value
21385     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21386       .addReg(OldCW);
21387
21388     // Get the X86 opcode to use.
21389     unsigned Opc;
21390     switch (MI->getOpcode()) {
21391     default: llvm_unreachable("illegal opcode!");
21392     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21393     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21394     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21395     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21396     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21397     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21398     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21399     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21400     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21401     }
21402
21403     X86AddressMode AM;
21404     MachineOperand &Op = MI->getOperand(0);
21405     if (Op.isReg()) {
21406       AM.BaseType = X86AddressMode::RegBase;
21407       AM.Base.Reg = Op.getReg();
21408     } else {
21409       AM.BaseType = X86AddressMode::FrameIndexBase;
21410       AM.Base.FrameIndex = Op.getIndex();
21411     }
21412     Op = MI->getOperand(1);
21413     if (Op.isImm())
21414       AM.Scale = Op.getImm();
21415     Op = MI->getOperand(2);
21416     if (Op.isImm())
21417       AM.IndexReg = Op.getImm();
21418     Op = MI->getOperand(3);
21419     if (Op.isGlobal()) {
21420       AM.GV = Op.getGlobal();
21421     } else {
21422       AM.Disp = Op.getImm();
21423     }
21424     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21425                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21426
21427     // Reload the original control word now.
21428     addFrameReference(BuildMI(*BB, MI, DL,
21429                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21430
21431     MI->eraseFromParent();   // The pseudo instruction is gone now.
21432     return BB;
21433   }
21434     // String/text processing lowering.
21435   case X86::PCMPISTRM128REG:
21436   case X86::VPCMPISTRM128REG:
21437   case X86::PCMPISTRM128MEM:
21438   case X86::VPCMPISTRM128MEM:
21439   case X86::PCMPESTRM128REG:
21440   case X86::VPCMPESTRM128REG:
21441   case X86::PCMPESTRM128MEM:
21442   case X86::VPCMPESTRM128MEM:
21443     assert(Subtarget->hasSSE42() &&
21444            "Target must have SSE4.2 or AVX features enabled");
21445     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21446
21447   // String/text processing lowering.
21448   case X86::PCMPISTRIREG:
21449   case X86::VPCMPISTRIREG:
21450   case X86::PCMPISTRIMEM:
21451   case X86::VPCMPISTRIMEM:
21452   case X86::PCMPESTRIREG:
21453   case X86::VPCMPESTRIREG:
21454   case X86::PCMPESTRIMEM:
21455   case X86::VPCMPESTRIMEM:
21456     assert(Subtarget->hasSSE42() &&
21457            "Target must have SSE4.2 or AVX features enabled");
21458     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21459
21460   // Thread synchronization.
21461   case X86::MONITOR:
21462     return EmitMonitor(MI, BB, Subtarget);
21463
21464   // xbegin
21465   case X86::XBEGIN:
21466     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21467
21468   case X86::VASTART_SAVE_XMM_REGS:
21469     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21470
21471   case X86::VAARG_64:
21472     return EmitVAARG64WithCustomInserter(MI, BB);
21473
21474   case X86::EH_SjLj_SetJmp32:
21475   case X86::EH_SjLj_SetJmp64:
21476     return emitEHSjLjSetJmp(MI, BB);
21477
21478   case X86::EH_SjLj_LongJmp32:
21479   case X86::EH_SjLj_LongJmp64:
21480     return emitEHSjLjLongJmp(MI, BB);
21481
21482   case TargetOpcode::STATEPOINT:
21483     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21484     // this point in the process.  We diverge later.
21485     return emitPatchPoint(MI, BB);
21486
21487   case TargetOpcode::STACKMAP:
21488   case TargetOpcode::PATCHPOINT:
21489     return emitPatchPoint(MI, BB);
21490
21491   case X86::VFMADDPDr213r:
21492   case X86::VFMADDPSr213r:
21493   case X86::VFMADDSDr213r:
21494   case X86::VFMADDSSr213r:
21495   case X86::VFMSUBPDr213r:
21496   case X86::VFMSUBPSr213r:
21497   case X86::VFMSUBSDr213r:
21498   case X86::VFMSUBSSr213r:
21499   case X86::VFNMADDPDr213r:
21500   case X86::VFNMADDPSr213r:
21501   case X86::VFNMADDSDr213r:
21502   case X86::VFNMADDSSr213r:
21503   case X86::VFNMSUBPDr213r:
21504   case X86::VFNMSUBPSr213r:
21505   case X86::VFNMSUBSDr213r:
21506   case X86::VFNMSUBSSr213r:
21507   case X86::VFMADDSUBPDr213r:
21508   case X86::VFMADDSUBPSr213r:
21509   case X86::VFMSUBADDPDr213r:
21510   case X86::VFMSUBADDPSr213r:
21511   case X86::VFMADDPDr213rY:
21512   case X86::VFMADDPSr213rY:
21513   case X86::VFMSUBPDr213rY:
21514   case X86::VFMSUBPSr213rY:
21515   case X86::VFNMADDPDr213rY:
21516   case X86::VFNMADDPSr213rY:
21517   case X86::VFNMSUBPDr213rY:
21518   case X86::VFNMSUBPSr213rY:
21519   case X86::VFMADDSUBPDr213rY:
21520   case X86::VFMADDSUBPSr213rY:
21521   case X86::VFMSUBADDPDr213rY:
21522   case X86::VFMSUBADDPSr213rY:
21523     return emitFMA3Instr(MI, BB);
21524   }
21525 }
21526
21527 //===----------------------------------------------------------------------===//
21528 //                           X86 Optimization Hooks
21529 //===----------------------------------------------------------------------===//
21530
21531 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21532                                                       APInt &KnownZero,
21533                                                       APInt &KnownOne,
21534                                                       const SelectionDAG &DAG,
21535                                                       unsigned Depth) const {
21536   unsigned BitWidth = KnownZero.getBitWidth();
21537   unsigned Opc = Op.getOpcode();
21538   assert((Opc >= ISD::BUILTIN_OP_END ||
21539           Opc == ISD::INTRINSIC_WO_CHAIN ||
21540           Opc == ISD::INTRINSIC_W_CHAIN ||
21541           Opc == ISD::INTRINSIC_VOID) &&
21542          "Should use MaskedValueIsZero if you don't know whether Op"
21543          " is a target node!");
21544
21545   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21546   switch (Opc) {
21547   default: break;
21548   case X86ISD::ADD:
21549   case X86ISD::SUB:
21550   case X86ISD::ADC:
21551   case X86ISD::SBB:
21552   case X86ISD::SMUL:
21553   case X86ISD::UMUL:
21554   case X86ISD::INC:
21555   case X86ISD::DEC:
21556   case X86ISD::OR:
21557   case X86ISD::XOR:
21558   case X86ISD::AND:
21559     // These nodes' second result is a boolean.
21560     if (Op.getResNo() == 0)
21561       break;
21562     // Fallthrough
21563   case X86ISD::SETCC:
21564     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21565     break;
21566   case ISD::INTRINSIC_WO_CHAIN: {
21567     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21568     unsigned NumLoBits = 0;
21569     switch (IntId) {
21570     default: break;
21571     case Intrinsic::x86_sse_movmsk_ps:
21572     case Intrinsic::x86_avx_movmsk_ps_256:
21573     case Intrinsic::x86_sse2_movmsk_pd:
21574     case Intrinsic::x86_avx_movmsk_pd_256:
21575     case Intrinsic::x86_mmx_pmovmskb:
21576     case Intrinsic::x86_sse2_pmovmskb_128:
21577     case Intrinsic::x86_avx2_pmovmskb: {
21578       // High bits of movmskp{s|d}, pmovmskb are known zero.
21579       switch (IntId) {
21580         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21581         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21582         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21583         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21584         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21585         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21586         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21587         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21588       }
21589       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21590       break;
21591     }
21592     }
21593     break;
21594   }
21595   }
21596 }
21597
21598 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21599   SDValue Op,
21600   const SelectionDAG &,
21601   unsigned Depth) const {
21602   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21603   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21604     return Op.getValueType().getScalarType().getSizeInBits();
21605
21606   // Fallback case.
21607   return 1;
21608 }
21609
21610 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21611 /// node is a GlobalAddress + offset.
21612 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21613                                        const GlobalValue* &GA,
21614                                        int64_t &Offset) const {
21615   if (N->getOpcode() == X86ISD::Wrapper) {
21616     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21617       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21618       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21619       return true;
21620     }
21621   }
21622   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21623 }
21624
21625 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21626 /// same as extracting the high 128-bit part of 256-bit vector and then
21627 /// inserting the result into the low part of a new 256-bit vector
21628 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21629   EVT VT = SVOp->getValueType(0);
21630   unsigned NumElems = VT.getVectorNumElements();
21631
21632   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21633   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21634     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21635         SVOp->getMaskElt(j) >= 0)
21636       return false;
21637
21638   return true;
21639 }
21640
21641 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21642 /// same as extracting the low 128-bit part of 256-bit vector and then
21643 /// inserting the result into the high part of a new 256-bit vector
21644 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21645   EVT VT = SVOp->getValueType(0);
21646   unsigned NumElems = VT.getVectorNumElements();
21647
21648   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21649   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21650     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21651         SVOp->getMaskElt(j) >= 0)
21652       return false;
21653
21654   return true;
21655 }
21656
21657 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21658 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21659                                         TargetLowering::DAGCombinerInfo &DCI,
21660                                         const X86Subtarget* Subtarget) {
21661   SDLoc dl(N);
21662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21663   SDValue V1 = SVOp->getOperand(0);
21664   SDValue V2 = SVOp->getOperand(1);
21665   EVT VT = SVOp->getValueType(0);
21666   unsigned NumElems = VT.getVectorNumElements();
21667
21668   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21669       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21670     //
21671     //                   0,0,0,...
21672     //                      |
21673     //    V      UNDEF    BUILD_VECTOR    UNDEF
21674     //     \      /           \           /
21675     //  CONCAT_VECTOR         CONCAT_VECTOR
21676     //         \                  /
21677     //          \                /
21678     //          RESULT: V + zero extended
21679     //
21680     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21681         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21682         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21683       return SDValue();
21684
21685     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21686       return SDValue();
21687
21688     // To match the shuffle mask, the first half of the mask should
21689     // be exactly the first vector, and all the rest a splat with the
21690     // first element of the second one.
21691     for (unsigned i = 0; i != NumElems/2; ++i)
21692       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21693           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21694         return SDValue();
21695
21696     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21697     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21698       if (Ld->hasNUsesOfValue(1, 0)) {
21699         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21700         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21701         SDValue ResNode =
21702           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21703                                   Ld->getMemoryVT(),
21704                                   Ld->getPointerInfo(),
21705                                   Ld->getAlignment(),
21706                                   false/*isVolatile*/, true/*ReadMem*/,
21707                                   false/*WriteMem*/);
21708
21709         // Make sure the newly-created LOAD is in the same position as Ld in
21710         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21711         // and update uses of Ld's output chain to use the TokenFactor.
21712         if (Ld->hasAnyUseOfValue(1)) {
21713           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21714                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21715           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21716           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21717                                  SDValue(ResNode.getNode(), 1));
21718         }
21719
21720         return DAG.getBitcast(VT, ResNode);
21721       }
21722     }
21723
21724     // Emit a zeroed vector and insert the desired subvector on its
21725     // first half.
21726     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21727     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21728     return DCI.CombineTo(N, InsV);
21729   }
21730
21731   //===--------------------------------------------------------------------===//
21732   // Combine some shuffles into subvector extracts and inserts:
21733   //
21734
21735   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21736   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21737     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21738     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21739     return DCI.CombineTo(N, InsV);
21740   }
21741
21742   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21743   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21744     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21745     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21746     return DCI.CombineTo(N, InsV);
21747   }
21748
21749   return SDValue();
21750 }
21751
21752 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21753 /// possible.
21754 ///
21755 /// This is the leaf of the recursive combinine below. When we have found some
21756 /// chain of single-use x86 shuffle instructions and accumulated the combined
21757 /// shuffle mask represented by them, this will try to pattern match that mask
21758 /// into either a single instruction if there is a special purpose instruction
21759 /// for this operation, or into a PSHUFB instruction which is a fully general
21760 /// instruction but should only be used to replace chains over a certain depth.
21761 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21762                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21763                                    TargetLowering::DAGCombinerInfo &DCI,
21764                                    const X86Subtarget *Subtarget) {
21765   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21766
21767   // Find the operand that enters the chain. Note that multiple uses are OK
21768   // here, we're not going to remove the operand we find.
21769   SDValue Input = Op.getOperand(0);
21770   while (Input.getOpcode() == ISD::BITCAST)
21771     Input = Input.getOperand(0);
21772
21773   MVT VT = Input.getSimpleValueType();
21774   MVT RootVT = Root.getSimpleValueType();
21775   SDLoc DL(Root);
21776
21777   // Just remove no-op shuffle masks.
21778   if (Mask.size() == 1) {
21779     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21780                   /*AddTo*/ true);
21781     return true;
21782   }
21783
21784   // Use the float domain if the operand type is a floating point type.
21785   bool FloatDomain = VT.isFloatingPoint();
21786
21787   // For floating point shuffles, we don't have free copies in the shuffle
21788   // instructions or the ability to load as part of the instruction, so
21789   // canonicalize their shuffles to UNPCK or MOV variants.
21790   //
21791   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21792   // vectors because it can have a load folded into it that UNPCK cannot. This
21793   // doesn't preclude something switching to the shorter encoding post-RA.
21794   //
21795   // FIXME: Should teach these routines about AVX vector widths.
21796   if (FloatDomain && VT.getSizeInBits() == 128) {
21797     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21798       bool Lo = Mask.equals({0, 0});
21799       unsigned Shuffle;
21800       MVT ShuffleVT;
21801       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21802       // is no slower than UNPCKLPD but has the option to fold the input operand
21803       // into even an unaligned memory load.
21804       if (Lo && Subtarget->hasSSE3()) {
21805         Shuffle = X86ISD::MOVDDUP;
21806         ShuffleVT = MVT::v2f64;
21807       } else {
21808         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21809         // than the UNPCK variants.
21810         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21811         ShuffleVT = MVT::v4f32;
21812       }
21813       if (Depth == 1 && Root->getOpcode() == Shuffle)
21814         return false; // Nothing to do!
21815       Op = DAG.getBitcast(ShuffleVT, Input);
21816       DCI.AddToWorklist(Op.getNode());
21817       if (Shuffle == X86ISD::MOVDDUP)
21818         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21819       else
21820         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21821       DCI.AddToWorklist(Op.getNode());
21822       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21823                     /*AddTo*/ true);
21824       return true;
21825     }
21826     if (Subtarget->hasSSE3() &&
21827         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21828       bool Lo = Mask.equals({0, 0, 2, 2});
21829       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21830       MVT ShuffleVT = MVT::v4f32;
21831       if (Depth == 1 && Root->getOpcode() == Shuffle)
21832         return false; // Nothing to do!
21833       Op = DAG.getBitcast(ShuffleVT, Input);
21834       DCI.AddToWorklist(Op.getNode());
21835       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21836       DCI.AddToWorklist(Op.getNode());
21837       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21838                     /*AddTo*/ true);
21839       return true;
21840     }
21841     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21842       bool Lo = Mask.equals({0, 0, 1, 1});
21843       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21844       MVT ShuffleVT = MVT::v4f32;
21845       if (Depth == 1 && Root->getOpcode() == Shuffle)
21846         return false; // Nothing to do!
21847       Op = DAG.getBitcast(ShuffleVT, Input);
21848       DCI.AddToWorklist(Op.getNode());
21849       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21850       DCI.AddToWorklist(Op.getNode());
21851       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21852                     /*AddTo*/ true);
21853       return true;
21854     }
21855   }
21856
21857   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21858   // variants as none of these have single-instruction variants that are
21859   // superior to the UNPCK formulation.
21860   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21861       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21862        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21863        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21864        Mask.equals(
21865            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21866     bool Lo = Mask[0] == 0;
21867     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21868     if (Depth == 1 && Root->getOpcode() == Shuffle)
21869       return false; // Nothing to do!
21870     MVT ShuffleVT;
21871     switch (Mask.size()) {
21872     case 8:
21873       ShuffleVT = MVT::v8i16;
21874       break;
21875     case 16:
21876       ShuffleVT = MVT::v16i8;
21877       break;
21878     default:
21879       llvm_unreachable("Impossible mask size!");
21880     };
21881     Op = DAG.getBitcast(ShuffleVT, Input);
21882     DCI.AddToWorklist(Op.getNode());
21883     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21884     DCI.AddToWorklist(Op.getNode());
21885     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21886                   /*AddTo*/ true);
21887     return true;
21888   }
21889
21890   // Don't try to re-form single instruction chains under any circumstances now
21891   // that we've done encoding canonicalization for them.
21892   if (Depth < 2)
21893     return false;
21894
21895   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21896   // can replace them with a single PSHUFB instruction profitably. Intel's
21897   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21898   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21899   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21900     SmallVector<SDValue, 16> PSHUFBMask;
21901     int NumBytes = VT.getSizeInBits() / 8;
21902     int Ratio = NumBytes / Mask.size();
21903     for (int i = 0; i < NumBytes; ++i) {
21904       if (Mask[i / Ratio] == SM_SentinelUndef) {
21905         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21906         continue;
21907       }
21908       int M = Mask[i / Ratio] != SM_SentinelZero
21909                   ? Ratio * Mask[i / Ratio] + i % Ratio
21910                   : 255;
21911       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21912     }
21913     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21914     Op = DAG.getBitcast(ByteVT, Input);
21915     DCI.AddToWorklist(Op.getNode());
21916     SDValue PSHUFBMaskOp =
21917         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21918     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21919     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21920     DCI.AddToWorklist(Op.getNode());
21921     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21922                   /*AddTo*/ true);
21923     return true;
21924   }
21925
21926   // Failed to find any combines.
21927   return false;
21928 }
21929
21930 /// \brief Fully generic combining of x86 shuffle instructions.
21931 ///
21932 /// This should be the last combine run over the x86 shuffle instructions. Once
21933 /// they have been fully optimized, this will recursively consider all chains
21934 /// of single-use shuffle instructions, build a generic model of the cumulative
21935 /// shuffle operation, and check for simpler instructions which implement this
21936 /// operation. We use this primarily for two purposes:
21937 ///
21938 /// 1) Collapse generic shuffles to specialized single instructions when
21939 ///    equivalent. In most cases, this is just an encoding size win, but
21940 ///    sometimes we will collapse multiple generic shuffles into a single
21941 ///    special-purpose shuffle.
21942 /// 2) Look for sequences of shuffle instructions with 3 or more total
21943 ///    instructions, and replace them with the slightly more expensive SSSE3
21944 ///    PSHUFB instruction if available. We do this as the last combining step
21945 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21946 ///    a suitable short sequence of other instructions. The PHUFB will either
21947 ///    use a register or have to read from memory and so is slightly (but only
21948 ///    slightly) more expensive than the other shuffle instructions.
21949 ///
21950 /// Because this is inherently a quadratic operation (for each shuffle in
21951 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21952 /// This should never be an issue in practice as the shuffle lowering doesn't
21953 /// produce sequences of more than 8 instructions.
21954 ///
21955 /// FIXME: We will currently miss some cases where the redundant shuffling
21956 /// would simplify under the threshold for PSHUFB formation because of
21957 /// combine-ordering. To fix this, we should do the redundant instruction
21958 /// combining in this recursive walk.
21959 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21960                                           ArrayRef<int> RootMask,
21961                                           int Depth, bool HasPSHUFB,
21962                                           SelectionDAG &DAG,
21963                                           TargetLowering::DAGCombinerInfo &DCI,
21964                                           const X86Subtarget *Subtarget) {
21965   // Bound the depth of our recursive combine because this is ultimately
21966   // quadratic in nature.
21967   if (Depth > 8)
21968     return false;
21969
21970   // Directly rip through bitcasts to find the underlying operand.
21971   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21972     Op = Op.getOperand(0);
21973
21974   MVT VT = Op.getSimpleValueType();
21975   if (!VT.isVector())
21976     return false; // Bail if we hit a non-vector.
21977
21978   assert(Root.getSimpleValueType().isVector() &&
21979          "Shuffles operate on vector types!");
21980   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21981          "Can only combine shuffles of the same vector register size.");
21982
21983   if (!isTargetShuffle(Op.getOpcode()))
21984     return false;
21985   SmallVector<int, 16> OpMask;
21986   bool IsUnary;
21987   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21988   // We only can combine unary shuffles which we can decode the mask for.
21989   if (!HaveMask || !IsUnary)
21990     return false;
21991
21992   assert(VT.getVectorNumElements() == OpMask.size() &&
21993          "Different mask size from vector size!");
21994   assert(((RootMask.size() > OpMask.size() &&
21995            RootMask.size() % OpMask.size() == 0) ||
21996           (OpMask.size() > RootMask.size() &&
21997            OpMask.size() % RootMask.size() == 0) ||
21998           OpMask.size() == RootMask.size()) &&
21999          "The smaller number of elements must divide the larger.");
22000   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22001   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22002   assert(((RootRatio == 1 && OpRatio == 1) ||
22003           (RootRatio == 1) != (OpRatio == 1)) &&
22004          "Must not have a ratio for both incoming and op masks!");
22005
22006   SmallVector<int, 16> Mask;
22007   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22008
22009   // Merge this shuffle operation's mask into our accumulated mask. Note that
22010   // this shuffle's mask will be the first applied to the input, followed by the
22011   // root mask to get us all the way to the root value arrangement. The reason
22012   // for this order is that we are recursing up the operation chain.
22013   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22014     int RootIdx = i / RootRatio;
22015     if (RootMask[RootIdx] < 0) {
22016       // This is a zero or undef lane, we're done.
22017       Mask.push_back(RootMask[RootIdx]);
22018       continue;
22019     }
22020
22021     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22022     int OpIdx = RootMaskedIdx / OpRatio;
22023     if (OpMask[OpIdx] < 0) {
22024       // The incoming lanes are zero or undef, it doesn't matter which ones we
22025       // are using.
22026       Mask.push_back(OpMask[OpIdx]);
22027       continue;
22028     }
22029
22030     // Ok, we have non-zero lanes, map them through.
22031     Mask.push_back(OpMask[OpIdx] * OpRatio +
22032                    RootMaskedIdx % OpRatio);
22033   }
22034
22035   // See if we can recurse into the operand to combine more things.
22036   switch (Op.getOpcode()) {
22037     case X86ISD::PSHUFB:
22038       HasPSHUFB = true;
22039     case X86ISD::PSHUFD:
22040     case X86ISD::PSHUFHW:
22041     case X86ISD::PSHUFLW:
22042       if (Op.getOperand(0).hasOneUse() &&
22043           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22044                                         HasPSHUFB, DAG, DCI, Subtarget))
22045         return true;
22046       break;
22047
22048     case X86ISD::UNPCKL:
22049     case X86ISD::UNPCKH:
22050       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22051       // We can't check for single use, we have to check that this shuffle is the only user.
22052       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22053           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22054                                         HasPSHUFB, DAG, DCI, Subtarget))
22055           return true;
22056       break;
22057   }
22058
22059   // Minor canonicalization of the accumulated shuffle mask to make it easier
22060   // to match below. All this does is detect masks with squential pairs of
22061   // elements, and shrink them to the half-width mask. It does this in a loop
22062   // so it will reduce the size of the mask to the minimal width mask which
22063   // performs an equivalent shuffle.
22064   SmallVector<int, 16> WidenedMask;
22065   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22066     Mask = std::move(WidenedMask);
22067     WidenedMask.clear();
22068   }
22069
22070   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22071                                 Subtarget);
22072 }
22073
22074 /// \brief Get the PSHUF-style mask from PSHUF node.
22075 ///
22076 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22077 /// PSHUF-style masks that can be reused with such instructions.
22078 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22079   MVT VT = N.getSimpleValueType();
22080   SmallVector<int, 4> Mask;
22081   bool IsUnary;
22082   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22083   (void)HaveMask;
22084   assert(HaveMask);
22085
22086   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22087   // matter. Check that the upper masks are repeats and remove them.
22088   if (VT.getSizeInBits() > 128) {
22089     int LaneElts = 128 / VT.getScalarSizeInBits();
22090 #ifndef NDEBUG
22091     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22092       for (int j = 0; j < LaneElts; ++j)
22093         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22094                "Mask doesn't repeat in high 128-bit lanes!");
22095 #endif
22096     Mask.resize(LaneElts);
22097   }
22098
22099   switch (N.getOpcode()) {
22100   case X86ISD::PSHUFD:
22101     return Mask;
22102   case X86ISD::PSHUFLW:
22103     Mask.resize(4);
22104     return Mask;
22105   case X86ISD::PSHUFHW:
22106     Mask.erase(Mask.begin(), Mask.begin() + 4);
22107     for (int &M : Mask)
22108       M -= 4;
22109     return Mask;
22110   default:
22111     llvm_unreachable("No valid shuffle instruction found!");
22112   }
22113 }
22114
22115 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22116 ///
22117 /// We walk up the chain and look for a combinable shuffle, skipping over
22118 /// shuffles that we could hoist this shuffle's transformation past without
22119 /// altering anything.
22120 static SDValue
22121 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22122                              SelectionDAG &DAG,
22123                              TargetLowering::DAGCombinerInfo &DCI) {
22124   assert(N.getOpcode() == X86ISD::PSHUFD &&
22125          "Called with something other than an x86 128-bit half shuffle!");
22126   SDLoc DL(N);
22127
22128   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22129   // of the shuffles in the chain so that we can form a fresh chain to replace
22130   // this one.
22131   SmallVector<SDValue, 8> Chain;
22132   SDValue V = N.getOperand(0);
22133   for (; V.hasOneUse(); V = V.getOperand(0)) {
22134     switch (V.getOpcode()) {
22135     default:
22136       return SDValue(); // Nothing combined!
22137
22138     case ISD::BITCAST:
22139       // Skip bitcasts as we always know the type for the target specific
22140       // instructions.
22141       continue;
22142
22143     case X86ISD::PSHUFD:
22144       // Found another dword shuffle.
22145       break;
22146
22147     case X86ISD::PSHUFLW:
22148       // Check that the low words (being shuffled) are the identity in the
22149       // dword shuffle, and the high words are self-contained.
22150       if (Mask[0] != 0 || Mask[1] != 1 ||
22151           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22152         return SDValue();
22153
22154       Chain.push_back(V);
22155       continue;
22156
22157     case X86ISD::PSHUFHW:
22158       // Check that the high words (being shuffled) are the identity in the
22159       // dword shuffle, and the low words are self-contained.
22160       if (Mask[2] != 2 || Mask[3] != 3 ||
22161           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22162         return SDValue();
22163
22164       Chain.push_back(V);
22165       continue;
22166
22167     case X86ISD::UNPCKL:
22168     case X86ISD::UNPCKH:
22169       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22170       // shuffle into a preceding word shuffle.
22171       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22172           V.getSimpleValueType().getScalarType() != MVT::i16)
22173         return SDValue();
22174
22175       // Search for a half-shuffle which we can combine with.
22176       unsigned CombineOp =
22177           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22178       if (V.getOperand(0) != V.getOperand(1) ||
22179           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22180         return SDValue();
22181       Chain.push_back(V);
22182       V = V.getOperand(0);
22183       do {
22184         switch (V.getOpcode()) {
22185         default:
22186           return SDValue(); // Nothing to combine.
22187
22188         case X86ISD::PSHUFLW:
22189         case X86ISD::PSHUFHW:
22190           if (V.getOpcode() == CombineOp)
22191             break;
22192
22193           Chain.push_back(V);
22194
22195           // Fallthrough!
22196         case ISD::BITCAST:
22197           V = V.getOperand(0);
22198           continue;
22199         }
22200         break;
22201       } while (V.hasOneUse());
22202       break;
22203     }
22204     // Break out of the loop if we break out of the switch.
22205     break;
22206   }
22207
22208   if (!V.hasOneUse())
22209     // We fell out of the loop without finding a viable combining instruction.
22210     return SDValue();
22211
22212   // Merge this node's mask and our incoming mask.
22213   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22214   for (int &M : Mask)
22215     M = VMask[M];
22216   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22217                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22218
22219   // Rebuild the chain around this new shuffle.
22220   while (!Chain.empty()) {
22221     SDValue W = Chain.pop_back_val();
22222
22223     if (V.getValueType() != W.getOperand(0).getValueType())
22224       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22225
22226     switch (W.getOpcode()) {
22227     default:
22228       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22229
22230     case X86ISD::UNPCKL:
22231     case X86ISD::UNPCKH:
22232       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22233       break;
22234
22235     case X86ISD::PSHUFD:
22236     case X86ISD::PSHUFLW:
22237     case X86ISD::PSHUFHW:
22238       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22239       break;
22240     }
22241   }
22242   if (V.getValueType() != N.getValueType())
22243     V = DAG.getBitcast(N.getValueType(), V);
22244
22245   // Return the new chain to replace N.
22246   return V;
22247 }
22248
22249 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22250 ///
22251 /// We walk up the chain, skipping shuffles of the other half and looking
22252 /// through shuffles which switch halves trying to find a shuffle of the same
22253 /// pair of dwords.
22254 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22255                                         SelectionDAG &DAG,
22256                                         TargetLowering::DAGCombinerInfo &DCI) {
22257   assert(
22258       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22259       "Called with something other than an x86 128-bit half shuffle!");
22260   SDLoc DL(N);
22261   unsigned CombineOpcode = N.getOpcode();
22262
22263   // Walk up a single-use chain looking for a combinable shuffle.
22264   SDValue V = N.getOperand(0);
22265   for (; V.hasOneUse(); V = V.getOperand(0)) {
22266     switch (V.getOpcode()) {
22267     default:
22268       return false; // Nothing combined!
22269
22270     case ISD::BITCAST:
22271       // Skip bitcasts as we always know the type for the target specific
22272       // instructions.
22273       continue;
22274
22275     case X86ISD::PSHUFLW:
22276     case X86ISD::PSHUFHW:
22277       if (V.getOpcode() == CombineOpcode)
22278         break;
22279
22280       // Other-half shuffles are no-ops.
22281       continue;
22282     }
22283     // Break out of the loop if we break out of the switch.
22284     break;
22285   }
22286
22287   if (!V.hasOneUse())
22288     // We fell out of the loop without finding a viable combining instruction.
22289     return false;
22290
22291   // Combine away the bottom node as its shuffle will be accumulated into
22292   // a preceding shuffle.
22293   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22294
22295   // Record the old value.
22296   SDValue Old = V;
22297
22298   // Merge this node's mask and our incoming mask (adjusted to account for all
22299   // the pshufd instructions encountered).
22300   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22301   for (int &M : Mask)
22302     M = VMask[M];
22303   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22304                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22305
22306   // Check that the shuffles didn't cancel each other out. If not, we need to
22307   // combine to the new one.
22308   if (Old != V)
22309     // Replace the combinable shuffle with the combined one, updating all users
22310     // so that we re-evaluate the chain here.
22311     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22312
22313   return true;
22314 }
22315
22316 /// \brief Try to combine x86 target specific shuffles.
22317 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22318                                            TargetLowering::DAGCombinerInfo &DCI,
22319                                            const X86Subtarget *Subtarget) {
22320   SDLoc DL(N);
22321   MVT VT = N.getSimpleValueType();
22322   SmallVector<int, 4> Mask;
22323
22324   switch (N.getOpcode()) {
22325   case X86ISD::PSHUFD:
22326   case X86ISD::PSHUFLW:
22327   case X86ISD::PSHUFHW:
22328     Mask = getPSHUFShuffleMask(N);
22329     assert(Mask.size() == 4);
22330     break;
22331   default:
22332     return SDValue();
22333   }
22334
22335   // Nuke no-op shuffles that show up after combining.
22336   if (isNoopShuffleMask(Mask))
22337     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22338
22339   // Look for simplifications involving one or two shuffle instructions.
22340   SDValue V = N.getOperand(0);
22341   switch (N.getOpcode()) {
22342   default:
22343     break;
22344   case X86ISD::PSHUFLW:
22345   case X86ISD::PSHUFHW:
22346     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22347
22348     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22349       return SDValue(); // We combined away this shuffle, so we're done.
22350
22351     // See if this reduces to a PSHUFD which is no more expensive and can
22352     // combine with more operations. Note that it has to at least flip the
22353     // dwords as otherwise it would have been removed as a no-op.
22354     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22355       int DMask[] = {0, 1, 2, 3};
22356       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22357       DMask[DOffset + 0] = DOffset + 1;
22358       DMask[DOffset + 1] = DOffset + 0;
22359       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22360       V = DAG.getBitcast(DVT, V);
22361       DCI.AddToWorklist(V.getNode());
22362       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22363                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22364       DCI.AddToWorklist(V.getNode());
22365       return DAG.getBitcast(VT, V);
22366     }
22367
22368     // Look for shuffle patterns which can be implemented as a single unpack.
22369     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22370     // only works when we have a PSHUFD followed by two half-shuffles.
22371     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22372         (V.getOpcode() == X86ISD::PSHUFLW ||
22373          V.getOpcode() == X86ISD::PSHUFHW) &&
22374         V.getOpcode() != N.getOpcode() &&
22375         V.hasOneUse()) {
22376       SDValue D = V.getOperand(0);
22377       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22378         D = D.getOperand(0);
22379       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22380         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22381         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22382         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22383         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22384         int WordMask[8];
22385         for (int i = 0; i < 4; ++i) {
22386           WordMask[i + NOffset] = Mask[i] + NOffset;
22387           WordMask[i + VOffset] = VMask[i] + VOffset;
22388         }
22389         // Map the word mask through the DWord mask.
22390         int MappedMask[8];
22391         for (int i = 0; i < 8; ++i)
22392           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22393         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22394             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22395           // We can replace all three shuffles with an unpack.
22396           V = DAG.getBitcast(VT, D.getOperand(0));
22397           DCI.AddToWorklist(V.getNode());
22398           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22399                                                 : X86ISD::UNPCKH,
22400                              DL, VT, V, V);
22401         }
22402       }
22403     }
22404
22405     break;
22406
22407   case X86ISD::PSHUFD:
22408     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22409       return NewN;
22410
22411     break;
22412   }
22413
22414   return SDValue();
22415 }
22416
22417 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22418 ///
22419 /// We combine this directly on the abstract vector shuffle nodes so it is
22420 /// easier to generically match. We also insert dummy vector shuffle nodes for
22421 /// the operands which explicitly discard the lanes which are unused by this
22422 /// operation to try to flow through the rest of the combiner the fact that
22423 /// they're unused.
22424 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22425   SDLoc DL(N);
22426   EVT VT = N->getValueType(0);
22427
22428   // We only handle target-independent shuffles.
22429   // FIXME: It would be easy and harmless to use the target shuffle mask
22430   // extraction tool to support more.
22431   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22432     return SDValue();
22433
22434   auto *SVN = cast<ShuffleVectorSDNode>(N);
22435   ArrayRef<int> Mask = SVN->getMask();
22436   SDValue V1 = N->getOperand(0);
22437   SDValue V2 = N->getOperand(1);
22438
22439   // We require the first shuffle operand to be the SUB node, and the second to
22440   // be the ADD node.
22441   // FIXME: We should support the commuted patterns.
22442   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22443     return SDValue();
22444
22445   // If there are other uses of these operations we can't fold them.
22446   if (!V1->hasOneUse() || !V2->hasOneUse())
22447     return SDValue();
22448
22449   // Ensure that both operations have the same operands. Note that we can
22450   // commute the FADD operands.
22451   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22452   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22453       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22454     return SDValue();
22455
22456   // We're looking for blends between FADD and FSUB nodes. We insist on these
22457   // nodes being lined up in a specific expected pattern.
22458   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22459         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22460         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22461     return SDValue();
22462
22463   // Only specific types are legal at this point, assert so we notice if and
22464   // when these change.
22465   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22466           VT == MVT::v4f64) &&
22467          "Unknown vector type encountered!");
22468
22469   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22470 }
22471
22472 /// PerformShuffleCombine - Performs several different shuffle combines.
22473 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22474                                      TargetLowering::DAGCombinerInfo &DCI,
22475                                      const X86Subtarget *Subtarget) {
22476   SDLoc dl(N);
22477   SDValue N0 = N->getOperand(0);
22478   SDValue N1 = N->getOperand(1);
22479   EVT VT = N->getValueType(0);
22480
22481   // Don't create instructions with illegal types after legalize types has run.
22482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22483   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22484     return SDValue();
22485
22486   // If we have legalized the vector types, look for blends of FADD and FSUB
22487   // nodes that we can fuse into an ADDSUB node.
22488   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22489     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22490       return AddSub;
22491
22492   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22493   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22494       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22495     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22496
22497   // During Type Legalization, when promoting illegal vector types,
22498   // the backend might introduce new shuffle dag nodes and bitcasts.
22499   //
22500   // This code performs the following transformation:
22501   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22502   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22503   //
22504   // We do this only if both the bitcast and the BINOP dag nodes have
22505   // one use. Also, perform this transformation only if the new binary
22506   // operation is legal. This is to avoid introducing dag nodes that
22507   // potentially need to be further expanded (or custom lowered) into a
22508   // less optimal sequence of dag nodes.
22509   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22510       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22511       N0.getOpcode() == ISD::BITCAST) {
22512     SDValue BC0 = N0.getOperand(0);
22513     EVT SVT = BC0.getValueType();
22514     unsigned Opcode = BC0.getOpcode();
22515     unsigned NumElts = VT.getVectorNumElements();
22516
22517     if (BC0.hasOneUse() && SVT.isVector() &&
22518         SVT.getVectorNumElements() * 2 == NumElts &&
22519         TLI.isOperationLegal(Opcode, VT)) {
22520       bool CanFold = false;
22521       switch (Opcode) {
22522       default : break;
22523       case ISD::ADD :
22524       case ISD::FADD :
22525       case ISD::SUB :
22526       case ISD::FSUB :
22527       case ISD::MUL :
22528       case ISD::FMUL :
22529         CanFold = true;
22530       }
22531
22532       unsigned SVTNumElts = SVT.getVectorNumElements();
22533       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22534       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22535         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22536       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22537         CanFold = SVOp->getMaskElt(i) < 0;
22538
22539       if (CanFold) {
22540         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22541         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22542         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22543         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22544       }
22545     }
22546   }
22547
22548   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22549   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22550   // consecutive, non-overlapping, and in the right order.
22551   SmallVector<SDValue, 16> Elts;
22552   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22553     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22554
22555   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22556     return LD;
22557
22558   if (isTargetShuffle(N->getOpcode())) {
22559     SDValue Shuffle =
22560         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22561     if (Shuffle.getNode())
22562       return Shuffle;
22563
22564     // Try recursively combining arbitrary sequences of x86 shuffle
22565     // instructions into higher-order shuffles. We do this after combining
22566     // specific PSHUF instruction sequences into their minimal form so that we
22567     // can evaluate how many specialized shuffle instructions are involved in
22568     // a particular chain.
22569     SmallVector<int, 1> NonceMask; // Just a placeholder.
22570     NonceMask.push_back(0);
22571     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22572                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22573                                       DCI, Subtarget))
22574       return SDValue(); // This routine will use CombineTo to replace N.
22575   }
22576
22577   return SDValue();
22578 }
22579
22580 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22581 /// specific shuffle of a load can be folded into a single element load.
22582 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22583 /// shuffles have been custom lowered so we need to handle those here.
22584 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22585                                          TargetLowering::DAGCombinerInfo &DCI) {
22586   if (DCI.isBeforeLegalizeOps())
22587     return SDValue();
22588
22589   SDValue InVec = N->getOperand(0);
22590   SDValue EltNo = N->getOperand(1);
22591
22592   if (!isa<ConstantSDNode>(EltNo))
22593     return SDValue();
22594
22595   EVT OriginalVT = InVec.getValueType();
22596
22597   if (InVec.getOpcode() == ISD::BITCAST) {
22598     // Don't duplicate a load with other uses.
22599     if (!InVec.hasOneUse())
22600       return SDValue();
22601     EVT BCVT = InVec.getOperand(0).getValueType();
22602     if (!BCVT.isVector() ||
22603         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22604       return SDValue();
22605     InVec = InVec.getOperand(0);
22606   }
22607
22608   EVT CurrentVT = InVec.getValueType();
22609
22610   if (!isTargetShuffle(InVec.getOpcode()))
22611     return SDValue();
22612
22613   // Don't duplicate a load with other uses.
22614   if (!InVec.hasOneUse())
22615     return SDValue();
22616
22617   SmallVector<int, 16> ShuffleMask;
22618   bool UnaryShuffle;
22619   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22620                             ShuffleMask, UnaryShuffle))
22621     return SDValue();
22622
22623   // Select the input vector, guarding against out of range extract vector.
22624   unsigned NumElems = CurrentVT.getVectorNumElements();
22625   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22626   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22627   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22628                                          : InVec.getOperand(1);
22629
22630   // If inputs to shuffle are the same for both ops, then allow 2 uses
22631   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22632                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22633
22634   if (LdNode.getOpcode() == ISD::BITCAST) {
22635     // Don't duplicate a load with other uses.
22636     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22637       return SDValue();
22638
22639     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22640     LdNode = LdNode.getOperand(0);
22641   }
22642
22643   if (!ISD::isNormalLoad(LdNode.getNode()))
22644     return SDValue();
22645
22646   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22647
22648   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22649     return SDValue();
22650
22651   EVT EltVT = N->getValueType(0);
22652   // If there's a bitcast before the shuffle, check if the load type and
22653   // alignment is valid.
22654   unsigned Align = LN0->getAlignment();
22655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22656   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22657       EltVT.getTypeForEVT(*DAG.getContext()));
22658
22659   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22660     return SDValue();
22661
22662   // All checks match so transform back to vector_shuffle so that DAG combiner
22663   // can finish the job
22664   SDLoc dl(N);
22665
22666   // Create shuffle node taking into account the case that its a unary shuffle
22667   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22668                                    : InVec.getOperand(1);
22669   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22670                                  InVec.getOperand(0), Shuffle,
22671                                  &ShuffleMask[0]);
22672   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22673   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22674                      EltNo);
22675 }
22676
22677 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22678 /// special and don't usually play with other vector types, it's better to
22679 /// handle them early to be sure we emit efficient code by avoiding
22680 /// store-load conversions.
22681 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22682   if (N->getValueType(0) != MVT::x86mmx ||
22683       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22684       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22685     return SDValue();
22686
22687   SDValue V = N->getOperand(0);
22688   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22689   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22690     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22691                        N->getValueType(0), V.getOperand(0));
22692
22693   return SDValue();
22694 }
22695
22696 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22697 /// generation and convert it from being a bunch of shuffles and extracts
22698 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22699 /// storing the value and loading scalars back, while for x64 we should
22700 /// use 64-bit extracts and shifts.
22701 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22702                                          TargetLowering::DAGCombinerInfo &DCI) {
22703   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22704     return NewOp;
22705
22706   SDValue InputVector = N->getOperand(0);
22707   SDLoc dl(InputVector);
22708   // Detect mmx to i32 conversion through a v2i32 elt extract.
22709   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22710       N->getValueType(0) == MVT::i32 &&
22711       InputVector.getValueType() == MVT::v2i32) {
22712
22713     // The bitcast source is a direct mmx result.
22714     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22715     if (MMXSrc.getValueType() == MVT::x86mmx)
22716       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22717                          N->getValueType(0),
22718                          InputVector.getNode()->getOperand(0));
22719
22720     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22721     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22722     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22723         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22724         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22725         MMXSrcOp.getValueType() == MVT::v1i64 &&
22726         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22727       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22728                          N->getValueType(0),
22729                          MMXSrcOp.getOperand(0));
22730   }
22731
22732   EVT VT = N->getValueType(0);
22733
22734   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22735       InputVector.getOpcode() == ISD::BITCAST &&
22736       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22737     uint64_t ExtractedElt =
22738           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22739     uint64_t InputValue =
22740           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22741     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22742     return DAG.getConstant(Res, dl, MVT::i1);
22743   }
22744   // Only operate on vectors of 4 elements, where the alternative shuffling
22745   // gets to be more expensive.
22746   if (InputVector.getValueType() != MVT::v4i32)
22747     return SDValue();
22748
22749   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22750   // single use which is a sign-extend or zero-extend, and all elements are
22751   // used.
22752   SmallVector<SDNode *, 4> Uses;
22753   unsigned ExtractedElements = 0;
22754   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22755        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22756     if (UI.getUse().getResNo() != InputVector.getResNo())
22757       return SDValue();
22758
22759     SDNode *Extract = *UI;
22760     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22761       return SDValue();
22762
22763     if (Extract->getValueType(0) != MVT::i32)
22764       return SDValue();
22765     if (!Extract->hasOneUse())
22766       return SDValue();
22767     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22768         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22769       return SDValue();
22770     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22771       return SDValue();
22772
22773     // Record which element was extracted.
22774     ExtractedElements |=
22775       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22776
22777     Uses.push_back(Extract);
22778   }
22779
22780   // If not all the elements were used, this may not be worthwhile.
22781   if (ExtractedElements != 15)
22782     return SDValue();
22783
22784   // Ok, we've now decided to do the transformation.
22785   // If 64-bit shifts are legal, use the extract-shift sequence,
22786   // otherwise bounce the vector off the cache.
22787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22788   SDValue Vals[4];
22789
22790   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22791     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22792     auto &DL = DAG.getDataLayout();
22793     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22794     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22795       DAG.getConstant(0, dl, VecIdxTy));
22796     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22797       DAG.getConstant(1, dl, VecIdxTy));
22798
22799     SDValue ShAmt = DAG.getConstant(
22800         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22801     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22802     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22803       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22804     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22805     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22806       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22807   } else {
22808     // Store the value to a temporary stack slot.
22809     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22810     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22811       MachinePointerInfo(), false, false, 0);
22812
22813     EVT ElementType = InputVector.getValueType().getVectorElementType();
22814     unsigned EltSize = ElementType.getSizeInBits() / 8;
22815
22816     // Replace each use (extract) with a load of the appropriate element.
22817     for (unsigned i = 0; i < 4; ++i) {
22818       uint64_t Offset = EltSize * i;
22819       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22820       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22821
22822       SDValue ScalarAddr =
22823           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22824
22825       // Load the scalar.
22826       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22827                             ScalarAddr, MachinePointerInfo(),
22828                             false, false, false, 0);
22829
22830     }
22831   }
22832
22833   // Replace the extracts
22834   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22835     UE = Uses.end(); UI != UE; ++UI) {
22836     SDNode *Extract = *UI;
22837
22838     SDValue Idx = Extract->getOperand(1);
22839     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22840     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22841   }
22842
22843   // The replacement was made in place; don't return anything.
22844   return SDValue();
22845 }
22846
22847 static SDValue
22848 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22849                                       const X86Subtarget *Subtarget) {
22850   SDLoc dl(N);
22851   SDValue Cond = N->getOperand(0);
22852   SDValue LHS = N->getOperand(1);
22853   SDValue RHS = N->getOperand(2);
22854
22855   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22856     SDValue CondSrc = Cond->getOperand(0);
22857     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22858       Cond = CondSrc->getOperand(0);
22859   }
22860
22861   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22862     return SDValue();
22863
22864   // A vselect where all conditions and data are constants can be optimized into
22865   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22866   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22867       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22868     return SDValue();
22869
22870   unsigned MaskValue = 0;
22871   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22872     return SDValue();
22873
22874   MVT VT = N->getSimpleValueType(0);
22875   unsigned NumElems = VT.getVectorNumElements();
22876   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22877   for (unsigned i = 0; i < NumElems; ++i) {
22878     // Be sure we emit undef where we can.
22879     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22880       ShuffleMask[i] = -1;
22881     else
22882       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22883   }
22884
22885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22886   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22887     return SDValue();
22888   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22889 }
22890
22891 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22892 /// nodes.
22893 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22894                                     TargetLowering::DAGCombinerInfo &DCI,
22895                                     const X86Subtarget *Subtarget) {
22896   SDLoc DL(N);
22897   SDValue Cond = N->getOperand(0);
22898   // Get the LHS/RHS of the select.
22899   SDValue LHS = N->getOperand(1);
22900   SDValue RHS = N->getOperand(2);
22901   EVT VT = LHS.getValueType();
22902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22903
22904   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22905   // instructions match the semantics of the common C idiom x<y?x:y but not
22906   // x<=y?x:y, because of how they handle negative zero (which can be
22907   // ignored in unsafe-math mode).
22908   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22909   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22910       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22911       (Subtarget->hasSSE2() ||
22912        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22913     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22914
22915     unsigned Opcode = 0;
22916     // Check for x CC y ? x : y.
22917     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22918         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22919       switch (CC) {
22920       default: break;
22921       case ISD::SETULT:
22922         // Converting this to a min would handle NaNs incorrectly, and swapping
22923         // the operands would cause it to handle comparisons between positive
22924         // and negative zero incorrectly.
22925         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22926           if (!DAG.getTarget().Options.UnsafeFPMath &&
22927               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22928             break;
22929           std::swap(LHS, RHS);
22930         }
22931         Opcode = X86ISD::FMIN;
22932         break;
22933       case ISD::SETOLE:
22934         // Converting this to a min would handle comparisons between positive
22935         // and negative zero incorrectly.
22936         if (!DAG.getTarget().Options.UnsafeFPMath &&
22937             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22938           break;
22939         Opcode = X86ISD::FMIN;
22940         break;
22941       case ISD::SETULE:
22942         // Converting this to a min would handle both negative zeros and NaNs
22943         // incorrectly, but we can swap the operands to fix both.
22944         std::swap(LHS, RHS);
22945       case ISD::SETOLT:
22946       case ISD::SETLT:
22947       case ISD::SETLE:
22948         Opcode = X86ISD::FMIN;
22949         break;
22950
22951       case ISD::SETOGE:
22952         // Converting this to a max would handle comparisons between positive
22953         // and negative zero incorrectly.
22954         if (!DAG.getTarget().Options.UnsafeFPMath &&
22955             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22956           break;
22957         Opcode = X86ISD::FMAX;
22958         break;
22959       case ISD::SETUGT:
22960         // Converting this to a max would handle NaNs incorrectly, and swapping
22961         // the operands would cause it to handle comparisons between positive
22962         // and negative zero incorrectly.
22963         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22964           if (!DAG.getTarget().Options.UnsafeFPMath &&
22965               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22966             break;
22967           std::swap(LHS, RHS);
22968         }
22969         Opcode = X86ISD::FMAX;
22970         break;
22971       case ISD::SETUGE:
22972         // Converting this to a max would handle both negative zeros and NaNs
22973         // incorrectly, but we can swap the operands to fix both.
22974         std::swap(LHS, RHS);
22975       case ISD::SETOGT:
22976       case ISD::SETGT:
22977       case ISD::SETGE:
22978         Opcode = X86ISD::FMAX;
22979         break;
22980       }
22981     // Check for x CC y ? y : x -- a min/max with reversed arms.
22982     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22983                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22984       switch (CC) {
22985       default: break;
22986       case ISD::SETOGE:
22987         // Converting this to a min would handle comparisons between positive
22988         // and negative zero incorrectly, and swapping the operands would
22989         // cause it to handle NaNs incorrectly.
22990         if (!DAG.getTarget().Options.UnsafeFPMath &&
22991             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22992           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22993             break;
22994           std::swap(LHS, RHS);
22995         }
22996         Opcode = X86ISD::FMIN;
22997         break;
22998       case ISD::SETUGT:
22999         // Converting this to a min would handle NaNs incorrectly.
23000         if (!DAG.getTarget().Options.UnsafeFPMath &&
23001             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23002           break;
23003         Opcode = X86ISD::FMIN;
23004         break;
23005       case ISD::SETUGE:
23006         // Converting this to a min would handle both negative zeros and NaNs
23007         // incorrectly, but we can swap the operands to fix both.
23008         std::swap(LHS, RHS);
23009       case ISD::SETOGT:
23010       case ISD::SETGT:
23011       case ISD::SETGE:
23012         Opcode = X86ISD::FMIN;
23013         break;
23014
23015       case ISD::SETULT:
23016         // Converting this to a max would handle NaNs incorrectly.
23017         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23018           break;
23019         Opcode = X86ISD::FMAX;
23020         break;
23021       case ISD::SETOLE:
23022         // Converting this to a max would handle comparisons between positive
23023         // and negative zero incorrectly, and swapping the operands would
23024         // cause it to handle NaNs incorrectly.
23025         if (!DAG.getTarget().Options.UnsafeFPMath &&
23026             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23027           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23028             break;
23029           std::swap(LHS, RHS);
23030         }
23031         Opcode = X86ISD::FMAX;
23032         break;
23033       case ISD::SETULE:
23034         // Converting this to a max would handle both negative zeros and NaNs
23035         // incorrectly, but we can swap the operands to fix both.
23036         std::swap(LHS, RHS);
23037       case ISD::SETOLT:
23038       case ISD::SETLT:
23039       case ISD::SETLE:
23040         Opcode = X86ISD::FMAX;
23041         break;
23042       }
23043     }
23044
23045     if (Opcode)
23046       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23047   }
23048
23049   EVT CondVT = Cond.getValueType();
23050   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23051       CondVT.getVectorElementType() == MVT::i1) {
23052     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23053     // lowering on KNL. In this case we convert it to
23054     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23055     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23056     // Since SKX these selects have a proper lowering.
23057     EVT OpVT = LHS.getValueType();
23058     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23059         (OpVT.getVectorElementType() == MVT::i8 ||
23060          OpVT.getVectorElementType() == MVT::i16) &&
23061         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23062       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23063       DCI.AddToWorklist(Cond.getNode());
23064       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23065     }
23066   }
23067   // If this is a select between two integer constants, try to do some
23068   // optimizations.
23069   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23070     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23071       // Don't do this for crazy integer types.
23072       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23073         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23074         // so that TrueC (the true value) is larger than FalseC.
23075         bool NeedsCondInvert = false;
23076
23077         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23078             // Efficiently invertible.
23079             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23080              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23081               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23082           NeedsCondInvert = true;
23083           std::swap(TrueC, FalseC);
23084         }
23085
23086         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23087         if (FalseC->getAPIntValue() == 0 &&
23088             TrueC->getAPIntValue().isPowerOf2()) {
23089           if (NeedsCondInvert) // Invert the condition if needed.
23090             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23091                                DAG.getConstant(1, DL, Cond.getValueType()));
23092
23093           // Zero extend the condition if needed.
23094           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23095
23096           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23097           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23098                              DAG.getConstant(ShAmt, DL, MVT::i8));
23099         }
23100
23101         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23102         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23103           if (NeedsCondInvert) // Invert the condition if needed.
23104             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23105                                DAG.getConstant(1, DL, Cond.getValueType()));
23106
23107           // Zero extend the condition if needed.
23108           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23109                              FalseC->getValueType(0), Cond);
23110           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23111                              SDValue(FalseC, 0));
23112         }
23113
23114         // Optimize cases that will turn into an LEA instruction.  This requires
23115         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23116         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23117           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23118           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23119
23120           bool isFastMultiplier = false;
23121           if (Diff < 10) {
23122             switch ((unsigned char)Diff) {
23123               default: break;
23124               case 1:  // result = add base, cond
23125               case 2:  // result = lea base(    , cond*2)
23126               case 3:  // result = lea base(cond, cond*2)
23127               case 4:  // result = lea base(    , cond*4)
23128               case 5:  // result = lea base(cond, cond*4)
23129               case 8:  // result = lea base(    , cond*8)
23130               case 9:  // result = lea base(cond, cond*8)
23131                 isFastMultiplier = true;
23132                 break;
23133             }
23134           }
23135
23136           if (isFastMultiplier) {
23137             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23138             if (NeedsCondInvert) // Invert the condition if needed.
23139               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23140                                  DAG.getConstant(1, DL, Cond.getValueType()));
23141
23142             // Zero extend the condition if needed.
23143             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23144                                Cond);
23145             // Scale the condition by the difference.
23146             if (Diff != 1)
23147               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23148                                  DAG.getConstant(Diff, DL,
23149                                                  Cond.getValueType()));
23150
23151             // Add the base if non-zero.
23152             if (FalseC->getAPIntValue() != 0)
23153               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23154                                  SDValue(FalseC, 0));
23155             return Cond;
23156           }
23157         }
23158       }
23159   }
23160
23161   // Canonicalize max and min:
23162   // (x > y) ? x : y -> (x >= y) ? x : y
23163   // (x < y) ? x : y -> (x <= y) ? x : y
23164   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23165   // the need for an extra compare
23166   // against zero. e.g.
23167   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23168   // subl   %esi, %edi
23169   // testl  %edi, %edi
23170   // movl   $0, %eax
23171   // cmovgl %edi, %eax
23172   // =>
23173   // xorl   %eax, %eax
23174   // subl   %esi, $edi
23175   // cmovsl %eax, %edi
23176   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23177       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23178       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23179     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23180     switch (CC) {
23181     default: break;
23182     case ISD::SETLT:
23183     case ISD::SETGT: {
23184       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23185       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23186                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23187       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23188     }
23189     }
23190   }
23191
23192   // Early exit check
23193   if (!TLI.isTypeLegal(VT))
23194     return SDValue();
23195
23196   // Match VSELECTs into subs with unsigned saturation.
23197   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23198       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23199       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23200        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23201     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23202
23203     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23204     // left side invert the predicate to simplify logic below.
23205     SDValue Other;
23206     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23207       Other = RHS;
23208       CC = ISD::getSetCCInverse(CC, true);
23209     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23210       Other = LHS;
23211     }
23212
23213     if (Other.getNode() && Other->getNumOperands() == 2 &&
23214         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23215       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23216       SDValue CondRHS = Cond->getOperand(1);
23217
23218       // Look for a general sub with unsigned saturation first.
23219       // x >= y ? x-y : 0 --> subus x, y
23220       // x >  y ? x-y : 0 --> subus x, y
23221       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23222           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23223         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23224
23225       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23226         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23227           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23228             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23229               // If the RHS is a constant we have to reverse the const
23230               // canonicalization.
23231               // x > C-1 ? x+-C : 0 --> subus x, C
23232               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23233                   CondRHSConst->getAPIntValue() ==
23234                       (-OpRHSConst->getAPIntValue() - 1))
23235                 return DAG.getNode(
23236                     X86ISD::SUBUS, DL, VT, OpLHS,
23237                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23238
23239           // Another special case: If C was a sign bit, the sub has been
23240           // canonicalized into a xor.
23241           // FIXME: Would it be better to use computeKnownBits to determine
23242           //        whether it's safe to decanonicalize the xor?
23243           // x s< 0 ? x^C : 0 --> subus x, C
23244           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23245               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23246               OpRHSConst->getAPIntValue().isSignBit())
23247             // Note that we have to rebuild the RHS constant here to ensure we
23248             // don't rely on particular values of undef lanes.
23249             return DAG.getNode(
23250                 X86ISD::SUBUS, DL, VT, OpLHS,
23251                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23252         }
23253     }
23254   }
23255
23256   // Simplify vector selection if condition value type matches vselect
23257   // operand type
23258   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23259     assert(Cond.getValueType().isVector() &&
23260            "vector select expects a vector selector!");
23261
23262     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23263     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23264
23265     // Try invert the condition if true value is not all 1s and false value
23266     // is not all 0s.
23267     if (!TValIsAllOnes && !FValIsAllZeros &&
23268         // Check if the selector will be produced by CMPP*/PCMP*
23269         Cond.getOpcode() == ISD::SETCC &&
23270         // Check if SETCC has already been promoted
23271         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23272             CondVT) {
23273       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23274       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23275
23276       if (TValIsAllZeros || FValIsAllOnes) {
23277         SDValue CC = Cond.getOperand(2);
23278         ISD::CondCode NewCC =
23279           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23280                                Cond.getOperand(0).getValueType().isInteger());
23281         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23282         std::swap(LHS, RHS);
23283         TValIsAllOnes = FValIsAllOnes;
23284         FValIsAllZeros = TValIsAllZeros;
23285       }
23286     }
23287
23288     if (TValIsAllOnes || FValIsAllZeros) {
23289       SDValue Ret;
23290
23291       if (TValIsAllOnes && FValIsAllZeros)
23292         Ret = Cond;
23293       else if (TValIsAllOnes)
23294         Ret =
23295             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23296       else if (FValIsAllZeros)
23297         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23298                           DAG.getBitcast(CondVT, LHS));
23299
23300       return DAG.getBitcast(VT, Ret);
23301     }
23302   }
23303
23304   // We should generate an X86ISD::BLENDI from a vselect if its argument
23305   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23306   // constants. This specific pattern gets generated when we split a
23307   // selector for a 512 bit vector in a machine without AVX512 (but with
23308   // 256-bit vectors), during legalization:
23309   //
23310   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23311   //
23312   // Iff we find this pattern and the build_vectors are built from
23313   // constants, we translate the vselect into a shuffle_vector that we
23314   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23315   if ((N->getOpcode() == ISD::VSELECT ||
23316        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23317       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23318     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23319     if (Shuffle.getNode())
23320       return Shuffle;
23321   }
23322
23323   // If this is a *dynamic* select (non-constant condition) and we can match
23324   // this node with one of the variable blend instructions, restructure the
23325   // condition so that the blends can use the high bit of each element and use
23326   // SimplifyDemandedBits to simplify the condition operand.
23327   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23328       !DCI.isBeforeLegalize() &&
23329       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23330     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23331
23332     // Don't optimize vector selects that map to mask-registers.
23333     if (BitWidth == 1)
23334       return SDValue();
23335
23336     // We can only handle the cases where VSELECT is directly legal on the
23337     // subtarget. We custom lower VSELECT nodes with constant conditions and
23338     // this makes it hard to see whether a dynamic VSELECT will correctly
23339     // lower, so we both check the operation's status and explicitly handle the
23340     // cases where a *dynamic* blend will fail even though a constant-condition
23341     // blend could be custom lowered.
23342     // FIXME: We should find a better way to handle this class of problems.
23343     // Potentially, we should combine constant-condition vselect nodes
23344     // pre-legalization into shuffles and not mark as many types as custom
23345     // lowered.
23346     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23347       return SDValue();
23348     // FIXME: We don't support i16-element blends currently. We could and
23349     // should support them by making *all* the bits in the condition be set
23350     // rather than just the high bit and using an i8-element blend.
23351     if (VT.getScalarType() == MVT::i16)
23352       return SDValue();
23353     // Dynamic blending was only available from SSE4.1 onward.
23354     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23355       return SDValue();
23356     // Byte blends are only available in AVX2
23357     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23358         !Subtarget->hasAVX2())
23359       return SDValue();
23360
23361     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23362     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23363
23364     APInt KnownZero, KnownOne;
23365     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23366                                           DCI.isBeforeLegalizeOps());
23367     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23368         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23369                                  TLO)) {
23370       // If we changed the computation somewhere in the DAG, this change
23371       // will affect all users of Cond.
23372       // Make sure it is fine and update all the nodes so that we do not
23373       // use the generic VSELECT anymore. Otherwise, we may perform
23374       // wrong optimizations as we messed up with the actual expectation
23375       // for the vector boolean values.
23376       if (Cond != TLO.Old) {
23377         // Check all uses of that condition operand to check whether it will be
23378         // consumed by non-BLEND instructions, which may depend on all bits are
23379         // set properly.
23380         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23381              I != E; ++I)
23382           if (I->getOpcode() != ISD::VSELECT)
23383             // TODO: Add other opcodes eventually lowered into BLEND.
23384             return SDValue();
23385
23386         // Update all the users of the condition, before committing the change,
23387         // so that the VSELECT optimizations that expect the correct vector
23388         // boolean value will not be triggered.
23389         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23390              I != E; ++I)
23391           DAG.ReplaceAllUsesOfValueWith(
23392               SDValue(*I, 0),
23393               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23394                           Cond, I->getOperand(1), I->getOperand(2)));
23395         DCI.CommitTargetLoweringOpt(TLO);
23396         return SDValue();
23397       }
23398       // At this point, only Cond is changed. Change the condition
23399       // just for N to keep the opportunity to optimize all other
23400       // users their own way.
23401       DAG.ReplaceAllUsesOfValueWith(
23402           SDValue(N, 0),
23403           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23404                       TLO.New, N->getOperand(1), N->getOperand(2)));
23405       return SDValue();
23406     }
23407   }
23408
23409   return SDValue();
23410 }
23411
23412 // Check whether a boolean test is testing a boolean value generated by
23413 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23414 // code.
23415 //
23416 // Simplify the following patterns:
23417 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23418 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23419 // to (Op EFLAGS Cond)
23420 //
23421 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23422 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23423 // to (Op EFLAGS !Cond)
23424 //
23425 // where Op could be BRCOND or CMOV.
23426 //
23427 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23428   // Quit if not CMP and SUB with its value result used.
23429   if (Cmp.getOpcode() != X86ISD::CMP &&
23430       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23431       return SDValue();
23432
23433   // Quit if not used as a boolean value.
23434   if (CC != X86::COND_E && CC != X86::COND_NE)
23435     return SDValue();
23436
23437   // Check CMP operands. One of them should be 0 or 1 and the other should be
23438   // an SetCC or extended from it.
23439   SDValue Op1 = Cmp.getOperand(0);
23440   SDValue Op2 = Cmp.getOperand(1);
23441
23442   SDValue SetCC;
23443   const ConstantSDNode* C = nullptr;
23444   bool needOppositeCond = (CC == X86::COND_E);
23445   bool checkAgainstTrue = false; // Is it a comparison against 1?
23446
23447   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23448     SetCC = Op2;
23449   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23450     SetCC = Op1;
23451   else // Quit if all operands are not constants.
23452     return SDValue();
23453
23454   if (C->getZExtValue() == 1) {
23455     needOppositeCond = !needOppositeCond;
23456     checkAgainstTrue = true;
23457   } else if (C->getZExtValue() != 0)
23458     // Quit if the constant is neither 0 or 1.
23459     return SDValue();
23460
23461   bool truncatedToBoolWithAnd = false;
23462   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23463   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23464          SetCC.getOpcode() == ISD::TRUNCATE ||
23465          SetCC.getOpcode() == ISD::AND) {
23466     if (SetCC.getOpcode() == ISD::AND) {
23467       int OpIdx = -1;
23468       ConstantSDNode *CS;
23469       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23470           CS->getZExtValue() == 1)
23471         OpIdx = 1;
23472       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23473           CS->getZExtValue() == 1)
23474         OpIdx = 0;
23475       if (OpIdx == -1)
23476         break;
23477       SetCC = SetCC.getOperand(OpIdx);
23478       truncatedToBoolWithAnd = true;
23479     } else
23480       SetCC = SetCC.getOperand(0);
23481   }
23482
23483   switch (SetCC.getOpcode()) {
23484   case X86ISD::SETCC_CARRY:
23485     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23486     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23487     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23488     // truncated to i1 using 'and'.
23489     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23490       break;
23491     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23492            "Invalid use of SETCC_CARRY!");
23493     // FALL THROUGH
23494   case X86ISD::SETCC:
23495     // Set the condition code or opposite one if necessary.
23496     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23497     if (needOppositeCond)
23498       CC = X86::GetOppositeBranchCondition(CC);
23499     return SetCC.getOperand(1);
23500   case X86ISD::CMOV: {
23501     // Check whether false/true value has canonical one, i.e. 0 or 1.
23502     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23503     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23504     // Quit if true value is not a constant.
23505     if (!TVal)
23506       return SDValue();
23507     // Quit if false value is not a constant.
23508     if (!FVal) {
23509       SDValue Op = SetCC.getOperand(0);
23510       // Skip 'zext' or 'trunc' node.
23511       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23512           Op.getOpcode() == ISD::TRUNCATE)
23513         Op = Op.getOperand(0);
23514       // A special case for rdrand/rdseed, where 0 is set if false cond is
23515       // found.
23516       if ((Op.getOpcode() != X86ISD::RDRAND &&
23517            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23518         return SDValue();
23519     }
23520     // Quit if false value is not the constant 0 or 1.
23521     bool FValIsFalse = true;
23522     if (FVal && FVal->getZExtValue() != 0) {
23523       if (FVal->getZExtValue() != 1)
23524         return SDValue();
23525       // If FVal is 1, opposite cond is needed.
23526       needOppositeCond = !needOppositeCond;
23527       FValIsFalse = false;
23528     }
23529     // Quit if TVal is not the constant opposite of FVal.
23530     if (FValIsFalse && TVal->getZExtValue() != 1)
23531       return SDValue();
23532     if (!FValIsFalse && TVal->getZExtValue() != 0)
23533       return SDValue();
23534     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23535     if (needOppositeCond)
23536       CC = X86::GetOppositeBranchCondition(CC);
23537     return SetCC.getOperand(3);
23538   }
23539   }
23540
23541   return SDValue();
23542 }
23543
23544 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23545 /// Match:
23546 ///   (X86or (X86setcc) (X86setcc))
23547 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23548 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23549                                            X86::CondCode &CC1, SDValue &Flags,
23550                                            bool &isAnd) {
23551   if (Cond->getOpcode() == X86ISD::CMP) {
23552     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23553     if (!CondOp1C || !CondOp1C->isNullValue())
23554       return false;
23555
23556     Cond = Cond->getOperand(0);
23557   }
23558
23559   isAnd = false;
23560
23561   SDValue SetCC0, SetCC1;
23562   switch (Cond->getOpcode()) {
23563   default: return false;
23564   case ISD::AND:
23565   case X86ISD::AND:
23566     isAnd = true;
23567     // fallthru
23568   case ISD::OR:
23569   case X86ISD::OR:
23570     SetCC0 = Cond->getOperand(0);
23571     SetCC1 = Cond->getOperand(1);
23572     break;
23573   };
23574
23575   // Make sure we have SETCC nodes, using the same flags value.
23576   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23577       SetCC1.getOpcode() != X86ISD::SETCC ||
23578       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23579     return false;
23580
23581   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23582   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23583   Flags = SetCC0->getOperand(1);
23584   return true;
23585 }
23586
23587 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23588 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23589                                   TargetLowering::DAGCombinerInfo &DCI,
23590                                   const X86Subtarget *Subtarget) {
23591   SDLoc DL(N);
23592
23593   // If the flag operand isn't dead, don't touch this CMOV.
23594   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23595     return SDValue();
23596
23597   SDValue FalseOp = N->getOperand(0);
23598   SDValue TrueOp = N->getOperand(1);
23599   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23600   SDValue Cond = N->getOperand(3);
23601
23602   if (CC == X86::COND_E || CC == X86::COND_NE) {
23603     switch (Cond.getOpcode()) {
23604     default: break;
23605     case X86ISD::BSR:
23606     case X86ISD::BSF:
23607       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23608       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23609         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23610     }
23611   }
23612
23613   SDValue Flags;
23614
23615   Flags = checkBoolTestSetCCCombine(Cond, CC);
23616   if (Flags.getNode() &&
23617       // Extra check as FCMOV only supports a subset of X86 cond.
23618       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23619     SDValue Ops[] = { FalseOp, TrueOp,
23620                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23621     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23622   }
23623
23624   // If this is a select between two integer constants, try to do some
23625   // optimizations.  Note that the operands are ordered the opposite of SELECT
23626   // operands.
23627   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23628     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23629       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23630       // larger than FalseC (the false value).
23631       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23632         CC = X86::GetOppositeBranchCondition(CC);
23633         std::swap(TrueC, FalseC);
23634         std::swap(TrueOp, FalseOp);
23635       }
23636
23637       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23638       // This is efficient for any integer data type (including i8/i16) and
23639       // shift amount.
23640       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23641         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23642                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23643
23644         // Zero extend the condition if needed.
23645         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23646
23647         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23648         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23649                            DAG.getConstant(ShAmt, DL, MVT::i8));
23650         if (N->getNumValues() == 2)  // Dead flag value?
23651           return DCI.CombineTo(N, Cond, SDValue());
23652         return Cond;
23653       }
23654
23655       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23656       // for any integer data type, including i8/i16.
23657       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23658         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23659                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23660
23661         // Zero extend the condition if needed.
23662         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23663                            FalseC->getValueType(0), Cond);
23664         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23665                            SDValue(FalseC, 0));
23666
23667         if (N->getNumValues() == 2)  // Dead flag value?
23668           return DCI.CombineTo(N, Cond, SDValue());
23669         return Cond;
23670       }
23671
23672       // Optimize cases that will turn into an LEA instruction.  This requires
23673       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23674       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23675         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23676         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23677
23678         bool isFastMultiplier = false;
23679         if (Diff < 10) {
23680           switch ((unsigned char)Diff) {
23681           default: break;
23682           case 1:  // result = add base, cond
23683           case 2:  // result = lea base(    , cond*2)
23684           case 3:  // result = lea base(cond, cond*2)
23685           case 4:  // result = lea base(    , cond*4)
23686           case 5:  // result = lea base(cond, cond*4)
23687           case 8:  // result = lea base(    , cond*8)
23688           case 9:  // result = lea base(cond, cond*8)
23689             isFastMultiplier = true;
23690             break;
23691           }
23692         }
23693
23694         if (isFastMultiplier) {
23695           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23696           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23697                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23698           // Zero extend the condition if needed.
23699           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23700                              Cond);
23701           // Scale the condition by the difference.
23702           if (Diff != 1)
23703             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23704                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23705
23706           // Add the base if non-zero.
23707           if (FalseC->getAPIntValue() != 0)
23708             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23709                                SDValue(FalseC, 0));
23710           if (N->getNumValues() == 2)  // Dead flag value?
23711             return DCI.CombineTo(N, Cond, SDValue());
23712           return Cond;
23713         }
23714       }
23715     }
23716   }
23717
23718   // Handle these cases:
23719   //   (select (x != c), e, c) -> select (x != c), e, x),
23720   //   (select (x == c), c, e) -> select (x == c), x, e)
23721   // where the c is an integer constant, and the "select" is the combination
23722   // of CMOV and CMP.
23723   //
23724   // The rationale for this change is that the conditional-move from a constant
23725   // needs two instructions, however, conditional-move from a register needs
23726   // only one instruction.
23727   //
23728   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23729   //  some instruction-combining opportunities. This opt needs to be
23730   //  postponed as late as possible.
23731   //
23732   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23733     // the DCI.xxxx conditions are provided to postpone the optimization as
23734     // late as possible.
23735
23736     ConstantSDNode *CmpAgainst = nullptr;
23737     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23738         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23739         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23740
23741       if (CC == X86::COND_NE &&
23742           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23743         CC = X86::GetOppositeBranchCondition(CC);
23744         std::swap(TrueOp, FalseOp);
23745       }
23746
23747       if (CC == X86::COND_E &&
23748           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23749         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23750                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23751         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23752       }
23753     }
23754   }
23755
23756   // Fold and/or of setcc's to double CMOV:
23757   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23758   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23759   //
23760   // This combine lets us generate:
23761   //   cmovcc1 (jcc1 if we don't have CMOV)
23762   //   cmovcc2 (same)
23763   // instead of:
23764   //   setcc1
23765   //   setcc2
23766   //   and/or
23767   //   cmovne (jne if we don't have CMOV)
23768   // When we can't use the CMOV instruction, it might increase branch
23769   // mispredicts.
23770   // When we can use CMOV, or when there is no mispredict, this improves
23771   // throughput and reduces register pressure.
23772   //
23773   if (CC == X86::COND_NE) {
23774     SDValue Flags;
23775     X86::CondCode CC0, CC1;
23776     bool isAndSetCC;
23777     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23778       if (isAndSetCC) {
23779         std::swap(FalseOp, TrueOp);
23780         CC0 = X86::GetOppositeBranchCondition(CC0);
23781         CC1 = X86::GetOppositeBranchCondition(CC1);
23782       }
23783
23784       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23785         Flags};
23786       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23787       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23788       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23789       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23790       return CMOV;
23791     }
23792   }
23793
23794   return SDValue();
23795 }
23796
23797 /// PerformMulCombine - Optimize a single multiply with constant into two
23798 /// in order to implement it with two cheaper instructions, e.g.
23799 /// LEA + SHL, LEA + LEA.
23800 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23801                                  TargetLowering::DAGCombinerInfo &DCI) {
23802   // An imul is usually smaller than the alternative sequence.
23803   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23804     return SDValue();
23805
23806   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23807     return SDValue();
23808
23809   EVT VT = N->getValueType(0);
23810   if (VT != MVT::i64 && VT != MVT::i32)
23811     return SDValue();
23812
23813   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23814   if (!C)
23815     return SDValue();
23816   uint64_t MulAmt = C->getZExtValue();
23817   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23818     return SDValue();
23819
23820   uint64_t MulAmt1 = 0;
23821   uint64_t MulAmt2 = 0;
23822   if ((MulAmt % 9) == 0) {
23823     MulAmt1 = 9;
23824     MulAmt2 = MulAmt / 9;
23825   } else if ((MulAmt % 5) == 0) {
23826     MulAmt1 = 5;
23827     MulAmt2 = MulAmt / 5;
23828   } else if ((MulAmt % 3) == 0) {
23829     MulAmt1 = 3;
23830     MulAmt2 = MulAmt / 3;
23831   }
23832   if (MulAmt2 &&
23833       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23834     SDLoc DL(N);
23835
23836     if (isPowerOf2_64(MulAmt2) &&
23837         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23838       // If second multiplifer is pow2, issue it first. We want the multiply by
23839       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23840       // is an add.
23841       std::swap(MulAmt1, MulAmt2);
23842
23843     SDValue NewMul;
23844     if (isPowerOf2_64(MulAmt1))
23845       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23846                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23847     else
23848       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23849                            DAG.getConstant(MulAmt1, DL, VT));
23850
23851     if (isPowerOf2_64(MulAmt2))
23852       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23853                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23854     else
23855       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23856                            DAG.getConstant(MulAmt2, DL, VT));
23857
23858     // Do not add new nodes to DAG combiner worklist.
23859     DCI.CombineTo(N, NewMul, false);
23860   }
23861   return SDValue();
23862 }
23863
23864 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23865   SDValue N0 = N->getOperand(0);
23866   SDValue N1 = N->getOperand(1);
23867   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23868   EVT VT = N0.getValueType();
23869
23870   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23871   // since the result of setcc_c is all zero's or all ones.
23872   if (VT.isInteger() && !VT.isVector() &&
23873       N1C && N0.getOpcode() == ISD::AND &&
23874       N0.getOperand(1).getOpcode() == ISD::Constant) {
23875     SDValue N00 = N0.getOperand(0);
23876     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23877     APInt ShAmt = N1C->getAPIntValue();
23878     Mask = Mask.shl(ShAmt);
23879     bool MaskOK = false;
23880     // We can handle cases concerning bit-widening nodes containing setcc_c if
23881     // we carefully interrogate the mask to make sure we are semantics
23882     // preserving.
23883     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23884     // of the underlying setcc_c operation if the setcc_c was zero extended.
23885     // Consider the following example:
23886     //   zext(setcc_c)                 -> i32 0x0000FFFF
23887     //   c1                            -> i32 0x0000FFFF
23888     //   c2                            -> i32 0x00000001
23889     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23890     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23891     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23892       MaskOK = true;
23893     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23894                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23895       MaskOK = true;
23896     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23897                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23898                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23899       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23900     }
23901     if (MaskOK && Mask != 0) {
23902       SDLoc DL(N);
23903       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23904     }
23905   }
23906
23907   // Hardware support for vector shifts is sparse which makes us scalarize the
23908   // vector operations in many cases. Also, on sandybridge ADD is faster than
23909   // shl.
23910   // (shl V, 1) -> add V,V
23911   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23912     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23913       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23914       // We shift all of the values by one. In many cases we do not have
23915       // hardware support for this operation. This is better expressed as an ADD
23916       // of two values.
23917       if (N1SplatC->getAPIntValue() == 1)
23918         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23919     }
23920
23921   return SDValue();
23922 }
23923
23924 /// \brief Returns a vector of 0s if the node in input is a vector logical
23925 /// shift by a constant amount which is known to be bigger than or equal
23926 /// to the vector element size in bits.
23927 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23928                                       const X86Subtarget *Subtarget) {
23929   EVT VT = N->getValueType(0);
23930
23931   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23932       (!Subtarget->hasInt256() ||
23933        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23934     return SDValue();
23935
23936   SDValue Amt = N->getOperand(1);
23937   SDLoc DL(N);
23938   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23939     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23940       APInt ShiftAmt = AmtSplat->getAPIntValue();
23941       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23942
23943       // SSE2/AVX2 logical shifts always return a vector of 0s
23944       // if the shift amount is bigger than or equal to
23945       // the element size. The constant shift amount will be
23946       // encoded as a 8-bit immediate.
23947       if (ShiftAmt.trunc(8).uge(MaxAmount))
23948         return getZeroVector(VT, Subtarget, DAG, DL);
23949     }
23950
23951   return SDValue();
23952 }
23953
23954 /// PerformShiftCombine - Combine shifts.
23955 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23956                                    TargetLowering::DAGCombinerInfo &DCI,
23957                                    const X86Subtarget *Subtarget) {
23958   if (N->getOpcode() == ISD::SHL)
23959     if (SDValue V = PerformSHLCombine(N, DAG))
23960       return V;
23961
23962   // Try to fold this logical shift into a zero vector.
23963   if (N->getOpcode() != ISD::SRA)
23964     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23965       return V;
23966
23967   return SDValue();
23968 }
23969
23970 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23971 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23972 // and friends.  Likewise for OR -> CMPNEQSS.
23973 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23974                             TargetLowering::DAGCombinerInfo &DCI,
23975                             const X86Subtarget *Subtarget) {
23976   unsigned opcode;
23977
23978   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23979   // we're requiring SSE2 for both.
23980   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23981     SDValue N0 = N->getOperand(0);
23982     SDValue N1 = N->getOperand(1);
23983     SDValue CMP0 = N0->getOperand(1);
23984     SDValue CMP1 = N1->getOperand(1);
23985     SDLoc DL(N);
23986
23987     // The SETCCs should both refer to the same CMP.
23988     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23989       return SDValue();
23990
23991     SDValue CMP00 = CMP0->getOperand(0);
23992     SDValue CMP01 = CMP0->getOperand(1);
23993     EVT     VT    = CMP00.getValueType();
23994
23995     if (VT == MVT::f32 || VT == MVT::f64) {
23996       bool ExpectingFlags = false;
23997       // Check for any users that want flags:
23998       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23999            !ExpectingFlags && UI != UE; ++UI)
24000         switch (UI->getOpcode()) {
24001         default:
24002         case ISD::BR_CC:
24003         case ISD::BRCOND:
24004         case ISD::SELECT:
24005           ExpectingFlags = true;
24006           break;
24007         case ISD::CopyToReg:
24008         case ISD::SIGN_EXTEND:
24009         case ISD::ZERO_EXTEND:
24010         case ISD::ANY_EXTEND:
24011           break;
24012         }
24013
24014       if (!ExpectingFlags) {
24015         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24016         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24017
24018         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24019           X86::CondCode tmp = cc0;
24020           cc0 = cc1;
24021           cc1 = tmp;
24022         }
24023
24024         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24025             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24026           // FIXME: need symbolic constants for these magic numbers.
24027           // See X86ATTInstPrinter.cpp:printSSECC().
24028           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24029           if (Subtarget->hasAVX512()) {
24030             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24031                                          CMP01,
24032                                          DAG.getConstant(x86cc, DL, MVT::i8));
24033             if (N->getValueType(0) != MVT::i1)
24034               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24035                                  FSetCC);
24036             return FSetCC;
24037           }
24038           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24039                                               CMP00.getValueType(), CMP00, CMP01,
24040                                               DAG.getConstant(x86cc, DL,
24041                                                               MVT::i8));
24042
24043           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24044           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24045
24046           if (is64BitFP && !Subtarget->is64Bit()) {
24047             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24048             // 64-bit integer, since that's not a legal type. Since
24049             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24050             // bits, but can do this little dance to extract the lowest 32 bits
24051             // and work with those going forward.
24052             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24053                                            OnesOrZeroesF);
24054             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24055             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24056                                         Vector32, DAG.getIntPtrConstant(0, DL));
24057             IntVT = MVT::i32;
24058           }
24059
24060           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24061           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24062                                       DAG.getConstant(1, DL, IntVT));
24063           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24064                                               ANDed);
24065           return OneBitOfTruth;
24066         }
24067       }
24068     }
24069   }
24070   return SDValue();
24071 }
24072
24073 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24074 /// so it can be folded inside ANDNP.
24075 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24076   EVT VT = N->getValueType(0);
24077
24078   // Match direct AllOnes for 128 and 256-bit vectors
24079   if (ISD::isBuildVectorAllOnes(N))
24080     return true;
24081
24082   // Look through a bit convert.
24083   if (N->getOpcode() == ISD::BITCAST)
24084     N = N->getOperand(0).getNode();
24085
24086   // Sometimes the operand may come from a insert_subvector building a 256-bit
24087   // allones vector
24088   if (VT.is256BitVector() &&
24089       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24090     SDValue V1 = N->getOperand(0);
24091     SDValue V2 = N->getOperand(1);
24092
24093     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24094         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24095         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24096         ISD::isBuildVectorAllOnes(V2.getNode()))
24097       return true;
24098   }
24099
24100   return false;
24101 }
24102
24103 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24104 // register. In most cases we actually compare or select YMM-sized registers
24105 // and mixing the two types creates horrible code. This method optimizes
24106 // some of the transition sequences.
24107 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24108                                  TargetLowering::DAGCombinerInfo &DCI,
24109                                  const X86Subtarget *Subtarget) {
24110   EVT VT = N->getValueType(0);
24111   if (!VT.is256BitVector())
24112     return SDValue();
24113
24114   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24115           N->getOpcode() == ISD::ZERO_EXTEND ||
24116           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24117
24118   SDValue Narrow = N->getOperand(0);
24119   EVT NarrowVT = Narrow->getValueType(0);
24120   if (!NarrowVT.is128BitVector())
24121     return SDValue();
24122
24123   if (Narrow->getOpcode() != ISD::XOR &&
24124       Narrow->getOpcode() != ISD::AND &&
24125       Narrow->getOpcode() != ISD::OR)
24126     return SDValue();
24127
24128   SDValue N0  = Narrow->getOperand(0);
24129   SDValue N1  = Narrow->getOperand(1);
24130   SDLoc DL(Narrow);
24131
24132   // The Left side has to be a trunc.
24133   if (N0.getOpcode() != ISD::TRUNCATE)
24134     return SDValue();
24135
24136   // The type of the truncated inputs.
24137   EVT WideVT = N0->getOperand(0)->getValueType(0);
24138   if (WideVT != VT)
24139     return SDValue();
24140
24141   // The right side has to be a 'trunc' or a constant vector.
24142   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24143   ConstantSDNode *RHSConstSplat = nullptr;
24144   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24145     RHSConstSplat = RHSBV->getConstantSplatNode();
24146   if (!RHSTrunc && !RHSConstSplat)
24147     return SDValue();
24148
24149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24150
24151   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24152     return SDValue();
24153
24154   // Set N0 and N1 to hold the inputs to the new wide operation.
24155   N0 = N0->getOperand(0);
24156   if (RHSConstSplat) {
24157     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24158                      SDValue(RHSConstSplat, 0));
24159     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24160     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24161   } else if (RHSTrunc) {
24162     N1 = N1->getOperand(0);
24163   }
24164
24165   // Generate the wide operation.
24166   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24167   unsigned Opcode = N->getOpcode();
24168   switch (Opcode) {
24169   case ISD::ANY_EXTEND:
24170     return Op;
24171   case ISD::ZERO_EXTEND: {
24172     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24173     APInt Mask = APInt::getAllOnesValue(InBits);
24174     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24175     return DAG.getNode(ISD::AND, DL, VT,
24176                        Op, DAG.getConstant(Mask, DL, VT));
24177   }
24178   case ISD::SIGN_EXTEND:
24179     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24180                        Op, DAG.getValueType(NarrowVT));
24181   default:
24182     llvm_unreachable("Unexpected opcode");
24183   }
24184 }
24185
24186 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24187                                  TargetLowering::DAGCombinerInfo &DCI,
24188                                  const X86Subtarget *Subtarget) {
24189   SDValue N0 = N->getOperand(0);
24190   SDValue N1 = N->getOperand(1);
24191   SDLoc DL(N);
24192
24193   // A vector zext_in_reg may be represented as a shuffle,
24194   // feeding into a bitcast (this represents anyext) feeding into
24195   // an and with a mask.
24196   // We'd like to try to combine that into a shuffle with zero
24197   // plus a bitcast, removing the and.
24198   if (N0.getOpcode() != ISD::BITCAST ||
24199       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24200     return SDValue();
24201
24202   // The other side of the AND should be a splat of 2^C, where C
24203   // is the number of bits in the source type.
24204   if (N1.getOpcode() == ISD::BITCAST)
24205     N1 = N1.getOperand(0);
24206   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24207     return SDValue();
24208   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24209
24210   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24211   EVT SrcType = Shuffle->getValueType(0);
24212
24213   // We expect a single-source shuffle
24214   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24215     return SDValue();
24216
24217   unsigned SrcSize = SrcType.getScalarSizeInBits();
24218
24219   APInt SplatValue, SplatUndef;
24220   unsigned SplatBitSize;
24221   bool HasAnyUndefs;
24222   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24223                                 SplatBitSize, HasAnyUndefs))
24224     return SDValue();
24225
24226   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24227   // Make sure the splat matches the mask we expect
24228   if (SplatBitSize > ResSize ||
24229       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24230     return SDValue();
24231
24232   // Make sure the input and output size make sense
24233   if (SrcSize >= ResSize || ResSize % SrcSize)
24234     return SDValue();
24235
24236   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24237   // The number of u's between each two values depends on the ratio between
24238   // the source and dest type.
24239   unsigned ZextRatio = ResSize / SrcSize;
24240   bool IsZext = true;
24241   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24242     if (i % ZextRatio) {
24243       if (Shuffle->getMaskElt(i) > 0) {
24244         // Expected undef
24245         IsZext = false;
24246         break;
24247       }
24248     } else {
24249       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24250         // Expected element number
24251         IsZext = false;
24252         break;
24253       }
24254     }
24255   }
24256
24257   if (!IsZext)
24258     return SDValue();
24259
24260   // Ok, perform the transformation - replace the shuffle with
24261   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24262   // (instead of undef) where the k elements come from the zero vector.
24263   SmallVector<int, 8> Mask;
24264   unsigned NumElems = SrcType.getVectorNumElements();
24265   for (unsigned i = 0; i < NumElems; ++i)
24266     if (i % ZextRatio)
24267       Mask.push_back(NumElems);
24268     else
24269       Mask.push_back(i / ZextRatio);
24270
24271   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24272     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24273   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24274 }
24275
24276 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24277                                  TargetLowering::DAGCombinerInfo &DCI,
24278                                  const X86Subtarget *Subtarget) {
24279   if (DCI.isBeforeLegalizeOps())
24280     return SDValue();
24281
24282   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24283     return Zext;
24284
24285   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24286     return R;
24287
24288   EVT VT = N->getValueType(0);
24289   SDValue N0 = N->getOperand(0);
24290   SDValue N1 = N->getOperand(1);
24291   SDLoc DL(N);
24292
24293   // Create BEXTR instructions
24294   // BEXTR is ((X >> imm) & (2**size-1))
24295   if (VT == MVT::i32 || VT == MVT::i64) {
24296     // Check for BEXTR.
24297     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24298         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24299       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24300       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24301       if (MaskNode && ShiftNode) {
24302         uint64_t Mask = MaskNode->getZExtValue();
24303         uint64_t Shift = ShiftNode->getZExtValue();
24304         if (isMask_64(Mask)) {
24305           uint64_t MaskSize = countPopulation(Mask);
24306           if (Shift + MaskSize <= VT.getSizeInBits())
24307             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24308                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24309                                                VT));
24310         }
24311       }
24312     } // BEXTR
24313
24314     return SDValue();
24315   }
24316
24317   // Want to form ANDNP nodes:
24318   // 1) In the hopes of then easily combining them with OR and AND nodes
24319   //    to form PBLEND/PSIGN.
24320   // 2) To match ANDN packed intrinsics
24321   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24322     return SDValue();
24323
24324   // Check LHS for vnot
24325   if (N0.getOpcode() == ISD::XOR &&
24326       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24327       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24328     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24329
24330   // Check RHS for vnot
24331   if (N1.getOpcode() == ISD::XOR &&
24332       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24333       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24334     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24335
24336   return SDValue();
24337 }
24338
24339 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24340                                 TargetLowering::DAGCombinerInfo &DCI,
24341                                 const X86Subtarget *Subtarget) {
24342   if (DCI.isBeforeLegalizeOps())
24343     return SDValue();
24344
24345   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24346     return R;
24347
24348   SDValue N0 = N->getOperand(0);
24349   SDValue N1 = N->getOperand(1);
24350   EVT VT = N->getValueType(0);
24351
24352   // look for psign/blend
24353   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24354     if (!Subtarget->hasSSSE3() ||
24355         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24356       return SDValue();
24357
24358     // Canonicalize pandn to RHS
24359     if (N0.getOpcode() == X86ISD::ANDNP)
24360       std::swap(N0, N1);
24361     // or (and (m, y), (pandn m, x))
24362     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24363       SDValue Mask = N1.getOperand(0);
24364       SDValue X    = N1.getOperand(1);
24365       SDValue Y;
24366       if (N0.getOperand(0) == Mask)
24367         Y = N0.getOperand(1);
24368       if (N0.getOperand(1) == Mask)
24369         Y = N0.getOperand(0);
24370
24371       // Check to see if the mask appeared in both the AND and ANDNP and
24372       if (!Y.getNode())
24373         return SDValue();
24374
24375       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24376       // Look through mask bitcast.
24377       if (Mask.getOpcode() == ISD::BITCAST)
24378         Mask = Mask.getOperand(0);
24379       if (X.getOpcode() == ISD::BITCAST)
24380         X = X.getOperand(0);
24381       if (Y.getOpcode() == ISD::BITCAST)
24382         Y = Y.getOperand(0);
24383
24384       EVT MaskVT = Mask.getValueType();
24385
24386       // Validate that the Mask operand is a vector sra node.
24387       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24388       // there is no psrai.b
24389       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24390       unsigned SraAmt = ~0;
24391       if (Mask.getOpcode() == ISD::SRA) {
24392         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24393           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24394             SraAmt = AmtConst->getZExtValue();
24395       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24396         SDValue SraC = Mask.getOperand(1);
24397         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24398       }
24399       if ((SraAmt + 1) != EltBits)
24400         return SDValue();
24401
24402       SDLoc DL(N);
24403
24404       // Now we know we at least have a plendvb with the mask val.  See if
24405       // we can form a psignb/w/d.
24406       // psign = x.type == y.type == mask.type && y = sub(0, x);
24407       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24408           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24409           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24410         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24411                "Unsupported VT for PSIGN");
24412         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24413         return DAG.getBitcast(VT, Mask);
24414       }
24415       // PBLENDVB only available on SSE 4.1
24416       if (!Subtarget->hasSSE41())
24417         return SDValue();
24418
24419       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24420
24421       X = DAG.getBitcast(BlendVT, X);
24422       Y = DAG.getBitcast(BlendVT, Y);
24423       Mask = DAG.getBitcast(BlendVT, Mask);
24424       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24425       return DAG.getBitcast(VT, Mask);
24426     }
24427   }
24428
24429   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24430     return SDValue();
24431
24432   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24433   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24434
24435   // SHLD/SHRD instructions have lower register pressure, but on some
24436   // platforms they have higher latency than the equivalent
24437   // series of shifts/or that would otherwise be generated.
24438   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24439   // have higher latencies and we are not optimizing for size.
24440   if (!OptForSize && Subtarget->isSHLDSlow())
24441     return SDValue();
24442
24443   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24444     std::swap(N0, N1);
24445   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24446     return SDValue();
24447   if (!N0.hasOneUse() || !N1.hasOneUse())
24448     return SDValue();
24449
24450   SDValue ShAmt0 = N0.getOperand(1);
24451   if (ShAmt0.getValueType() != MVT::i8)
24452     return SDValue();
24453   SDValue ShAmt1 = N1.getOperand(1);
24454   if (ShAmt1.getValueType() != MVT::i8)
24455     return SDValue();
24456   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24457     ShAmt0 = ShAmt0.getOperand(0);
24458   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24459     ShAmt1 = ShAmt1.getOperand(0);
24460
24461   SDLoc DL(N);
24462   unsigned Opc = X86ISD::SHLD;
24463   SDValue Op0 = N0.getOperand(0);
24464   SDValue Op1 = N1.getOperand(0);
24465   if (ShAmt0.getOpcode() == ISD::SUB) {
24466     Opc = X86ISD::SHRD;
24467     std::swap(Op0, Op1);
24468     std::swap(ShAmt0, ShAmt1);
24469   }
24470
24471   unsigned Bits = VT.getSizeInBits();
24472   if (ShAmt1.getOpcode() == ISD::SUB) {
24473     SDValue Sum = ShAmt1.getOperand(0);
24474     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24475       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24476       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24477         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24478       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24479         return DAG.getNode(Opc, DL, VT,
24480                            Op0, Op1,
24481                            DAG.getNode(ISD::TRUNCATE, DL,
24482                                        MVT::i8, ShAmt0));
24483     }
24484   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24485     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24486     if (ShAmt0C &&
24487         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24488       return DAG.getNode(Opc, DL, VT,
24489                          N0.getOperand(0), N1.getOperand(0),
24490                          DAG.getNode(ISD::TRUNCATE, DL,
24491                                        MVT::i8, ShAmt0));
24492   }
24493
24494   return SDValue();
24495 }
24496
24497 // Generate NEG and CMOV for integer abs.
24498 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24499   EVT VT = N->getValueType(0);
24500
24501   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24502   // 8-bit integer abs to NEG and CMOV.
24503   if (VT.isInteger() && VT.getSizeInBits() == 8)
24504     return SDValue();
24505
24506   SDValue N0 = N->getOperand(0);
24507   SDValue N1 = N->getOperand(1);
24508   SDLoc DL(N);
24509
24510   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24511   // and change it to SUB and CMOV.
24512   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24513       N0.getOpcode() == ISD::ADD &&
24514       N0.getOperand(1) == N1 &&
24515       N1.getOpcode() == ISD::SRA &&
24516       N1.getOperand(0) == N0.getOperand(0))
24517     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24518       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24519         // Generate SUB & CMOV.
24520         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24521                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24522
24523         SDValue Ops[] = { N0.getOperand(0), Neg,
24524                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24525                           SDValue(Neg.getNode(), 1) };
24526         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24527       }
24528   return SDValue();
24529 }
24530
24531 // Try to turn tests against the signbit in the form of:
24532 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24533 // into:
24534 //   SETGT(X, -1)
24535 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24536   // This is only worth doing if the output type is i8.
24537   if (N->getValueType(0) != MVT::i8)
24538     return SDValue();
24539
24540   SDValue N0 = N->getOperand(0);
24541   SDValue N1 = N->getOperand(1);
24542
24543   // We should be performing an xor against a truncated shift.
24544   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24545     return SDValue();
24546
24547   // Make sure we are performing an xor against one.
24548   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24549     return SDValue();
24550
24551   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24552   SDValue Shift = N0.getOperand(0);
24553   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24554     return SDValue();
24555
24556   // Make sure we are truncating from one of i16, i32 or i64.
24557   EVT ShiftTy = Shift.getValueType();
24558   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24559     return SDValue();
24560
24561   // Make sure the shift amount extracts the sign bit.
24562   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24563       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24564     return SDValue();
24565
24566   // Create a greater-than comparison against -1.
24567   // N.B. Using SETGE against 0 works but we want a canonical looking
24568   // comparison, using SETGT matches up with what TranslateX86CC.
24569   SDLoc DL(N);
24570   SDValue ShiftOp = Shift.getOperand(0);
24571   EVT ShiftOpTy = ShiftOp.getValueType();
24572   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24573                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24574   return Cond;
24575 }
24576
24577 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24578                                  TargetLowering::DAGCombinerInfo &DCI,
24579                                  const X86Subtarget *Subtarget) {
24580   if (DCI.isBeforeLegalizeOps())
24581     return SDValue();
24582
24583   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24584     return RV;
24585
24586   if (Subtarget->hasCMov())
24587     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24588       return RV;
24589
24590   return SDValue();
24591 }
24592
24593 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24594 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24595                                   TargetLowering::DAGCombinerInfo &DCI,
24596                                   const X86Subtarget *Subtarget) {
24597   LoadSDNode *Ld = cast<LoadSDNode>(N);
24598   EVT RegVT = Ld->getValueType(0);
24599   EVT MemVT = Ld->getMemoryVT();
24600   SDLoc dl(Ld);
24601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24602
24603   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24604   // into two 16-byte operations.
24605   ISD::LoadExtType Ext = Ld->getExtensionType();
24606   bool Fast;
24607   unsigned AddressSpace = Ld->getAddressSpace();
24608   unsigned Alignment = Ld->getAlignment();
24609   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24610       Ext == ISD::NON_EXTLOAD &&
24611       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24612                              AddressSpace, Alignment, &Fast) && !Fast) {
24613     unsigned NumElems = RegVT.getVectorNumElements();
24614     if (NumElems < 2)
24615       return SDValue();
24616
24617     SDValue Ptr = Ld->getBasePtr();
24618     SDValue Increment =
24619         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24620
24621     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24622                                   NumElems/2);
24623     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24624                                 Ld->getPointerInfo(), Ld->isVolatile(),
24625                                 Ld->isNonTemporal(), Ld->isInvariant(),
24626                                 Alignment);
24627     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24628     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24629                                 Ld->getPointerInfo(), Ld->isVolatile(),
24630                                 Ld->isNonTemporal(), Ld->isInvariant(),
24631                                 std::min(16U, Alignment));
24632     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24633                              Load1.getValue(1),
24634                              Load2.getValue(1));
24635
24636     SDValue NewVec = DAG.getUNDEF(RegVT);
24637     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24638     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24639     return DCI.CombineTo(N, NewVec, TF, true);
24640   }
24641
24642   return SDValue();
24643 }
24644
24645 /// PerformMLOADCombine - Resolve extending loads
24646 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24647                                    TargetLowering::DAGCombinerInfo &DCI,
24648                                    const X86Subtarget *Subtarget) {
24649   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24650   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24651     return SDValue();
24652
24653   EVT VT = Mld->getValueType(0);
24654   unsigned NumElems = VT.getVectorNumElements();
24655   EVT LdVT = Mld->getMemoryVT();
24656   SDLoc dl(Mld);
24657
24658   assert(LdVT != VT && "Cannot extend to the same type");
24659   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24660   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24661   // From, To sizes and ElemCount must be pow of two
24662   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24663     "Unexpected size for extending masked load");
24664
24665   unsigned SizeRatio  = ToSz / FromSz;
24666   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24667
24668   // Create a type on which we perform the shuffle
24669   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24670           LdVT.getScalarType(), NumElems*SizeRatio);
24671   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24672
24673   // Convert Src0 value
24674   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24675   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24676     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24677     for (unsigned i = 0; i != NumElems; ++i)
24678       ShuffleVec[i] = i * SizeRatio;
24679
24680     // Can't shuffle using an illegal type.
24681     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24682             && "WideVecVT should be legal");
24683     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24684                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24685   }
24686   // Prepare the new mask
24687   SDValue NewMask;
24688   SDValue Mask = Mld->getMask();
24689   if (Mask.getValueType() == VT) {
24690     // Mask and original value have the same type
24691     NewMask = DAG.getBitcast(WideVecVT, Mask);
24692     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24693     for (unsigned i = 0; i != NumElems; ++i)
24694       ShuffleVec[i] = i * SizeRatio;
24695     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24696       ShuffleVec[i] = NumElems*SizeRatio;
24697     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24698                                    DAG.getConstant(0, dl, WideVecVT),
24699                                    &ShuffleVec[0]);
24700   }
24701   else {
24702     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24703     unsigned WidenNumElts = NumElems*SizeRatio;
24704     unsigned MaskNumElts = VT.getVectorNumElements();
24705     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24706                                      WidenNumElts);
24707
24708     unsigned NumConcat = WidenNumElts / MaskNumElts;
24709     SmallVector<SDValue, 16> Ops(NumConcat);
24710     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24711     Ops[0] = Mask;
24712     for (unsigned i = 1; i != NumConcat; ++i)
24713       Ops[i] = ZeroVal;
24714
24715     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24716   }
24717
24718   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24719                                      Mld->getBasePtr(), NewMask, WideSrc0,
24720                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24721                                      ISD::NON_EXTLOAD);
24722   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24723   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24724
24725 }
24726 /// PerformMSTORECombine - Resolve truncating stores
24727 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24728                                     const X86Subtarget *Subtarget) {
24729   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24730   if (!Mst->isTruncatingStore())
24731     return SDValue();
24732
24733   EVT VT = Mst->getValue().getValueType();
24734   unsigned NumElems = VT.getVectorNumElements();
24735   EVT StVT = Mst->getMemoryVT();
24736   SDLoc dl(Mst);
24737
24738   assert(StVT != VT && "Cannot truncate to the same type");
24739   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24740   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24741
24742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24743
24744   // The truncating store is legal in some cases. For example
24745   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24746   // are designated for truncate store.
24747   // In this case we don't need any further transformations.
24748   if (TLI.isTruncStoreLegal(VT, StVT))
24749     return SDValue();
24750
24751   // From, To sizes and ElemCount must be pow of two
24752   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24753     "Unexpected size for truncating masked store");
24754   // We are going to use the original vector elt for storing.
24755   // Accumulated smaller vector elements must be a multiple of the store size.
24756   assert (((NumElems * FromSz) % ToSz) == 0 &&
24757           "Unexpected ratio for truncating masked store");
24758
24759   unsigned SizeRatio  = FromSz / ToSz;
24760   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24761
24762   // Create a type on which we perform the shuffle
24763   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24764           StVT.getScalarType(), NumElems*SizeRatio);
24765
24766   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24767
24768   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24769   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24770   for (unsigned i = 0; i != NumElems; ++i)
24771     ShuffleVec[i] = i * SizeRatio;
24772
24773   // Can't shuffle using an illegal type.
24774   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24775           && "WideVecVT should be legal");
24776
24777   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24778                                         DAG.getUNDEF(WideVecVT),
24779                                         &ShuffleVec[0]);
24780
24781   SDValue NewMask;
24782   SDValue Mask = Mst->getMask();
24783   if (Mask.getValueType() == VT) {
24784     // Mask and original value have the same type
24785     NewMask = DAG.getBitcast(WideVecVT, Mask);
24786     for (unsigned i = 0; i != NumElems; ++i)
24787       ShuffleVec[i] = i * SizeRatio;
24788     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24789       ShuffleVec[i] = NumElems*SizeRatio;
24790     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24791                                    DAG.getConstant(0, dl, WideVecVT),
24792                                    &ShuffleVec[0]);
24793   }
24794   else {
24795     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24796     unsigned WidenNumElts = NumElems*SizeRatio;
24797     unsigned MaskNumElts = VT.getVectorNumElements();
24798     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24799                                      WidenNumElts);
24800
24801     unsigned NumConcat = WidenNumElts / MaskNumElts;
24802     SmallVector<SDValue, 16> Ops(NumConcat);
24803     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24804     Ops[0] = Mask;
24805     for (unsigned i = 1; i != NumConcat; ++i)
24806       Ops[i] = ZeroVal;
24807
24808     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24809   }
24810
24811   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24812                             NewMask, StVT, Mst->getMemOperand(), false);
24813 }
24814 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24815 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24816                                    const X86Subtarget *Subtarget) {
24817   StoreSDNode *St = cast<StoreSDNode>(N);
24818   EVT VT = St->getValue().getValueType();
24819   EVT StVT = St->getMemoryVT();
24820   SDLoc dl(St);
24821   SDValue StoredVal = St->getOperand(1);
24822   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24823
24824   // If we are saving a concatenation of two XMM registers and 32-byte stores
24825   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24826   bool Fast;
24827   unsigned AddressSpace = St->getAddressSpace();
24828   unsigned Alignment = St->getAlignment();
24829   if (VT.is256BitVector() && StVT == VT &&
24830       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24831                              AddressSpace, Alignment, &Fast) && !Fast) {
24832     unsigned NumElems = VT.getVectorNumElements();
24833     if (NumElems < 2)
24834       return SDValue();
24835
24836     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24837     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24838
24839     SDValue Stride =
24840         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24841     SDValue Ptr0 = St->getBasePtr();
24842     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24843
24844     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24845                                 St->getPointerInfo(), St->isVolatile(),
24846                                 St->isNonTemporal(), Alignment);
24847     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24848                                 St->getPointerInfo(), St->isVolatile(),
24849                                 St->isNonTemporal(),
24850                                 std::min(16U, Alignment));
24851     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24852   }
24853
24854   // Optimize trunc store (of multiple scalars) to shuffle and store.
24855   // First, pack all of the elements in one place. Next, store to memory
24856   // in fewer chunks.
24857   if (St->isTruncatingStore() && VT.isVector()) {
24858     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24859     unsigned NumElems = VT.getVectorNumElements();
24860     assert(StVT != VT && "Cannot truncate to the same type");
24861     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24862     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24863
24864     // The truncating store is legal in some cases. For example
24865     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24866     // are designated for truncate store.
24867     // In this case we don't need any further transformations.
24868     if (TLI.isTruncStoreLegal(VT, StVT))
24869       return SDValue();
24870
24871     // From, To sizes and ElemCount must be pow of two
24872     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24873     // We are going to use the original vector elt for storing.
24874     // Accumulated smaller vector elements must be a multiple of the store size.
24875     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24876
24877     unsigned SizeRatio  = FromSz / ToSz;
24878
24879     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24880
24881     // Create a type on which we perform the shuffle
24882     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24883             StVT.getScalarType(), NumElems*SizeRatio);
24884
24885     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24886
24887     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24888     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24889     for (unsigned i = 0; i != NumElems; ++i)
24890       ShuffleVec[i] = i * SizeRatio;
24891
24892     // Can't shuffle using an illegal type.
24893     if (!TLI.isTypeLegal(WideVecVT))
24894       return SDValue();
24895
24896     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24897                                          DAG.getUNDEF(WideVecVT),
24898                                          &ShuffleVec[0]);
24899     // At this point all of the data is stored at the bottom of the
24900     // register. We now need to save it to mem.
24901
24902     // Find the largest store unit
24903     MVT StoreType = MVT::i8;
24904     for (MVT Tp : MVT::integer_valuetypes()) {
24905       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24906         StoreType = Tp;
24907     }
24908
24909     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24910     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24911         (64 <= NumElems * ToSz))
24912       StoreType = MVT::f64;
24913
24914     // Bitcast the original vector into a vector of store-size units
24915     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24916             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24917     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24918     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24919     SmallVector<SDValue, 8> Chains;
24920     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24921                                         TLI.getPointerTy(DAG.getDataLayout()));
24922     SDValue Ptr = St->getBasePtr();
24923
24924     // Perform one or more big stores into memory.
24925     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24926       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24927                                    StoreType, ShuffWide,
24928                                    DAG.getIntPtrConstant(i, dl));
24929       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24930                                 St->getPointerInfo(), St->isVolatile(),
24931                                 St->isNonTemporal(), St->getAlignment());
24932       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24933       Chains.push_back(Ch);
24934     }
24935
24936     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24937   }
24938
24939   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24940   // the FP state in cases where an emms may be missing.
24941   // A preferable solution to the general problem is to figure out the right
24942   // places to insert EMMS.  This qualifies as a quick hack.
24943
24944   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24945   if (VT.getSizeInBits() != 64)
24946     return SDValue();
24947
24948   const Function *F = DAG.getMachineFunction().getFunction();
24949   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24950   bool F64IsLegal =
24951       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24952   if ((VT.isVector() ||
24953        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24954       isa<LoadSDNode>(St->getValue()) &&
24955       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24956       St->getChain().hasOneUse() && !St->isVolatile()) {
24957     SDNode* LdVal = St->getValue().getNode();
24958     LoadSDNode *Ld = nullptr;
24959     int TokenFactorIndex = -1;
24960     SmallVector<SDValue, 8> Ops;
24961     SDNode* ChainVal = St->getChain().getNode();
24962     // Must be a store of a load.  We currently handle two cases:  the load
24963     // is a direct child, and it's under an intervening TokenFactor.  It is
24964     // possible to dig deeper under nested TokenFactors.
24965     if (ChainVal == LdVal)
24966       Ld = cast<LoadSDNode>(St->getChain());
24967     else if (St->getValue().hasOneUse() &&
24968              ChainVal->getOpcode() == ISD::TokenFactor) {
24969       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24970         if (ChainVal->getOperand(i).getNode() == LdVal) {
24971           TokenFactorIndex = i;
24972           Ld = cast<LoadSDNode>(St->getValue());
24973         } else
24974           Ops.push_back(ChainVal->getOperand(i));
24975       }
24976     }
24977
24978     if (!Ld || !ISD::isNormalLoad(Ld))
24979       return SDValue();
24980
24981     // If this is not the MMX case, i.e. we are just turning i64 load/store
24982     // into f64 load/store, avoid the transformation if there are multiple
24983     // uses of the loaded value.
24984     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24985       return SDValue();
24986
24987     SDLoc LdDL(Ld);
24988     SDLoc StDL(N);
24989     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24990     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24991     // pair instead.
24992     if (Subtarget->is64Bit() || F64IsLegal) {
24993       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24994       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24995                                   Ld->getPointerInfo(), Ld->isVolatile(),
24996                                   Ld->isNonTemporal(), Ld->isInvariant(),
24997                                   Ld->getAlignment());
24998       SDValue NewChain = NewLd.getValue(1);
24999       if (TokenFactorIndex != -1) {
25000         Ops.push_back(NewChain);
25001         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25002       }
25003       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25004                           St->getPointerInfo(),
25005                           St->isVolatile(), St->isNonTemporal(),
25006                           St->getAlignment());
25007     }
25008
25009     // Otherwise, lower to two pairs of 32-bit loads / stores.
25010     SDValue LoAddr = Ld->getBasePtr();
25011     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25012                                  DAG.getConstant(4, LdDL, MVT::i32));
25013
25014     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25015                                Ld->getPointerInfo(),
25016                                Ld->isVolatile(), Ld->isNonTemporal(),
25017                                Ld->isInvariant(), Ld->getAlignment());
25018     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25019                                Ld->getPointerInfo().getWithOffset(4),
25020                                Ld->isVolatile(), Ld->isNonTemporal(),
25021                                Ld->isInvariant(),
25022                                MinAlign(Ld->getAlignment(), 4));
25023
25024     SDValue NewChain = LoLd.getValue(1);
25025     if (TokenFactorIndex != -1) {
25026       Ops.push_back(LoLd);
25027       Ops.push_back(HiLd);
25028       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25029     }
25030
25031     LoAddr = St->getBasePtr();
25032     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25033                          DAG.getConstant(4, StDL, MVT::i32));
25034
25035     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25036                                 St->getPointerInfo(),
25037                                 St->isVolatile(), St->isNonTemporal(),
25038                                 St->getAlignment());
25039     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25040                                 St->getPointerInfo().getWithOffset(4),
25041                                 St->isVolatile(),
25042                                 St->isNonTemporal(),
25043                                 MinAlign(St->getAlignment(), 4));
25044     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25045   }
25046
25047   // This is similar to the above case, but here we handle a scalar 64-bit
25048   // integer store that is extracted from a vector on a 32-bit target.
25049   // If we have SSE2, then we can treat it like a floating-point double
25050   // to get past legalization. The execution dependencies fixup pass will
25051   // choose the optimal machine instruction for the store if this really is
25052   // an integer or v2f32 rather than an f64.
25053   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25054       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25055     SDValue OldExtract = St->getOperand(1);
25056     SDValue ExtOp0 = OldExtract.getOperand(0);
25057     unsigned VecSize = ExtOp0.getValueSizeInBits();
25058     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25059     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25060     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25061                                      BitCast, OldExtract.getOperand(1));
25062     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25063                         St->getPointerInfo(), St->isVolatile(),
25064                         St->isNonTemporal(), St->getAlignment());
25065   }
25066
25067   return SDValue();
25068 }
25069
25070 /// Return 'true' if this vector operation is "horizontal"
25071 /// and return the operands for the horizontal operation in LHS and RHS.  A
25072 /// horizontal operation performs the binary operation on successive elements
25073 /// of its first operand, then on successive elements of its second operand,
25074 /// returning the resulting values in a vector.  For example, if
25075 ///   A = < float a0, float a1, float a2, float a3 >
25076 /// and
25077 ///   B = < float b0, float b1, float b2, float b3 >
25078 /// then the result of doing a horizontal operation on A and B is
25079 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25080 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25081 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25082 /// set to A, RHS to B, and the routine returns 'true'.
25083 /// Note that the binary operation should have the property that if one of the
25084 /// operands is UNDEF then the result is UNDEF.
25085 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25086   // Look for the following pattern: if
25087   //   A = < float a0, float a1, float a2, float a3 >
25088   //   B = < float b0, float b1, float b2, float b3 >
25089   // and
25090   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25091   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25092   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25093   // which is A horizontal-op B.
25094
25095   // At least one of the operands should be a vector shuffle.
25096   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25097       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25098     return false;
25099
25100   MVT VT = LHS.getSimpleValueType();
25101
25102   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25103          "Unsupported vector type for horizontal add/sub");
25104
25105   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25106   // operate independently on 128-bit lanes.
25107   unsigned NumElts = VT.getVectorNumElements();
25108   unsigned NumLanes = VT.getSizeInBits()/128;
25109   unsigned NumLaneElts = NumElts / NumLanes;
25110   assert((NumLaneElts % 2 == 0) &&
25111          "Vector type should have an even number of elements in each lane");
25112   unsigned HalfLaneElts = NumLaneElts/2;
25113
25114   // View LHS in the form
25115   //   LHS = VECTOR_SHUFFLE A, B, LMask
25116   // If LHS is not a shuffle then pretend it is the shuffle
25117   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25118   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25119   // type VT.
25120   SDValue A, B;
25121   SmallVector<int, 16> LMask(NumElts);
25122   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25123     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25124       A = LHS.getOperand(0);
25125     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25126       B = LHS.getOperand(1);
25127     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25128     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25129   } else {
25130     if (LHS.getOpcode() != ISD::UNDEF)
25131       A = LHS;
25132     for (unsigned i = 0; i != NumElts; ++i)
25133       LMask[i] = i;
25134   }
25135
25136   // Likewise, view RHS in the form
25137   //   RHS = VECTOR_SHUFFLE C, D, RMask
25138   SDValue C, D;
25139   SmallVector<int, 16> RMask(NumElts);
25140   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25141     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25142       C = RHS.getOperand(0);
25143     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25144       D = RHS.getOperand(1);
25145     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25146     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25147   } else {
25148     if (RHS.getOpcode() != ISD::UNDEF)
25149       C = RHS;
25150     for (unsigned i = 0; i != NumElts; ++i)
25151       RMask[i] = i;
25152   }
25153
25154   // Check that the shuffles are both shuffling the same vectors.
25155   if (!(A == C && B == D) && !(A == D && B == C))
25156     return false;
25157
25158   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25159   if (!A.getNode() && !B.getNode())
25160     return false;
25161
25162   // If A and B occur in reverse order in RHS, then "swap" them (which means
25163   // rewriting the mask).
25164   if (A != C)
25165     ShuffleVectorSDNode::commuteMask(RMask);
25166
25167   // At this point LHS and RHS are equivalent to
25168   //   LHS = VECTOR_SHUFFLE A, B, LMask
25169   //   RHS = VECTOR_SHUFFLE A, B, RMask
25170   // Check that the masks correspond to performing a horizontal operation.
25171   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25172     for (unsigned i = 0; i != NumLaneElts; ++i) {
25173       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25174
25175       // Ignore any UNDEF components.
25176       if (LIdx < 0 || RIdx < 0 ||
25177           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25178           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25179         continue;
25180
25181       // Check that successive elements are being operated on.  If not, this is
25182       // not a horizontal operation.
25183       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25184       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25185       if (!(LIdx == Index && RIdx == Index + 1) &&
25186           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25187         return false;
25188     }
25189   }
25190
25191   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25192   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25193   return true;
25194 }
25195
25196 /// Do target-specific dag combines on floating point adds.
25197 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25198                                   const X86Subtarget *Subtarget) {
25199   EVT VT = N->getValueType(0);
25200   SDValue LHS = N->getOperand(0);
25201   SDValue RHS = N->getOperand(1);
25202
25203   // Try to synthesize horizontal adds from adds of shuffles.
25204   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25205        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25206       isHorizontalBinOp(LHS, RHS, true))
25207     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25208   return SDValue();
25209 }
25210
25211 /// Do target-specific dag combines on floating point subs.
25212 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25213                                   const X86Subtarget *Subtarget) {
25214   EVT VT = N->getValueType(0);
25215   SDValue LHS = N->getOperand(0);
25216   SDValue RHS = N->getOperand(1);
25217
25218   // Try to synthesize horizontal subs from subs of shuffles.
25219   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25220        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25221       isHorizontalBinOp(LHS, RHS, false))
25222     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25223   return SDValue();
25224 }
25225
25226 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25227 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25228                                  const X86Subtarget *Subtarget) {
25229   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25230
25231   // F[X]OR(0.0, x) -> x
25232   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25233     if (C->getValueAPF().isPosZero())
25234       return N->getOperand(1);
25235
25236   // F[X]OR(x, 0.0) -> x
25237   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25238     if (C->getValueAPF().isPosZero())
25239       return N->getOperand(0);
25240
25241   EVT VT = N->getValueType(0);
25242   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25243     SDLoc dl(N);
25244     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25245     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25246
25247     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25248     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25249     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25250     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25251     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25252   }
25253   return SDValue();
25254 }
25255
25256 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25257 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25258   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25259
25260   // Only perform optimizations if UnsafeMath is used.
25261   if (!DAG.getTarget().Options.UnsafeFPMath)
25262     return SDValue();
25263
25264   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25265   // into FMINC and FMAXC, which are Commutative operations.
25266   unsigned NewOp = 0;
25267   switch (N->getOpcode()) {
25268     default: llvm_unreachable("unknown opcode");
25269     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25270     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25271   }
25272
25273   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25274                      N->getOperand(0), N->getOperand(1));
25275 }
25276
25277 /// Do target-specific dag combines on X86ISD::FAND nodes.
25278 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25279   // FAND(0.0, x) -> 0.0
25280   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25281     if (C->getValueAPF().isPosZero())
25282       return N->getOperand(0);
25283
25284   // FAND(x, 0.0) -> 0.0
25285   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25286     if (C->getValueAPF().isPosZero())
25287       return N->getOperand(1);
25288
25289   return SDValue();
25290 }
25291
25292 /// Do target-specific dag combines on X86ISD::FANDN nodes
25293 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25294   // FANDN(0.0, x) -> x
25295   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25296     if (C->getValueAPF().isPosZero())
25297       return N->getOperand(1);
25298
25299   // FANDN(x, 0.0) -> 0.0
25300   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25301     if (C->getValueAPF().isPosZero())
25302       return N->getOperand(1);
25303
25304   return SDValue();
25305 }
25306
25307 static SDValue PerformBTCombine(SDNode *N,
25308                                 SelectionDAG &DAG,
25309                                 TargetLowering::DAGCombinerInfo &DCI) {
25310   // BT ignores high bits in the bit index operand.
25311   SDValue Op1 = N->getOperand(1);
25312   if (Op1.hasOneUse()) {
25313     unsigned BitWidth = Op1.getValueSizeInBits();
25314     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25315     APInt KnownZero, KnownOne;
25316     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25317                                           !DCI.isBeforeLegalizeOps());
25318     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25319     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25320         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25321       DCI.CommitTargetLoweringOpt(TLO);
25322   }
25323   return SDValue();
25324 }
25325
25326 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25327   SDValue Op = N->getOperand(0);
25328   if (Op.getOpcode() == ISD::BITCAST)
25329     Op = Op.getOperand(0);
25330   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25331   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25332       VT.getVectorElementType().getSizeInBits() ==
25333       OpVT.getVectorElementType().getSizeInBits()) {
25334     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25335   }
25336   return SDValue();
25337 }
25338
25339 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25340                                                const X86Subtarget *Subtarget) {
25341   EVT VT = N->getValueType(0);
25342   if (!VT.isVector())
25343     return SDValue();
25344
25345   SDValue N0 = N->getOperand(0);
25346   SDValue N1 = N->getOperand(1);
25347   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25348   SDLoc dl(N);
25349
25350   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25351   // both SSE and AVX2 since there is no sign-extended shift right
25352   // operation on a vector with 64-bit elements.
25353   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25354   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25355   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25356       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25357     SDValue N00 = N0.getOperand(0);
25358
25359     // EXTLOAD has a better solution on AVX2,
25360     // it may be replaced with X86ISD::VSEXT node.
25361     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25362       if (!ISD::isNormalLoad(N00.getNode()))
25363         return SDValue();
25364
25365     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25366         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25367                                   N00, N1);
25368       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25369     }
25370   }
25371   return SDValue();
25372 }
25373
25374 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25375                                   TargetLowering::DAGCombinerInfo &DCI,
25376                                   const X86Subtarget *Subtarget) {
25377   SDValue N0 = N->getOperand(0);
25378   EVT VT = N->getValueType(0);
25379   EVT SVT = VT.getScalarType();
25380   EVT InVT = N0.getValueType();
25381   EVT InSVT = InVT.getScalarType();
25382   SDLoc DL(N);
25383
25384   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25385   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25386   // This exposes the sext to the sdivrem lowering, so that it directly extends
25387   // from AH (which we otherwise need to do contortions to access).
25388   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25389       InVT == MVT::i8 && VT == MVT::i32) {
25390     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25391     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25392                             N0.getOperand(0), N0.getOperand(1));
25393     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25394     return R.getValue(1);
25395   }
25396
25397   if (!DCI.isBeforeLegalizeOps()) {
25398     if (InVT == MVT::i1) {
25399       SDValue Zero = DAG.getConstant(0, DL, VT);
25400       SDValue AllOnes =
25401         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25402       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25403     }
25404     return SDValue();
25405   }
25406
25407   if (VT.isVector() && Subtarget->hasSSE2()) {
25408     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25409       EVT InVT = N.getValueType();
25410       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25411                                    Size / InVT.getScalarSizeInBits());
25412       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25413                                     DAG.getUNDEF(InVT));
25414       Opnds[0] = N;
25415       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25416     };
25417
25418     // If target-size is less than 128-bits, extend to a type that would extend
25419     // to 128 bits, extend that and extract the original target vector.
25420     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25421         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25422         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25423       unsigned Scale = 128 / VT.getSizeInBits();
25424       EVT ExVT =
25425           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25426       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25427       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25428       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25429                          DAG.getIntPtrConstant(0, DL));
25430     }
25431
25432     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25433     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25434     if (VT.getSizeInBits() == 128 &&
25435         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25436         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25437       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25438       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25439     }
25440
25441     // On pre-AVX2 targets, split into 128-bit nodes of
25442     // ISD::SIGN_EXTEND_VECTOR_INREG.
25443     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25444         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25445         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25446       unsigned NumVecs = VT.getSizeInBits() / 128;
25447       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25448       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25449       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25450
25451       SmallVector<SDValue, 8> Opnds;
25452       for (unsigned i = 0, Offset = 0; i != NumVecs;
25453            ++i, Offset += NumSubElts) {
25454         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25455                                      DAG.getIntPtrConstant(Offset, DL));
25456         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25457         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25458         Opnds.push_back(SrcVec);
25459       }
25460       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25461     }
25462   }
25463
25464   if (!Subtarget->hasFp256())
25465     return SDValue();
25466
25467   if (VT.isVector() && VT.getSizeInBits() == 256)
25468     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25469       return R;
25470
25471   return SDValue();
25472 }
25473
25474 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25475                                  const X86Subtarget* Subtarget) {
25476   SDLoc dl(N);
25477   EVT VT = N->getValueType(0);
25478
25479   // Let legalize expand this if it isn't a legal type yet.
25480   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25481     return SDValue();
25482
25483   EVT ScalarVT = VT.getScalarType();
25484   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25485       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25486        !Subtarget->hasAVX512()))
25487     return SDValue();
25488
25489   SDValue A = N->getOperand(0);
25490   SDValue B = N->getOperand(1);
25491   SDValue C = N->getOperand(2);
25492
25493   bool NegA = (A.getOpcode() == ISD::FNEG);
25494   bool NegB = (B.getOpcode() == ISD::FNEG);
25495   bool NegC = (C.getOpcode() == ISD::FNEG);
25496
25497   // Negative multiplication when NegA xor NegB
25498   bool NegMul = (NegA != NegB);
25499   if (NegA)
25500     A = A.getOperand(0);
25501   if (NegB)
25502     B = B.getOperand(0);
25503   if (NegC)
25504     C = C.getOperand(0);
25505
25506   unsigned Opcode;
25507   if (!NegMul)
25508     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25509   else
25510     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25511
25512   return DAG.getNode(Opcode, dl, VT, A, B, C);
25513 }
25514
25515 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25516                                   TargetLowering::DAGCombinerInfo &DCI,
25517                                   const X86Subtarget *Subtarget) {
25518   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25519   //           (and (i32 x86isd::setcc_carry), 1)
25520   // This eliminates the zext. This transformation is necessary because
25521   // ISD::SETCC is always legalized to i8.
25522   SDLoc dl(N);
25523   SDValue N0 = N->getOperand(0);
25524   EVT VT = N->getValueType(0);
25525
25526   if (N0.getOpcode() == ISD::AND &&
25527       N0.hasOneUse() &&
25528       N0.getOperand(0).hasOneUse()) {
25529     SDValue N00 = N0.getOperand(0);
25530     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25531       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25532       if (!C || C->getZExtValue() != 1)
25533         return SDValue();
25534       return DAG.getNode(ISD::AND, dl, VT,
25535                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25536                                      N00.getOperand(0), N00.getOperand(1)),
25537                          DAG.getConstant(1, dl, VT));
25538     }
25539   }
25540
25541   if (N0.getOpcode() == ISD::TRUNCATE &&
25542       N0.hasOneUse() &&
25543       N0.getOperand(0).hasOneUse()) {
25544     SDValue N00 = N0.getOperand(0);
25545     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25546       return DAG.getNode(ISD::AND, dl, VT,
25547                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25548                                      N00.getOperand(0), N00.getOperand(1)),
25549                          DAG.getConstant(1, dl, VT));
25550     }
25551   }
25552
25553   if (VT.is256BitVector())
25554     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25555       return R;
25556
25557   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25558   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25559   // This exposes the zext to the udivrem lowering, so that it directly extends
25560   // from AH (which we otherwise need to do contortions to access).
25561   if (N0.getOpcode() == ISD::UDIVREM &&
25562       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25563       (VT == MVT::i32 || VT == MVT::i64)) {
25564     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25565     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25566                             N0.getOperand(0), N0.getOperand(1));
25567     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25568     return R.getValue(1);
25569   }
25570
25571   return SDValue();
25572 }
25573
25574 // Optimize x == -y --> x+y == 0
25575 //          x != -y --> x+y != 0
25576 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25577                                       const X86Subtarget* Subtarget) {
25578   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25579   SDValue LHS = N->getOperand(0);
25580   SDValue RHS = N->getOperand(1);
25581   EVT VT = N->getValueType(0);
25582   SDLoc DL(N);
25583
25584   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25585     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25586       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25587         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25588                                    LHS.getOperand(1));
25589         return DAG.getSetCC(DL, N->getValueType(0), addV,
25590                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25591       }
25592   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25593     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25594       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25595         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25596                                    RHS.getOperand(1));
25597         return DAG.getSetCC(DL, N->getValueType(0), addV,
25598                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25599       }
25600
25601   if (VT.getScalarType() == MVT::i1 &&
25602       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25603     bool IsSEXT0 =
25604         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25605         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25606     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25607
25608     if (!IsSEXT0 || !IsVZero1) {
25609       // Swap the operands and update the condition code.
25610       std::swap(LHS, RHS);
25611       CC = ISD::getSetCCSwappedOperands(CC);
25612
25613       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25614                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25615       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25616     }
25617
25618     if (IsSEXT0 && IsVZero1) {
25619       assert(VT == LHS.getOperand(0).getValueType() &&
25620              "Uexpected operand type");
25621       if (CC == ISD::SETGT)
25622         return DAG.getConstant(0, DL, VT);
25623       if (CC == ISD::SETLE)
25624         return DAG.getConstant(1, DL, VT);
25625       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25626         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25627
25628       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25629              "Unexpected condition code!");
25630       return LHS.getOperand(0);
25631     }
25632   }
25633
25634   return SDValue();
25635 }
25636
25637 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25638                                          SelectionDAG &DAG) {
25639   SDLoc dl(Load);
25640   MVT VT = Load->getSimpleValueType(0);
25641   MVT EVT = VT.getVectorElementType();
25642   SDValue Addr = Load->getOperand(1);
25643   SDValue NewAddr = DAG.getNode(
25644       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25645       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25646                       Addr.getSimpleValueType()));
25647
25648   SDValue NewLoad =
25649       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25650                   DAG.getMachineFunction().getMachineMemOperand(
25651                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25652   return NewLoad;
25653 }
25654
25655 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25656                                       const X86Subtarget *Subtarget) {
25657   SDLoc dl(N);
25658   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25659   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25660          "X86insertps is only defined for v4x32");
25661
25662   SDValue Ld = N->getOperand(1);
25663   if (MayFoldLoad(Ld)) {
25664     // Extract the countS bits from the immediate so we can get the proper
25665     // address when narrowing the vector load to a specific element.
25666     // When the second source op is a memory address, insertps doesn't use
25667     // countS and just gets an f32 from that address.
25668     unsigned DestIndex =
25669         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25670
25671     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25672
25673     // Create this as a scalar to vector to match the instruction pattern.
25674     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25675     // countS bits are ignored when loading from memory on insertps, which
25676     // means we don't need to explicitly set them to 0.
25677     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25678                        LoadScalarToVector, N->getOperand(2));
25679   }
25680   return SDValue();
25681 }
25682
25683 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25684   SDValue V0 = N->getOperand(0);
25685   SDValue V1 = N->getOperand(1);
25686   SDLoc DL(N);
25687   EVT VT = N->getValueType(0);
25688
25689   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25690   // operands and changing the mask to 1. This saves us a bunch of
25691   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25692   // x86InstrInfo knows how to commute this back after instruction selection
25693   // if it would help register allocation.
25694
25695   // TODO: If optimizing for size or a processor that doesn't suffer from
25696   // partial register update stalls, this should be transformed into a MOVSD
25697   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25698
25699   if (VT == MVT::v2f64)
25700     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25701       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25702         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25703         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25704       }
25705
25706   return SDValue();
25707 }
25708
25709 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25710 // as "sbb reg,reg", since it can be extended without zext and produces
25711 // an all-ones bit which is more useful than 0/1 in some cases.
25712 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25713                                MVT VT) {
25714   if (VT == MVT::i8)
25715     return DAG.getNode(ISD::AND, DL, VT,
25716                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25717                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25718                                    EFLAGS),
25719                        DAG.getConstant(1, DL, VT));
25720   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25721   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25722                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25723                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25724                                  EFLAGS));
25725 }
25726
25727 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25728 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25729                                    TargetLowering::DAGCombinerInfo &DCI,
25730                                    const X86Subtarget *Subtarget) {
25731   SDLoc DL(N);
25732   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25733   SDValue EFLAGS = N->getOperand(1);
25734
25735   if (CC == X86::COND_A) {
25736     // Try to convert COND_A into COND_B in an attempt to facilitate
25737     // materializing "setb reg".
25738     //
25739     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25740     // cannot take an immediate as its first operand.
25741     //
25742     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25743         EFLAGS.getValueType().isInteger() &&
25744         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25745       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25746                                    EFLAGS.getNode()->getVTList(),
25747                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25748       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25749       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25750     }
25751   }
25752
25753   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25754   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25755   // cases.
25756   if (CC == X86::COND_B)
25757     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25758
25759   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25760     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25761     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25762   }
25763
25764   return SDValue();
25765 }
25766
25767 // Optimize branch condition evaluation.
25768 //
25769 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25770                                     TargetLowering::DAGCombinerInfo &DCI,
25771                                     const X86Subtarget *Subtarget) {
25772   SDLoc DL(N);
25773   SDValue Chain = N->getOperand(0);
25774   SDValue Dest = N->getOperand(1);
25775   SDValue EFLAGS = N->getOperand(3);
25776   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25777
25778   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25779     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25780     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25781                        Flags);
25782   }
25783
25784   return SDValue();
25785 }
25786
25787 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25788                                                          SelectionDAG &DAG) {
25789   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25790   // optimize away operation when it's from a constant.
25791   //
25792   // The general transformation is:
25793   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25794   //       AND(VECTOR_CMP(x,y), constant2)
25795   //    constant2 = UNARYOP(constant)
25796
25797   // Early exit if this isn't a vector operation, the operand of the
25798   // unary operation isn't a bitwise AND, or if the sizes of the operations
25799   // aren't the same.
25800   EVT VT = N->getValueType(0);
25801   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25802       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25803       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25804     return SDValue();
25805
25806   // Now check that the other operand of the AND is a constant. We could
25807   // make the transformation for non-constant splats as well, but it's unclear
25808   // that would be a benefit as it would not eliminate any operations, just
25809   // perform one more step in scalar code before moving to the vector unit.
25810   if (BuildVectorSDNode *BV =
25811           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25812     // Bail out if the vector isn't a constant.
25813     if (!BV->isConstant())
25814       return SDValue();
25815
25816     // Everything checks out. Build up the new and improved node.
25817     SDLoc DL(N);
25818     EVT IntVT = BV->getValueType(0);
25819     // Create a new constant of the appropriate type for the transformed
25820     // DAG.
25821     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25822     // The AND node needs bitcasts to/from an integer vector type around it.
25823     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25824     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25825                                  N->getOperand(0)->getOperand(0), MaskConst);
25826     SDValue Res = DAG.getBitcast(VT, NewAnd);
25827     return Res;
25828   }
25829
25830   return SDValue();
25831 }
25832
25833 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25834                                         const X86Subtarget *Subtarget) {
25835   SDValue Op0 = N->getOperand(0);
25836   EVT VT = N->getValueType(0);
25837   EVT InVT = Op0.getValueType();
25838   EVT InSVT = InVT.getScalarType();
25839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25840
25841   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25842   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25843   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25844     SDLoc dl(N);
25845     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25846                                  InVT.getVectorNumElements());
25847     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25848
25849     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25850       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25851
25852     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25853   }
25854
25855   return SDValue();
25856 }
25857
25858 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25859                                         const X86Subtarget *Subtarget) {
25860   // First try to optimize away the conversion entirely when it's
25861   // conditionally from a constant. Vectors only.
25862   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25863     return Res;
25864
25865   // Now move on to more general possibilities.
25866   SDValue Op0 = N->getOperand(0);
25867   EVT VT = N->getValueType(0);
25868   EVT InVT = Op0.getValueType();
25869   EVT InSVT = InVT.getScalarType();
25870
25871   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25872   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25873   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25874     SDLoc dl(N);
25875     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25876                                  InVT.getVectorNumElements());
25877     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25878     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25879   }
25880
25881   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25882   // a 32-bit target where SSE doesn't support i64->FP operations.
25883   if (Op0.getOpcode() == ISD::LOAD) {
25884     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25885     EVT LdVT = Ld->getValueType(0);
25886
25887     // This transformation is not supported if the result type is f16
25888     if (VT == MVT::f16)
25889       return SDValue();
25890
25891     if (!Ld->isVolatile() && !VT.isVector() &&
25892         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25893         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25894       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25895           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25896       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25897       return FILDChain;
25898     }
25899   }
25900   return SDValue();
25901 }
25902
25903 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25904 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25905                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25906   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25907   // the result is either zero or one (depending on the input carry bit).
25908   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25909   if (X86::isZeroNode(N->getOperand(0)) &&
25910       X86::isZeroNode(N->getOperand(1)) &&
25911       // We don't have a good way to replace an EFLAGS use, so only do this when
25912       // dead right now.
25913       SDValue(N, 1).use_empty()) {
25914     SDLoc DL(N);
25915     EVT VT = N->getValueType(0);
25916     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25917     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25918                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25919                                            DAG.getConstant(X86::COND_B, DL,
25920                                                            MVT::i8),
25921                                            N->getOperand(2)),
25922                                DAG.getConstant(1, DL, VT));
25923     return DCI.CombineTo(N, Res1, CarryOut);
25924   }
25925
25926   return SDValue();
25927 }
25928
25929 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25930 //      (add Y, (setne X, 0)) -> sbb -1, Y
25931 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25932 //      (sub (setne X, 0), Y) -> adc -1, Y
25933 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25934   SDLoc DL(N);
25935
25936   // Look through ZExts.
25937   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25938   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25939     return SDValue();
25940
25941   SDValue SetCC = Ext.getOperand(0);
25942   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25943     return SDValue();
25944
25945   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25946   if (CC != X86::COND_E && CC != X86::COND_NE)
25947     return SDValue();
25948
25949   SDValue Cmp = SetCC.getOperand(1);
25950   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25951       !X86::isZeroNode(Cmp.getOperand(1)) ||
25952       !Cmp.getOperand(0).getValueType().isInteger())
25953     return SDValue();
25954
25955   SDValue CmpOp0 = Cmp.getOperand(0);
25956   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25957                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25958
25959   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25960   if (CC == X86::COND_NE)
25961     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25962                        DL, OtherVal.getValueType(), OtherVal,
25963                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25964                        NewCmp);
25965   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25966                      DL, OtherVal.getValueType(), OtherVal,
25967                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25968 }
25969
25970 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25971 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25972                                  const X86Subtarget *Subtarget) {
25973   EVT VT = N->getValueType(0);
25974   SDValue Op0 = N->getOperand(0);
25975   SDValue Op1 = N->getOperand(1);
25976
25977   // Try to synthesize horizontal adds from adds of shuffles.
25978   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25979        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25980       isHorizontalBinOp(Op0, Op1, true))
25981     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25982
25983   return OptimizeConditionalInDecrement(N, DAG);
25984 }
25985
25986 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25987                                  const X86Subtarget *Subtarget) {
25988   SDValue Op0 = N->getOperand(0);
25989   SDValue Op1 = N->getOperand(1);
25990
25991   // X86 can't encode an immediate LHS of a sub. See if we can push the
25992   // negation into a preceding instruction.
25993   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25994     // If the RHS of the sub is a XOR with one use and a constant, invert the
25995     // immediate. Then add one to the LHS of the sub so we can turn
25996     // X-Y -> X+~Y+1, saving one register.
25997     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25998         isa<ConstantSDNode>(Op1.getOperand(1))) {
25999       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26000       EVT VT = Op0.getValueType();
26001       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26002                                    Op1.getOperand(0),
26003                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26004       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26005                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26006     }
26007   }
26008
26009   // Try to synthesize horizontal adds from adds of shuffles.
26010   EVT VT = N->getValueType(0);
26011   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26012        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26013       isHorizontalBinOp(Op0, Op1, true))
26014     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26015
26016   return OptimizeConditionalInDecrement(N, DAG);
26017 }
26018
26019 /// performVZEXTCombine - Performs build vector combines
26020 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26021                                    TargetLowering::DAGCombinerInfo &DCI,
26022                                    const X86Subtarget *Subtarget) {
26023   SDLoc DL(N);
26024   MVT VT = N->getSimpleValueType(0);
26025   SDValue Op = N->getOperand(0);
26026   MVT OpVT = Op.getSimpleValueType();
26027   MVT OpEltVT = OpVT.getVectorElementType();
26028   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26029
26030   // (vzext (bitcast (vzext (x)) -> (vzext x)
26031   SDValue V = Op;
26032   while (V.getOpcode() == ISD::BITCAST)
26033     V = V.getOperand(0);
26034
26035   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26036     MVT InnerVT = V.getSimpleValueType();
26037     MVT InnerEltVT = InnerVT.getVectorElementType();
26038
26039     // If the element sizes match exactly, we can just do one larger vzext. This
26040     // is always an exact type match as vzext operates on integer types.
26041     if (OpEltVT == InnerEltVT) {
26042       assert(OpVT == InnerVT && "Types must match for vzext!");
26043       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26044     }
26045
26046     // The only other way we can combine them is if only a single element of the
26047     // inner vzext is used in the input to the outer vzext.
26048     if (InnerEltVT.getSizeInBits() < InputBits)
26049       return SDValue();
26050
26051     // In this case, the inner vzext is completely dead because we're going to
26052     // only look at bits inside of the low element. Just do the outer vzext on
26053     // a bitcast of the input to the inner.
26054     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26055   }
26056
26057   // Check if we can bypass extracting and re-inserting an element of an input
26058   // vector. Essentially:
26059   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26060   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26061       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26062       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26063     SDValue ExtractedV = V.getOperand(0);
26064     SDValue OrigV = ExtractedV.getOperand(0);
26065     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26066       if (ExtractIdx->getZExtValue() == 0) {
26067         MVT OrigVT = OrigV.getSimpleValueType();
26068         // Extract a subvector if necessary...
26069         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26070           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26071           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26072                                     OrigVT.getVectorNumElements() / Ratio);
26073           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26074                               DAG.getIntPtrConstant(0, DL));
26075         }
26076         Op = DAG.getBitcast(OpVT, OrigV);
26077         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26078       }
26079   }
26080
26081   return SDValue();
26082 }
26083
26084 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26085                                              DAGCombinerInfo &DCI) const {
26086   SelectionDAG &DAG = DCI.DAG;
26087   switch (N->getOpcode()) {
26088   default: break;
26089   case ISD::EXTRACT_VECTOR_ELT:
26090     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26091   case ISD::VSELECT:
26092   case ISD::SELECT:
26093   case X86ISD::SHRUNKBLEND:
26094     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26095   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26096   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26097   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26098   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26099   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26100   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26101   case ISD::SHL:
26102   case ISD::SRA:
26103   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26104   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26105   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26106   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26107   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26108   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26109   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26110   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26111   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26112   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26113   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26114   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26115   case X86ISD::FXOR:
26116   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26117   case X86ISD::FMIN:
26118   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26119   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26120   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26121   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26122   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26123   case ISD::ANY_EXTEND:
26124   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26125   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26126   case ISD::SIGN_EXTEND_INREG:
26127     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26128   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26129   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26130   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26131   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26132   case X86ISD::SHUFP:       // Handle all target specific shuffles
26133   case X86ISD::PALIGNR:
26134   case X86ISD::UNPCKH:
26135   case X86ISD::UNPCKL:
26136   case X86ISD::MOVHLPS:
26137   case X86ISD::MOVLHPS:
26138   case X86ISD::PSHUFB:
26139   case X86ISD::PSHUFD:
26140   case X86ISD::PSHUFHW:
26141   case X86ISD::PSHUFLW:
26142   case X86ISD::MOVSS:
26143   case X86ISD::MOVSD:
26144   case X86ISD::VPERMILPI:
26145   case X86ISD::VPERM2X128:
26146   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26147   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26148   case X86ISD::INSERTPS: {
26149     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26150       return PerformINSERTPSCombine(N, DAG, Subtarget);
26151     break;
26152   }
26153   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26154   }
26155
26156   return SDValue();
26157 }
26158
26159 /// isTypeDesirableForOp - Return true if the target has native support for
26160 /// the specified value type and it is 'desirable' to use the type for the
26161 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26162 /// instruction encodings are longer and some i16 instructions are slow.
26163 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26164   if (!isTypeLegal(VT))
26165     return false;
26166   if (VT != MVT::i16)
26167     return true;
26168
26169   switch (Opc) {
26170   default:
26171     return true;
26172   case ISD::LOAD:
26173   case ISD::SIGN_EXTEND:
26174   case ISD::ZERO_EXTEND:
26175   case ISD::ANY_EXTEND:
26176   case ISD::SHL:
26177   case ISD::SRL:
26178   case ISD::SUB:
26179   case ISD::ADD:
26180   case ISD::MUL:
26181   case ISD::AND:
26182   case ISD::OR:
26183   case ISD::XOR:
26184     return false;
26185   }
26186 }
26187
26188 /// IsDesirableToPromoteOp - This method query the target whether it is
26189 /// beneficial for dag combiner to promote the specified node. If true, it
26190 /// should return the desired promotion type by reference.
26191 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26192   EVT VT = Op.getValueType();
26193   if (VT != MVT::i16)
26194     return false;
26195
26196   bool Promote = false;
26197   bool Commute = false;
26198   switch (Op.getOpcode()) {
26199   default: break;
26200   case ISD::LOAD: {
26201     LoadSDNode *LD = cast<LoadSDNode>(Op);
26202     // If the non-extending load has a single use and it's not live out, then it
26203     // might be folded.
26204     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26205                                                      Op.hasOneUse()*/) {
26206       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26207              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26208         // The only case where we'd want to promote LOAD (rather then it being
26209         // promoted as an operand is when it's only use is liveout.
26210         if (UI->getOpcode() != ISD::CopyToReg)
26211           return false;
26212       }
26213     }
26214     Promote = true;
26215     break;
26216   }
26217   case ISD::SIGN_EXTEND:
26218   case ISD::ZERO_EXTEND:
26219   case ISD::ANY_EXTEND:
26220     Promote = true;
26221     break;
26222   case ISD::SHL:
26223   case ISD::SRL: {
26224     SDValue N0 = Op.getOperand(0);
26225     // Look out for (store (shl (load), x)).
26226     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26227       return false;
26228     Promote = true;
26229     break;
26230   }
26231   case ISD::ADD:
26232   case ISD::MUL:
26233   case ISD::AND:
26234   case ISD::OR:
26235   case ISD::XOR:
26236     Commute = true;
26237     // fallthrough
26238   case ISD::SUB: {
26239     SDValue N0 = Op.getOperand(0);
26240     SDValue N1 = Op.getOperand(1);
26241     if (!Commute && MayFoldLoad(N1))
26242       return false;
26243     // Avoid disabling potential load folding opportunities.
26244     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26245       return false;
26246     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26247       return false;
26248     Promote = true;
26249   }
26250   }
26251
26252   PVT = MVT::i32;
26253   return Promote;
26254 }
26255
26256 //===----------------------------------------------------------------------===//
26257 //                           X86 Inline Assembly Support
26258 //===----------------------------------------------------------------------===//
26259
26260 // Helper to match a string separated by whitespace.
26261 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26262   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26263
26264   for (StringRef Piece : Pieces) {
26265     if (!S.startswith(Piece)) // Check if the piece matches.
26266       return false;
26267
26268     S = S.substr(Piece.size());
26269     StringRef::size_type Pos = S.find_first_not_of(" \t");
26270     if (Pos == 0) // We matched a prefix.
26271       return false;
26272
26273     S = S.substr(Pos);
26274   }
26275
26276   return S.empty();
26277 }
26278
26279 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26280
26281   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26282     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26283         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26284         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26285
26286       if (AsmPieces.size() == 3)
26287         return true;
26288       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26289         return true;
26290     }
26291   }
26292   return false;
26293 }
26294
26295 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26296   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26297
26298   std::string AsmStr = IA->getAsmString();
26299
26300   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26301   if (!Ty || Ty->getBitWidth() % 16 != 0)
26302     return false;
26303
26304   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26305   SmallVector<StringRef, 4> AsmPieces;
26306   SplitString(AsmStr, AsmPieces, ";\n");
26307
26308   switch (AsmPieces.size()) {
26309   default: return false;
26310   case 1:
26311     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26312     // we will turn this bswap into something that will be lowered to logical
26313     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26314     // lower so don't worry about this.
26315     // bswap $0
26316     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26317         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26318         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26319         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26320         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26321         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26322       // No need to check constraints, nothing other than the equivalent of
26323       // "=r,0" would be valid here.
26324       return IntrinsicLowering::LowerToByteSwap(CI);
26325     }
26326
26327     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26328     if (CI->getType()->isIntegerTy(16) &&
26329         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26330         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26331          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26332       AsmPieces.clear();
26333       StringRef ConstraintsStr = IA->getConstraintString();
26334       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26335       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26336       if (clobbersFlagRegisters(AsmPieces))
26337         return IntrinsicLowering::LowerToByteSwap(CI);
26338     }
26339     break;
26340   case 3:
26341     if (CI->getType()->isIntegerTy(32) &&
26342         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26343         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26344         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26345         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26346       AsmPieces.clear();
26347       StringRef ConstraintsStr = IA->getConstraintString();
26348       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26349       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26350       if (clobbersFlagRegisters(AsmPieces))
26351         return IntrinsicLowering::LowerToByteSwap(CI);
26352     }
26353
26354     if (CI->getType()->isIntegerTy(64)) {
26355       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26356       if (Constraints.size() >= 2 &&
26357           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26358           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26359         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26360         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26361             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26362             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26363           return IntrinsicLowering::LowerToByteSwap(CI);
26364       }
26365     }
26366     break;
26367   }
26368   return false;
26369 }
26370
26371 /// getConstraintType - Given a constraint letter, return the type of
26372 /// constraint it is for this target.
26373 X86TargetLowering::ConstraintType
26374 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26375   if (Constraint.size() == 1) {
26376     switch (Constraint[0]) {
26377     case 'R':
26378     case 'q':
26379     case 'Q':
26380     case 'f':
26381     case 't':
26382     case 'u':
26383     case 'y':
26384     case 'x':
26385     case 'Y':
26386     case 'l':
26387       return C_RegisterClass;
26388     case 'a':
26389     case 'b':
26390     case 'c':
26391     case 'd':
26392     case 'S':
26393     case 'D':
26394     case 'A':
26395       return C_Register;
26396     case 'I':
26397     case 'J':
26398     case 'K':
26399     case 'L':
26400     case 'M':
26401     case 'N':
26402     case 'G':
26403     case 'C':
26404     case 'e':
26405     case 'Z':
26406       return C_Other;
26407     default:
26408       break;
26409     }
26410   }
26411   return TargetLowering::getConstraintType(Constraint);
26412 }
26413
26414 /// Examine constraint type and operand type and determine a weight value.
26415 /// This object must already have been set up with the operand type
26416 /// and the current alternative constraint selected.
26417 TargetLowering::ConstraintWeight
26418   X86TargetLowering::getSingleConstraintMatchWeight(
26419     AsmOperandInfo &info, const char *constraint) const {
26420   ConstraintWeight weight = CW_Invalid;
26421   Value *CallOperandVal = info.CallOperandVal;
26422     // If we don't have a value, we can't do a match,
26423     // but allow it at the lowest weight.
26424   if (!CallOperandVal)
26425     return CW_Default;
26426   Type *type = CallOperandVal->getType();
26427   // Look at the constraint type.
26428   switch (*constraint) {
26429   default:
26430     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26431   case 'R':
26432   case 'q':
26433   case 'Q':
26434   case 'a':
26435   case 'b':
26436   case 'c':
26437   case 'd':
26438   case 'S':
26439   case 'D':
26440   case 'A':
26441     if (CallOperandVal->getType()->isIntegerTy())
26442       weight = CW_SpecificReg;
26443     break;
26444   case 'f':
26445   case 't':
26446   case 'u':
26447     if (type->isFloatingPointTy())
26448       weight = CW_SpecificReg;
26449     break;
26450   case 'y':
26451     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26452       weight = CW_SpecificReg;
26453     break;
26454   case 'x':
26455   case 'Y':
26456     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26457         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26458       weight = CW_Register;
26459     break;
26460   case 'I':
26461     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26462       if (C->getZExtValue() <= 31)
26463         weight = CW_Constant;
26464     }
26465     break;
26466   case 'J':
26467     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26468       if (C->getZExtValue() <= 63)
26469         weight = CW_Constant;
26470     }
26471     break;
26472   case 'K':
26473     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26474       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26475         weight = CW_Constant;
26476     }
26477     break;
26478   case 'L':
26479     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26480       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26481         weight = CW_Constant;
26482     }
26483     break;
26484   case 'M':
26485     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26486       if (C->getZExtValue() <= 3)
26487         weight = CW_Constant;
26488     }
26489     break;
26490   case 'N':
26491     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26492       if (C->getZExtValue() <= 0xff)
26493         weight = CW_Constant;
26494     }
26495     break;
26496   case 'G':
26497   case 'C':
26498     if (isa<ConstantFP>(CallOperandVal)) {
26499       weight = CW_Constant;
26500     }
26501     break;
26502   case 'e':
26503     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26504       if ((C->getSExtValue() >= -0x80000000LL) &&
26505           (C->getSExtValue() <= 0x7fffffffLL))
26506         weight = CW_Constant;
26507     }
26508     break;
26509   case 'Z':
26510     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26511       if (C->getZExtValue() <= 0xffffffff)
26512         weight = CW_Constant;
26513     }
26514     break;
26515   }
26516   return weight;
26517 }
26518
26519 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26520 /// with another that has more specific requirements based on the type of the
26521 /// corresponding operand.
26522 const char *X86TargetLowering::
26523 LowerXConstraint(EVT ConstraintVT) const {
26524   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26525   // 'f' like normal targets.
26526   if (ConstraintVT.isFloatingPoint()) {
26527     if (Subtarget->hasSSE2())
26528       return "Y";
26529     if (Subtarget->hasSSE1())
26530       return "x";
26531   }
26532
26533   return TargetLowering::LowerXConstraint(ConstraintVT);
26534 }
26535
26536 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26537 /// vector.  If it is invalid, don't add anything to Ops.
26538 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26539                                                      std::string &Constraint,
26540                                                      std::vector<SDValue>&Ops,
26541                                                      SelectionDAG &DAG) const {
26542   SDValue Result;
26543
26544   // Only support length 1 constraints for now.
26545   if (Constraint.length() > 1) return;
26546
26547   char ConstraintLetter = Constraint[0];
26548   switch (ConstraintLetter) {
26549   default: break;
26550   case 'I':
26551     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26552       if (C->getZExtValue() <= 31) {
26553         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26554                                        Op.getValueType());
26555         break;
26556       }
26557     }
26558     return;
26559   case 'J':
26560     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26561       if (C->getZExtValue() <= 63) {
26562         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26563                                        Op.getValueType());
26564         break;
26565       }
26566     }
26567     return;
26568   case 'K':
26569     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26570       if (isInt<8>(C->getSExtValue())) {
26571         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26572                                        Op.getValueType());
26573         break;
26574       }
26575     }
26576     return;
26577   case 'L':
26578     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26579       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26580           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26581         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26582                                        Op.getValueType());
26583         break;
26584       }
26585     }
26586     return;
26587   case 'M':
26588     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26589       if (C->getZExtValue() <= 3) {
26590         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26591                                        Op.getValueType());
26592         break;
26593       }
26594     }
26595     return;
26596   case 'N':
26597     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26598       if (C->getZExtValue() <= 255) {
26599         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26600                                        Op.getValueType());
26601         break;
26602       }
26603     }
26604     return;
26605   case 'O':
26606     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26607       if (C->getZExtValue() <= 127) {
26608         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26609                                        Op.getValueType());
26610         break;
26611       }
26612     }
26613     return;
26614   case 'e': {
26615     // 32-bit signed value
26616     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26617       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26618                                            C->getSExtValue())) {
26619         // Widen to 64 bits here to get it sign extended.
26620         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26621         break;
26622       }
26623     // FIXME gcc accepts some relocatable values here too, but only in certain
26624     // memory models; it's complicated.
26625     }
26626     return;
26627   }
26628   case 'Z': {
26629     // 32-bit unsigned value
26630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26631       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26632                                            C->getZExtValue())) {
26633         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26634                                        Op.getValueType());
26635         break;
26636       }
26637     }
26638     // FIXME gcc accepts some relocatable values here too, but only in certain
26639     // memory models; it's complicated.
26640     return;
26641   }
26642   case 'i': {
26643     // Literal immediates are always ok.
26644     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26645       // Widen to 64 bits here to get it sign extended.
26646       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26647       break;
26648     }
26649
26650     // In any sort of PIC mode addresses need to be computed at runtime by
26651     // adding in a register or some sort of table lookup.  These can't
26652     // be used as immediates.
26653     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26654       return;
26655
26656     // If we are in non-pic codegen mode, we allow the address of a global (with
26657     // an optional displacement) to be used with 'i'.
26658     GlobalAddressSDNode *GA = nullptr;
26659     int64_t Offset = 0;
26660
26661     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26662     while (1) {
26663       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26664         Offset += GA->getOffset();
26665         break;
26666       } else if (Op.getOpcode() == ISD::ADD) {
26667         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26668           Offset += C->getZExtValue();
26669           Op = Op.getOperand(0);
26670           continue;
26671         }
26672       } else if (Op.getOpcode() == ISD::SUB) {
26673         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26674           Offset += -C->getZExtValue();
26675           Op = Op.getOperand(0);
26676           continue;
26677         }
26678       }
26679
26680       // Otherwise, this isn't something we can handle, reject it.
26681       return;
26682     }
26683
26684     const GlobalValue *GV = GA->getGlobal();
26685     // If we require an extra load to get this address, as in PIC mode, we
26686     // can't accept it.
26687     if (isGlobalStubReference(
26688             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26689       return;
26690
26691     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26692                                         GA->getValueType(0), Offset);
26693     break;
26694   }
26695   }
26696
26697   if (Result.getNode()) {
26698     Ops.push_back(Result);
26699     return;
26700   }
26701   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26702 }
26703
26704 std::pair<unsigned, const TargetRegisterClass *>
26705 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26706                                                 StringRef Constraint,
26707                                                 MVT VT) const {
26708   // First, see if this is a constraint that directly corresponds to an LLVM
26709   // register class.
26710   if (Constraint.size() == 1) {
26711     // GCC Constraint Letters
26712     switch (Constraint[0]) {
26713     default: break;
26714       // TODO: Slight differences here in allocation order and leaving
26715       // RIP in the class. Do they matter any more here than they do
26716       // in the normal allocation?
26717     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26718       if (Subtarget->is64Bit()) {
26719         if (VT == MVT::i32 || VT == MVT::f32)
26720           return std::make_pair(0U, &X86::GR32RegClass);
26721         if (VT == MVT::i16)
26722           return std::make_pair(0U, &X86::GR16RegClass);
26723         if (VT == MVT::i8 || VT == MVT::i1)
26724           return std::make_pair(0U, &X86::GR8RegClass);
26725         if (VT == MVT::i64 || VT == MVT::f64)
26726           return std::make_pair(0U, &X86::GR64RegClass);
26727         break;
26728       }
26729       // 32-bit fallthrough
26730     case 'Q':   // Q_REGS
26731       if (VT == MVT::i32 || VT == MVT::f32)
26732         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26733       if (VT == MVT::i16)
26734         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26735       if (VT == MVT::i8 || VT == MVT::i1)
26736         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26737       if (VT == MVT::i64)
26738         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26739       break;
26740     case 'r':   // GENERAL_REGS
26741     case 'l':   // INDEX_REGS
26742       if (VT == MVT::i8 || VT == MVT::i1)
26743         return std::make_pair(0U, &X86::GR8RegClass);
26744       if (VT == MVT::i16)
26745         return std::make_pair(0U, &X86::GR16RegClass);
26746       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26747         return std::make_pair(0U, &X86::GR32RegClass);
26748       return std::make_pair(0U, &X86::GR64RegClass);
26749     case 'R':   // LEGACY_REGS
26750       if (VT == MVT::i8 || VT == MVT::i1)
26751         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26752       if (VT == MVT::i16)
26753         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26754       if (VT == MVT::i32 || !Subtarget->is64Bit())
26755         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26756       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26757     case 'f':  // FP Stack registers.
26758       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26759       // value to the correct fpstack register class.
26760       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26761         return std::make_pair(0U, &X86::RFP32RegClass);
26762       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26763         return std::make_pair(0U, &X86::RFP64RegClass);
26764       return std::make_pair(0U, &X86::RFP80RegClass);
26765     case 'y':   // MMX_REGS if MMX allowed.
26766       if (!Subtarget->hasMMX()) break;
26767       return std::make_pair(0U, &X86::VR64RegClass);
26768     case 'Y':   // SSE_REGS if SSE2 allowed
26769       if (!Subtarget->hasSSE2()) break;
26770       // FALL THROUGH.
26771     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26772       if (!Subtarget->hasSSE1()) break;
26773
26774       switch (VT.SimpleTy) {
26775       default: break;
26776       // Scalar SSE types.
26777       case MVT::f32:
26778       case MVT::i32:
26779         return std::make_pair(0U, &X86::FR32RegClass);
26780       case MVT::f64:
26781       case MVT::i64:
26782         return std::make_pair(0U, &X86::FR64RegClass);
26783       // Vector types.
26784       case MVT::v16i8:
26785       case MVT::v8i16:
26786       case MVT::v4i32:
26787       case MVT::v2i64:
26788       case MVT::v4f32:
26789       case MVT::v2f64:
26790         return std::make_pair(0U, &X86::VR128RegClass);
26791       // AVX types.
26792       case MVT::v32i8:
26793       case MVT::v16i16:
26794       case MVT::v8i32:
26795       case MVT::v4i64:
26796       case MVT::v8f32:
26797       case MVT::v4f64:
26798         return std::make_pair(0U, &X86::VR256RegClass);
26799       case MVT::v8f64:
26800       case MVT::v16f32:
26801       case MVT::v16i32:
26802       case MVT::v8i64:
26803         return std::make_pair(0U, &X86::VR512RegClass);
26804       }
26805       break;
26806     }
26807   }
26808
26809   // Use the default implementation in TargetLowering to convert the register
26810   // constraint into a member of a register class.
26811   std::pair<unsigned, const TargetRegisterClass*> Res;
26812   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26813
26814   // Not found as a standard register?
26815   if (!Res.second) {
26816     // Map st(0) -> st(7) -> ST0
26817     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26818         tolower(Constraint[1]) == 's' &&
26819         tolower(Constraint[2]) == 't' &&
26820         Constraint[3] == '(' &&
26821         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26822         Constraint[5] == ')' &&
26823         Constraint[6] == '}') {
26824
26825       Res.first = X86::FP0+Constraint[4]-'0';
26826       Res.second = &X86::RFP80RegClass;
26827       return Res;
26828     }
26829
26830     // GCC allows "st(0)" to be called just plain "st".
26831     if (StringRef("{st}").equals_lower(Constraint)) {
26832       Res.first = X86::FP0;
26833       Res.second = &X86::RFP80RegClass;
26834       return Res;
26835     }
26836
26837     // flags -> EFLAGS
26838     if (StringRef("{flags}").equals_lower(Constraint)) {
26839       Res.first = X86::EFLAGS;
26840       Res.second = &X86::CCRRegClass;
26841       return Res;
26842     }
26843
26844     // 'A' means EAX + EDX.
26845     if (Constraint == "A") {
26846       Res.first = X86::EAX;
26847       Res.second = &X86::GR32_ADRegClass;
26848       return Res;
26849     }
26850     return Res;
26851   }
26852
26853   // Otherwise, check to see if this is a register class of the wrong value
26854   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26855   // turn into {ax},{dx}.
26856   // MVT::Other is used to specify clobber names.
26857   if (Res.second->hasType(VT) || VT == MVT::Other)
26858     return Res;   // Correct type already, nothing to do.
26859
26860   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26861   // return "eax". This should even work for things like getting 64bit integer
26862   // registers when given an f64 type.
26863   const TargetRegisterClass *Class = Res.second;
26864   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26865       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26866     unsigned Size = VT.getSizeInBits();
26867     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26868                                   : Size == 16 ? MVT::i16
26869                                   : Size == 32 ? MVT::i32
26870                                   : Size == 64 ? MVT::i64
26871                                   : MVT::Other;
26872     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26873     if (DestReg > 0) {
26874       Res.first = DestReg;
26875       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26876                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26877                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26878                  : &X86::GR64RegClass;
26879       assert(Res.second->contains(Res.first) && "Register in register class");
26880     } else {
26881       // No register found/type mismatch.
26882       Res.first = 0;
26883       Res.second = nullptr;
26884     }
26885   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26886              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26887              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26888              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26889              Class == &X86::VR512RegClass) {
26890     // Handle references to XMM physical registers that got mapped into the
26891     // wrong class.  This can happen with constraints like {xmm0} where the
26892     // target independent register mapper will just pick the first match it can
26893     // find, ignoring the required type.
26894
26895     if (VT == MVT::f32 || VT == MVT::i32)
26896       Res.second = &X86::FR32RegClass;
26897     else if (VT == MVT::f64 || VT == MVT::i64)
26898       Res.second = &X86::FR64RegClass;
26899     else if (X86::VR128RegClass.hasType(VT))
26900       Res.second = &X86::VR128RegClass;
26901     else if (X86::VR256RegClass.hasType(VT))
26902       Res.second = &X86::VR256RegClass;
26903     else if (X86::VR512RegClass.hasType(VT))
26904       Res.second = &X86::VR512RegClass;
26905     else {
26906       // Type mismatch and not a clobber: Return an error;
26907       Res.first = 0;
26908       Res.second = nullptr;
26909     }
26910   }
26911
26912   return Res;
26913 }
26914
26915 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26916                                             const AddrMode &AM, Type *Ty,
26917                                             unsigned AS) const {
26918   // Scaling factors are not free at all.
26919   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26920   // will take 2 allocations in the out of order engine instead of 1
26921   // for plain addressing mode, i.e. inst (reg1).
26922   // E.g.,
26923   // vaddps (%rsi,%drx), %ymm0, %ymm1
26924   // Requires two allocations (one for the load, one for the computation)
26925   // whereas:
26926   // vaddps (%rsi), %ymm0, %ymm1
26927   // Requires just 1 allocation, i.e., freeing allocations for other operations
26928   // and having less micro operations to execute.
26929   //
26930   // For some X86 architectures, this is even worse because for instance for
26931   // stores, the complex addressing mode forces the instruction to use the
26932   // "load" ports instead of the dedicated "store" port.
26933   // E.g., on Haswell:
26934   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26935   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26936   if (isLegalAddressingMode(DL, AM, Ty, AS))
26937     // Scale represents reg2 * scale, thus account for 1
26938     // as soon as we use a second register.
26939     return AM.Scale != 0;
26940   return -1;
26941 }
26942
26943 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26944   // Integer division on x86 is expensive. However, when aggressively optimizing
26945   // for code size, we prefer to use a div instruction, as it is usually smaller
26946   // than the alternative sequence.
26947   // The exception to this is vector division. Since x86 doesn't have vector
26948   // integer division, leaving the division as-is is a loss even in terms of
26949   // size, because it will have to be scalarized, while the alternative code
26950   // sequence can be performed in vector form.
26951   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26952                                    Attribute::MinSize);
26953   return OptSize && !VT.isVector();
26954 }