AVX512: Implemented encoding and intrinsics for VGETMANTPD/S , VGETMANTSD/S instructions
[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   setOperationAction(ISD::CATCHRET        , MVT::Other, Custom);
421   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
422   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
423   // support continuation, user-level threading, and etc.. As a result, no
424   // other SjLj exception interfaces are implemented and please don't build
425   // your own exception handling based on them.
426   // LLVM/Clang supports zero-cost DWARF exception handling.
427   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
428   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
429
430   // Darwin ABI issue.
431   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
432   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
433   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
435   if (Subtarget->is64Bit())
436     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
437   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
438   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
439   if (Subtarget->is64Bit()) {
440     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
441     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
442     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
443     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
444     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
445   }
446   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
447   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
448   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
450   if (Subtarget->is64Bit()) {
451     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
452     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
454   }
455
456   if (Subtarget->hasSSE1())
457     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
458
459   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
460
461   // Expand certain atomics
462   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
463     MVT VT = IntVTs[i];
464     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
465     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
466     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
467   }
468
469   if (Subtarget->hasCmpxchg16b()) {
470     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
471   }
472
473   // FIXME - use subtarget debug flags
474   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
475       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
476     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
477   }
478
479   if (Subtarget->isTarget64BitLP64()) {
480     setExceptionPointerRegister(X86::RAX);
481     setExceptionSelectorRegister(X86::RDX);
482   } else {
483     setExceptionPointerRegister(X86::EAX);
484     setExceptionSelectorRegister(X86::EDX);
485   }
486   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
488
489   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
491
492   setOperationAction(ISD::TRAP, MVT::Other, Legal);
493   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
494
495   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
497   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
498   if (Subtarget->is64Bit()) {
499     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
500     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
501   } else {
502     // TargetInfo::CharPtrBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
505   }
506
507   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
508   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
509
510   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
511
512   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
515
516   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!Subtarget->useSoftFloat()) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!Subtarget->useSoftFloat()) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749
750       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
751       // split/scalarized right now.
752       if (VT.getVectorElementType() == MVT::f16)
753         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754     }
755   }
756
757   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
758   // with -msoft-float, disable use of MMX as well.
759   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
760     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
761     // No operations on x86mmx supported, everything uses intrinsics.
762   }
763
764   // MMX-sized vectors (other than x86mmx) are expected to be expanded
765   // into smaller operations.
766   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
767     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
768     setOperationAction(ISD::AND,                MMXTy,      Expand);
769     setOperationAction(ISD::OR,                 MMXTy,      Expand);
770     setOperationAction(ISD::XOR,                MMXTy,      Expand);
771     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
772     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
773     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
774   }
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776
777   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
778     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779
780     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
785     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
786     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
787     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
788     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
789     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
790     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
793     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
794   }
795
796   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
797     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798
799     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
800     // registers cannot be used even for integer operations.
801     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
802     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
803     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
804     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805
806     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
807     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
808     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
809     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
810     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
811     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
812     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
813     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
816     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
829
830     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
832     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
833     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
834
835     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
839
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
845
846     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
850
851     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
852     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
853       MVT VT = (MVT::SimpleValueType)i;
854       // Do not attempt to custom lower non-power-of-2 vectors
855       if (!isPowerOf2_32(VT.getVectorNumElements()))
856         continue;
857       // Do not attempt to custom lower non-128-bit vectors
858       if (!VT.is128BitVector())
859         continue;
860       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
862       setOperationAction(ISD::VSELECT,            VT, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864     }
865
866     // We support custom legalizing of sext and anyext loads for specific
867     // memory vector types which we can load as a scalar (or sequence of
868     // scalars) and extend in-register to a legal 128-bit vector type. For sext
869     // loads these must work with a single scalar load.
870     for (MVT VT : MVT::integer_vector_valuetypes()) {
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
880     }
881
882     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
884     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
886     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
887     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
888     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
889     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
890
891     if (Subtarget->is64Bit()) {
892       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
893       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894     }
895
896     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
897     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
898       MVT VT = (MVT::SimpleValueType)i;
899
900       // Do not attempt to promote non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903
904       setOperationAction(ISD::AND,    VT, Promote);
905       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
906       setOperationAction(ISD::OR,     VT, Promote);
907       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    VT, Promote);
909       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   VT, Promote);
911       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, VT, Promote);
913       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914     }
915
916     // Custom lower v2i64 and v2f64 selects.
917     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
918     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
919     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
920     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
921
922     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
924
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
958     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
960     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
962
963     // FIXME: Do we need to handle scalar-to-vector here?
964     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
965
966     // We directly match byte blends in the backend as they match the VSELECT
967     // condition form.
968     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
969
970     // SSE41 brings specific instructions for doing vector sign extend even in
971     // cases where we don't have SRA.
972     for (MVT VT : MVT::integer_vector_valuetypes()) {
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976     }
977
978     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
985
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
992
993     // i8 and i16 vectors are custom because the source register and source
994     // source memory operand types are not the same width.  f32 vectors are
995     // custom since the immediate controlling the insert encodes additional
996     // information.
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1001
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1006
1007     // FIXME: these should be Legal, but that's only for the case where
1008     // the index is constant.  For now custom expand to deal with that.
1009     if (Subtarget->is64Bit()) {
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1012     }
1013   }
1014
1015   if (Subtarget->hasSSE2()) {
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1019
1020     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1022
1023     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1024     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1025
1026     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1027     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1028
1029     // In the customized shift lowering, the legal cases in AVX2 will be
1030     // recognized.
1031     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1033
1034     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1035     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1036
1037     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1038     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1039   }
1040
1041   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1042     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1044     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1046     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1047     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1048
1049     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1052
1053     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1056     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1061     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1063     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1064     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1065
1066     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1069     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1070     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1076     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1077     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1078
1079     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1080     // even though v8i16 is a legal type.
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1082     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1084
1085     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1086     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1087     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1090     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1091
1092     for (MVT VT : MVT::fp_vector_valuetypes())
1093       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1094
1095     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1099     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1100
1101     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1102     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1103
1104     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1106     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1107     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1108
1109     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1110     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1111     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1112
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1114     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1115     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1117     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1118     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1120     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1121     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1123     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1124     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1125
1126     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1128     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1129     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1130
1131     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1132       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1136       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1137       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1138     }
1139
1140     if (Subtarget->hasInt256()) {
1141       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1143       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1144       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1145
1146       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1148       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1149       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1150
1151       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1152       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1153       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1154       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1155
1156       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1157       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1158       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1159       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1160
1161       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1168       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1169       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1171       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1172       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1173
1174       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1175       // when we have a 256bit-wide blend with immediate.
1176       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1177
1178       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1183       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1184       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1185
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1190       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1191       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1192     } else {
1193       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1197
1198       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1202
1203       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1207
1208       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1209       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1210       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1211       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1212       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1213       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1214       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1215       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1216       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1217       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1218       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1219       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1220     }
1221
1222     // In the customized shift lowering, the legal cases in AVX2 will be
1223     // recognized.
1224     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1226
1227     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1228     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1229
1230     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1231     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1232
1233     // Custom lower several nodes for 256-bit types.
1234     for (MVT VT : MVT::vector_valuetypes()) {
1235       if (VT.getScalarSizeInBits() >= 32) {
1236         setOperationAction(ISD::MLOAD,  VT, Legal);
1237         setOperationAction(ISD::MSTORE, VT, Legal);
1238       }
1239       // Extract subvector is special because the value type
1240       // (result) is 128-bit but the source is 256-bit wide.
1241       if (VT.is128BitVector()) {
1242         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1243       }
1244       // Do not attempt to custom lower other non-256-bit vectors
1245       if (!VT.is256BitVector())
1246         continue;
1247
1248       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1249       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1250       setOperationAction(ISD::VSELECT,            VT, Custom);
1251       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1252       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1253       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1254       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1255       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1256     }
1257
1258     if (Subtarget->hasInt256())
1259       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1260
1261
1262     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1263     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1264       MVT VT = (MVT::SimpleValueType)i;
1265
1266       // Do not attempt to promote non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::AND,    VT, Promote);
1271       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1272       setOperationAction(ISD::OR,     VT, Promote);
1273       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1274       setOperationAction(ISD::XOR,    VT, Promote);
1275       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1276       setOperationAction(ISD::LOAD,   VT, Promote);
1277       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1278       setOperationAction(ISD::SELECT, VT, Promote);
1279       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1280     }
1281   }
1282
1283   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1284     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1285     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1286     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1287     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1288
1289     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1290     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1291     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1292
1293     for (MVT VT : MVT::fp_vector_valuetypes())
1294       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1295
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1299     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1301     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1303     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1304     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1305     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1306     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1307     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1308
1309     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1310     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1311     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1312     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1313     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1314     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1315     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1316     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1317     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1322
1323     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1329
1330     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1336     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1337     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1338
1339     // FIXME:  [US]INT_TO_FP are not legal for f80.
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1342     if (Subtarget->is64Bit()) {
1343       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1344       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1345     }
1346     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1347     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1349     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1352     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1360     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1361     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1362
1363     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1364     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1365     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1366     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1367     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1368     if (Subtarget->hasVLX()){
1369       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1370       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1371       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1372       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1373       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1374
1375       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1376       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1377       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1378       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1379       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1380     }
1381     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1382     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1384     if (Subtarget->hasDQI()) {
1385       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1386       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1387
1388       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1389       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1390       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1391       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1392       if (Subtarget->hasVLX()) {
1393         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1394         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1395         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1396         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1397         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1398         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1399         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1400         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1401       }
1402     }
1403     if (Subtarget->hasVLX()) {
1404       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1406       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1408       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1409       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1411       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1412     }
1413     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1414     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1415     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1416     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1417     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1418     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1419     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1422     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1424     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1425     if (Subtarget->hasDQI()) {
1426       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1427       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1428     }
1429     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1430     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1431     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1432     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1433     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1434     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1435     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1436     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1437     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1438     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1439
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1462
1463     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1464     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1465     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1466     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1467     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1468     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1469     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1470     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1471
1472     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1474
1475     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1477
1478     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1481     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1482
1483     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1487     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1488
1489     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1492     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1493     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1494     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1495
1496     if (Subtarget->hasCDI()) {
1497       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1498       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1499     }
1500     if (Subtarget->hasDQI()) {
1501       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1502       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1503       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1504     }
1505     // Custom lower several nodes.
1506     for (MVT VT : MVT::vector_valuetypes()) {
1507       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1508       if (EltSize == 1) {
1509         setOperationAction(ISD::AND, VT, Legal);
1510         setOperationAction(ISD::OR,  VT, Legal);
1511         setOperationAction(ISD::XOR,  VT, Legal);
1512       }
1513       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1514         setOperationAction(ISD::MGATHER,  VT, Custom);
1515         setOperationAction(ISD::MSCATTER, VT, Custom);
1516       }
1517       // Extract subvector is special because the value type
1518       // (result) is 256/128-bit but the source is 512-bit wide.
1519       if (VT.is128BitVector() || VT.is256BitVector()) {
1520         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1521       }
1522       if (VT.getVectorElementType() == MVT::i1)
1523         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1524
1525       // Do not attempt to custom lower other non-512-bit vectors
1526       if (!VT.is512BitVector())
1527         continue;
1528
1529       if (EltSize >= 32) {
1530         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1531         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1532         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1533         setOperationAction(ISD::VSELECT,             VT, Legal);
1534         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1535         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1536         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1537         setOperationAction(ISD::MLOAD,               VT, Legal);
1538         setOperationAction(ISD::MSTORE,              VT, Legal);
1539       }
1540     }
1541     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1542       MVT VT = (MVT::SimpleValueType)i;
1543
1544       // Do not attempt to promote non-512-bit vectors.
1545       if (!VT.is512BitVector())
1546         continue;
1547
1548       setOperationAction(ISD::SELECT, VT, Promote);
1549       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1550     }
1551   }// has  AVX-512
1552
1553   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1554     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1555     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1556
1557     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1558     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1559
1560     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1561     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1562     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1563     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1564     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1565     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1566     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1567     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1568     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1569     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1570     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1571     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1572     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1573     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1574     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1575     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1576     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1577     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1578     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1579     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1580     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1581     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1582     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1583     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1584     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1585     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1586     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1587     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1588     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1589     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1590
1591     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1592     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1593     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1594     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1595     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1596     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1597     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1598     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1599
1600     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1601     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1602     if (Subtarget->hasVLX())
1603       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1604
1605     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1606       const MVT VT = (MVT::SimpleValueType)i;
1607
1608       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1609
1610       // Do not attempt to promote non-512-bit vectors.
1611       if (!VT.is512BitVector())
1612         continue;
1613
1614       if (EltSize < 32) {
1615         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1616         setOperationAction(ISD::VSELECT,             VT, Legal);
1617       }
1618     }
1619   }
1620
1621   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1622     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1623     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1624
1625     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1626     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1627     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1628     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1629     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1630     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1631     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1632     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1633     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1634     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1635
1636     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1637     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1638     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1639     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1640     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1641     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1642     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1643     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1644
1645     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1646     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1647     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1648     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1649     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1650     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1651     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1652     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1653   }
1654
1655   // We want to custom lower some of our intrinsics.
1656   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1657   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1658   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1659   if (!Subtarget->is64Bit())
1660     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1661
1662   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1663   // handle type legalization for these operations here.
1664   //
1665   // FIXME: We really should do custom legalization for addition and
1666   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1667   // than generic legalization for 64-bit multiplication-with-overflow, though.
1668   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1669     // Add/Sub/Mul with overflow operations are custom lowered.
1670     MVT VT = IntVTs[i];
1671     setOperationAction(ISD::SADDO, VT, Custom);
1672     setOperationAction(ISD::UADDO, VT, Custom);
1673     setOperationAction(ISD::SSUBO, VT, Custom);
1674     setOperationAction(ISD::USUBO, VT, Custom);
1675     setOperationAction(ISD::SMULO, VT, Custom);
1676     setOperationAction(ISD::UMULO, VT, Custom);
1677   }
1678
1679
1680   if (!Subtarget->is64Bit()) {
1681     // These libcalls are not available in 32-bit.
1682     setLibcallName(RTLIB::SHL_I128, nullptr);
1683     setLibcallName(RTLIB::SRL_I128, nullptr);
1684     setLibcallName(RTLIB::SRA_I128, nullptr);
1685   }
1686
1687   // Combine sin / cos into one node or libcall if possible.
1688   if (Subtarget->hasSinCos()) {
1689     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1690     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1691     if (Subtarget->isTargetDarwin()) {
1692       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1693       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1694       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1695       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1696     }
1697   }
1698
1699   if (Subtarget->isTargetWin64()) {
1700     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1701     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1702     setOperationAction(ISD::SREM, MVT::i128, Custom);
1703     setOperationAction(ISD::UREM, MVT::i128, Custom);
1704     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1705     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1706   }
1707
1708   // We have target-specific dag combine patterns for the following nodes:
1709   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1710   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1711   setTargetDAGCombine(ISD::BITCAST);
1712   setTargetDAGCombine(ISD::VSELECT);
1713   setTargetDAGCombine(ISD::SELECT);
1714   setTargetDAGCombine(ISD::SHL);
1715   setTargetDAGCombine(ISD::SRA);
1716   setTargetDAGCombine(ISD::SRL);
1717   setTargetDAGCombine(ISD::OR);
1718   setTargetDAGCombine(ISD::AND);
1719   setTargetDAGCombine(ISD::ADD);
1720   setTargetDAGCombine(ISD::FADD);
1721   setTargetDAGCombine(ISD::FSUB);
1722   setTargetDAGCombine(ISD::FMA);
1723   setTargetDAGCombine(ISD::SUB);
1724   setTargetDAGCombine(ISD::LOAD);
1725   setTargetDAGCombine(ISD::MLOAD);
1726   setTargetDAGCombine(ISD::STORE);
1727   setTargetDAGCombine(ISD::MSTORE);
1728   setTargetDAGCombine(ISD::ZERO_EXTEND);
1729   setTargetDAGCombine(ISD::ANY_EXTEND);
1730   setTargetDAGCombine(ISD::SIGN_EXTEND);
1731   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1732   setTargetDAGCombine(ISD::SINT_TO_FP);
1733   setTargetDAGCombine(ISD::UINT_TO_FP);
1734   setTargetDAGCombine(ISD::SETCC);
1735   setTargetDAGCombine(ISD::BUILD_VECTOR);
1736   setTargetDAGCombine(ISD::MUL);
1737   setTargetDAGCombine(ISD::XOR);
1738
1739   computeRegisterProperties(Subtarget->getRegisterInfo());
1740
1741   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1742   MaxStoresPerMemsetOptSize = 8;
1743   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1744   MaxStoresPerMemcpyOptSize = 4;
1745   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1746   MaxStoresPerMemmoveOptSize = 4;
1747   setPrefLoopAlignment(4); // 2^4 bytes.
1748
1749   // Predictable cmov don't hurt on atom because it's in-order.
1750   PredictableSelectIsExpensive = !Subtarget->isAtom();
1751   EnableExtLdPromotion = true;
1752   setPrefFunctionAlignment(4); // 2^4 bytes.
1753
1754   verifyIntrinsicTables();
1755 }
1756
1757 // This has so far only been implemented for 64-bit MachO.
1758 bool X86TargetLowering::useLoadStackGuardNode() const {
1759   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1760 }
1761
1762 TargetLoweringBase::LegalizeTypeAction
1763 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1764   if (ExperimentalVectorWideningLegalization &&
1765       VT.getVectorNumElements() != 1 &&
1766       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1767     return TypeWidenVector;
1768
1769   return TargetLoweringBase::getPreferredVectorAction(VT);
1770 }
1771
1772 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1773                                           EVT VT) const {
1774   if (!VT.isVector())
1775     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1776
1777   const unsigned NumElts = VT.getVectorNumElements();
1778   const EVT EltVT = VT.getVectorElementType();
1779   if (VT.is512BitVector()) {
1780     if (Subtarget->hasAVX512())
1781       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1782           EltVT == MVT::f32 || EltVT == MVT::f64)
1783         switch(NumElts) {
1784         case  8: return MVT::v8i1;
1785         case 16: return MVT::v16i1;
1786       }
1787     if (Subtarget->hasBWI())
1788       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1789         switch(NumElts) {
1790         case 32: return MVT::v32i1;
1791         case 64: return MVT::v64i1;
1792       }
1793   }
1794
1795   if (VT.is256BitVector() || VT.is128BitVector()) {
1796     if (Subtarget->hasVLX())
1797       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1798           EltVT == MVT::f32 || EltVT == MVT::f64)
1799         switch(NumElts) {
1800         case 2: return MVT::v2i1;
1801         case 4: return MVT::v4i1;
1802         case 8: return MVT::v8i1;
1803       }
1804     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1805       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1806         switch(NumElts) {
1807         case  8: return MVT::v8i1;
1808         case 16: return MVT::v16i1;
1809         case 32: return MVT::v32i1;
1810       }
1811   }
1812
1813   return VT.changeVectorElementTypeToInteger();
1814 }
1815
1816 /// Helper for getByValTypeAlignment to determine
1817 /// the desired ByVal argument alignment.
1818 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1819   if (MaxAlign == 16)
1820     return;
1821   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1822     if (VTy->getBitWidth() == 128)
1823       MaxAlign = 16;
1824   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1825     unsigned EltAlign = 0;
1826     getMaxByValAlign(ATy->getElementType(), EltAlign);
1827     if (EltAlign > MaxAlign)
1828       MaxAlign = EltAlign;
1829   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1830     for (auto *EltTy : STy->elements()) {
1831       unsigned EltAlign = 0;
1832       getMaxByValAlign(EltTy, EltAlign);
1833       if (EltAlign > MaxAlign)
1834         MaxAlign = EltAlign;
1835       if (MaxAlign == 16)
1836         break;
1837     }
1838   }
1839 }
1840
1841 /// Return the desired alignment for ByVal aggregate
1842 /// function arguments in the caller parameter area. For X86, aggregates
1843 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1844 /// are at 4-byte boundaries.
1845 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1846                                                   const DataLayout &DL) const {
1847   if (Subtarget->is64Bit()) {
1848     // Max of 8 and alignment of type.
1849     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1850     if (TyAlign > 8)
1851       return TyAlign;
1852     return 8;
1853   }
1854
1855   unsigned Align = 4;
1856   if (Subtarget->hasSSE1())
1857     getMaxByValAlign(Ty, Align);
1858   return Align;
1859 }
1860
1861 /// Returns the target specific optimal type for load
1862 /// and store operations as a result of memset, memcpy, and memmove
1863 /// lowering. If DstAlign is zero that means it's safe to destination
1864 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1865 /// means there isn't a need to check it against alignment requirement,
1866 /// probably because the source does not need to be loaded. If 'IsMemset' is
1867 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1868 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1869 /// source is constant so it does not need to be loaded.
1870 /// It returns EVT::Other if the type should be determined using generic
1871 /// target-independent logic.
1872 EVT
1873 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1874                                        unsigned DstAlign, unsigned SrcAlign,
1875                                        bool IsMemset, bool ZeroMemset,
1876                                        bool MemcpyStrSrc,
1877                                        MachineFunction &MF) const {
1878   const Function *F = MF.getFunction();
1879   if ((!IsMemset || ZeroMemset) &&
1880       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1881     if (Size >= 16 &&
1882         (!Subtarget->isUnalignedMem16Slow() ||
1883          ((DstAlign == 0 || DstAlign >= 16) &&
1884           (SrcAlign == 0 || SrcAlign >= 16)))) {
1885       if (Size >= 32) {
1886         // FIXME: Check if unaligned 32-byte accesses are slow.
1887         if (Subtarget->hasInt256())
1888           return MVT::v8i32;
1889         if (Subtarget->hasFp256())
1890           return MVT::v8f32;
1891       }
1892       if (Subtarget->hasSSE2())
1893         return MVT::v4i32;
1894       if (Subtarget->hasSSE1())
1895         return MVT::v4f32;
1896     } else if (!MemcpyStrSrc && Size >= 8 &&
1897                !Subtarget->is64Bit() &&
1898                Subtarget->hasSSE2()) {
1899       // Do not use f64 to lower memcpy if source is string constant. It's
1900       // better to use i32 to avoid the loads.
1901       return MVT::f64;
1902     }
1903   }
1904   // This is a compromise. If we reach here, unaligned accesses may be slow on
1905   // this target. However, creating smaller, aligned accesses could be even
1906   // slower and would certainly be a lot more code.
1907   if (Subtarget->is64Bit() && Size >= 8)
1908     return MVT::i64;
1909   return MVT::i32;
1910 }
1911
1912 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1913   if (VT == MVT::f32)
1914     return X86ScalarSSEf32;
1915   else if (VT == MVT::f64)
1916     return X86ScalarSSEf64;
1917   return true;
1918 }
1919
1920 bool
1921 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1922                                                   unsigned,
1923                                                   unsigned,
1924                                                   bool *Fast) const {
1925   if (Fast) {
1926     if (VT.getSizeInBits() == 256)
1927       *Fast = !Subtarget->isUnalignedMem32Slow();
1928     else
1929       // FIXME: We should always return that 8-byte and under accesses are fast.
1930       // That is what other x86 lowering code assumes.
1931       *Fast = !Subtarget->isUnalignedMem16Slow();
1932   }
1933   return true;
1934 }
1935
1936 /// Return the entry encoding for a jump table in the
1937 /// current function.  The returned value is a member of the
1938 /// MachineJumpTableInfo::JTEntryKind enum.
1939 unsigned X86TargetLowering::getJumpTableEncoding() const {
1940   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1941   // symbol.
1942   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1943       Subtarget->isPICStyleGOT())
1944     return MachineJumpTableInfo::EK_Custom32;
1945
1946   // Otherwise, use the normal jump table encoding heuristics.
1947   return TargetLowering::getJumpTableEncoding();
1948 }
1949
1950 bool X86TargetLowering::useSoftFloat() const {
1951   return Subtarget->useSoftFloat();
1952 }
1953
1954 const MCExpr *
1955 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1956                                              const MachineBasicBlock *MBB,
1957                                              unsigned uid,MCContext &Ctx) const{
1958   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1959          Subtarget->isPICStyleGOT());
1960   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1961   // entries.
1962   return MCSymbolRefExpr::create(MBB->getSymbol(),
1963                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1964 }
1965
1966 /// Returns relocation base for the given PIC jumptable.
1967 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1968                                                     SelectionDAG &DAG) const {
1969   if (!Subtarget->is64Bit())
1970     // This doesn't have SDLoc associated with it, but is not really the
1971     // same as a Register.
1972     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1973                        getPointerTy(DAG.getDataLayout()));
1974   return Table;
1975 }
1976
1977 /// This returns the relocation base for the given PIC jumptable,
1978 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1979 const MCExpr *X86TargetLowering::
1980 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1981                              MCContext &Ctx) const {
1982   // X86-64 uses RIP relative addressing based on the jump table label.
1983   if (Subtarget->isPICStyleRIPRel())
1984     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1985
1986   // Otherwise, the reference is relative to the PIC base.
1987   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1988 }
1989
1990 std::pair<const TargetRegisterClass *, uint8_t>
1991 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1992                                            MVT VT) const {
1993   const TargetRegisterClass *RRC = nullptr;
1994   uint8_t Cost = 1;
1995   switch (VT.SimpleTy) {
1996   default:
1997     return TargetLowering::findRepresentativeClass(TRI, VT);
1998   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1999     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2000     break;
2001   case MVT::x86mmx:
2002     RRC = &X86::VR64RegClass;
2003     break;
2004   case MVT::f32: case MVT::f64:
2005   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2006   case MVT::v4f32: case MVT::v2f64:
2007   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2008   case MVT::v4f64:
2009     RRC = &X86::VR128RegClass;
2010     break;
2011   }
2012   return std::make_pair(RRC, Cost);
2013 }
2014
2015 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2016                                                unsigned &Offset) const {
2017   if (!Subtarget->isTargetLinux())
2018     return false;
2019
2020   if (Subtarget->is64Bit()) {
2021     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2022     Offset = 0x28;
2023     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2024       AddressSpace = 256;
2025     else
2026       AddressSpace = 257;
2027   } else {
2028     // %gs:0x14 on i386
2029     Offset = 0x14;
2030     AddressSpace = 256;
2031   }
2032   return true;
2033 }
2034
2035 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2036                                             unsigned DestAS) const {
2037   assert(SrcAS != DestAS && "Expected different address spaces!");
2038
2039   return SrcAS < 256 && DestAS < 256;
2040 }
2041
2042 //===----------------------------------------------------------------------===//
2043 //               Return Value Calling Convention Implementation
2044 //===----------------------------------------------------------------------===//
2045
2046 #include "X86GenCallingConv.inc"
2047
2048 bool
2049 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2050                                   MachineFunction &MF, bool isVarArg,
2051                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2052                         LLVMContext &Context) const {
2053   SmallVector<CCValAssign, 16> RVLocs;
2054   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2055   return CCInfo.CheckReturn(Outs, RetCC_X86);
2056 }
2057
2058 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2059   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2060   return ScratchRegs;
2061 }
2062
2063 SDValue
2064 X86TargetLowering::LowerReturn(SDValue Chain,
2065                                CallingConv::ID CallConv, bool isVarArg,
2066                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2067                                const SmallVectorImpl<SDValue> &OutVals,
2068                                SDLoc dl, SelectionDAG &DAG) const {
2069   MachineFunction &MF = DAG.getMachineFunction();
2070   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2071
2072   SmallVector<CCValAssign, 16> RVLocs;
2073   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2074   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2075
2076   SDValue Flag;
2077   SmallVector<SDValue, 6> RetOps;
2078   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2079   // Operand #1 = Bytes To Pop
2080   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2081                    MVT::i16));
2082
2083   // Copy the result values into the output registers.
2084   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2085     CCValAssign &VA = RVLocs[i];
2086     assert(VA.isRegLoc() && "Can only return in registers!");
2087     SDValue ValToCopy = OutVals[i];
2088     EVT ValVT = ValToCopy.getValueType();
2089
2090     // Promote values to the appropriate types.
2091     if (VA.getLocInfo() == CCValAssign::SExt)
2092       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2093     else if (VA.getLocInfo() == CCValAssign::ZExt)
2094       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2095     else if (VA.getLocInfo() == CCValAssign::AExt) {
2096       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2097         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2098       else
2099         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2100     }
2101     else if (VA.getLocInfo() == CCValAssign::BCvt)
2102       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2103
2104     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2105            "Unexpected FP-extend for return value.");
2106
2107     // If this is x86-64, and we disabled SSE, we can't return FP values,
2108     // or SSE or MMX vectors.
2109     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2110          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2111           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2112       report_fatal_error("SSE register return with SSE disabled");
2113     }
2114     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2115     // llvm-gcc has never done it right and no one has noticed, so this
2116     // should be OK for now.
2117     if (ValVT == MVT::f64 &&
2118         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2119       report_fatal_error("SSE2 register return with SSE2 disabled");
2120
2121     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2122     // the RET instruction and handled by the FP Stackifier.
2123     if (VA.getLocReg() == X86::FP0 ||
2124         VA.getLocReg() == X86::FP1) {
2125       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2126       // change the value to the FP stack register class.
2127       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2128         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2129       RetOps.push_back(ValToCopy);
2130       // Don't emit a copytoreg.
2131       continue;
2132     }
2133
2134     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2135     // which is returned in RAX / RDX.
2136     if (Subtarget->is64Bit()) {
2137       if (ValVT == MVT::x86mmx) {
2138         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2139           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2140           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2141                                   ValToCopy);
2142           // If we don't have SSE2 available, convert to v4f32 so the generated
2143           // register is legal.
2144           if (!Subtarget->hasSSE2())
2145             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2146         }
2147       }
2148     }
2149
2150     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2151     Flag = Chain.getValue(1);
2152     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2153   }
2154
2155   // All x86 ABIs require that for returning structs by value we copy
2156   // the sret argument into %rax/%eax (depending on ABI) for the return.
2157   // We saved the argument into a virtual register in the entry block,
2158   // so now we copy the value out and into %rax/%eax.
2159   //
2160   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2161   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2162   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2163   // either case FuncInfo->setSRetReturnReg() will have been called.
2164   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2165     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2166                                      getPointerTy(MF.getDataLayout()));
2167
2168     unsigned RetValReg
2169         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2170           X86::RAX : X86::EAX;
2171     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2172     Flag = Chain.getValue(1);
2173
2174     // RAX/EAX now acts like a return value.
2175     RetOps.push_back(
2176         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2177   }
2178
2179   RetOps[0] = Chain;  // Update chain.
2180
2181   // Add the flag if we have it.
2182   if (Flag.getNode())
2183     RetOps.push_back(Flag);
2184
2185   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2186 }
2187
2188 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2189   if (N->getNumValues() != 1)
2190     return false;
2191   if (!N->hasNUsesOfValue(1, 0))
2192     return false;
2193
2194   SDValue TCChain = Chain;
2195   SDNode *Copy = *N->use_begin();
2196   if (Copy->getOpcode() == ISD::CopyToReg) {
2197     // If the copy has a glue operand, we conservatively assume it isn't safe to
2198     // perform a tail call.
2199     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2200       return false;
2201     TCChain = Copy->getOperand(0);
2202   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2203     return false;
2204
2205   bool HasRet = false;
2206   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2207        UI != UE; ++UI) {
2208     if (UI->getOpcode() != X86ISD::RET_FLAG)
2209       return false;
2210     // If we are returning more than one value, we can definitely
2211     // not make a tail call see PR19530
2212     if (UI->getNumOperands() > 4)
2213       return false;
2214     if (UI->getNumOperands() == 4 &&
2215         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2216       return false;
2217     HasRet = true;
2218   }
2219
2220   if (!HasRet)
2221     return false;
2222
2223   Chain = TCChain;
2224   return true;
2225 }
2226
2227 EVT
2228 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2229                                             ISD::NodeType ExtendKind) const {
2230   MVT ReturnMVT;
2231   // TODO: Is this also valid on 32-bit?
2232   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2233     ReturnMVT = MVT::i8;
2234   else
2235     ReturnMVT = MVT::i32;
2236
2237   EVT MinVT = getRegisterType(Context, ReturnMVT);
2238   return VT.bitsLT(MinVT) ? MinVT : VT;
2239 }
2240
2241 /// Lower the result values of a call into the
2242 /// appropriate copies out of appropriate physical registers.
2243 ///
2244 SDValue
2245 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2246                                    CallingConv::ID CallConv, bool isVarArg,
2247                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2248                                    SDLoc dl, SelectionDAG &DAG,
2249                                    SmallVectorImpl<SDValue> &InVals) const {
2250
2251   // Assign locations to each value returned by this call.
2252   SmallVector<CCValAssign, 16> RVLocs;
2253   bool Is64Bit = Subtarget->is64Bit();
2254   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2255                  *DAG.getContext());
2256   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2257
2258   // Copy all of the result registers out of their specified physreg.
2259   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2260     CCValAssign &VA = RVLocs[i];
2261     EVT CopyVT = VA.getLocVT();
2262
2263     // If this is x86-64, and we disabled SSE, we can't return FP values
2264     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2265         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2266       report_fatal_error("SSE register return with SSE disabled");
2267     }
2268
2269     // If we prefer to use the value in xmm registers, copy it out as f80 and
2270     // use a truncate to move it from fp stack reg to xmm reg.
2271     bool RoundAfterCopy = false;
2272     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2273         isScalarFPTypeInSSEReg(VA.getValVT())) {
2274       CopyVT = MVT::f80;
2275       RoundAfterCopy = (CopyVT != VA.getLocVT());
2276     }
2277
2278     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2279                                CopyVT, InFlag).getValue(1);
2280     SDValue Val = Chain.getValue(0);
2281
2282     if (RoundAfterCopy)
2283       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2284                         // This truncation won't change the value.
2285                         DAG.getIntPtrConstant(1, dl));
2286
2287     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2288       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2289
2290     InFlag = Chain.getValue(2);
2291     InVals.push_back(Val);
2292   }
2293
2294   return Chain;
2295 }
2296
2297 //===----------------------------------------------------------------------===//
2298 //                C & StdCall & Fast Calling Convention implementation
2299 //===----------------------------------------------------------------------===//
2300 //  StdCall calling convention seems to be standard for many Windows' API
2301 //  routines and around. It differs from C calling convention just a little:
2302 //  callee should clean up the stack, not caller. Symbols should be also
2303 //  decorated in some fancy way :) It doesn't support any vector arguments.
2304 //  For info on fast calling convention see Fast Calling Convention (tail call)
2305 //  implementation LowerX86_32FastCCCallTo.
2306
2307 /// CallIsStructReturn - Determines whether a call uses struct return
2308 /// semantics.
2309 enum StructReturnType {
2310   NotStructReturn,
2311   RegStructReturn,
2312   StackStructReturn
2313 };
2314 static StructReturnType
2315 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2316   if (Outs.empty())
2317     return NotStructReturn;
2318
2319   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2320   if (!Flags.isSRet())
2321     return NotStructReturn;
2322   if (Flags.isInReg())
2323     return RegStructReturn;
2324   return StackStructReturn;
2325 }
2326
2327 /// Determines whether a function uses struct return semantics.
2328 static StructReturnType
2329 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2330   if (Ins.empty())
2331     return NotStructReturn;
2332
2333   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2334   if (!Flags.isSRet())
2335     return NotStructReturn;
2336   if (Flags.isInReg())
2337     return RegStructReturn;
2338   return StackStructReturn;
2339 }
2340
2341 /// Make a copy of an aggregate at address specified by "Src" to address
2342 /// "Dst" with size and alignment information specified by the specific
2343 /// parameter attribute. The copy will be passed as a byval function parameter.
2344 static SDValue
2345 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2346                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2347                           SDLoc dl) {
2348   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2349
2350   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2351                        /*isVolatile*/false, /*AlwaysInline=*/true,
2352                        /*isTailCall*/false,
2353                        MachinePointerInfo(), MachinePointerInfo());
2354 }
2355
2356 /// Return true if the calling convention is one that
2357 /// supports tail call optimization.
2358 static bool IsTailCallConvention(CallingConv::ID CC) {
2359   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2360           CC == CallingConv::HiPE);
2361 }
2362
2363 /// \brief Return true if the calling convention is a C calling convention.
2364 static bool IsCCallConvention(CallingConv::ID CC) {
2365   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2366           CC == CallingConv::X86_64_SysV);
2367 }
2368
2369 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2370   auto Attr =
2371       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2372   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2373     return false;
2374
2375   CallSite CS(CI);
2376   CallingConv::ID CalleeCC = CS.getCallingConv();
2377   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2378     return false;
2379
2380   return true;
2381 }
2382
2383 /// Return true if the function is being made into
2384 /// a tailcall target by changing its ABI.
2385 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2386                                    bool GuaranteedTailCallOpt) {
2387   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2388 }
2389
2390 SDValue
2391 X86TargetLowering::LowerMemArgument(SDValue Chain,
2392                                     CallingConv::ID CallConv,
2393                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2394                                     SDLoc dl, SelectionDAG &DAG,
2395                                     const CCValAssign &VA,
2396                                     MachineFrameInfo *MFI,
2397                                     unsigned i) const {
2398   // Create the nodes corresponding to a load from this parameter slot.
2399   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2400   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2401       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2402   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2403   EVT ValVT;
2404
2405   // If value is passed by pointer we have address passed instead of the value
2406   // itself.
2407   bool ExtendedInMem = VA.isExtInLoc() &&
2408     VA.getValVT().getScalarType() == MVT::i1;
2409
2410   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2411     ValVT = VA.getLocVT();
2412   else
2413     ValVT = VA.getValVT();
2414
2415   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2416   // changed with more analysis.
2417   // In case of tail call optimization mark all arguments mutable. Since they
2418   // could be overwritten by lowering of arguments in case of a tail call.
2419   if (Flags.isByVal()) {
2420     unsigned Bytes = Flags.getByValSize();
2421     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2422     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2423     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2424   } else {
2425     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2426                                     VA.getLocMemOffset(), isImmutable);
2427     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2428     SDValue Val = DAG.getLoad(
2429         ValVT, dl, Chain, FIN,
2430         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2431         false, false, 0);
2432     return ExtendedInMem ?
2433       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2434   }
2435 }
2436
2437 // FIXME: Get this from tablegen.
2438 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2439                                                 const X86Subtarget *Subtarget) {
2440   assert(Subtarget->is64Bit());
2441
2442   if (Subtarget->isCallingConvWin64(CallConv)) {
2443     static const MCPhysReg GPR64ArgRegsWin64[] = {
2444       X86::RCX, X86::RDX, X86::R8,  X86::R9
2445     };
2446     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2447   }
2448
2449   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2450     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2451   };
2452   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2453 }
2454
2455 // FIXME: Get this from tablegen.
2456 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2457                                                 CallingConv::ID CallConv,
2458                                                 const X86Subtarget *Subtarget) {
2459   assert(Subtarget->is64Bit());
2460   if (Subtarget->isCallingConvWin64(CallConv)) {
2461     // The XMM registers which might contain var arg parameters are shadowed
2462     // in their paired GPR.  So we only need to save the GPR to their home
2463     // slots.
2464     // TODO: __vectorcall will change this.
2465     return None;
2466   }
2467
2468   const Function *Fn = MF.getFunction();
2469   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2470   bool isSoftFloat = Subtarget->useSoftFloat();
2471   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2472          "SSE register cannot be used when SSE is disabled!");
2473   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2474     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2475     // registers.
2476     return None;
2477
2478   static const MCPhysReg XMMArgRegs64Bit[] = {
2479     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2480     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2481   };
2482   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2483 }
2484
2485 SDValue
2486 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2487                                         CallingConv::ID CallConv,
2488                                         bool isVarArg,
2489                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2490                                         SDLoc dl,
2491                                         SelectionDAG &DAG,
2492                                         SmallVectorImpl<SDValue> &InVals)
2493                                           const {
2494   MachineFunction &MF = DAG.getMachineFunction();
2495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2496   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2497
2498   const Function* Fn = MF.getFunction();
2499   if (Fn->hasExternalLinkage() &&
2500       Subtarget->isTargetCygMing() &&
2501       Fn->getName() == "main")
2502     FuncInfo->setForceFramePointer(true);
2503
2504   MachineFrameInfo *MFI = MF.getFrameInfo();
2505   bool Is64Bit = Subtarget->is64Bit();
2506   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Assign locations to all of the incoming arguments.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2514
2515   // Allocate shadow area for Win64
2516   if (IsWin64)
2517     CCInfo.AllocateStack(32, 8);
2518
2519   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2520
2521   unsigned LastVal = ~0U;
2522   SDValue ArgValue;
2523   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524     CCValAssign &VA = ArgLocs[i];
2525     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2526     // places.
2527     assert(VA.getValNo() != LastVal &&
2528            "Don't support value assigned to multiple locs yet");
2529     (void)LastVal;
2530     LastVal = VA.getValNo();
2531
2532     if (VA.isRegLoc()) {
2533       EVT RegVT = VA.getLocVT();
2534       const TargetRegisterClass *RC;
2535       if (RegVT == MVT::i32)
2536         RC = &X86::GR32RegClass;
2537       else if (Is64Bit && RegVT == MVT::i64)
2538         RC = &X86::GR64RegClass;
2539       else if (RegVT == MVT::f32)
2540         RC = &X86::FR32RegClass;
2541       else if (RegVT == MVT::f64)
2542         RC = &X86::FR64RegClass;
2543       else if (RegVT.is512BitVector())
2544         RC = &X86::VR512RegClass;
2545       else if (RegVT.is256BitVector())
2546         RC = &X86::VR256RegClass;
2547       else if (RegVT.is128BitVector())
2548         RC = &X86::VR128RegClass;
2549       else if (RegVT == MVT::x86mmx)
2550         RC = &X86::VR64RegClass;
2551       else if (RegVT == MVT::i1)
2552         RC = &X86::VK1RegClass;
2553       else if (RegVT == MVT::v8i1)
2554         RC = &X86::VK8RegClass;
2555       else if (RegVT == MVT::v16i1)
2556         RC = &X86::VK16RegClass;
2557       else if (RegVT == MVT::v32i1)
2558         RC = &X86::VK32RegClass;
2559       else if (RegVT == MVT::v64i1)
2560         RC = &X86::VK64RegClass;
2561       else
2562         llvm_unreachable("Unknown argument type!");
2563
2564       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2565       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2566
2567       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2568       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2569       // right size.
2570       if (VA.getLocInfo() == CCValAssign::SExt)
2571         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2572                                DAG.getValueType(VA.getValVT()));
2573       else if (VA.getLocInfo() == CCValAssign::ZExt)
2574         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2575                                DAG.getValueType(VA.getValVT()));
2576       else if (VA.getLocInfo() == CCValAssign::BCvt)
2577         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2578
2579       if (VA.isExtInLoc()) {
2580         // Handle MMX values passed in XMM regs.
2581         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2582           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2583         else
2584           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2585       }
2586     } else {
2587       assert(VA.isMemLoc());
2588       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2589     }
2590
2591     // If value is passed via pointer - do a load.
2592     if (VA.getLocInfo() == CCValAssign::Indirect)
2593       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2594                              MachinePointerInfo(), false, false, false, 0);
2595
2596     InVals.push_back(ArgValue);
2597   }
2598
2599   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2600     // All x86 ABIs require that for returning structs by value we copy the
2601     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2602     // the argument into a virtual register so that we can access it from the
2603     // return points.
2604     if (Ins[i].Flags.isSRet()) {
2605       unsigned Reg = FuncInfo->getSRetReturnReg();
2606       if (!Reg) {
2607         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2608         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2609         FuncInfo->setSRetReturnReg(Reg);
2610       }
2611       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2612       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2613       break;
2614     }
2615   }
2616
2617   unsigned StackSize = CCInfo.getNextStackOffset();
2618   // Align stack specially for tail calls.
2619   if (FuncIsMadeTailCallSafe(CallConv,
2620                              MF.getTarget().Options.GuaranteedTailCallOpt))
2621     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2622
2623   // If the function takes variable number of arguments, make a frame index for
2624   // the start of the first vararg value... for expansion of llvm.va_start. We
2625   // can skip this if there are no va_start calls.
2626   if (MFI->hasVAStart() &&
2627       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2628                    CallConv != CallingConv::X86_ThisCall))) {
2629     FuncInfo->setVarArgsFrameIndex(
2630         MFI->CreateFixedObject(1, StackSize, true));
2631   }
2632
2633   MachineModuleInfo &MMI = MF.getMMI();
2634   const Function *WinEHParent = nullptr;
2635   if (MMI.hasWinEHFuncInfo(Fn))
2636     WinEHParent = MMI.getWinEHParent(Fn);
2637   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2638   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2639
2640   // Figure out if XMM registers are in use.
2641   assert(!(Subtarget->useSoftFloat() &&
2642            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2643          "SSE register cannot be used when SSE is disabled!");
2644
2645   // 64-bit calling conventions support varargs and register parameters, so we
2646   // have to do extra work to spill them in the prologue.
2647   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2648     // Find the first unallocated argument registers.
2649     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2650     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2651     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2652     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2653     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2654            "SSE register cannot be used when SSE is disabled!");
2655
2656     // Gather all the live in physical registers.
2657     SmallVector<SDValue, 6> LiveGPRs;
2658     SmallVector<SDValue, 8> LiveXMMRegs;
2659     SDValue ALVal;
2660     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2661       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2662       LiveGPRs.push_back(
2663           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2664     }
2665     if (!ArgXMMs.empty()) {
2666       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2667       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2668       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2669         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2670         LiveXMMRegs.push_back(
2671             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2672       }
2673     }
2674
2675     if (IsWin64) {
2676       // Get to the caller-allocated home save location.  Add 8 to account
2677       // for the return address.
2678       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2679       FuncInfo->setRegSaveFrameIndex(
2680           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2681       // Fixup to set vararg frame on shadow area (4 x i64).
2682       if (NumIntRegs < 4)
2683         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2684     } else {
2685       // For X86-64, if there are vararg parameters that are passed via
2686       // registers, then we must store them to their spots on the stack so
2687       // they may be loaded by deferencing the result of va_next.
2688       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2689       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2690       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2691           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2692     }
2693
2694     // Store the integer parameter registers.
2695     SmallVector<SDValue, 8> MemOps;
2696     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2697                                       getPointerTy(DAG.getDataLayout()));
2698     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2699     for (SDValue Val : LiveGPRs) {
2700       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2701                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2702       SDValue Store =
2703           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2704                        MachinePointerInfo::getFixedStack(
2705                            DAG.getMachineFunction(),
2706                            FuncInfo->getRegSaveFrameIndex(), Offset),
2707                        false, false, 0);
2708       MemOps.push_back(Store);
2709       Offset += 8;
2710     }
2711
2712     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2713       // Now store the XMM (fp + vector) parameter registers.
2714       SmallVector<SDValue, 12> SaveXMMOps;
2715       SaveXMMOps.push_back(Chain);
2716       SaveXMMOps.push_back(ALVal);
2717       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2718                              FuncInfo->getRegSaveFrameIndex(), dl));
2719       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2720                              FuncInfo->getVarArgsFPOffset(), dl));
2721       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2722                         LiveXMMRegs.end());
2723       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2724                                    MVT::Other, SaveXMMOps));
2725     }
2726
2727     if (!MemOps.empty())
2728       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2729   } else if (IsWin64 && IsWinEHOutlined) {
2730     // Get to the caller-allocated home save location.  Add 8 to account
2731     // for the return address.
2732     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2733     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2734         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2735
2736     MMI.getWinEHFuncInfo(Fn)
2737         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2738         FuncInfo->getRegSaveFrameIndex();
2739
2740     // Store the second integer parameter (rdx) into rsp+16 relative to the
2741     // stack pointer at the entry of the function.
2742     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2743                                       getPointerTy(DAG.getDataLayout()));
2744     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2745     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2746     Chain = DAG.getStore(
2747         Val.getValue(1), dl, Val, RSFIN,
2748         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2749                                           FuncInfo->getRegSaveFrameIndex()),
2750         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2751   }
2752
2753   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2754     // Find the largest legal vector type.
2755     MVT VecVT = MVT::Other;
2756     // FIXME: Only some x86_32 calling conventions support AVX512.
2757     if (Subtarget->hasAVX512() &&
2758         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2759                      CallConv == CallingConv::Intel_OCL_BI)))
2760       VecVT = MVT::v16f32;
2761     else if (Subtarget->hasAVX())
2762       VecVT = MVT::v8f32;
2763     else if (Subtarget->hasSSE2())
2764       VecVT = MVT::v4f32;
2765
2766     // We forward some GPRs and some vector types.
2767     SmallVector<MVT, 2> RegParmTypes;
2768     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2769     RegParmTypes.push_back(IntVT);
2770     if (VecVT != MVT::Other)
2771       RegParmTypes.push_back(VecVT);
2772
2773     // Compute the set of forwarded registers. The rest are scratch.
2774     SmallVectorImpl<ForwardedRegister> &Forwards =
2775         FuncInfo->getForwardedMustTailRegParms();
2776     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2777
2778     // Conservatively forward AL on x86_64, since it might be used for varargs.
2779     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2780       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2781       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2782     }
2783
2784     // Copy all forwards from physical to virtual registers.
2785     for (ForwardedRegister &F : Forwards) {
2786       // FIXME: Can we use a less constrained schedule?
2787       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2788       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2789       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2790     }
2791   }
2792
2793   // Some CCs need callee pop.
2794   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2795                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2796     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2797   } else {
2798     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2799     // If this is an sret function, the return should pop the hidden pointer.
2800     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2801         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2802         argsAreStructReturn(Ins) == StackStructReturn)
2803       FuncInfo->setBytesToPopOnReturn(4);
2804   }
2805
2806   if (!Is64Bit) {
2807     // RegSaveFrameIndex is X86-64 only.
2808     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2809     if (CallConv == CallingConv::X86_FastCall ||
2810         CallConv == CallingConv::X86_ThisCall)
2811       // fastcc functions can't have varargs.
2812       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2813   }
2814
2815   FuncInfo->setArgumentStackSize(StackSize);
2816
2817   if (IsWinEHParent) {
2818     if (Is64Bit) {
2819       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2820       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2821       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2822       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2823       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2824                            MachinePointerInfo::getFixedStack(
2825                                DAG.getMachineFunction(), UnwindHelpFI),
2826                            /*isVolatile=*/true,
2827                            /*isNonTemporal=*/false, /*Alignment=*/0);
2828     } else {
2829       // Functions using Win32 EH are considered to have opaque SP adjustments
2830       // to force local variables to be addressed from the frame or base
2831       // pointers.
2832       MFI->setHasOpaqueSPAdjustment(true);
2833     }
2834   }
2835
2836   return Chain;
2837 }
2838
2839 SDValue
2840 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2841                                     SDValue StackPtr, SDValue Arg,
2842                                     SDLoc dl, SelectionDAG &DAG,
2843                                     const CCValAssign &VA,
2844                                     ISD::ArgFlagsTy Flags) const {
2845   unsigned LocMemOffset = VA.getLocMemOffset();
2846   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2847   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2848                        StackPtr, PtrOff);
2849   if (Flags.isByVal())
2850     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2851
2852   return DAG.getStore(
2853       Chain, dl, Arg, PtrOff,
2854       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2855       false, false, 0);
2856 }
2857
2858 /// Emit a load of return address if tail call
2859 /// optimization is performed and it is required.
2860 SDValue
2861 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2862                                            SDValue &OutRetAddr, SDValue Chain,
2863                                            bool IsTailCall, bool Is64Bit,
2864                                            int FPDiff, SDLoc dl) const {
2865   // Adjust the Return address stack slot.
2866   EVT VT = getPointerTy(DAG.getDataLayout());
2867   OutRetAddr = getReturnAddressFrameIndex(DAG);
2868
2869   // Load the "old" Return address.
2870   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2871                            false, false, false, 0);
2872   return SDValue(OutRetAddr.getNode(), 1);
2873 }
2874
2875 /// Emit a store of the return address if tail call
2876 /// optimization is performed and it is required (FPDiff!=0).
2877 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2878                                         SDValue Chain, SDValue RetAddrFrIdx,
2879                                         EVT PtrVT, unsigned SlotSize,
2880                                         int FPDiff, SDLoc dl) {
2881   // Store the return address to the appropriate stack slot.
2882   if (!FPDiff) return Chain;
2883   // Calculate the new stack slot for the return address.
2884   int NewReturnAddrFI =
2885     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2886                                          false);
2887   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2888   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2889                        MachinePointerInfo::getFixedStack(
2890                            DAG.getMachineFunction(), NewReturnAddrFI),
2891                        false, false, 0);
2892   return Chain;
2893 }
2894
2895 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2896 /// operation of specified width.
2897 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2898                        SDValue V2) {
2899   unsigned NumElems = VT.getVectorNumElements();
2900   SmallVector<int, 8> Mask;
2901   Mask.push_back(NumElems);
2902   for (unsigned i = 1; i != NumElems; ++i)
2903     Mask.push_back(i);
2904   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2905 }
2906
2907 SDValue
2908 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2909                              SmallVectorImpl<SDValue> &InVals) const {
2910   SelectionDAG &DAG                     = CLI.DAG;
2911   SDLoc &dl                             = CLI.DL;
2912   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2913   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2914   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2915   SDValue Chain                         = CLI.Chain;
2916   SDValue Callee                        = CLI.Callee;
2917   CallingConv::ID CallConv              = CLI.CallConv;
2918   bool &isTailCall                      = CLI.IsTailCall;
2919   bool isVarArg                         = CLI.IsVarArg;
2920
2921   MachineFunction &MF = DAG.getMachineFunction();
2922   bool Is64Bit        = Subtarget->is64Bit();
2923   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2924   StructReturnType SR = callIsStructReturn(Outs);
2925   bool IsSibcall      = false;
2926   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2927   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2928
2929   if (Attr.getValueAsString() == "true")
2930     isTailCall = false;
2931
2932   if (Subtarget->isPICStyleGOT() &&
2933       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2934     // If we are using a GOT, disable tail calls to external symbols with
2935     // default visibility. Tail calling such a symbol requires using a GOT
2936     // relocation, which forces early binding of the symbol. This breaks code
2937     // that require lazy function symbol resolution. Using musttail or
2938     // GuaranteedTailCallOpt will override this.
2939     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2940     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2941                G->getGlobal()->hasDefaultVisibility()))
2942       isTailCall = false;
2943   }
2944
2945   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2946   if (IsMustTail) {
2947     // Force this to be a tail call.  The verifier rules are enough to ensure
2948     // that we can lower this successfully without moving the return address
2949     // around.
2950     isTailCall = true;
2951   } else if (isTailCall) {
2952     // Check if it's really possible to do a tail call.
2953     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2954                     isVarArg, SR != NotStructReturn,
2955                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2956                     Outs, OutVals, Ins, DAG);
2957
2958     // Sibcalls are automatically detected tailcalls which do not require
2959     // ABI changes.
2960     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2961       IsSibcall = true;
2962
2963     if (isTailCall)
2964       ++NumTailCalls;
2965   }
2966
2967   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2968          "Var args not supported with calling convention fastcc, ghc or hipe");
2969
2970   // Analyze operands of the call, assigning locations to each operand.
2971   SmallVector<CCValAssign, 16> ArgLocs;
2972   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2973
2974   // Allocate shadow area for Win64
2975   if (IsWin64)
2976     CCInfo.AllocateStack(32, 8);
2977
2978   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2979
2980   // Get a count of how many bytes are to be pushed on the stack.
2981   unsigned NumBytes = CCInfo.getNextStackOffset();
2982   if (IsSibcall)
2983     // This is a sibcall. The memory operands are available in caller's
2984     // own caller's stack.
2985     NumBytes = 0;
2986   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2987            IsTailCallConvention(CallConv))
2988     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2989
2990   int FPDiff = 0;
2991   if (isTailCall && !IsSibcall && !IsMustTail) {
2992     // Lower arguments at fp - stackoffset + fpdiff.
2993     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2994
2995     FPDiff = NumBytesCallerPushed - NumBytes;
2996
2997     // Set the delta of movement of the returnaddr stackslot.
2998     // But only set if delta is greater than previous delta.
2999     if (FPDiff < X86Info->getTCReturnAddrDelta())
3000       X86Info->setTCReturnAddrDelta(FPDiff);
3001   }
3002
3003   unsigned NumBytesToPush = NumBytes;
3004   unsigned NumBytesToPop = NumBytes;
3005
3006   // If we have an inalloca argument, all stack space has already been allocated
3007   // for us and be right at the top of the stack.  We don't support multiple
3008   // arguments passed in memory when using inalloca.
3009   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3010     NumBytesToPush = 0;
3011     if (!ArgLocs.back().isMemLoc())
3012       report_fatal_error("cannot use inalloca attribute on a register "
3013                          "parameter");
3014     if (ArgLocs.back().getLocMemOffset() != 0)
3015       report_fatal_error("any parameter with the inalloca attribute must be "
3016                          "the only memory argument");
3017   }
3018
3019   if (!IsSibcall)
3020     Chain = DAG.getCALLSEQ_START(
3021         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3022
3023   SDValue RetAddrFrIdx;
3024   // Load return address for tail calls.
3025   if (isTailCall && FPDiff)
3026     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3027                                     Is64Bit, FPDiff, dl);
3028
3029   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3030   SmallVector<SDValue, 8> MemOpChains;
3031   SDValue StackPtr;
3032
3033   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3034   // of tail call optimization arguments are handle later.
3035   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3036   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3037     // Skip inalloca arguments, they have already been written.
3038     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3039     if (Flags.isInAlloca())
3040       continue;
3041
3042     CCValAssign &VA = ArgLocs[i];
3043     EVT RegVT = VA.getLocVT();
3044     SDValue Arg = OutVals[i];
3045     bool isByVal = Flags.isByVal();
3046
3047     // Promote the value if needed.
3048     switch (VA.getLocInfo()) {
3049     default: llvm_unreachable("Unknown loc info!");
3050     case CCValAssign::Full: break;
3051     case CCValAssign::SExt:
3052       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3053       break;
3054     case CCValAssign::ZExt:
3055       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3056       break;
3057     case CCValAssign::AExt:
3058       if (Arg.getValueType().isVector() &&
3059           Arg.getValueType().getScalarType() == MVT::i1)
3060         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3061       else if (RegVT.is128BitVector()) {
3062         // Special case: passing MMX values in XMM registers.
3063         Arg = DAG.getBitcast(MVT::i64, Arg);
3064         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3065         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3066       } else
3067         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3068       break;
3069     case CCValAssign::BCvt:
3070       Arg = DAG.getBitcast(RegVT, Arg);
3071       break;
3072     case CCValAssign::Indirect: {
3073       // Store the argument.
3074       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3075       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3076       Chain = DAG.getStore(
3077           Chain, dl, Arg, SpillSlot,
3078           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3079           false, false, 0);
3080       Arg = SpillSlot;
3081       break;
3082     }
3083     }
3084
3085     if (VA.isRegLoc()) {
3086       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3087       if (isVarArg && IsWin64) {
3088         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3089         // shadow reg if callee is a varargs function.
3090         unsigned ShadowReg = 0;
3091         switch (VA.getLocReg()) {
3092         case X86::XMM0: ShadowReg = X86::RCX; break;
3093         case X86::XMM1: ShadowReg = X86::RDX; break;
3094         case X86::XMM2: ShadowReg = X86::R8; break;
3095         case X86::XMM3: ShadowReg = X86::R9; break;
3096         }
3097         if (ShadowReg)
3098           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3099       }
3100     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3101       assert(VA.isMemLoc());
3102       if (!StackPtr.getNode())
3103         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3104                                       getPointerTy(DAG.getDataLayout()));
3105       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3106                                              dl, DAG, VA, Flags));
3107     }
3108   }
3109
3110   if (!MemOpChains.empty())
3111     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3112
3113   if (Subtarget->isPICStyleGOT()) {
3114     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3115     // GOT pointer.
3116     if (!isTailCall) {
3117       RegsToPass.push_back(std::make_pair(
3118           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3119                                           getPointerTy(DAG.getDataLayout()))));
3120     } else {
3121       // If we are tail calling and generating PIC/GOT style code load the
3122       // address of the callee into ECX. The value in ecx is used as target of
3123       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3124       // for tail calls on PIC/GOT architectures. Normally we would just put the
3125       // address of GOT into ebx and then call target@PLT. But for tail calls
3126       // ebx would be restored (since ebx is callee saved) before jumping to the
3127       // target@PLT.
3128
3129       // Note: The actual moving to ECX is done further down.
3130       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3131       if (G && !G->getGlobal()->hasLocalLinkage() &&
3132           G->getGlobal()->hasDefaultVisibility())
3133         Callee = LowerGlobalAddress(Callee, DAG);
3134       else if (isa<ExternalSymbolSDNode>(Callee))
3135         Callee = LowerExternalSymbol(Callee, DAG);
3136     }
3137   }
3138
3139   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3140     // From AMD64 ABI document:
3141     // For calls that may call functions that use varargs or stdargs
3142     // (prototype-less calls or calls to functions containing ellipsis (...) in
3143     // the declaration) %al is used as hidden argument to specify the number
3144     // of SSE registers used. The contents of %al do not need to match exactly
3145     // the number of registers, but must be an ubound on the number of SSE
3146     // registers used and is in the range 0 - 8 inclusive.
3147
3148     // Count the number of XMM registers allocated.
3149     static const MCPhysReg XMMArgRegs[] = {
3150       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3151       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3152     };
3153     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3154     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3155            && "SSE registers cannot be used when SSE is disabled");
3156
3157     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3158                                         DAG.getConstant(NumXMMRegs, dl,
3159                                                         MVT::i8)));
3160   }
3161
3162   if (isVarArg && IsMustTail) {
3163     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3164     for (const auto &F : Forwards) {
3165       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3166       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3167     }
3168   }
3169
3170   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3171   // don't need this because the eligibility check rejects calls that require
3172   // shuffling arguments passed in memory.
3173   if (!IsSibcall && isTailCall) {
3174     // Force all the incoming stack arguments to be loaded from the stack
3175     // before any new outgoing arguments are stored to the stack, because the
3176     // outgoing stack slots may alias the incoming argument stack slots, and
3177     // the alias isn't otherwise explicit. This is slightly more conservative
3178     // than necessary, because it means that each store effectively depends
3179     // on every argument instead of just those arguments it would clobber.
3180     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3181
3182     SmallVector<SDValue, 8> MemOpChains2;
3183     SDValue FIN;
3184     int FI = 0;
3185     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3186       CCValAssign &VA = ArgLocs[i];
3187       if (VA.isRegLoc())
3188         continue;
3189       assert(VA.isMemLoc());
3190       SDValue Arg = OutVals[i];
3191       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3192       // Skip inalloca arguments.  They don't require any work.
3193       if (Flags.isInAlloca())
3194         continue;
3195       // Create frame index.
3196       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3197       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3198       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3199       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3200
3201       if (Flags.isByVal()) {
3202         // Copy relative to framepointer.
3203         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3204         if (!StackPtr.getNode())
3205           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3206                                         getPointerTy(DAG.getDataLayout()));
3207         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3208                              StackPtr, Source);
3209
3210         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3211                                                          ArgChain,
3212                                                          Flags, DAG, dl));
3213       } else {
3214         // Store relative to framepointer.
3215         MemOpChains2.push_back(DAG.getStore(
3216             ArgChain, dl, Arg, FIN,
3217             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3218             false, false, 0));
3219       }
3220     }
3221
3222     if (!MemOpChains2.empty())
3223       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3224
3225     // Store the return address to the appropriate stack slot.
3226     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3227                                      getPointerTy(DAG.getDataLayout()),
3228                                      RegInfo->getSlotSize(), FPDiff, dl);
3229   }
3230
3231   // Build a sequence of copy-to-reg nodes chained together with token chain
3232   // and flag operands which copy the outgoing args into registers.
3233   SDValue InFlag;
3234   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3235     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3236                              RegsToPass[i].second, InFlag);
3237     InFlag = Chain.getValue(1);
3238   }
3239
3240   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3241     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3242     // In the 64-bit large code model, we have to make all calls
3243     // through a register, since the call instruction's 32-bit
3244     // pc-relative offset may not be large enough to hold the whole
3245     // address.
3246   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3247     // If the callee is a GlobalAddress node (quite common, every direct call
3248     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3249     // it.
3250     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3251
3252     // We should use extra load for direct calls to dllimported functions in
3253     // non-JIT mode.
3254     const GlobalValue *GV = G->getGlobal();
3255     if (!GV->hasDLLImportStorageClass()) {
3256       unsigned char OpFlags = 0;
3257       bool ExtraLoad = false;
3258       unsigned WrapperKind = ISD::DELETED_NODE;
3259
3260       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3261       // external symbols most go through the PLT in PIC mode.  If the symbol
3262       // has hidden or protected visibility, or if it is static or local, then
3263       // we don't need to use the PLT - we can directly call it.
3264       if (Subtarget->isTargetELF() &&
3265           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3266           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3267         OpFlags = X86II::MO_PLT;
3268       } else if (Subtarget->isPICStyleStubAny() &&
3269                  !GV->isStrongDefinitionForLinker() &&
3270                  (!Subtarget->getTargetTriple().isMacOSX() ||
3271                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3272         // PC-relative references to external symbols should go through $stub,
3273         // unless we're building with the leopard linker or later, which
3274         // automatically synthesizes these stubs.
3275         OpFlags = X86II::MO_DARWIN_STUB;
3276       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3277                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3278         // If the function is marked as non-lazy, generate an indirect call
3279         // which loads from the GOT directly. This avoids runtime overhead
3280         // at the cost of eager binding (and one extra byte of encoding).
3281         OpFlags = X86II::MO_GOTPCREL;
3282         WrapperKind = X86ISD::WrapperRIP;
3283         ExtraLoad = true;
3284       }
3285
3286       Callee = DAG.getTargetGlobalAddress(
3287           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3288
3289       // Add a wrapper if needed.
3290       if (WrapperKind != ISD::DELETED_NODE)
3291         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3292                              getPointerTy(DAG.getDataLayout()), Callee);
3293       // Add extra indirection if needed.
3294       if (ExtraLoad)
3295         Callee = DAG.getLoad(
3296             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3297             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3298             false, 0);
3299     }
3300   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3301     unsigned char OpFlags = 0;
3302
3303     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3304     // external symbols should go through the PLT.
3305     if (Subtarget->isTargetELF() &&
3306         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3307       OpFlags = X86II::MO_PLT;
3308     } else if (Subtarget->isPICStyleStubAny() &&
3309                (!Subtarget->getTargetTriple().isMacOSX() ||
3310                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3311       // PC-relative references to external symbols should go through $stub,
3312       // unless we're building with the leopard linker or later, which
3313       // automatically synthesizes these stubs.
3314       OpFlags = X86II::MO_DARWIN_STUB;
3315     }
3316
3317     Callee = DAG.getTargetExternalSymbol(
3318         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3319   } else if (Subtarget->isTarget64BitILP32() &&
3320              Callee->getValueType(0) == MVT::i32) {
3321     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3322     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3323   }
3324
3325   // Returns a chain & a flag for retval copy to use.
3326   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3327   SmallVector<SDValue, 8> Ops;
3328
3329   if (!IsSibcall && isTailCall) {
3330     Chain = DAG.getCALLSEQ_END(Chain,
3331                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3332                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3333     InFlag = Chain.getValue(1);
3334   }
3335
3336   Ops.push_back(Chain);
3337   Ops.push_back(Callee);
3338
3339   if (isTailCall)
3340     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3341
3342   // Add argument registers to the end of the list so that they are known live
3343   // into the call.
3344   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3345     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3346                                   RegsToPass[i].second.getValueType()));
3347
3348   // Add a register mask operand representing the call-preserved registers.
3349   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3350   assert(Mask && "Missing call preserved mask for calling convention");
3351
3352   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3353   // the function clobbers all registers. If an exception is thrown, the runtime
3354   // will not restore CSRs.
3355   // FIXME: Model this more precisely so that we can register allocate across
3356   // the normal edge and spill and fill across the exceptional edge.
3357   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3358     const Function *CallerFn = MF.getFunction();
3359     EHPersonality Pers =
3360         CallerFn->hasPersonalityFn()
3361             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3362             : EHPersonality::Unknown;
3363     if (isMSVCEHPersonality(Pers))
3364       Mask = RegInfo->getNoPreservedMask();
3365   }
3366
3367   Ops.push_back(DAG.getRegisterMask(Mask));
3368
3369   if (InFlag.getNode())
3370     Ops.push_back(InFlag);
3371
3372   if (isTailCall) {
3373     // We used to do:
3374     //// If this is the first return lowered for this function, add the regs
3375     //// to the liveout set for the function.
3376     // This isn't right, although it's probably harmless on x86; liveouts
3377     // should be computed from returns not tail calls.  Consider a void
3378     // function making a tail call to a function returning int.
3379     MF.getFrameInfo()->setHasTailCall();
3380     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3381   }
3382
3383   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3384   InFlag = Chain.getValue(1);
3385
3386   // Create the CALLSEQ_END node.
3387   unsigned NumBytesForCalleeToPop;
3388   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3389                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3390     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3391   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3392            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3393            SR == StackStructReturn)
3394     // If this is a call to a struct-return function, the callee
3395     // pops the hidden struct pointer, so we have to push it back.
3396     // This is common for Darwin/X86, Linux & Mingw32 targets.
3397     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3398     NumBytesForCalleeToPop = 4;
3399   else
3400     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3401
3402   // Returns a flag for retval copy to use.
3403   if (!IsSibcall) {
3404     Chain = DAG.getCALLSEQ_END(Chain,
3405                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3406                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3407                                                      true),
3408                                InFlag, dl);
3409     InFlag = Chain.getValue(1);
3410   }
3411
3412   // Handle result values, copying them out of physregs into vregs that we
3413   // return.
3414   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3415                          Ins, dl, DAG, InVals);
3416 }
3417
3418 //===----------------------------------------------------------------------===//
3419 //                Fast Calling Convention (tail call) implementation
3420 //===----------------------------------------------------------------------===//
3421
3422 //  Like std call, callee cleans arguments, convention except that ECX is
3423 //  reserved for storing the tail called function address. Only 2 registers are
3424 //  free for argument passing (inreg). Tail call optimization is performed
3425 //  provided:
3426 //                * tailcallopt is enabled
3427 //                * caller/callee are fastcc
3428 //  On X86_64 architecture with GOT-style position independent code only local
3429 //  (within module) calls are supported at the moment.
3430 //  To keep the stack aligned according to platform abi the function
3431 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3432 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3433 //  If a tail called function callee has more arguments than the caller the
3434 //  caller needs to make sure that there is room to move the RETADDR to. This is
3435 //  achieved by reserving an area the size of the argument delta right after the
3436 //  original RETADDR, but before the saved framepointer or the spilled registers
3437 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3438 //  stack layout:
3439 //    arg1
3440 //    arg2
3441 //    RETADDR
3442 //    [ new RETADDR
3443 //      move area ]
3444 //    (possible EBP)
3445 //    ESI
3446 //    EDI
3447 //    local1 ..
3448
3449 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3450 /// requirement.
3451 unsigned
3452 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3453                                                SelectionDAG& DAG) const {
3454   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3455   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3456   unsigned StackAlignment = TFI.getStackAlignment();
3457   uint64_t AlignMask = StackAlignment - 1;
3458   int64_t Offset = StackSize;
3459   unsigned SlotSize = RegInfo->getSlotSize();
3460   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3461     // Number smaller than 12 so just add the difference.
3462     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3463   } else {
3464     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3465     Offset = ((~AlignMask) & Offset) + StackAlignment +
3466       (StackAlignment-SlotSize);
3467   }
3468   return Offset;
3469 }
3470
3471 /// Return true if the given stack call argument is already available in the
3472 /// same position (relatively) of the caller's incoming argument stack.
3473 static
3474 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3475                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3476                          const X86InstrInfo *TII) {
3477   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3478   int FI = INT_MAX;
3479   if (Arg.getOpcode() == ISD::CopyFromReg) {
3480     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3481     if (!TargetRegisterInfo::isVirtualRegister(VR))
3482       return false;
3483     MachineInstr *Def = MRI->getVRegDef(VR);
3484     if (!Def)
3485       return false;
3486     if (!Flags.isByVal()) {
3487       if (!TII->isLoadFromStackSlot(Def, FI))
3488         return false;
3489     } else {
3490       unsigned Opcode = Def->getOpcode();
3491       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3492            Opcode == X86::LEA64_32r) &&
3493           Def->getOperand(1).isFI()) {
3494         FI = Def->getOperand(1).getIndex();
3495         Bytes = Flags.getByValSize();
3496       } else
3497         return false;
3498     }
3499   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3500     if (Flags.isByVal())
3501       // ByVal argument is passed in as a pointer but it's now being
3502       // dereferenced. e.g.
3503       // define @foo(%struct.X* %A) {
3504       //   tail call @bar(%struct.X* byval %A)
3505       // }
3506       return false;
3507     SDValue Ptr = Ld->getBasePtr();
3508     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3509     if (!FINode)
3510       return false;
3511     FI = FINode->getIndex();
3512   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3513     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3514     FI = FINode->getIndex();
3515     Bytes = Flags.getByValSize();
3516   } else
3517     return false;
3518
3519   assert(FI != INT_MAX);
3520   if (!MFI->isFixedObjectIndex(FI))
3521     return false;
3522   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3523 }
3524
3525 /// Check whether the call is eligible for tail call optimization. Targets
3526 /// that want to do tail call optimization should implement this function.
3527 bool
3528 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3529                                                      CallingConv::ID CalleeCC,
3530                                                      bool isVarArg,
3531                                                      bool isCalleeStructRet,
3532                                                      bool isCallerStructRet,
3533                                                      Type *RetTy,
3534                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3535                                     const SmallVectorImpl<SDValue> &OutVals,
3536                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3537                                                      SelectionDAG &DAG) const {
3538   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3539     return false;
3540
3541   // If -tailcallopt is specified, make fastcc functions tail-callable.
3542   const MachineFunction &MF = DAG.getMachineFunction();
3543   const Function *CallerF = MF.getFunction();
3544
3545   // If the function return type is x86_fp80 and the callee return type is not,
3546   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3547   // perform a tailcall optimization here.
3548   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3549     return false;
3550
3551   CallingConv::ID CallerCC = CallerF->getCallingConv();
3552   bool CCMatch = CallerCC == CalleeCC;
3553   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3554   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3555
3556   // Win64 functions have extra shadow space for argument homing. Don't do the
3557   // sibcall if the caller and callee have mismatched expectations for this
3558   // space.
3559   if (IsCalleeWin64 != IsCallerWin64)
3560     return false;
3561
3562   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3563     if (IsTailCallConvention(CalleeCC) && CCMatch)
3564       return true;
3565     return false;
3566   }
3567
3568   // Look for obvious safe cases to perform tail call optimization that do not
3569   // require ABI changes. This is what gcc calls sibcall.
3570
3571   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3572   // emit a special epilogue.
3573   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3574   if (RegInfo->needsStackRealignment(MF))
3575     return false;
3576
3577   // Also avoid sibcall optimization if either caller or callee uses struct
3578   // return semantics.
3579   if (isCalleeStructRet || isCallerStructRet)
3580     return false;
3581
3582   // An stdcall/thiscall caller is expected to clean up its arguments; the
3583   // callee isn't going to do that.
3584   // FIXME: this is more restrictive than needed. We could produce a tailcall
3585   // when the stack adjustment matches. For example, with a thiscall that takes
3586   // only one argument.
3587   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3588                    CallerCC == CallingConv::X86_ThisCall))
3589     return false;
3590
3591   // Do not sibcall optimize vararg calls unless all arguments are passed via
3592   // registers.
3593   if (isVarArg && !Outs.empty()) {
3594
3595     // Optimizing for varargs on Win64 is unlikely to be safe without
3596     // additional testing.
3597     if (IsCalleeWin64 || IsCallerWin64)
3598       return false;
3599
3600     SmallVector<CCValAssign, 16> ArgLocs;
3601     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3602                    *DAG.getContext());
3603
3604     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3605     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3606       if (!ArgLocs[i].isRegLoc())
3607         return false;
3608   }
3609
3610   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3611   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3612   // this into a sibcall.
3613   bool Unused = false;
3614   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3615     if (!Ins[i].Used) {
3616       Unused = true;
3617       break;
3618     }
3619   }
3620   if (Unused) {
3621     SmallVector<CCValAssign, 16> RVLocs;
3622     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3623                    *DAG.getContext());
3624     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3625     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3626       CCValAssign &VA = RVLocs[i];
3627       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3628         return false;
3629     }
3630   }
3631
3632   // If the calling conventions do not match, then we'd better make sure the
3633   // results are returned in the same way as what the caller expects.
3634   if (!CCMatch) {
3635     SmallVector<CCValAssign, 16> RVLocs1;
3636     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3637                     *DAG.getContext());
3638     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3639
3640     SmallVector<CCValAssign, 16> RVLocs2;
3641     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3642                     *DAG.getContext());
3643     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3644
3645     if (RVLocs1.size() != RVLocs2.size())
3646       return false;
3647     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3648       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3649         return false;
3650       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3651         return false;
3652       if (RVLocs1[i].isRegLoc()) {
3653         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3654           return false;
3655       } else {
3656         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3657           return false;
3658       }
3659     }
3660   }
3661
3662   // If the callee takes no arguments then go on to check the results of the
3663   // call.
3664   if (!Outs.empty()) {
3665     // Check if stack adjustment is needed. For now, do not do this if any
3666     // argument is passed on the stack.
3667     SmallVector<CCValAssign, 16> ArgLocs;
3668     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3669                    *DAG.getContext());
3670
3671     // Allocate shadow area for Win64
3672     if (IsCalleeWin64)
3673       CCInfo.AllocateStack(32, 8);
3674
3675     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3676     if (CCInfo.getNextStackOffset()) {
3677       MachineFunction &MF = DAG.getMachineFunction();
3678       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3679         return false;
3680
3681       // Check if the arguments are already laid out in the right way as
3682       // the caller's fixed stack objects.
3683       MachineFrameInfo *MFI = MF.getFrameInfo();
3684       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3685       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3686       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3687         CCValAssign &VA = ArgLocs[i];
3688         SDValue Arg = OutVals[i];
3689         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3690         if (VA.getLocInfo() == CCValAssign::Indirect)
3691           return false;
3692         if (!VA.isRegLoc()) {
3693           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3694                                    MFI, MRI, TII))
3695             return false;
3696         }
3697       }
3698     }
3699
3700     // If the tailcall address may be in a register, then make sure it's
3701     // possible to register allocate for it. In 32-bit, the call address can
3702     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3703     // callee-saved registers are restored. These happen to be the same
3704     // registers used to pass 'inreg' arguments so watch out for those.
3705     if (!Subtarget->is64Bit() &&
3706         ((!isa<GlobalAddressSDNode>(Callee) &&
3707           !isa<ExternalSymbolSDNode>(Callee)) ||
3708          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3709       unsigned NumInRegs = 0;
3710       // In PIC we need an extra register to formulate the address computation
3711       // for the callee.
3712       unsigned MaxInRegs =
3713         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3714
3715       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3716         CCValAssign &VA = ArgLocs[i];
3717         if (!VA.isRegLoc())
3718           continue;
3719         unsigned Reg = VA.getLocReg();
3720         switch (Reg) {
3721         default: break;
3722         case X86::EAX: case X86::EDX: case X86::ECX:
3723           if (++NumInRegs == MaxInRegs)
3724             return false;
3725           break;
3726         }
3727       }
3728     }
3729   }
3730
3731   return true;
3732 }
3733
3734 FastISel *
3735 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3736                                   const TargetLibraryInfo *libInfo) const {
3737   return X86::createFastISel(funcInfo, libInfo);
3738 }
3739
3740 //===----------------------------------------------------------------------===//
3741 //                           Other Lowering Hooks
3742 //===----------------------------------------------------------------------===//
3743
3744 static bool MayFoldLoad(SDValue Op) {
3745   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3746 }
3747
3748 static bool MayFoldIntoStore(SDValue Op) {
3749   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3750 }
3751
3752 static bool isTargetShuffle(unsigned Opcode) {
3753   switch(Opcode) {
3754   default: return false;
3755   case X86ISD::BLENDI:
3756   case X86ISD::PSHUFB:
3757   case X86ISD::PSHUFD:
3758   case X86ISD::PSHUFHW:
3759   case X86ISD::PSHUFLW:
3760   case X86ISD::SHUFP:
3761   case X86ISD::PALIGNR:
3762   case X86ISD::MOVLHPS:
3763   case X86ISD::MOVLHPD:
3764   case X86ISD::MOVHLPS:
3765   case X86ISD::MOVLPS:
3766   case X86ISD::MOVLPD:
3767   case X86ISD::MOVSHDUP:
3768   case X86ISD::MOVSLDUP:
3769   case X86ISD::MOVDDUP:
3770   case X86ISD::MOVSS:
3771   case X86ISD::MOVSD:
3772   case X86ISD::UNPCKL:
3773   case X86ISD::UNPCKH:
3774   case X86ISD::VPERMILPI:
3775   case X86ISD::VPERM2X128:
3776   case X86ISD::VPERMI:
3777     return true;
3778   }
3779 }
3780
3781 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3782                                     SDValue V1, unsigned TargetMask,
3783                                     SelectionDAG &DAG) {
3784   switch(Opc) {
3785   default: llvm_unreachable("Unknown x86 shuffle node");
3786   case X86ISD::PSHUFD:
3787   case X86ISD::PSHUFHW:
3788   case X86ISD::PSHUFLW:
3789   case X86ISD::VPERMILPI:
3790   case X86ISD::VPERMI:
3791     return DAG.getNode(Opc, dl, VT, V1,
3792                        DAG.getConstant(TargetMask, dl, MVT::i8));
3793   }
3794 }
3795
3796 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3797                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3798   switch(Opc) {
3799   default: llvm_unreachable("Unknown x86 shuffle node");
3800   case X86ISD::MOVLHPS:
3801   case X86ISD::MOVLHPD:
3802   case X86ISD::MOVHLPS:
3803   case X86ISD::MOVLPS:
3804   case X86ISD::MOVLPD:
3805   case X86ISD::MOVSS:
3806   case X86ISD::MOVSD:
3807   case X86ISD::UNPCKL:
3808   case X86ISD::UNPCKH:
3809     return DAG.getNode(Opc, dl, VT, V1, V2);
3810   }
3811 }
3812
3813 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3814   MachineFunction &MF = DAG.getMachineFunction();
3815   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3816   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3817   int ReturnAddrIndex = FuncInfo->getRAIndex();
3818
3819   if (ReturnAddrIndex == 0) {
3820     // Set up a frame object for the return address.
3821     unsigned SlotSize = RegInfo->getSlotSize();
3822     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3823                                                            -(int64_t)SlotSize,
3824                                                            false);
3825     FuncInfo->setRAIndex(ReturnAddrIndex);
3826   }
3827
3828   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3829 }
3830
3831 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3832                                        bool hasSymbolicDisplacement) {
3833   // Offset should fit into 32 bit immediate field.
3834   if (!isInt<32>(Offset))
3835     return false;
3836
3837   // If we don't have a symbolic displacement - we don't have any extra
3838   // restrictions.
3839   if (!hasSymbolicDisplacement)
3840     return true;
3841
3842   // FIXME: Some tweaks might be needed for medium code model.
3843   if (M != CodeModel::Small && M != CodeModel::Kernel)
3844     return false;
3845
3846   // For small code model we assume that latest object is 16MB before end of 31
3847   // bits boundary. We may also accept pretty large negative constants knowing
3848   // that all objects are in the positive half of address space.
3849   if (M == CodeModel::Small && Offset < 16*1024*1024)
3850     return true;
3851
3852   // For kernel code model we know that all object resist in the negative half
3853   // of 32bits address space. We may not accept negative offsets, since they may
3854   // be just off and we may accept pretty large positive ones.
3855   if (M == CodeModel::Kernel && Offset >= 0)
3856     return true;
3857
3858   return false;
3859 }
3860
3861 /// Determines whether the callee is required to pop its own arguments.
3862 /// Callee pop is necessary to support tail calls.
3863 bool X86::isCalleePop(CallingConv::ID CallingConv,
3864                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3865   switch (CallingConv) {
3866   default:
3867     return false;
3868   case CallingConv::X86_StdCall:
3869   case CallingConv::X86_FastCall:
3870   case CallingConv::X86_ThisCall:
3871     return !is64Bit;
3872   case CallingConv::Fast:
3873   case CallingConv::GHC:
3874   case CallingConv::HiPE:
3875     if (IsVarArg)
3876       return false;
3877     return TailCallOpt;
3878   }
3879 }
3880
3881 /// \brief Return true if the condition is an unsigned comparison operation.
3882 static bool isX86CCUnsigned(unsigned X86CC) {
3883   switch (X86CC) {
3884   default: llvm_unreachable("Invalid integer condition!");
3885   case X86::COND_E:     return true;
3886   case X86::COND_G:     return false;
3887   case X86::COND_GE:    return false;
3888   case X86::COND_L:     return false;
3889   case X86::COND_LE:    return false;
3890   case X86::COND_NE:    return true;
3891   case X86::COND_B:     return true;
3892   case X86::COND_A:     return true;
3893   case X86::COND_BE:    return true;
3894   case X86::COND_AE:    return true;
3895   }
3896   llvm_unreachable("covered switch fell through?!");
3897 }
3898
3899 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3900 /// condition code, returning the condition code and the LHS/RHS of the
3901 /// comparison to make.
3902 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3903                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3904   if (!isFP) {
3905     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3906       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3907         // X > -1   -> X == 0, jump !sign.
3908         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3909         return X86::COND_NS;
3910       }
3911       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3912         // X < 0   -> X == 0, jump on sign.
3913         return X86::COND_S;
3914       }
3915       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3916         // X < 1   -> X <= 0
3917         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3918         return X86::COND_LE;
3919       }
3920     }
3921
3922     switch (SetCCOpcode) {
3923     default: llvm_unreachable("Invalid integer condition!");
3924     case ISD::SETEQ:  return X86::COND_E;
3925     case ISD::SETGT:  return X86::COND_G;
3926     case ISD::SETGE:  return X86::COND_GE;
3927     case ISD::SETLT:  return X86::COND_L;
3928     case ISD::SETLE:  return X86::COND_LE;
3929     case ISD::SETNE:  return X86::COND_NE;
3930     case ISD::SETULT: return X86::COND_B;
3931     case ISD::SETUGT: return X86::COND_A;
3932     case ISD::SETULE: return X86::COND_BE;
3933     case ISD::SETUGE: return X86::COND_AE;
3934     }
3935   }
3936
3937   // First determine if it is required or is profitable to flip the operands.
3938
3939   // If LHS is a foldable load, but RHS is not, flip the condition.
3940   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3941       !ISD::isNON_EXTLoad(RHS.getNode())) {
3942     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3943     std::swap(LHS, RHS);
3944   }
3945
3946   switch (SetCCOpcode) {
3947   default: break;
3948   case ISD::SETOLT:
3949   case ISD::SETOLE:
3950   case ISD::SETUGT:
3951   case ISD::SETUGE:
3952     std::swap(LHS, RHS);
3953     break;
3954   }
3955
3956   // On a floating point condition, the flags are set as follows:
3957   // ZF  PF  CF   op
3958   //  0 | 0 | 0 | X > Y
3959   //  0 | 0 | 1 | X < Y
3960   //  1 | 0 | 0 | X == Y
3961   //  1 | 1 | 1 | unordered
3962   switch (SetCCOpcode) {
3963   default: llvm_unreachable("Condcode should be pre-legalized away");
3964   case ISD::SETUEQ:
3965   case ISD::SETEQ:   return X86::COND_E;
3966   case ISD::SETOLT:              // flipped
3967   case ISD::SETOGT:
3968   case ISD::SETGT:   return X86::COND_A;
3969   case ISD::SETOLE:              // flipped
3970   case ISD::SETOGE:
3971   case ISD::SETGE:   return X86::COND_AE;
3972   case ISD::SETUGT:              // flipped
3973   case ISD::SETULT:
3974   case ISD::SETLT:   return X86::COND_B;
3975   case ISD::SETUGE:              // flipped
3976   case ISD::SETULE:
3977   case ISD::SETLE:   return X86::COND_BE;
3978   case ISD::SETONE:
3979   case ISD::SETNE:   return X86::COND_NE;
3980   case ISD::SETUO:   return X86::COND_P;
3981   case ISD::SETO:    return X86::COND_NP;
3982   case ISD::SETOEQ:
3983   case ISD::SETUNE:  return X86::COND_INVALID;
3984   }
3985 }
3986
3987 /// Is there a floating point cmov for the specific X86 condition code?
3988 /// Current x86 isa includes the following FP cmov instructions:
3989 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3990 static bool hasFPCMov(unsigned X86CC) {
3991   switch (X86CC) {
3992   default:
3993     return false;
3994   case X86::COND_B:
3995   case X86::COND_BE:
3996   case X86::COND_E:
3997   case X86::COND_P:
3998   case X86::COND_A:
3999   case X86::COND_AE:
4000   case X86::COND_NE:
4001   case X86::COND_NP:
4002     return true;
4003   }
4004 }
4005
4006 /// Returns true if the target can instruction select the
4007 /// specified FP immediate natively. If false, the legalizer will
4008 /// materialize the FP immediate as a load from a constant pool.
4009 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4010   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4011     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4012       return true;
4013   }
4014   return false;
4015 }
4016
4017 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4018                                               ISD::LoadExtType ExtTy,
4019                                               EVT NewVT) const {
4020   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4021   // relocation target a movq or addq instruction: don't let the load shrink.
4022   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4023   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4024     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4025       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4026   return true;
4027 }
4028
4029 /// \brief Returns true if it is beneficial to convert a load of a constant
4030 /// to just the constant itself.
4031 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4032                                                           Type *Ty) const {
4033   assert(Ty->isIntegerTy());
4034
4035   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4036   if (BitSize == 0 || BitSize > 64)
4037     return false;
4038   return true;
4039 }
4040
4041 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4042                                                 unsigned Index) const {
4043   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4044     return false;
4045
4046   return (Index == 0 || Index == ResVT.getVectorNumElements());
4047 }
4048
4049 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4050   // Speculate cttz only if we can directly use TZCNT.
4051   return Subtarget->hasBMI();
4052 }
4053
4054 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4055   // Speculate ctlz only if we can directly use LZCNT.
4056   return Subtarget->hasLZCNT();
4057 }
4058
4059 /// Return true if every element in Mask, beginning
4060 /// from position Pos and ending in Pos+Size is undef.
4061 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4062   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4063     if (0 <= Mask[i])
4064       return false;
4065   return true;
4066 }
4067
4068 /// Return true if Val is undef or if its value falls within the
4069 /// specified range (L, H].
4070 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4071   return (Val < 0) || (Val >= Low && Val < Hi);
4072 }
4073
4074 /// Val is either less than zero (undef) or equal to the specified value.
4075 static bool isUndefOrEqual(int Val, int CmpVal) {
4076   return (Val < 0 || Val == CmpVal);
4077 }
4078
4079 /// Return true if every element in Mask, beginning
4080 /// from position Pos and ending in Pos+Size, falls within the specified
4081 /// sequential range (Low, Low+Size]. or is undef.
4082 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4083                                        unsigned Pos, unsigned Size, int Low) {
4084   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4085     if (!isUndefOrEqual(Mask[i], Low))
4086       return false;
4087   return true;
4088 }
4089
4090 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4091 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4092 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4093   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4094   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4095     return false;
4096
4097   // The index should be aligned on a vecWidth-bit boundary.
4098   uint64_t Index =
4099     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4100
4101   MVT VT = N->getSimpleValueType(0);
4102   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4103   bool Result = (Index * ElSize) % vecWidth == 0;
4104
4105   return Result;
4106 }
4107
4108 /// Return true if the specified INSERT_SUBVECTOR
4109 /// operand specifies a subvector insert that is suitable for input to
4110 /// insertion of 128 or 256-bit subvectors
4111 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4112   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4113   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4114     return false;
4115   // The index should be aligned on a vecWidth-bit boundary.
4116   uint64_t Index =
4117     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4118
4119   MVT VT = N->getSimpleValueType(0);
4120   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4121   bool Result = (Index * ElSize) % vecWidth == 0;
4122
4123   return Result;
4124 }
4125
4126 bool X86::isVINSERT128Index(SDNode *N) {
4127   return isVINSERTIndex(N, 128);
4128 }
4129
4130 bool X86::isVINSERT256Index(SDNode *N) {
4131   return isVINSERTIndex(N, 256);
4132 }
4133
4134 bool X86::isVEXTRACT128Index(SDNode *N) {
4135   return isVEXTRACTIndex(N, 128);
4136 }
4137
4138 bool X86::isVEXTRACT256Index(SDNode *N) {
4139   return isVEXTRACTIndex(N, 256);
4140 }
4141
4142 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4143   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4144   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4145     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4146
4147   uint64_t Index =
4148     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4149
4150   MVT VecVT = N->getOperand(0).getSimpleValueType();
4151   MVT ElVT = VecVT.getVectorElementType();
4152
4153   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4154   return Index / NumElemsPerChunk;
4155 }
4156
4157 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4158   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4159   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4160     llvm_unreachable("Illegal insert subvector for VINSERT");
4161
4162   uint64_t Index =
4163     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4164
4165   MVT VecVT = N->getSimpleValueType(0);
4166   MVT ElVT = VecVT.getVectorElementType();
4167
4168   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4169   return Index / NumElemsPerChunk;
4170 }
4171
4172 /// Return the appropriate immediate to extract the specified
4173 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4174 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4175   return getExtractVEXTRACTImmediate(N, 128);
4176 }
4177
4178 /// Return the appropriate immediate to extract the specified
4179 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4180 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4181   return getExtractVEXTRACTImmediate(N, 256);
4182 }
4183
4184 /// Return the appropriate immediate to insert at the specified
4185 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4186 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4187   return getInsertVINSERTImmediate(N, 128);
4188 }
4189
4190 /// Return the appropriate immediate to insert at the specified
4191 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4192 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4193   return getInsertVINSERTImmediate(N, 256);
4194 }
4195
4196 /// Returns true if Elt is a constant integer zero
4197 static bool isZero(SDValue V) {
4198   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4199   return C && C->isNullValue();
4200 }
4201
4202 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4203 bool X86::isZeroNode(SDValue Elt) {
4204   if (isZero(Elt))
4205     return true;
4206   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4207     return CFP->getValueAPF().isPosZero();
4208   return false;
4209 }
4210
4211 /// Returns a vector of specified type with all zero elements.
4212 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4213                              SelectionDAG &DAG, SDLoc dl) {
4214   assert(VT.isVector() && "Expected a vector type");
4215
4216   // Always build SSE zero vectors as <4 x i32> bitcasted
4217   // to their dest type. This ensures they get CSE'd.
4218   SDValue Vec;
4219   if (VT.is128BitVector()) {  // SSE
4220     if (Subtarget->hasSSE2()) {  // SSE2
4221       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223     } else { // SSE1
4224       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4225       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4226     }
4227   } else if (VT.is256BitVector()) { // AVX
4228     if (Subtarget->hasInt256()) { // AVX2
4229       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4230       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4232     } else {
4233       // 256-bit logic and arithmetic instructions in AVX are all
4234       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4235       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4236       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4237       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4238     }
4239   } else if (VT.is512BitVector()) { // AVX-512
4240       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4241       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4242                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4243       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4244   } else if (VT.getScalarType() == MVT::i1) {
4245
4246     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4247             && "Unexpected vector type");
4248     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4249             && "Unexpected vector type");
4250     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4251     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4252     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4253   } else
4254     llvm_unreachable("Unexpected vector type");
4255
4256   return DAG.getBitcast(VT, Vec);
4257 }
4258
4259 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4260                                 SelectionDAG &DAG, SDLoc dl,
4261                                 unsigned vectorWidth) {
4262   assert((vectorWidth == 128 || vectorWidth == 256) &&
4263          "Unsupported vector width");
4264   EVT VT = Vec.getValueType();
4265   EVT ElVT = VT.getVectorElementType();
4266   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4267   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4268                                   VT.getVectorNumElements()/Factor);
4269
4270   // Extract from UNDEF is UNDEF.
4271   if (Vec.getOpcode() == ISD::UNDEF)
4272     return DAG.getUNDEF(ResultVT);
4273
4274   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4275   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4276
4277   // This is the index of the first element of the vectorWidth-bit chunk
4278   // we want.
4279   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4280                                * ElemsPerChunk);
4281
4282   // If the input is a buildvector just emit a smaller one.
4283   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4284     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4285                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4286                                     ElemsPerChunk));
4287
4288   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4289   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4290 }
4291
4292 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4293 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4294 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4295 /// instructions or a simple subregister reference. Idx is an index in the
4296 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4297 /// lowering EXTRACT_VECTOR_ELT operations easier.
4298 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4299                                    SelectionDAG &DAG, SDLoc dl) {
4300   assert((Vec.getValueType().is256BitVector() ||
4301           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4302   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4303 }
4304
4305 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4306 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4307                                    SelectionDAG &DAG, SDLoc dl) {
4308   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4309   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4310 }
4311
4312 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4313                                unsigned IdxVal, SelectionDAG &DAG,
4314                                SDLoc dl, unsigned vectorWidth) {
4315   assert((vectorWidth == 128 || vectorWidth == 256) &&
4316          "Unsupported vector width");
4317   // Inserting UNDEF is Result
4318   if (Vec.getOpcode() == ISD::UNDEF)
4319     return Result;
4320   EVT VT = Vec.getValueType();
4321   EVT ElVT = VT.getVectorElementType();
4322   EVT ResultVT = Result.getValueType();
4323
4324   // Insert the relevant vectorWidth bits.
4325   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4326
4327   // This is the index of the first element of the vectorWidth-bit chunk
4328   // we want.
4329   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4330                                * ElemsPerChunk);
4331
4332   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4333   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4334 }
4335
4336 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4337 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4338 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4339 /// simple superregister reference.  Idx is an index in the 128 bits
4340 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4341 /// lowering INSERT_VECTOR_ELT operations easier.
4342 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4343                                   SelectionDAG &DAG, SDLoc dl) {
4344   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4345
4346   // For insertion into the zero index (low half) of a 256-bit vector, it is
4347   // more efficient to generate a blend with immediate instead of an insert*128.
4348   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4349   // extend the subvector to the size of the result vector. Make sure that
4350   // we are not recursing on that node by checking for undef here.
4351   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4352       Result.getOpcode() != ISD::UNDEF) {
4353     EVT ResultVT = Result.getValueType();
4354     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4355     SDValue Undef = DAG.getUNDEF(ResultVT);
4356     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4357                                  Vec, ZeroIndex);
4358
4359     // The blend instruction, and therefore its mask, depend on the data type.
4360     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4361     if (ScalarType.isFloatingPoint()) {
4362       // Choose either vblendps (float) or vblendpd (double).
4363       unsigned ScalarSize = ScalarType.getSizeInBits();
4364       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4365       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4366       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4367       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4368     }
4369
4370     const X86Subtarget &Subtarget =
4371     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4372
4373     // AVX2 is needed for 256-bit integer blend support.
4374     // Integers must be cast to 32-bit because there is only vpblendd;
4375     // vpblendw can't be used for this because it has a handicapped mask.
4376
4377     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4378     // is still more efficient than using the wrong domain vinsertf128 that
4379     // will be created by InsertSubVector().
4380     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4381
4382     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4383     Vec256 = DAG.getBitcast(CastVT, Vec256);
4384     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4385     return DAG.getBitcast(ResultVT, Vec256);
4386   }
4387
4388   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4389 }
4390
4391 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4392                                   SelectionDAG &DAG, SDLoc dl) {
4393   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4394   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4395 }
4396
4397 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4398 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4399 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4400 /// large BUILD_VECTORS.
4401 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4402                                    unsigned NumElems, SelectionDAG &DAG,
4403                                    SDLoc dl) {
4404   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4405   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4406 }
4407
4408 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4409                                    unsigned NumElems, SelectionDAG &DAG,
4410                                    SDLoc dl) {
4411   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4412   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4413 }
4414
4415 /// Returns a vector of specified type with all bits set.
4416 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4417 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4418 /// Then bitcast to their original type, ensuring they get CSE'd.
4419 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4420                              SDLoc dl) {
4421   assert(VT.isVector() && "Expected a vector type");
4422
4423   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4424   SDValue Vec;
4425   if (VT.is256BitVector()) {
4426     if (HasInt256) { // AVX2
4427       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4428       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4429     } else { // AVX
4430       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4431       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4432     }
4433   } else if (VT.is128BitVector()) {
4434     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4435   } else
4436     llvm_unreachable("Unexpected vector type");
4437
4438   return DAG.getBitcast(VT, Vec);
4439 }
4440
4441 /// Returns a vector_shuffle node for an unpackl operation.
4442 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4443                           SDValue V2) {
4444   unsigned NumElems = VT.getVectorNumElements();
4445   SmallVector<int, 8> Mask;
4446   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4447     Mask.push_back(i);
4448     Mask.push_back(i + NumElems);
4449   }
4450   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4451 }
4452
4453 /// Returns a vector_shuffle node for an unpackh operation.
4454 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4455                           SDValue V2) {
4456   unsigned NumElems = VT.getVectorNumElements();
4457   SmallVector<int, 8> Mask;
4458   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4459     Mask.push_back(i + Half);
4460     Mask.push_back(i + NumElems + Half);
4461   }
4462   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4463 }
4464
4465 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4466 /// This produces a shuffle where the low element of V2 is swizzled into the
4467 /// zero/undef vector, landing at element Idx.
4468 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4469 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4470                                            bool IsZero,
4471                                            const X86Subtarget *Subtarget,
4472                                            SelectionDAG &DAG) {
4473   MVT VT = V2.getSimpleValueType();
4474   SDValue V1 = IsZero
4475     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4476   unsigned NumElems = VT.getVectorNumElements();
4477   SmallVector<int, 16> MaskVec;
4478   for (unsigned i = 0; i != NumElems; ++i)
4479     // If this is the insertion idx, put the low elt of V2 here.
4480     MaskVec.push_back(i == Idx ? NumElems : i);
4481   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4482 }
4483
4484 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4485 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4486 /// uses one source. Note that this will set IsUnary for shuffles which use a
4487 /// single input multiple times, and in those cases it will
4488 /// adjust the mask to only have indices within that single input.
4489 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4490 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4491                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4492   unsigned NumElems = VT.getVectorNumElements();
4493   SDValue ImmN;
4494
4495   IsUnary = false;
4496   bool IsFakeUnary = false;
4497   switch(N->getOpcode()) {
4498   case X86ISD::BLENDI:
4499     ImmN = N->getOperand(N->getNumOperands()-1);
4500     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501     break;
4502   case X86ISD::SHUFP:
4503     ImmN = N->getOperand(N->getNumOperands()-1);
4504     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4506     break;
4507   case X86ISD::UNPCKH:
4508     DecodeUNPCKHMask(VT, Mask);
4509     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4510     break;
4511   case X86ISD::UNPCKL:
4512     DecodeUNPCKLMask(VT, Mask);
4513     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4514     break;
4515   case X86ISD::MOVHLPS:
4516     DecodeMOVHLPSMask(NumElems, Mask);
4517     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4518     break;
4519   case X86ISD::MOVLHPS:
4520     DecodeMOVLHPSMask(NumElems, Mask);
4521     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4522     break;
4523   case X86ISD::PALIGNR:
4524     ImmN = N->getOperand(N->getNumOperands()-1);
4525     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526     break;
4527   case X86ISD::PSHUFD:
4528   case X86ISD::VPERMILPI:
4529     ImmN = N->getOperand(N->getNumOperands()-1);
4530     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4531     IsUnary = true;
4532     break;
4533   case X86ISD::PSHUFHW:
4534     ImmN = N->getOperand(N->getNumOperands()-1);
4535     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4536     IsUnary = true;
4537     break;
4538   case X86ISD::PSHUFLW:
4539     ImmN = N->getOperand(N->getNumOperands()-1);
4540     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4541     IsUnary = true;
4542     break;
4543   case X86ISD::PSHUFB: {
4544     IsUnary = true;
4545     SDValue MaskNode = N->getOperand(1);
4546     while (MaskNode->getOpcode() == ISD::BITCAST)
4547       MaskNode = MaskNode->getOperand(0);
4548
4549     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4550       // If we have a build-vector, then things are easy.
4551       EVT VT = MaskNode.getValueType();
4552       assert(VT.isVector() &&
4553              "Can't produce a non-vector with a build_vector!");
4554       if (!VT.isInteger())
4555         return false;
4556
4557       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4558
4559       SmallVector<uint64_t, 32> RawMask;
4560       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4561         SDValue Op = MaskNode->getOperand(i);
4562         if (Op->getOpcode() == ISD::UNDEF) {
4563           RawMask.push_back((uint64_t)SM_SentinelUndef);
4564           continue;
4565         }
4566         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4567         if (!CN)
4568           return false;
4569         APInt MaskElement = CN->getAPIntValue();
4570
4571         // We now have to decode the element which could be any integer size and
4572         // extract each byte of it.
4573         for (int j = 0; j < NumBytesPerElement; ++j) {
4574           // Note that this is x86 and so always little endian: the low byte is
4575           // the first byte of the mask.
4576           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4577           MaskElement = MaskElement.lshr(8);
4578         }
4579       }
4580       DecodePSHUFBMask(RawMask, Mask);
4581       break;
4582     }
4583
4584     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4585     if (!MaskLoad)
4586       return false;
4587
4588     SDValue Ptr = MaskLoad->getBasePtr();
4589     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4590         Ptr->getOpcode() == X86ISD::WrapperRIP)
4591       Ptr = Ptr->getOperand(0);
4592
4593     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4594     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4595       return false;
4596
4597     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4598       DecodePSHUFBMask(C, Mask);
4599       if (Mask.empty())
4600         return false;
4601       break;
4602     }
4603
4604     return false;
4605   }
4606   case X86ISD::VPERMI:
4607     ImmN = N->getOperand(N->getNumOperands()-1);
4608     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4609     IsUnary = true;
4610     break;
4611   case X86ISD::MOVSS:
4612   case X86ISD::MOVSD:
4613     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4614     break;
4615   case X86ISD::VPERM2X128:
4616     ImmN = N->getOperand(N->getNumOperands()-1);
4617     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4618     if (Mask.empty()) return false;
4619     // Mask only contains negative index if an element is zero.
4620     if (std::any_of(Mask.begin(), Mask.end(),
4621                     [](int M){ return M == SM_SentinelZero; }))
4622       return false;
4623     break;
4624   case X86ISD::MOVSLDUP:
4625     DecodeMOVSLDUPMask(VT, Mask);
4626     IsUnary = true;
4627     break;
4628   case X86ISD::MOVSHDUP:
4629     DecodeMOVSHDUPMask(VT, Mask);
4630     IsUnary = true;
4631     break;
4632   case X86ISD::MOVDDUP:
4633     DecodeMOVDDUPMask(VT, Mask);
4634     IsUnary = true;
4635     break;
4636   case X86ISD::MOVLHPD:
4637   case X86ISD::MOVLPD:
4638   case X86ISD::MOVLPS:
4639     // Not yet implemented
4640     return false;
4641   default: llvm_unreachable("unknown target shuffle node");
4642   }
4643
4644   // If we have a fake unary shuffle, the shuffle mask is spread across two
4645   // inputs that are actually the same node. Re-map the mask to always point
4646   // into the first input.
4647   if (IsFakeUnary)
4648     for (int &M : Mask)
4649       if (M >= (int)Mask.size())
4650         M -= Mask.size();
4651
4652   return true;
4653 }
4654
4655 /// Returns the scalar element that will make up the ith
4656 /// element of the result of the vector shuffle.
4657 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4658                                    unsigned Depth) {
4659   if (Depth == 6)
4660     return SDValue();  // Limit search depth.
4661
4662   SDValue V = SDValue(N, 0);
4663   EVT VT = V.getValueType();
4664   unsigned Opcode = V.getOpcode();
4665
4666   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4667   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4668     int Elt = SV->getMaskElt(Index);
4669
4670     if (Elt < 0)
4671       return DAG.getUNDEF(VT.getVectorElementType());
4672
4673     unsigned NumElems = VT.getVectorNumElements();
4674     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4675                                          : SV->getOperand(1);
4676     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4677   }
4678
4679   // Recurse into target specific vector shuffles to find scalars.
4680   if (isTargetShuffle(Opcode)) {
4681     MVT ShufVT = V.getSimpleValueType();
4682     unsigned NumElems = ShufVT.getVectorNumElements();
4683     SmallVector<int, 16> ShuffleMask;
4684     bool IsUnary;
4685
4686     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4687       return SDValue();
4688
4689     int Elt = ShuffleMask[Index];
4690     if (Elt < 0)
4691       return DAG.getUNDEF(ShufVT.getVectorElementType());
4692
4693     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4694                                          : N->getOperand(1);
4695     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4696                                Depth+1);
4697   }
4698
4699   // Actual nodes that may contain scalar elements
4700   if (Opcode == ISD::BITCAST) {
4701     V = V.getOperand(0);
4702     EVT SrcVT = V.getValueType();
4703     unsigned NumElems = VT.getVectorNumElements();
4704
4705     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4706       return SDValue();
4707   }
4708
4709   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4710     return (Index == 0) ? V.getOperand(0)
4711                         : DAG.getUNDEF(VT.getVectorElementType());
4712
4713   if (V.getOpcode() == ISD::BUILD_VECTOR)
4714     return V.getOperand(Index);
4715
4716   return SDValue();
4717 }
4718
4719 /// Custom lower build_vector of v16i8.
4720 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4721                                        unsigned NumNonZero, unsigned NumZero,
4722                                        SelectionDAG &DAG,
4723                                        const X86Subtarget* Subtarget,
4724                                        const TargetLowering &TLI) {
4725   if (NumNonZero > 8)
4726     return SDValue();
4727
4728   SDLoc dl(Op);
4729   SDValue V;
4730   bool First = true;
4731
4732   // SSE4.1 - use PINSRB to insert each byte directly.
4733   if (Subtarget->hasSSE41()) {
4734     for (unsigned i = 0; i < 16; ++i) {
4735       bool isNonZero = (NonZeros & (1 << i)) != 0;
4736       if (isNonZero) {
4737         if (First) {
4738           if (NumZero)
4739             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4740           else
4741             V = DAG.getUNDEF(MVT::v16i8);
4742           First = false;
4743         }
4744         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4745                         MVT::v16i8, V, Op.getOperand(i),
4746                         DAG.getIntPtrConstant(i, dl));
4747       }
4748     }
4749
4750     return V;
4751   }
4752
4753   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4754   for (unsigned i = 0; i < 16; ++i) {
4755     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4756     if (ThisIsNonZero && First) {
4757       if (NumZero)
4758         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4759       else
4760         V = DAG.getUNDEF(MVT::v8i16);
4761       First = false;
4762     }
4763
4764     if ((i & 1) != 0) {
4765       SDValue ThisElt, LastElt;
4766       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4767       if (LastIsNonZero) {
4768         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4769                               MVT::i16, Op.getOperand(i-1));
4770       }
4771       if (ThisIsNonZero) {
4772         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4773         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4774                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4775         if (LastIsNonZero)
4776           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4777       } else
4778         ThisElt = LastElt;
4779
4780       if (ThisElt.getNode())
4781         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4782                         DAG.getIntPtrConstant(i/2, dl));
4783     }
4784   }
4785
4786   return DAG.getBitcast(MVT::v16i8, V);
4787 }
4788
4789 /// Custom lower build_vector of v8i16.
4790 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4791                                      unsigned NumNonZero, unsigned NumZero,
4792                                      SelectionDAG &DAG,
4793                                      const X86Subtarget* Subtarget,
4794                                      const TargetLowering &TLI) {
4795   if (NumNonZero > 4)
4796     return SDValue();
4797
4798   SDLoc dl(Op);
4799   SDValue V;
4800   bool First = true;
4801   for (unsigned i = 0; i < 8; ++i) {
4802     bool isNonZero = (NonZeros & (1 << i)) != 0;
4803     if (isNonZero) {
4804       if (First) {
4805         if (NumZero)
4806           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4807         else
4808           V = DAG.getUNDEF(MVT::v8i16);
4809         First = false;
4810       }
4811       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4812                       MVT::v8i16, V, Op.getOperand(i),
4813                       DAG.getIntPtrConstant(i, dl));
4814     }
4815   }
4816
4817   return V;
4818 }
4819
4820 /// Custom lower build_vector of v4i32 or v4f32.
4821 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4822                                      const X86Subtarget *Subtarget,
4823                                      const TargetLowering &TLI) {
4824   // Find all zeroable elements.
4825   std::bitset<4> Zeroable;
4826   for (int i=0; i < 4; ++i) {
4827     SDValue Elt = Op->getOperand(i);
4828     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4829   }
4830   assert(Zeroable.size() - Zeroable.count() > 1 &&
4831          "We expect at least two non-zero elements!");
4832
4833   // We only know how to deal with build_vector nodes where elements are either
4834   // zeroable or extract_vector_elt with constant index.
4835   SDValue FirstNonZero;
4836   unsigned FirstNonZeroIdx;
4837   for (unsigned i=0; i < 4; ++i) {
4838     if (Zeroable[i])
4839       continue;
4840     SDValue Elt = Op->getOperand(i);
4841     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4842         !isa<ConstantSDNode>(Elt.getOperand(1)))
4843       return SDValue();
4844     // Make sure that this node is extracting from a 128-bit vector.
4845     MVT VT = Elt.getOperand(0).getSimpleValueType();
4846     if (!VT.is128BitVector())
4847       return SDValue();
4848     if (!FirstNonZero.getNode()) {
4849       FirstNonZero = Elt;
4850       FirstNonZeroIdx = i;
4851     }
4852   }
4853
4854   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4855   SDValue V1 = FirstNonZero.getOperand(0);
4856   MVT VT = V1.getSimpleValueType();
4857
4858   // See if this build_vector can be lowered as a blend with zero.
4859   SDValue Elt;
4860   unsigned EltMaskIdx, EltIdx;
4861   int Mask[4];
4862   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4863     if (Zeroable[EltIdx]) {
4864       // The zero vector will be on the right hand side.
4865       Mask[EltIdx] = EltIdx+4;
4866       continue;
4867     }
4868
4869     Elt = Op->getOperand(EltIdx);
4870     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4871     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4872     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4873       break;
4874     Mask[EltIdx] = EltIdx;
4875   }
4876
4877   if (EltIdx == 4) {
4878     // Let the shuffle legalizer deal with blend operations.
4879     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4880     if (V1.getSimpleValueType() != VT)
4881       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4882     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4883   }
4884
4885   // See if we can lower this build_vector to a INSERTPS.
4886   if (!Subtarget->hasSSE41())
4887     return SDValue();
4888
4889   SDValue V2 = Elt.getOperand(0);
4890   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4891     V1 = SDValue();
4892
4893   bool CanFold = true;
4894   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4895     if (Zeroable[i])
4896       continue;
4897
4898     SDValue Current = Op->getOperand(i);
4899     SDValue SrcVector = Current->getOperand(0);
4900     if (!V1.getNode())
4901       V1 = SrcVector;
4902     CanFold = SrcVector == V1 &&
4903       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4904   }
4905
4906   if (!CanFold)
4907     return SDValue();
4908
4909   assert(V1.getNode() && "Expected at least two non-zero elements!");
4910   if (V1.getSimpleValueType() != MVT::v4f32)
4911     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4912   if (V2.getSimpleValueType() != MVT::v4f32)
4913     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4914
4915   // Ok, we can emit an INSERTPS instruction.
4916   unsigned ZMask = Zeroable.to_ulong();
4917
4918   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4919   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4920   SDLoc DL(Op);
4921   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4922                                DAG.getIntPtrConstant(InsertPSMask, DL));
4923   return DAG.getBitcast(VT, Result);
4924 }
4925
4926 /// Return a vector logical shift node.
4927 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4928                          unsigned NumBits, SelectionDAG &DAG,
4929                          const TargetLowering &TLI, SDLoc dl) {
4930   assert(VT.is128BitVector() && "Unknown type for VShift");
4931   MVT ShVT = MVT::v2i64;
4932   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4933   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4934   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4935   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4936   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4937   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4938 }
4939
4940 static SDValue
4941 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4942
4943   // Check if the scalar load can be widened into a vector load. And if
4944   // the address is "base + cst" see if the cst can be "absorbed" into
4945   // the shuffle mask.
4946   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4947     SDValue Ptr = LD->getBasePtr();
4948     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4949       return SDValue();
4950     EVT PVT = LD->getValueType(0);
4951     if (PVT != MVT::i32 && PVT != MVT::f32)
4952       return SDValue();
4953
4954     int FI = -1;
4955     int64_t Offset = 0;
4956     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4957       FI = FINode->getIndex();
4958       Offset = 0;
4959     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4960                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4961       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4962       Offset = Ptr.getConstantOperandVal(1);
4963       Ptr = Ptr.getOperand(0);
4964     } else {
4965       return SDValue();
4966     }
4967
4968     // FIXME: 256-bit vector instructions don't require a strict alignment,
4969     // improve this code to support it better.
4970     unsigned RequiredAlign = VT.getSizeInBits()/8;
4971     SDValue Chain = LD->getChain();
4972     // Make sure the stack object alignment is at least 16 or 32.
4973     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4974     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4975       if (MFI->isFixedObjectIndex(FI)) {
4976         // Can't change the alignment. FIXME: It's possible to compute
4977         // the exact stack offset and reference FI + adjust offset instead.
4978         // If someone *really* cares about this. That's the way to implement it.
4979         return SDValue();
4980       } else {
4981         MFI->setObjectAlignment(FI, RequiredAlign);
4982       }
4983     }
4984
4985     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4986     // Ptr + (Offset & ~15).
4987     if (Offset < 0)
4988       return SDValue();
4989     if ((Offset % RequiredAlign) & 3)
4990       return SDValue();
4991     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4992     if (StartOffset) {
4993       SDLoc DL(Ptr);
4994       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4995                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4996     }
4997
4998     int EltNo = (Offset - StartOffset) >> 2;
4999     unsigned NumElems = VT.getVectorNumElements();
5000
5001     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5002     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5003                              LD->getPointerInfo().getWithOffset(StartOffset),
5004                              false, false, false, 0);
5005
5006     SmallVector<int, 8> Mask(NumElems, EltNo);
5007
5008     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5009   }
5010
5011   return SDValue();
5012 }
5013
5014 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5015 /// elements can be replaced by a single large load which has the same value as
5016 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5017 ///
5018 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5019 ///
5020 /// FIXME: we'd also like to handle the case where the last elements are zero
5021 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5022 /// There's even a handy isZeroNode for that purpose.
5023 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5024                                         SDLoc &DL, SelectionDAG &DAG,
5025                                         bool isAfterLegalize) {
5026   unsigned NumElems = Elts.size();
5027
5028   LoadSDNode *LDBase = nullptr;
5029   unsigned LastLoadedElt = -1U;
5030
5031   // For each element in the initializer, see if we've found a load or an undef.
5032   // If we don't find an initial load element, or later load elements are
5033   // non-consecutive, bail out.
5034   for (unsigned i = 0; i < NumElems; ++i) {
5035     SDValue Elt = Elts[i];
5036     // Look through a bitcast.
5037     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5038       Elt = Elt.getOperand(0);
5039     if (!Elt.getNode() ||
5040         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5041       return SDValue();
5042     if (!LDBase) {
5043       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5044         return SDValue();
5045       LDBase = cast<LoadSDNode>(Elt.getNode());
5046       LastLoadedElt = i;
5047       continue;
5048     }
5049     if (Elt.getOpcode() == ISD::UNDEF)
5050       continue;
5051
5052     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5053     EVT LdVT = Elt.getValueType();
5054     // Each loaded element must be the correct fractional portion of the
5055     // requested vector load.
5056     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5057       return SDValue();
5058     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5059       return SDValue();
5060     LastLoadedElt = i;
5061   }
5062
5063   // If we have found an entire vector of loads and undefs, then return a large
5064   // load of the entire vector width starting at the base pointer.  If we found
5065   // consecutive loads for the low half, generate a vzext_load node.
5066   if (LastLoadedElt == NumElems - 1) {
5067     assert(LDBase && "Did not find base load for merging consecutive loads");
5068     EVT EltVT = LDBase->getValueType(0);
5069     // Ensure that the input vector size for the merged loads matches the
5070     // cumulative size of the input elements.
5071     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5072       return SDValue();
5073
5074     if (isAfterLegalize &&
5075         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5076       return SDValue();
5077
5078     SDValue NewLd = SDValue();
5079
5080     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5081                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5082                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5083                         LDBase->getAlignment());
5084
5085     if (LDBase->hasAnyUseOfValue(1)) {
5086       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5087                                      SDValue(LDBase, 1),
5088                                      SDValue(NewLd.getNode(), 1));
5089       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5090       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5091                              SDValue(NewLd.getNode(), 1));
5092     }
5093
5094     return NewLd;
5095   }
5096
5097   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5098   //of a v4i32 / v4f32. It's probably worth generalizing.
5099   EVT EltVT = VT.getVectorElementType();
5100   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5101       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5102     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5103     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5104     SDValue ResNode =
5105         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5106                                 LDBase->getPointerInfo(),
5107                                 LDBase->getAlignment(),
5108                                 false/*isVolatile*/, true/*ReadMem*/,
5109                                 false/*WriteMem*/);
5110
5111     // Make sure the newly-created LOAD is in the same position as LDBase in
5112     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5113     // update uses of LDBase's output chain to use the TokenFactor.
5114     if (LDBase->hasAnyUseOfValue(1)) {
5115       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5116                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5117       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5118       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5119                              SDValue(ResNode.getNode(), 1));
5120     }
5121
5122     return DAG.getBitcast(VT, ResNode);
5123   }
5124   return SDValue();
5125 }
5126
5127 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5128 /// to generate a splat value for the following cases:
5129 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5130 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5131 /// a scalar load, or a constant.
5132 /// The VBROADCAST node is returned when a pattern is found,
5133 /// or SDValue() otherwise.
5134 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5135                                     SelectionDAG &DAG) {
5136   // VBROADCAST requires AVX.
5137   // TODO: Splats could be generated for non-AVX CPUs using SSE
5138   // instructions, but there's less potential gain for only 128-bit vectors.
5139   if (!Subtarget->hasAVX())
5140     return SDValue();
5141
5142   MVT VT = Op.getSimpleValueType();
5143   SDLoc dl(Op);
5144
5145   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5146          "Unsupported vector type for broadcast.");
5147
5148   SDValue Ld;
5149   bool ConstSplatVal;
5150
5151   switch (Op.getOpcode()) {
5152     default:
5153       // Unknown pattern found.
5154       return SDValue();
5155
5156     case ISD::BUILD_VECTOR: {
5157       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5158       BitVector UndefElements;
5159       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5160
5161       // We need a splat of a single value to use broadcast, and it doesn't
5162       // make any sense if the value is only in one element of the vector.
5163       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5164         return SDValue();
5165
5166       Ld = Splat;
5167       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5168                        Ld.getOpcode() == ISD::ConstantFP);
5169
5170       // Make sure that all of the users of a non-constant load are from the
5171       // BUILD_VECTOR node.
5172       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5173         return SDValue();
5174       break;
5175     }
5176
5177     case ISD::VECTOR_SHUFFLE: {
5178       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5179
5180       // Shuffles must have a splat mask where the first element is
5181       // broadcasted.
5182       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5183         return SDValue();
5184
5185       SDValue Sc = Op.getOperand(0);
5186       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5187           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5188
5189         if (!Subtarget->hasInt256())
5190           return SDValue();
5191
5192         // Use the register form of the broadcast instruction available on AVX2.
5193         if (VT.getSizeInBits() >= 256)
5194           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5195         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5196       }
5197
5198       Ld = Sc.getOperand(0);
5199       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5200                        Ld.getOpcode() == ISD::ConstantFP);
5201
5202       // The scalar_to_vector node and the suspected
5203       // load node must have exactly one user.
5204       // Constants may have multiple users.
5205
5206       // AVX-512 has register version of the broadcast
5207       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5208         Ld.getValueType().getSizeInBits() >= 32;
5209       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5210           !hasRegVer))
5211         return SDValue();
5212       break;
5213     }
5214   }
5215
5216   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5217   bool IsGE256 = (VT.getSizeInBits() >= 256);
5218
5219   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5220   // instruction to save 8 or more bytes of constant pool data.
5221   // TODO: If multiple splats are generated to load the same constant,
5222   // it may be detrimental to overall size. There needs to be a way to detect
5223   // that condition to know if this is truly a size win.
5224   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5225
5226   // Handle broadcasting a single constant scalar from the constant pool
5227   // into a vector.
5228   // On Sandybridge (no AVX2), it is still better to load a constant vector
5229   // from the constant pool and not to broadcast it from a scalar.
5230   // But override that restriction when optimizing for size.
5231   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5232   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5233     EVT CVT = Ld.getValueType();
5234     assert(!CVT.isVector() && "Must not broadcast a vector type");
5235
5236     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5237     // For size optimization, also splat v2f64 and v2i64, and for size opt
5238     // with AVX2, also splat i8 and i16.
5239     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5240     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5241         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5242       const Constant *C = nullptr;
5243       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5244         C = CI->getConstantIntValue();
5245       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5246         C = CF->getConstantFPValue();
5247
5248       assert(C && "Invalid constant type");
5249
5250       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5251       SDValue CP =
5252           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5253       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5254       Ld = DAG.getLoad(
5255           CVT, dl, DAG.getEntryNode(), CP,
5256           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5257           false, false, Alignment);
5258
5259       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5260     }
5261   }
5262
5263   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5264
5265   // Handle AVX2 in-register broadcasts.
5266   if (!IsLoad && Subtarget->hasInt256() &&
5267       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5268     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5269
5270   // The scalar source must be a normal load.
5271   if (!IsLoad)
5272     return SDValue();
5273
5274   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5275       (Subtarget->hasVLX() && ScalarSize == 64))
5276     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5277
5278   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5279   // double since there is no vbroadcastsd xmm
5280   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5281     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5282       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5283   }
5284
5285   // Unsupported broadcast.
5286   return SDValue();
5287 }
5288
5289 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5290 /// underlying vector and index.
5291 ///
5292 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5293 /// index.
5294 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5295                                          SDValue ExtIdx) {
5296   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5297   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5298     return Idx;
5299
5300   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5301   // lowered this:
5302   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5303   // to:
5304   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5305   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5306   //                           undef)
5307   //                       Constant<0>)
5308   // In this case the vector is the extract_subvector expression and the index
5309   // is 2, as specified by the shuffle.
5310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5311   SDValue ShuffleVec = SVOp->getOperand(0);
5312   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5313   assert(ShuffleVecVT.getVectorElementType() ==
5314          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5315
5316   int ShuffleIdx = SVOp->getMaskElt(Idx);
5317   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5318     ExtractedFromVec = ShuffleVec;
5319     return ShuffleIdx;
5320   }
5321   return Idx;
5322 }
5323
5324 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5325   MVT VT = Op.getSimpleValueType();
5326
5327   // Skip if insert_vec_elt is not supported.
5328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5329   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5330     return SDValue();
5331
5332   SDLoc DL(Op);
5333   unsigned NumElems = Op.getNumOperands();
5334
5335   SDValue VecIn1;
5336   SDValue VecIn2;
5337   SmallVector<unsigned, 4> InsertIndices;
5338   SmallVector<int, 8> Mask(NumElems, -1);
5339
5340   for (unsigned i = 0; i != NumElems; ++i) {
5341     unsigned Opc = Op.getOperand(i).getOpcode();
5342
5343     if (Opc == ISD::UNDEF)
5344       continue;
5345
5346     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5347       // Quit if more than 1 elements need inserting.
5348       if (InsertIndices.size() > 1)
5349         return SDValue();
5350
5351       InsertIndices.push_back(i);
5352       continue;
5353     }
5354
5355     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5356     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5357     // Quit if non-constant index.
5358     if (!isa<ConstantSDNode>(ExtIdx))
5359       return SDValue();
5360     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5361
5362     // Quit if extracted from vector of different type.
5363     if (ExtractedFromVec.getValueType() != VT)
5364       return SDValue();
5365
5366     if (!VecIn1.getNode())
5367       VecIn1 = ExtractedFromVec;
5368     else if (VecIn1 != ExtractedFromVec) {
5369       if (!VecIn2.getNode())
5370         VecIn2 = ExtractedFromVec;
5371       else if (VecIn2 != ExtractedFromVec)
5372         // Quit if more than 2 vectors to shuffle
5373         return SDValue();
5374     }
5375
5376     if (ExtractedFromVec == VecIn1)
5377       Mask[i] = Idx;
5378     else if (ExtractedFromVec == VecIn2)
5379       Mask[i] = Idx + NumElems;
5380   }
5381
5382   if (!VecIn1.getNode())
5383     return SDValue();
5384
5385   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5386   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5387   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5388     unsigned Idx = InsertIndices[i];
5389     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5390                      DAG.getIntPtrConstant(Idx, DL));
5391   }
5392
5393   return NV;
5394 }
5395
5396 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5397   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5398          Op.getScalarValueSizeInBits() == 1 &&
5399          "Can not convert non-constant vector");
5400   uint64_t Immediate = 0;
5401   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5402     SDValue In = Op.getOperand(idx);
5403     if (In.getOpcode() != ISD::UNDEF)
5404       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5405   }
5406   SDLoc dl(Op);
5407   MVT VT =
5408    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5409   return DAG.getConstant(Immediate, dl, VT);
5410 }
5411 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5412 SDValue
5413 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5414
5415   MVT VT = Op.getSimpleValueType();
5416   assert((VT.getVectorElementType() == MVT::i1) &&
5417          "Unexpected type in LowerBUILD_VECTORvXi1!");
5418
5419   SDLoc dl(Op);
5420   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5421     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5422     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5423     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5424   }
5425
5426   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5427     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5428     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5429     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5430   }
5431
5432   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5433     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5434     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5435       return DAG.getBitcast(VT, Imm);
5436     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5437     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5438                         DAG.getIntPtrConstant(0, dl));
5439   }
5440
5441   // Vector has one or more non-const elements
5442   uint64_t Immediate = 0;
5443   SmallVector<unsigned, 16> NonConstIdx;
5444   bool IsSplat = true;
5445   bool HasConstElts = false;
5446   int SplatIdx = -1;
5447   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5448     SDValue In = Op.getOperand(idx);
5449     if (In.getOpcode() == ISD::UNDEF)
5450       continue;
5451     if (!isa<ConstantSDNode>(In))
5452       NonConstIdx.push_back(idx);
5453     else {
5454       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5455       HasConstElts = true;
5456     }
5457     if (SplatIdx == -1)
5458       SplatIdx = idx;
5459     else if (In != Op.getOperand(SplatIdx))
5460       IsSplat = false;
5461   }
5462
5463   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5464   if (IsSplat)
5465     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5466                        DAG.getConstant(1, dl, VT),
5467                        DAG.getConstant(0, dl, VT));
5468
5469   // insert elements one by one
5470   SDValue DstVec;
5471   SDValue Imm;
5472   if (Immediate) {
5473     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5474     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5475   }
5476   else if (HasConstElts)
5477     Imm = DAG.getConstant(0, dl, VT);
5478   else
5479     Imm = DAG.getUNDEF(VT);
5480   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5481     DstVec = DAG.getBitcast(VT, Imm);
5482   else {
5483     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5484     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5485                          DAG.getIntPtrConstant(0, dl));
5486   }
5487
5488   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5489     unsigned InsertIdx = NonConstIdx[i];
5490     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5491                          Op.getOperand(InsertIdx),
5492                          DAG.getIntPtrConstant(InsertIdx, dl));
5493   }
5494   return DstVec;
5495 }
5496
5497 /// \brief Return true if \p N implements a horizontal binop and return the
5498 /// operands for the horizontal binop into V0 and V1.
5499 ///
5500 /// This is a helper function of LowerToHorizontalOp().
5501 /// This function checks that the build_vector \p N in input implements a
5502 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5503 /// operation to match.
5504 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5505 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5506 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5507 /// arithmetic sub.
5508 ///
5509 /// This function only analyzes elements of \p N whose indices are
5510 /// in range [BaseIdx, LastIdx).
5511 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5512                               SelectionDAG &DAG,
5513                               unsigned BaseIdx, unsigned LastIdx,
5514                               SDValue &V0, SDValue &V1) {
5515   EVT VT = N->getValueType(0);
5516
5517   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5518   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5519          "Invalid Vector in input!");
5520
5521   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5522   bool CanFold = true;
5523   unsigned ExpectedVExtractIdx = BaseIdx;
5524   unsigned NumElts = LastIdx - BaseIdx;
5525   V0 = DAG.getUNDEF(VT);
5526   V1 = DAG.getUNDEF(VT);
5527
5528   // Check if N implements a horizontal binop.
5529   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5530     SDValue Op = N->getOperand(i + BaseIdx);
5531
5532     // Skip UNDEFs.
5533     if (Op->getOpcode() == ISD::UNDEF) {
5534       // Update the expected vector extract index.
5535       if (i * 2 == NumElts)
5536         ExpectedVExtractIdx = BaseIdx;
5537       ExpectedVExtractIdx += 2;
5538       continue;
5539     }
5540
5541     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5542
5543     if (!CanFold)
5544       break;
5545
5546     SDValue Op0 = Op.getOperand(0);
5547     SDValue Op1 = Op.getOperand(1);
5548
5549     // Try to match the following pattern:
5550     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5551     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5552         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5553         Op0.getOperand(0) == Op1.getOperand(0) &&
5554         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5555         isa<ConstantSDNode>(Op1.getOperand(1)));
5556     if (!CanFold)
5557       break;
5558
5559     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5560     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5561
5562     if (i * 2 < NumElts) {
5563       if (V0.getOpcode() == ISD::UNDEF) {
5564         V0 = Op0.getOperand(0);
5565         if (V0.getValueType() != VT)
5566           return false;
5567       }
5568     } else {
5569       if (V1.getOpcode() == ISD::UNDEF) {
5570         V1 = Op0.getOperand(0);
5571         if (V1.getValueType() != VT)
5572           return false;
5573       }
5574       if (i * 2 == NumElts)
5575         ExpectedVExtractIdx = BaseIdx;
5576     }
5577
5578     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5579     if (I0 == ExpectedVExtractIdx)
5580       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5581     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5582       // Try to match the following dag sequence:
5583       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5584       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5585     } else
5586       CanFold = false;
5587
5588     ExpectedVExtractIdx += 2;
5589   }
5590
5591   return CanFold;
5592 }
5593
5594 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5595 /// a concat_vector.
5596 ///
5597 /// This is a helper function of LowerToHorizontalOp().
5598 /// This function expects two 256-bit vectors called V0 and V1.
5599 /// At first, each vector is split into two separate 128-bit vectors.
5600 /// Then, the resulting 128-bit vectors are used to implement two
5601 /// horizontal binary operations.
5602 ///
5603 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5604 ///
5605 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5606 /// the two new horizontal binop.
5607 /// When Mode is set, the first horizontal binop dag node would take as input
5608 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5609 /// horizontal binop dag node would take as input the lower 128-bit of V1
5610 /// and the upper 128-bit of V1.
5611 ///   Example:
5612 ///     HADD V0_LO, V0_HI
5613 ///     HADD V1_LO, V1_HI
5614 ///
5615 /// Otherwise, the first horizontal binop dag node takes as input the lower
5616 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5617 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5618 ///   Example:
5619 ///     HADD V0_LO, V1_LO
5620 ///     HADD V0_HI, V1_HI
5621 ///
5622 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5623 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5624 /// the upper 128-bits of the result.
5625 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5626                                      SDLoc DL, SelectionDAG &DAG,
5627                                      unsigned X86Opcode, bool Mode,
5628                                      bool isUndefLO, bool isUndefHI) {
5629   EVT VT = V0.getValueType();
5630   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5631          "Invalid nodes in input!");
5632
5633   unsigned NumElts = VT.getVectorNumElements();
5634   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5635   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5636   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5637   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5638   EVT NewVT = V0_LO.getValueType();
5639
5640   SDValue LO = DAG.getUNDEF(NewVT);
5641   SDValue HI = DAG.getUNDEF(NewVT);
5642
5643   if (Mode) {
5644     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5645     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5646       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5647     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5648       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5649   } else {
5650     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5651     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5652                        V1_LO->getOpcode() != ISD::UNDEF))
5653       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5654
5655     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5656                        V1_HI->getOpcode() != ISD::UNDEF))
5657       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5658   }
5659
5660   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5661 }
5662
5663 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5664 /// node.
5665 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5666                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5667   EVT VT = BV->getValueType(0);
5668   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5669       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5670     return SDValue();
5671
5672   SDLoc DL(BV);
5673   unsigned NumElts = VT.getVectorNumElements();
5674   SDValue InVec0 = DAG.getUNDEF(VT);
5675   SDValue InVec1 = DAG.getUNDEF(VT);
5676
5677   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5678           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5679
5680   // Odd-numbered elements in the input build vector are obtained from
5681   // adding two integer/float elements.
5682   // Even-numbered elements in the input build vector are obtained from
5683   // subtracting two integer/float elements.
5684   unsigned ExpectedOpcode = ISD::FSUB;
5685   unsigned NextExpectedOpcode = ISD::FADD;
5686   bool AddFound = false;
5687   bool SubFound = false;
5688
5689   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5690     SDValue Op = BV->getOperand(i);
5691
5692     // Skip 'undef' values.
5693     unsigned Opcode = Op.getOpcode();
5694     if (Opcode == ISD::UNDEF) {
5695       std::swap(ExpectedOpcode, NextExpectedOpcode);
5696       continue;
5697     }
5698
5699     // Early exit if we found an unexpected opcode.
5700     if (Opcode != ExpectedOpcode)
5701       return SDValue();
5702
5703     SDValue Op0 = Op.getOperand(0);
5704     SDValue Op1 = Op.getOperand(1);
5705
5706     // Try to match the following pattern:
5707     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5708     // Early exit if we cannot match that sequence.
5709     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5710         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5711         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5712         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5713         Op0.getOperand(1) != Op1.getOperand(1))
5714       return SDValue();
5715
5716     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5717     if (I0 != i)
5718       return SDValue();
5719
5720     // We found a valid add/sub node. Update the information accordingly.
5721     if (i & 1)
5722       AddFound = true;
5723     else
5724       SubFound = true;
5725
5726     // Update InVec0 and InVec1.
5727     if (InVec0.getOpcode() == ISD::UNDEF) {
5728       InVec0 = Op0.getOperand(0);
5729       if (InVec0.getValueType() != VT)
5730         return SDValue();
5731     }
5732     if (InVec1.getOpcode() == ISD::UNDEF) {
5733       InVec1 = Op1.getOperand(0);
5734       if (InVec1.getValueType() != VT)
5735         return SDValue();
5736     }
5737
5738     // Make sure that operands in input to each add/sub node always
5739     // come from a same pair of vectors.
5740     if (InVec0 != Op0.getOperand(0)) {
5741       if (ExpectedOpcode == ISD::FSUB)
5742         return SDValue();
5743
5744       // FADD is commutable. Try to commute the operands
5745       // and then test again.
5746       std::swap(Op0, Op1);
5747       if (InVec0 != Op0.getOperand(0))
5748         return SDValue();
5749     }
5750
5751     if (InVec1 != Op1.getOperand(0))
5752       return SDValue();
5753
5754     // Update the pair of expected opcodes.
5755     std::swap(ExpectedOpcode, NextExpectedOpcode);
5756   }
5757
5758   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5759   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5760       InVec1.getOpcode() != ISD::UNDEF)
5761     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5762
5763   return SDValue();
5764 }
5765
5766 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5767 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5768                                    const X86Subtarget *Subtarget,
5769                                    SelectionDAG &DAG) {
5770   EVT VT = BV->getValueType(0);
5771   unsigned NumElts = VT.getVectorNumElements();
5772   unsigned NumUndefsLO = 0;
5773   unsigned NumUndefsHI = 0;
5774   unsigned Half = NumElts/2;
5775
5776   // Count the number of UNDEF operands in the build_vector in input.
5777   for (unsigned i = 0, e = Half; i != e; ++i)
5778     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5779       NumUndefsLO++;
5780
5781   for (unsigned i = Half, e = NumElts; i != e; ++i)
5782     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5783       NumUndefsHI++;
5784
5785   // Early exit if this is either a build_vector of all UNDEFs or all the
5786   // operands but one are UNDEF.
5787   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5788     return SDValue();
5789
5790   SDLoc DL(BV);
5791   SDValue InVec0, InVec1;
5792   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5793     // Try to match an SSE3 float HADD/HSUB.
5794     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5795       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5796
5797     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5798       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5799   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5800     // Try to match an SSSE3 integer HADD/HSUB.
5801     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5802       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5803
5804     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5805       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5806   }
5807
5808   if (!Subtarget->hasAVX())
5809     return SDValue();
5810
5811   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5812     // Try to match an AVX horizontal add/sub of packed single/double
5813     // precision floating point values from 256-bit vectors.
5814     SDValue InVec2, InVec3;
5815     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5816         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5817         ((InVec0.getOpcode() == ISD::UNDEF ||
5818           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5819         ((InVec1.getOpcode() == ISD::UNDEF ||
5820           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5821       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5822
5823     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5824         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5825         ((InVec0.getOpcode() == ISD::UNDEF ||
5826           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5827         ((InVec1.getOpcode() == ISD::UNDEF ||
5828           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5829       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5830   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5831     // Try to match an AVX2 horizontal add/sub of signed integers.
5832     SDValue InVec2, InVec3;
5833     unsigned X86Opcode;
5834     bool CanFold = true;
5835
5836     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5837         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5838         ((InVec0.getOpcode() == ISD::UNDEF ||
5839           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5840         ((InVec1.getOpcode() == ISD::UNDEF ||
5841           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5842       X86Opcode = X86ISD::HADD;
5843     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5844         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5845         ((InVec0.getOpcode() == ISD::UNDEF ||
5846           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5847         ((InVec1.getOpcode() == ISD::UNDEF ||
5848           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5849       X86Opcode = X86ISD::HSUB;
5850     else
5851       CanFold = false;
5852
5853     if (CanFold) {
5854       // Fold this build_vector into a single horizontal add/sub.
5855       // Do this only if the target has AVX2.
5856       if (Subtarget->hasAVX2())
5857         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5858
5859       // Do not try to expand this build_vector into a pair of horizontal
5860       // add/sub if we can emit a pair of scalar add/sub.
5861       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5862         return SDValue();
5863
5864       // Convert this build_vector into a pair of horizontal binop followed by
5865       // a concat vector.
5866       bool isUndefLO = NumUndefsLO == Half;
5867       bool isUndefHI = NumUndefsHI == Half;
5868       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5869                                    isUndefLO, isUndefHI);
5870     }
5871   }
5872
5873   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5874        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5875     unsigned X86Opcode;
5876     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5877       X86Opcode = X86ISD::HADD;
5878     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5879       X86Opcode = X86ISD::HSUB;
5880     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5881       X86Opcode = X86ISD::FHADD;
5882     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5883       X86Opcode = X86ISD::FHSUB;
5884     else
5885       return SDValue();
5886
5887     // Don't try to expand this build_vector into a pair of horizontal add/sub
5888     // if we can simply emit a pair of scalar add/sub.
5889     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5890       return SDValue();
5891
5892     // Convert this build_vector into two horizontal add/sub followed by
5893     // a concat vector.
5894     bool isUndefLO = NumUndefsLO == Half;
5895     bool isUndefHI = NumUndefsHI == Half;
5896     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5897                                  isUndefLO, isUndefHI);
5898   }
5899
5900   return SDValue();
5901 }
5902
5903 SDValue
5904 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5905   SDLoc dl(Op);
5906
5907   MVT VT = Op.getSimpleValueType();
5908   MVT ExtVT = VT.getVectorElementType();
5909   unsigned NumElems = Op.getNumOperands();
5910
5911   // Generate vectors for predicate vectors.
5912   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5913     return LowerBUILD_VECTORvXi1(Op, DAG);
5914
5915   // Vectors containing all zeros can be matched by pxor and xorps later
5916   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5917     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5918     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5919     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5920       return Op;
5921
5922     return getZeroVector(VT, Subtarget, DAG, dl);
5923   }
5924
5925   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5926   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5927   // vpcmpeqd on 256-bit vectors.
5928   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5929     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5930       return Op;
5931
5932     if (!VT.is512BitVector())
5933       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5934   }
5935
5936   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5937   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5938     return AddSub;
5939   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5940     return HorizontalOp;
5941   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5942     return Broadcast;
5943
5944   unsigned EVTBits = ExtVT.getSizeInBits();
5945
5946   unsigned NumZero  = 0;
5947   unsigned NumNonZero = 0;
5948   unsigned NonZeros = 0;
5949   bool IsAllConstants = true;
5950   SmallSet<SDValue, 8> Values;
5951   for (unsigned i = 0; i < NumElems; ++i) {
5952     SDValue Elt = Op.getOperand(i);
5953     if (Elt.getOpcode() == ISD::UNDEF)
5954       continue;
5955     Values.insert(Elt);
5956     if (Elt.getOpcode() != ISD::Constant &&
5957         Elt.getOpcode() != ISD::ConstantFP)
5958       IsAllConstants = false;
5959     if (X86::isZeroNode(Elt))
5960       NumZero++;
5961     else {
5962       NonZeros |= (1 << i);
5963       NumNonZero++;
5964     }
5965   }
5966
5967   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5968   if (NumNonZero == 0)
5969     return DAG.getUNDEF(VT);
5970
5971   // Special case for single non-zero, non-undef, element.
5972   if (NumNonZero == 1) {
5973     unsigned Idx = countTrailingZeros(NonZeros);
5974     SDValue Item = Op.getOperand(Idx);
5975
5976     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5977     // the value are obviously zero, truncate the value to i32 and do the
5978     // insertion that way.  Only do this if the value is non-constant or if the
5979     // value is a constant being inserted into element 0.  It is cheaper to do
5980     // a constant pool load than it is to do a movd + shuffle.
5981     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5982         (!IsAllConstants || Idx == 0)) {
5983       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5984         // Handle SSE only.
5985         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5986         EVT VecVT = MVT::v4i32;
5987
5988         // Truncate the value (which may itself be a constant) to i32, and
5989         // convert it to a vector with movd (S2V+shuffle to zero extend).
5990         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5991         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5992         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5993                                       Item, Idx * 2, true, Subtarget, DAG));
5994       }
5995     }
5996
5997     // If we have a constant or non-constant insertion into the low element of
5998     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5999     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6000     // depending on what the source datatype is.
6001     if (Idx == 0) {
6002       if (NumZero == 0)
6003         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6004
6005       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6006           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6007         if (VT.is512BitVector()) {
6008           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6009           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6010                              Item, DAG.getIntPtrConstant(0, dl));
6011         }
6012         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6013                "Expected an SSE value type!");
6014         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6015         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6016         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6017       }
6018
6019       // We can't directly insert an i8 or i16 into a vector, so zero extend
6020       // it to i32 first.
6021       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6022         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6023         if (VT.is256BitVector()) {
6024           if (Subtarget->hasAVX()) {
6025             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6026             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6027           } else {
6028             // Without AVX, we need to extend to a 128-bit vector and then
6029             // insert into the 256-bit vector.
6030             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6031             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6032             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6033           }
6034         } else {
6035           assert(VT.is128BitVector() && "Expected an SSE value type!");
6036           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6037           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6038         }
6039         return DAG.getBitcast(VT, Item);
6040       }
6041     }
6042
6043     // Is it a vector logical left shift?
6044     if (NumElems == 2 && Idx == 1 &&
6045         X86::isZeroNode(Op.getOperand(0)) &&
6046         !X86::isZeroNode(Op.getOperand(1))) {
6047       unsigned NumBits = VT.getSizeInBits();
6048       return getVShift(true, VT,
6049                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6050                                    VT, Op.getOperand(1)),
6051                        NumBits/2, DAG, *this, dl);
6052     }
6053
6054     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6055       return SDValue();
6056
6057     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6058     // is a non-constant being inserted into an element other than the low one,
6059     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6060     // movd/movss) to move this into the low element, then shuffle it into
6061     // place.
6062     if (EVTBits == 32) {
6063       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6064       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6065     }
6066   }
6067
6068   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6069   if (Values.size() == 1) {
6070     if (EVTBits == 32) {
6071       // Instead of a shuffle like this:
6072       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6073       // Check if it's possible to issue this instead.
6074       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6075       unsigned Idx = countTrailingZeros(NonZeros);
6076       SDValue Item = Op.getOperand(Idx);
6077       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6078         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6079     }
6080     return SDValue();
6081   }
6082
6083   // A vector full of immediates; various special cases are already
6084   // handled, so this is best done with a single constant-pool load.
6085   if (IsAllConstants)
6086     return SDValue();
6087
6088   // For AVX-length vectors, see if we can use a vector load to get all of the
6089   // elements, otherwise build the individual 128-bit pieces and use
6090   // shuffles to put them in place.
6091   if (VT.is256BitVector() || VT.is512BitVector()) {
6092     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6093
6094     // Check for a build vector of consecutive loads.
6095     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6096       return LD;
6097
6098     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6099
6100     // Build both the lower and upper subvector.
6101     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6102                                 makeArrayRef(&V[0], NumElems/2));
6103     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6104                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6105
6106     // Recreate the wider vector with the lower and upper part.
6107     if (VT.is256BitVector())
6108       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6109     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6110   }
6111
6112   // Let legalizer expand 2-wide build_vectors.
6113   if (EVTBits == 64) {
6114     if (NumNonZero == 1) {
6115       // One half is zero or undef.
6116       unsigned Idx = countTrailingZeros(NonZeros);
6117       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6118                                  Op.getOperand(Idx));
6119       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6120     }
6121     return SDValue();
6122   }
6123
6124   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6125   if (EVTBits == 8 && NumElems == 16)
6126     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6127                                         Subtarget, *this))
6128       return V;
6129
6130   if (EVTBits == 16 && NumElems == 8)
6131     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6132                                       Subtarget, *this))
6133       return V;
6134
6135   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6136   if (EVTBits == 32 && NumElems == 4)
6137     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6138       return V;
6139
6140   // If element VT is == 32 bits, turn it into a number of shuffles.
6141   SmallVector<SDValue, 8> V(NumElems);
6142   if (NumElems == 4 && NumZero > 0) {
6143     for (unsigned i = 0; i < 4; ++i) {
6144       bool isZero = !(NonZeros & (1 << i));
6145       if (isZero)
6146         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6147       else
6148         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6149     }
6150
6151     for (unsigned i = 0; i < 2; ++i) {
6152       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6153         default: break;
6154         case 0:
6155           V[i] = V[i*2];  // Must be a zero vector.
6156           break;
6157         case 1:
6158           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6159           break;
6160         case 2:
6161           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6162           break;
6163         case 3:
6164           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6165           break;
6166       }
6167     }
6168
6169     bool Reverse1 = (NonZeros & 0x3) == 2;
6170     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6171     int MaskVec[] = {
6172       Reverse1 ? 1 : 0,
6173       Reverse1 ? 0 : 1,
6174       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6175       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6176     };
6177     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6178   }
6179
6180   if (Values.size() > 1 && VT.is128BitVector()) {
6181     // Check for a build vector of consecutive loads.
6182     for (unsigned i = 0; i < NumElems; ++i)
6183       V[i] = Op.getOperand(i);
6184
6185     // Check for elements which are consecutive loads.
6186     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6187       return LD;
6188
6189     // Check for a build vector from mostly shuffle plus few inserting.
6190     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6191       return Sh;
6192
6193     // For SSE 4.1, use insertps to put the high elements into the low element.
6194     if (Subtarget->hasSSE41()) {
6195       SDValue Result;
6196       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6197         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6198       else
6199         Result = DAG.getUNDEF(VT);
6200
6201       for (unsigned i = 1; i < NumElems; ++i) {
6202         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6203         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6204                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6205       }
6206       return Result;
6207     }
6208
6209     // Otherwise, expand into a number of unpckl*, start by extending each of
6210     // our (non-undef) elements to the full vector width with the element in the
6211     // bottom slot of the vector (which generates no code for SSE).
6212     for (unsigned i = 0; i < NumElems; ++i) {
6213       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6214         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6215       else
6216         V[i] = DAG.getUNDEF(VT);
6217     }
6218
6219     // Next, we iteratively mix elements, e.g. for v4f32:
6220     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6221     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6222     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6223     unsigned EltStride = NumElems >> 1;
6224     while (EltStride != 0) {
6225       for (unsigned i = 0; i < EltStride; ++i) {
6226         // If V[i+EltStride] is undef and this is the first round of mixing,
6227         // then it is safe to just drop this shuffle: V[i] is already in the
6228         // right place, the one element (since it's the first round) being
6229         // inserted as undef can be dropped.  This isn't safe for successive
6230         // rounds because they will permute elements within both vectors.
6231         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6232             EltStride == NumElems/2)
6233           continue;
6234
6235         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6236       }
6237       EltStride >>= 1;
6238     }
6239     return V[0];
6240   }
6241   return SDValue();
6242 }
6243
6244 // 256-bit AVX can use the vinsertf128 instruction
6245 // to create 256-bit vectors from two other 128-bit ones.
6246 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6247   SDLoc dl(Op);
6248   MVT ResVT = Op.getSimpleValueType();
6249
6250   assert((ResVT.is256BitVector() ||
6251           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6252
6253   SDValue V1 = Op.getOperand(0);
6254   SDValue V2 = Op.getOperand(1);
6255   unsigned NumElems = ResVT.getVectorNumElements();
6256   if (ResVT.is256BitVector())
6257     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6258
6259   if (Op.getNumOperands() == 4) {
6260     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6261                                 ResVT.getVectorNumElements()/2);
6262     SDValue V3 = Op.getOperand(2);
6263     SDValue V4 = Op.getOperand(3);
6264     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6265       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6266   }
6267   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6268 }
6269
6270 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6271                                        const X86Subtarget *Subtarget,
6272                                        SelectionDAG & DAG) {
6273   SDLoc dl(Op);
6274   MVT ResVT = Op.getSimpleValueType();
6275   unsigned NumOfOperands = Op.getNumOperands();
6276
6277   assert(isPowerOf2_32(NumOfOperands) &&
6278          "Unexpected number of operands in CONCAT_VECTORS");
6279
6280   if (NumOfOperands > 2) {
6281     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6282                                   ResVT.getVectorNumElements()/2);
6283     SmallVector<SDValue, 2> Ops;
6284     for (unsigned i = 0; i < NumOfOperands/2; i++)
6285       Ops.push_back(Op.getOperand(i));
6286     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6287     Ops.clear();
6288     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6289       Ops.push_back(Op.getOperand(i));
6290     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6291     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6292   }
6293
6294   SDValue V1 = Op.getOperand(0);
6295   SDValue V2 = Op.getOperand(1);
6296   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6297   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6298
6299   if (IsZeroV1 && IsZeroV2)
6300     return getZeroVector(ResVT, Subtarget, DAG, dl);
6301
6302   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6303   SDValue Undef = DAG.getUNDEF(ResVT);
6304   unsigned NumElems = ResVT.getVectorNumElements();
6305   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6306
6307   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6308   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6309   if (IsZeroV1)
6310     return V2;
6311
6312   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6313   // Zero the upper bits of V1
6314   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6315   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6316   if (IsZeroV2)
6317     return V1;
6318   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6319 }
6320
6321 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6322                                    const X86Subtarget *Subtarget,
6323                                    SelectionDAG &DAG) {
6324   MVT VT = Op.getSimpleValueType();
6325   if (VT.getVectorElementType() == MVT::i1)
6326     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6327
6328   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6329          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6330           Op.getNumOperands() == 4)));
6331
6332   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6333   // from two other 128-bit ones.
6334
6335   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6336   return LowerAVXCONCAT_VECTORS(Op, DAG);
6337 }
6338
6339
6340 //===----------------------------------------------------------------------===//
6341 // Vector shuffle lowering
6342 //
6343 // This is an experimental code path for lowering vector shuffles on x86. It is
6344 // designed to handle arbitrary vector shuffles and blends, gracefully
6345 // degrading performance as necessary. It works hard to recognize idiomatic
6346 // shuffles and lower them to optimal instruction patterns without leaving
6347 // a framework that allows reasonably efficient handling of all vector shuffle
6348 // patterns.
6349 //===----------------------------------------------------------------------===//
6350
6351 /// \brief Tiny helper function to identify a no-op mask.
6352 ///
6353 /// This is a somewhat boring predicate function. It checks whether the mask
6354 /// array input, which is assumed to be a single-input shuffle mask of the kind
6355 /// used by the X86 shuffle instructions (not a fully general
6356 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6357 /// in-place shuffle are 'no-op's.
6358 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6359   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6360     if (Mask[i] != -1 && Mask[i] != i)
6361       return false;
6362   return true;
6363 }
6364
6365 /// \brief Helper function to classify a mask as a single-input mask.
6366 ///
6367 /// This isn't a generic single-input test because in the vector shuffle
6368 /// lowering we canonicalize single inputs to be the first input operand. This
6369 /// means we can more quickly test for a single input by only checking whether
6370 /// an input from the second operand exists. We also assume that the size of
6371 /// mask corresponds to the size of the input vectors which isn't true in the
6372 /// fully general case.
6373 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6374   for (int M : Mask)
6375     if (M >= (int)Mask.size())
6376       return false;
6377   return true;
6378 }
6379
6380 /// \brief Test whether there are elements crossing 128-bit lanes in this
6381 /// shuffle mask.
6382 ///
6383 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6384 /// and we routinely test for these.
6385 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6386   int LaneSize = 128 / VT.getScalarSizeInBits();
6387   int Size = Mask.size();
6388   for (int i = 0; i < Size; ++i)
6389     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6390       return true;
6391   return false;
6392 }
6393
6394 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6395 ///
6396 /// This checks a shuffle mask to see if it is performing the same
6397 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6398 /// that it is also not lane-crossing. It may however involve a blend from the
6399 /// same lane of a second vector.
6400 ///
6401 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6402 /// non-trivial to compute in the face of undef lanes. The representation is
6403 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6404 /// entries from both V1 and V2 inputs to the wider mask.
6405 static bool
6406 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6407                                 SmallVectorImpl<int> &RepeatedMask) {
6408   int LaneSize = 128 / VT.getScalarSizeInBits();
6409   RepeatedMask.resize(LaneSize, -1);
6410   int Size = Mask.size();
6411   for (int i = 0; i < Size; ++i) {
6412     if (Mask[i] < 0)
6413       continue;
6414     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6415       // This entry crosses lanes, so there is no way to model this shuffle.
6416       return false;
6417
6418     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6419     if (RepeatedMask[i % LaneSize] == -1)
6420       // This is the first non-undef entry in this slot of a 128-bit lane.
6421       RepeatedMask[i % LaneSize] =
6422           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6423     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6424       // Found a mismatch with the repeated mask.
6425       return false;
6426   }
6427   return true;
6428 }
6429
6430 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6431 /// arguments.
6432 ///
6433 /// This is a fast way to test a shuffle mask against a fixed pattern:
6434 ///
6435 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6436 ///
6437 /// It returns true if the mask is exactly as wide as the argument list, and
6438 /// each element of the mask is either -1 (signifying undef) or the value given
6439 /// in the argument.
6440 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6441                                 ArrayRef<int> ExpectedMask) {
6442   if (Mask.size() != ExpectedMask.size())
6443     return false;
6444
6445   int Size = Mask.size();
6446
6447   // If the values are build vectors, we can look through them to find
6448   // equivalent inputs that make the shuffles equivalent.
6449   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6450   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6451
6452   for (int i = 0; i < Size; ++i)
6453     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6454       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6455       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6456       if (!MaskBV || !ExpectedBV ||
6457           MaskBV->getOperand(Mask[i] % Size) !=
6458               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6459         return false;
6460     }
6461
6462   return true;
6463 }
6464
6465 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6466 ///
6467 /// This helper function produces an 8-bit shuffle immediate corresponding to
6468 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6469 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6470 /// example.
6471 ///
6472 /// NB: We rely heavily on "undef" masks preserving the input lane.
6473 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6474                                           SelectionDAG &DAG) {
6475   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6476   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6477   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6478   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6479   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6480
6481   unsigned Imm = 0;
6482   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6483   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6484   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6485   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6486   return DAG.getConstant(Imm, DL, MVT::i8);
6487 }
6488
6489 /// \brief Compute whether each element of a shuffle is zeroable.
6490 ///
6491 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6492 /// Either it is an undef element in the shuffle mask, the element of the input
6493 /// referenced is undef, or the element of the input referenced is known to be
6494 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6495 /// as many lanes with this technique as possible to simplify the remaining
6496 /// shuffle.
6497 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6498                                                      SDValue V1, SDValue V2) {
6499   SmallBitVector Zeroable(Mask.size(), false);
6500
6501   while (V1.getOpcode() == ISD::BITCAST)
6502     V1 = V1->getOperand(0);
6503   while (V2.getOpcode() == ISD::BITCAST)
6504     V2 = V2->getOperand(0);
6505
6506   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6507   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6508
6509   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6510     int M = Mask[i];
6511     // Handle the easy cases.
6512     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6513       Zeroable[i] = true;
6514       continue;
6515     }
6516
6517     // If this is an index into a build_vector node (which has the same number
6518     // of elements), dig out the input value and use it.
6519     SDValue V = M < Size ? V1 : V2;
6520     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6521       continue;
6522
6523     SDValue Input = V.getOperand(M % Size);
6524     // The UNDEF opcode check really should be dead code here, but not quite
6525     // worth asserting on (it isn't invalid, just unexpected).
6526     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6527       Zeroable[i] = true;
6528   }
6529
6530   return Zeroable;
6531 }
6532
6533 /// \brief Try to emit a bitmask instruction for a shuffle.
6534 ///
6535 /// This handles cases where we can model a blend exactly as a bitmask due to
6536 /// one of the inputs being zeroable.
6537 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6538                                            SDValue V2, ArrayRef<int> Mask,
6539                                            SelectionDAG &DAG) {
6540   MVT EltVT = VT.getScalarType();
6541   int NumEltBits = EltVT.getSizeInBits();
6542   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6543   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6544   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6545                                     IntEltVT);
6546   if (EltVT.isFloatingPoint()) {
6547     Zero = DAG.getBitcast(EltVT, Zero);
6548     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6549   }
6550   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6551   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6552   SDValue V;
6553   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6554     if (Zeroable[i])
6555       continue;
6556     if (Mask[i] % Size != i)
6557       return SDValue(); // Not a blend.
6558     if (!V)
6559       V = Mask[i] < Size ? V1 : V2;
6560     else if (V != (Mask[i] < Size ? V1 : V2))
6561       return SDValue(); // Can only let one input through the mask.
6562
6563     VMaskOps[i] = AllOnes;
6564   }
6565   if (!V)
6566     return SDValue(); // No non-zeroable elements!
6567
6568   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6569   V = DAG.getNode(VT.isFloatingPoint()
6570                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6571                   DL, VT, V, VMask);
6572   return V;
6573 }
6574
6575 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6576 ///
6577 /// This is used as a fallback approach when first class blend instructions are
6578 /// unavailable. Currently it is only suitable for integer vectors, but could
6579 /// be generalized for floating point vectors if desirable.
6580 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6581                                             SDValue V2, ArrayRef<int> Mask,
6582                                             SelectionDAG &DAG) {
6583   assert(VT.isInteger() && "Only supports integer vector types!");
6584   MVT EltVT = VT.getScalarType();
6585   int NumEltBits = EltVT.getSizeInBits();
6586   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6587   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6588                                     EltVT);
6589   SmallVector<SDValue, 16> MaskOps;
6590   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6591     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6592       return SDValue(); // Shuffled input!
6593     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6594   }
6595
6596   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6597   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6598   // We have to cast V2 around.
6599   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6600   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6601                                       DAG.getBitcast(MaskVT, V1Mask),
6602                                       DAG.getBitcast(MaskVT, V2)));
6603   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6604 }
6605
6606 /// \brief Try to emit a blend instruction for a shuffle.
6607 ///
6608 /// This doesn't do any checks for the availability of instructions for blending
6609 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6610 /// be matched in the backend with the type given. What it does check for is
6611 /// that the shuffle mask is in fact a blend.
6612 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6613                                          SDValue V2, ArrayRef<int> Mask,
6614                                          const X86Subtarget *Subtarget,
6615                                          SelectionDAG &DAG) {
6616   unsigned BlendMask = 0;
6617   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6618     if (Mask[i] >= Size) {
6619       if (Mask[i] != i + Size)
6620         return SDValue(); // Shuffled V2 input!
6621       BlendMask |= 1u << i;
6622       continue;
6623     }
6624     if (Mask[i] >= 0 && Mask[i] != i)
6625       return SDValue(); // Shuffled V1 input!
6626   }
6627   switch (VT.SimpleTy) {
6628   case MVT::v2f64:
6629   case MVT::v4f32:
6630   case MVT::v4f64:
6631   case MVT::v8f32:
6632     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6633                        DAG.getConstant(BlendMask, DL, MVT::i8));
6634
6635   case MVT::v4i64:
6636   case MVT::v8i32:
6637     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6638     // FALLTHROUGH
6639   case MVT::v2i64:
6640   case MVT::v4i32:
6641     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6642     // that instruction.
6643     if (Subtarget->hasAVX2()) {
6644       // Scale the blend by the number of 32-bit dwords per element.
6645       int Scale =  VT.getScalarSizeInBits() / 32;
6646       BlendMask = 0;
6647       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6648         if (Mask[i] >= Size)
6649           for (int j = 0; j < Scale; ++j)
6650             BlendMask |= 1u << (i * Scale + j);
6651
6652       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6653       V1 = DAG.getBitcast(BlendVT, V1);
6654       V2 = DAG.getBitcast(BlendVT, V2);
6655       return DAG.getBitcast(
6656           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6657                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6658     }
6659     // FALLTHROUGH
6660   case MVT::v8i16: {
6661     // For integer shuffles we need to expand the mask and cast the inputs to
6662     // v8i16s prior to blending.
6663     int Scale = 8 / VT.getVectorNumElements();
6664     BlendMask = 0;
6665     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6666       if (Mask[i] >= Size)
6667         for (int j = 0; j < Scale; ++j)
6668           BlendMask |= 1u << (i * Scale + j);
6669
6670     V1 = DAG.getBitcast(MVT::v8i16, V1);
6671     V2 = DAG.getBitcast(MVT::v8i16, V2);
6672     return DAG.getBitcast(VT,
6673                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6674                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6675   }
6676
6677   case MVT::v16i16: {
6678     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6679     SmallVector<int, 8> RepeatedMask;
6680     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6681       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6682       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6683       BlendMask = 0;
6684       for (int i = 0; i < 8; ++i)
6685         if (RepeatedMask[i] >= 16)
6686           BlendMask |= 1u << i;
6687       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6688                          DAG.getConstant(BlendMask, DL, MVT::i8));
6689     }
6690   }
6691     // FALLTHROUGH
6692   case MVT::v16i8:
6693   case MVT::v32i8: {
6694     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6695            "256-bit byte-blends require AVX2 support!");
6696
6697     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6698     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6699       return Masked;
6700
6701     // Scale the blend by the number of bytes per element.
6702     int Scale = VT.getScalarSizeInBits() / 8;
6703
6704     // This form of blend is always done on bytes. Compute the byte vector
6705     // type.
6706     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6707
6708     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6709     // mix of LLVM's code generator and the x86 backend. We tell the code
6710     // generator that boolean values in the elements of an x86 vector register
6711     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6712     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6713     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6714     // of the element (the remaining are ignored) and 0 in that high bit would
6715     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6716     // the LLVM model for boolean values in vector elements gets the relevant
6717     // bit set, it is set backwards and over constrained relative to x86's
6718     // actual model.
6719     SmallVector<SDValue, 32> VSELECTMask;
6720     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6721       for (int j = 0; j < Scale; ++j)
6722         VSELECTMask.push_back(
6723             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6724                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6725                                           MVT::i8));
6726
6727     V1 = DAG.getBitcast(BlendVT, V1);
6728     V2 = DAG.getBitcast(BlendVT, V2);
6729     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6730                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6731                                                       BlendVT, VSELECTMask),
6732                                           V1, V2));
6733   }
6734
6735   default:
6736     llvm_unreachable("Not a supported integer vector type!");
6737   }
6738 }
6739
6740 /// \brief Try to lower as a blend of elements from two inputs followed by
6741 /// a single-input permutation.
6742 ///
6743 /// This matches the pattern where we can blend elements from two inputs and
6744 /// then reduce the shuffle to a single-input permutation.
6745 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6746                                                    SDValue V2,
6747                                                    ArrayRef<int> Mask,
6748                                                    SelectionDAG &DAG) {
6749   // We build up the blend mask while checking whether a blend is a viable way
6750   // to reduce the shuffle.
6751   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6752   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6753
6754   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6755     if (Mask[i] < 0)
6756       continue;
6757
6758     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6759
6760     if (BlendMask[Mask[i] % Size] == -1)
6761       BlendMask[Mask[i] % Size] = Mask[i];
6762     else if (BlendMask[Mask[i] % Size] != Mask[i])
6763       return SDValue(); // Can't blend in the needed input!
6764
6765     PermuteMask[i] = Mask[i] % Size;
6766   }
6767
6768   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6769   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6770 }
6771
6772 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6773 /// blends and permutes.
6774 ///
6775 /// This matches the extremely common pattern for handling combined
6776 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6777 /// operations. It will try to pick the best arrangement of shuffles and
6778 /// blends.
6779 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6780                                                           SDValue V1,
6781                                                           SDValue V2,
6782                                                           ArrayRef<int> Mask,
6783                                                           SelectionDAG &DAG) {
6784   // Shuffle the input elements into the desired positions in V1 and V2 and
6785   // blend them together.
6786   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6787   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6788   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6789   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6790     if (Mask[i] >= 0 && Mask[i] < Size) {
6791       V1Mask[i] = Mask[i];
6792       BlendMask[i] = i;
6793     } else if (Mask[i] >= Size) {
6794       V2Mask[i] = Mask[i] - Size;
6795       BlendMask[i] = i + Size;
6796     }
6797
6798   // Try to lower with the simpler initial blend strategy unless one of the
6799   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6800   // shuffle may be able to fold with a load or other benefit. However, when
6801   // we'll have to do 2x as many shuffles in order to achieve this, blending
6802   // first is a better strategy.
6803   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6804     if (SDValue BlendPerm =
6805             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6806       return BlendPerm;
6807
6808   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6809   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6810   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6811 }
6812
6813 /// \brief Try to lower a vector shuffle as a byte rotation.
6814 ///
6815 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6816 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6817 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6818 /// try to generically lower a vector shuffle through such an pattern. It
6819 /// does not check for the profitability of lowering either as PALIGNR or
6820 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6821 /// This matches shuffle vectors that look like:
6822 ///
6823 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6824 ///
6825 /// Essentially it concatenates V1 and V2, shifts right by some number of
6826 /// elements, and takes the low elements as the result. Note that while this is
6827 /// specified as a *right shift* because x86 is little-endian, it is a *left
6828 /// rotate* of the vector lanes.
6829 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6830                                               SDValue V2,
6831                                               ArrayRef<int> Mask,
6832                                               const X86Subtarget *Subtarget,
6833                                               SelectionDAG &DAG) {
6834   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6835
6836   int NumElts = Mask.size();
6837   int NumLanes = VT.getSizeInBits() / 128;
6838   int NumLaneElts = NumElts / NumLanes;
6839
6840   // We need to detect various ways of spelling a rotation:
6841   //   [11, 12, 13, 14, 15,  0,  1,  2]
6842   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6843   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6844   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6845   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6846   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6847   int Rotation = 0;
6848   SDValue Lo, Hi;
6849   for (int l = 0; l < NumElts; l += NumLaneElts) {
6850     for (int i = 0; i < NumLaneElts; ++i) {
6851       if (Mask[l + i] == -1)
6852         continue;
6853       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6854
6855       // Get the mod-Size index and lane correct it.
6856       int LaneIdx = (Mask[l + i] % NumElts) - l;
6857       // Make sure it was in this lane.
6858       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6859         return SDValue();
6860
6861       // Determine where a rotated vector would have started.
6862       int StartIdx = i - LaneIdx;
6863       if (StartIdx == 0)
6864         // The identity rotation isn't interesting, stop.
6865         return SDValue();
6866
6867       // If we found the tail of a vector the rotation must be the missing
6868       // front. If we found the head of a vector, it must be how much of the
6869       // head.
6870       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6871
6872       if (Rotation == 0)
6873         Rotation = CandidateRotation;
6874       else if (Rotation != CandidateRotation)
6875         // The rotations don't match, so we can't match this mask.
6876         return SDValue();
6877
6878       // Compute which value this mask is pointing at.
6879       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6880
6881       // Compute which of the two target values this index should be assigned
6882       // to. This reflects whether the high elements are remaining or the low
6883       // elements are remaining.
6884       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6885
6886       // Either set up this value if we've not encountered it before, or check
6887       // that it remains consistent.
6888       if (!TargetV)
6889         TargetV = MaskV;
6890       else if (TargetV != MaskV)
6891         // This may be a rotation, but it pulls from the inputs in some
6892         // unsupported interleaving.
6893         return SDValue();
6894     }
6895   }
6896
6897   // Check that we successfully analyzed the mask, and normalize the results.
6898   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6899   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6900   if (!Lo)
6901     Lo = Hi;
6902   else if (!Hi)
6903     Hi = Lo;
6904
6905   // The actual rotate instruction rotates bytes, so we need to scale the
6906   // rotation based on how many bytes are in the vector lane.
6907   int Scale = 16 / NumLaneElts;
6908
6909   // SSSE3 targets can use the palignr instruction.
6910   if (Subtarget->hasSSSE3()) {
6911     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6912     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6913     Lo = DAG.getBitcast(AlignVT, Lo);
6914     Hi = DAG.getBitcast(AlignVT, Hi);
6915
6916     return DAG.getBitcast(
6917         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
6918                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6919   }
6920
6921   assert(VT.getSizeInBits() == 128 &&
6922          "Rotate-based lowering only supports 128-bit lowering!");
6923   assert(Mask.size() <= 16 &&
6924          "Can shuffle at most 16 bytes in a 128-bit vector!");
6925
6926   // Default SSE2 implementation
6927   int LoByteShift = 16 - Rotation * Scale;
6928   int HiByteShift = Rotation * Scale;
6929
6930   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6931   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6932   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6933
6934   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6935                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6936   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6937                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6938   return DAG.getBitcast(VT,
6939                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6940 }
6941
6942 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6943 ///
6944 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6945 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6946 /// matches elements from one of the input vectors shuffled to the left or
6947 /// right with zeroable elements 'shifted in'. It handles both the strictly
6948 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6949 /// quad word lane.
6950 ///
6951 /// PSHL : (little-endian) left bit shift.
6952 /// [ zz, 0, zz,  2 ]
6953 /// [ -1, 4, zz, -1 ]
6954 /// PSRL : (little-endian) right bit shift.
6955 /// [  1, zz,  3, zz]
6956 /// [ -1, -1,  7, zz]
6957 /// PSLLDQ : (little-endian) left byte shift
6958 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6959 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6960 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6961 /// PSRLDQ : (little-endian) right byte shift
6962 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6963 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6964 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6965 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6966                                          SDValue V2, ArrayRef<int> Mask,
6967                                          SelectionDAG &DAG) {
6968   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6969
6970   int Size = Mask.size();
6971   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6972
6973   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6974     for (int i = 0; i < Size; i += Scale)
6975       for (int j = 0; j < Shift; ++j)
6976         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6977           return false;
6978
6979     return true;
6980   };
6981
6982   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6983     for (int i = 0; i != Size; i += Scale) {
6984       unsigned Pos = Left ? i + Shift : i;
6985       unsigned Low = Left ? i : i + Shift;
6986       unsigned Len = Scale - Shift;
6987       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6988                                       Low + (V == V1 ? 0 : Size)))
6989         return SDValue();
6990     }
6991
6992     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6993     bool ByteShift = ShiftEltBits > 64;
6994     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6995                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6996     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6997
6998     // Normalize the scale for byte shifts to still produce an i64 element
6999     // type.
7000     Scale = ByteShift ? Scale / 2 : Scale;
7001
7002     // We need to round trip through the appropriate type for the shift.
7003     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7004     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7005     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7006            "Illegal integer vector type");
7007     V = DAG.getBitcast(ShiftVT, V);
7008
7009     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7010                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7011     return DAG.getBitcast(VT, V);
7012   };
7013
7014   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7015   // keep doubling the size of the integer elements up to that. We can
7016   // then shift the elements of the integer vector by whole multiples of
7017   // their width within the elements of the larger integer vector. Test each
7018   // multiple to see if we can find a match with the moved element indices
7019   // and that the shifted in elements are all zeroable.
7020   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7021     for (int Shift = 1; Shift != Scale; ++Shift)
7022       for (bool Left : {true, false})
7023         if (CheckZeros(Shift, Scale, Left))
7024           for (SDValue V : {V1, V2})
7025             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7026               return Match;
7027
7028   // no match
7029   return SDValue();
7030 }
7031
7032 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7033 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7034                                            SDValue V2, ArrayRef<int> Mask,
7035                                            SelectionDAG &DAG) {
7036   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7037   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7038
7039   int Size = Mask.size();
7040   int HalfSize = Size / 2;
7041   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7042
7043   // Upper half must be undefined.
7044   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7045     return SDValue();
7046
7047   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7048   // Remainder of lower half result is zero and upper half is all undef.
7049   auto LowerAsEXTRQ = [&]() {
7050     // Determine the extraction length from the part of the
7051     // lower half that isn't zeroable.
7052     int Len = HalfSize;
7053     for (; Len >= 0; --Len)
7054       if (!Zeroable[Len - 1])
7055         break;
7056     assert(Len > 0 && "Zeroable shuffle mask");
7057
7058     // Attempt to match first Len sequential elements from the lower half.
7059     SDValue Src;
7060     int Idx = -1;
7061     for (int i = 0; i != Len; ++i) {
7062       int M = Mask[i];
7063       if (M < 0)
7064         continue;
7065       SDValue &V = (M < Size ? V1 : V2);
7066       M = M % Size;
7067
7068       // All mask elements must be in the lower half.
7069       if (M > HalfSize)
7070         return SDValue();
7071
7072       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7073         Src = V;
7074         Idx = M - i;
7075         continue;
7076       }
7077       return SDValue();
7078     }
7079
7080     if (Idx < 0)
7081       return SDValue();
7082
7083     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7084     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7085     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7086     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7087                        DAG.getConstant(BitLen, DL, MVT::i8),
7088                        DAG.getConstant(BitIdx, DL, MVT::i8));
7089   };
7090
7091   if (SDValue ExtrQ = LowerAsEXTRQ())
7092     return ExtrQ;
7093
7094   // INSERTQ: Extract lowest Len elements from lower half of second source and
7095   // insert over first source, starting at Idx.
7096   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7097   auto LowerAsInsertQ = [&]() {
7098     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7099       SDValue Base;
7100
7101       // Attempt to match first source from mask before insertion point.
7102       if (isUndefInRange(Mask, 0, Idx)) {
7103         /* EMPTY */
7104       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7105         Base = V1;
7106       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7107         Base = V2;
7108       } else {
7109         continue;
7110       }
7111
7112       // Extend the extraction length looking to match both the insertion of
7113       // the second source and the remaining elements of the first.
7114       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7115         SDValue Insert;
7116         int Len = Hi - Idx;
7117
7118         // Match insertion.
7119         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7120           Insert = V1;
7121         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7122           Insert = V2;
7123         } else {
7124           continue;
7125         }
7126
7127         // Match the remaining elements of the lower half.
7128         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7129           /* EMPTY */
7130         } else if ((!Base || (Base == V1)) &&
7131                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7132           Base = V1;
7133         } else if ((!Base || (Base == V2)) &&
7134                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7135                                               Size + Hi)) {
7136           Base = V2;
7137         } else {
7138           continue;
7139         }
7140
7141         // We may not have a base (first source) - this can safely be undefined.
7142         if (!Base)
7143           Base = DAG.getUNDEF(VT);
7144
7145         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7146         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7147         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7148                            DAG.getConstant(BitLen, DL, MVT::i8),
7149                            DAG.getConstant(BitIdx, DL, MVT::i8));
7150       }
7151     }
7152
7153     return SDValue();
7154   };
7155
7156   if (SDValue InsertQ = LowerAsInsertQ())
7157     return InsertQ;
7158
7159   return SDValue();
7160 }
7161
7162 /// \brief Lower a vector shuffle as a zero or any extension.
7163 ///
7164 /// Given a specific number of elements, element bit width, and extension
7165 /// stride, produce either a zero or any extension based on the available
7166 /// features of the subtarget.
7167 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7168     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7169     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7170   assert(Scale > 1 && "Need a scale to extend.");
7171   int NumElements = VT.getVectorNumElements();
7172   int EltBits = VT.getScalarSizeInBits();
7173   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7174          "Only 8, 16, and 32 bit elements can be extended.");
7175   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7176
7177   // Found a valid zext mask! Try various lowering strategies based on the
7178   // input type and available ISA extensions.
7179   if (Subtarget->hasSSE41()) {
7180     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7181                                  NumElements / Scale);
7182     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7183   }
7184
7185   // For any extends we can cheat for larger element sizes and use shuffle
7186   // instructions that can fold with a load and/or copy.
7187   if (AnyExt && EltBits == 32) {
7188     int PSHUFDMask[4] = {0, -1, 1, -1};
7189     return DAG.getBitcast(
7190         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7191                         DAG.getBitcast(MVT::v4i32, InputV),
7192                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7193   }
7194   if (AnyExt && EltBits == 16 && Scale > 2) {
7195     int PSHUFDMask[4] = {0, -1, 0, -1};
7196     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7197                          DAG.getBitcast(MVT::v4i32, InputV),
7198                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7199     int PSHUFHWMask[4] = {1, -1, -1, -1};
7200     return DAG.getBitcast(
7201         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7202                         DAG.getBitcast(MVT::v8i16, InputV),
7203                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7204   }
7205
7206   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7207   // to 64-bits.
7208   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7209     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7210     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7211
7212     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7213                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7214                                          DAG.getConstant(EltBits, DL, MVT::i8),
7215                                          DAG.getConstant(0, DL, MVT::i8)));
7216     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7217       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7218
7219     SDValue Hi =
7220         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7221                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7222                                 DAG.getConstant(EltBits, DL, MVT::i8),
7223                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7224     return DAG.getNode(ISD::BITCAST, DL, VT,
7225                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7226   }
7227
7228   // If this would require more than 2 unpack instructions to expand, use
7229   // pshufb when available. We can only use more than 2 unpack instructions
7230   // when zero extending i8 elements which also makes it easier to use pshufb.
7231   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7232     assert(NumElements == 16 && "Unexpected byte vector width!");
7233     SDValue PSHUFBMask[16];
7234     for (int i = 0; i < 16; ++i)
7235       PSHUFBMask[i] =
7236           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7237     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7238     return DAG.getBitcast(VT,
7239                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7240                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7241                                                   MVT::v16i8, PSHUFBMask)));
7242   }
7243
7244   // Otherwise emit a sequence of unpacks.
7245   do {
7246     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7247     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7248                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7249     InputV = DAG.getBitcast(InputVT, InputV);
7250     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7251     Scale /= 2;
7252     EltBits *= 2;
7253     NumElements /= 2;
7254   } while (Scale > 1);
7255   return DAG.getBitcast(VT, InputV);
7256 }
7257
7258 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7259 ///
7260 /// This routine will try to do everything in its power to cleverly lower
7261 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7262 /// check for the profitability of this lowering,  it tries to aggressively
7263 /// match this pattern. It will use all of the micro-architectural details it
7264 /// can to emit an efficient lowering. It handles both blends with all-zero
7265 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7266 /// masking out later).
7267 ///
7268 /// The reason we have dedicated lowering for zext-style shuffles is that they
7269 /// are both incredibly common and often quite performance sensitive.
7270 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7271     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7272     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7273   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7274
7275   int Bits = VT.getSizeInBits();
7276   int NumElements = VT.getVectorNumElements();
7277   assert(VT.getScalarSizeInBits() <= 32 &&
7278          "Exceeds 32-bit integer zero extension limit");
7279   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7280
7281   // Define a helper function to check a particular ext-scale and lower to it if
7282   // valid.
7283   auto Lower = [&](int Scale) -> SDValue {
7284     SDValue InputV;
7285     bool AnyExt = true;
7286     for (int i = 0; i < NumElements; ++i) {
7287       if (Mask[i] == -1)
7288         continue; // Valid anywhere but doesn't tell us anything.
7289       if (i % Scale != 0) {
7290         // Each of the extended elements need to be zeroable.
7291         if (!Zeroable[i])
7292           return SDValue();
7293
7294         // We no longer are in the anyext case.
7295         AnyExt = false;
7296         continue;
7297       }
7298
7299       // Each of the base elements needs to be consecutive indices into the
7300       // same input vector.
7301       SDValue V = Mask[i] < NumElements ? V1 : V2;
7302       if (!InputV)
7303         InputV = V;
7304       else if (InputV != V)
7305         return SDValue(); // Flip-flopping inputs.
7306
7307       if (Mask[i] % NumElements != i / Scale)
7308         return SDValue(); // Non-consecutive strided elements.
7309     }
7310
7311     // If we fail to find an input, we have a zero-shuffle which should always
7312     // have already been handled.
7313     // FIXME: Maybe handle this here in case during blending we end up with one?
7314     if (!InputV)
7315       return SDValue();
7316
7317     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7318         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7319   };
7320
7321   // The widest scale possible for extending is to a 64-bit integer.
7322   assert(Bits % 64 == 0 &&
7323          "The number of bits in a vector must be divisible by 64 on x86!");
7324   int NumExtElements = Bits / 64;
7325
7326   // Each iteration, try extending the elements half as much, but into twice as
7327   // many elements.
7328   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7329     assert(NumElements % NumExtElements == 0 &&
7330            "The input vector size must be divisible by the extended size.");
7331     if (SDValue V = Lower(NumElements / NumExtElements))
7332       return V;
7333   }
7334
7335   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7336   if (Bits != 128)
7337     return SDValue();
7338
7339   // Returns one of the source operands if the shuffle can be reduced to a
7340   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7341   auto CanZExtLowHalf = [&]() {
7342     for (int i = NumElements / 2; i != NumElements; ++i)
7343       if (!Zeroable[i])
7344         return SDValue();
7345     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7346       return V1;
7347     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7348       return V2;
7349     return SDValue();
7350   };
7351
7352   if (SDValue V = CanZExtLowHalf()) {
7353     V = DAG.getBitcast(MVT::v2i64, V);
7354     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7355     return DAG.getBitcast(VT, V);
7356   }
7357
7358   // No viable ext lowering found.
7359   return SDValue();
7360 }
7361
7362 /// \brief Try to get a scalar value for a specific element of a vector.
7363 ///
7364 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7365 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7366                                               SelectionDAG &DAG) {
7367   MVT VT = V.getSimpleValueType();
7368   MVT EltVT = VT.getVectorElementType();
7369   while (V.getOpcode() == ISD::BITCAST)
7370     V = V.getOperand(0);
7371   // If the bitcasts shift the element size, we can't extract an equivalent
7372   // element from it.
7373   MVT NewVT = V.getSimpleValueType();
7374   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7375     return SDValue();
7376
7377   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7378       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7379     // Ensure the scalar operand is the same size as the destination.
7380     // FIXME: Add support for scalar truncation where possible.
7381     SDValue S = V.getOperand(Idx);
7382     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7383       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7384   }
7385
7386   return SDValue();
7387 }
7388
7389 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7390 ///
7391 /// This is particularly important because the set of instructions varies
7392 /// significantly based on whether the operand is a load or not.
7393 static bool isShuffleFoldableLoad(SDValue V) {
7394   while (V.getOpcode() == ISD::BITCAST)
7395     V = V.getOperand(0);
7396
7397   return ISD::isNON_EXTLoad(V.getNode());
7398 }
7399
7400 /// \brief Try to lower insertion of a single element into a zero vector.
7401 ///
7402 /// This is a common pattern that we have especially efficient patterns to lower
7403 /// across all subtarget feature sets.
7404 static SDValue lowerVectorShuffleAsElementInsertion(
7405     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7406     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7407   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7408   MVT ExtVT = VT;
7409   MVT EltVT = VT.getVectorElementType();
7410
7411   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7412                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7413                 Mask.begin();
7414   bool IsV1Zeroable = true;
7415   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7416     if (i != V2Index && !Zeroable[i]) {
7417       IsV1Zeroable = false;
7418       break;
7419     }
7420
7421   // Check for a single input from a SCALAR_TO_VECTOR node.
7422   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7423   // all the smarts here sunk into that routine. However, the current
7424   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7425   // vector shuffle lowering is dead.
7426   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7427                                                DAG);
7428   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7429     // We need to zext the scalar if it is smaller than an i32.
7430     V2S = DAG.getBitcast(EltVT, V2S);
7431     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7432       // Using zext to expand a narrow element won't work for non-zero
7433       // insertions.
7434       if (!IsV1Zeroable)
7435         return SDValue();
7436
7437       // Zero-extend directly to i32.
7438       ExtVT = MVT::v4i32;
7439       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7440     }
7441     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7442   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7443              EltVT == MVT::i16) {
7444     // Either not inserting from the low element of the input or the input
7445     // element size is too small to use VZEXT_MOVL to clear the high bits.
7446     return SDValue();
7447   }
7448
7449   if (!IsV1Zeroable) {
7450     // If V1 can't be treated as a zero vector we have fewer options to lower
7451     // this. We can't support integer vectors or non-zero targets cheaply, and
7452     // the V1 elements can't be permuted in any way.
7453     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7454     if (!VT.isFloatingPoint() || V2Index != 0)
7455       return SDValue();
7456     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7457     V1Mask[V2Index] = -1;
7458     if (!isNoopShuffleMask(V1Mask))
7459       return SDValue();
7460     // This is essentially a special case blend operation, but if we have
7461     // general purpose blend operations, they are always faster. Bail and let
7462     // the rest of the lowering handle these as blends.
7463     if (Subtarget->hasSSE41())
7464       return SDValue();
7465
7466     // Otherwise, use MOVSD or MOVSS.
7467     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7468            "Only two types of floating point element types to handle!");
7469     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7470                        ExtVT, V1, V2);
7471   }
7472
7473   // This lowering only works for the low element with floating point vectors.
7474   if (VT.isFloatingPoint() && V2Index != 0)
7475     return SDValue();
7476
7477   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7478   if (ExtVT != VT)
7479     V2 = DAG.getBitcast(VT, V2);
7480
7481   if (V2Index != 0) {
7482     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7483     // the desired position. Otherwise it is more efficient to do a vector
7484     // shift left. We know that we can do a vector shift left because all
7485     // the inputs are zero.
7486     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7487       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7488       V2Shuffle[V2Index] = 0;
7489       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7490     } else {
7491       V2 = DAG.getBitcast(MVT::v2i64, V2);
7492       V2 = DAG.getNode(
7493           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7494           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7495                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7496                               DAG.getDataLayout(), VT)));
7497       V2 = DAG.getBitcast(VT, V2);
7498     }
7499   }
7500   return V2;
7501 }
7502
7503 /// \brief Try to lower broadcast of a single element.
7504 ///
7505 /// For convenience, this code also bundles all of the subtarget feature set
7506 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7507 /// a convenient way to factor it out.
7508 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7509                                              ArrayRef<int> Mask,
7510                                              const X86Subtarget *Subtarget,
7511                                              SelectionDAG &DAG) {
7512   if (!Subtarget->hasAVX())
7513     return SDValue();
7514   if (VT.isInteger() && !Subtarget->hasAVX2())
7515     return SDValue();
7516
7517   // Check that the mask is a broadcast.
7518   int BroadcastIdx = -1;
7519   for (int M : Mask)
7520     if (M >= 0 && BroadcastIdx == -1)
7521       BroadcastIdx = M;
7522     else if (M >= 0 && M != BroadcastIdx)
7523       return SDValue();
7524
7525   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7526                                             "a sorted mask where the broadcast "
7527                                             "comes from V1.");
7528
7529   // Go up the chain of (vector) values to find a scalar load that we can
7530   // combine with the broadcast.
7531   for (;;) {
7532     switch (V.getOpcode()) {
7533     case ISD::CONCAT_VECTORS: {
7534       int OperandSize = Mask.size() / V.getNumOperands();
7535       V = V.getOperand(BroadcastIdx / OperandSize);
7536       BroadcastIdx %= OperandSize;
7537       continue;
7538     }
7539
7540     case ISD::INSERT_SUBVECTOR: {
7541       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7542       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7543       if (!ConstantIdx)
7544         break;
7545
7546       int BeginIdx = (int)ConstantIdx->getZExtValue();
7547       int EndIdx =
7548           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7549       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7550         BroadcastIdx -= BeginIdx;
7551         V = VInner;
7552       } else {
7553         V = VOuter;
7554       }
7555       continue;
7556     }
7557     }
7558     break;
7559   }
7560
7561   // Check if this is a broadcast of a scalar. We special case lowering
7562   // for scalars so that we can more effectively fold with loads.
7563   // First, look through bitcast: if the original value has a larger element
7564   // type than the shuffle, the broadcast element is in essence truncated.
7565   // Make that explicit to ease folding.
7566   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7567     EVT EltVT = VT.getVectorElementType();
7568     SDValue V0 = V.getOperand(0);
7569     EVT V0VT = V0.getValueType();
7570
7571     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7572         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7573          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7574       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7575       BroadcastIdx = 0;
7576     }
7577   }
7578
7579   // Also check the simpler case, where we can directly reuse the scalar.
7580   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7581       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7582     V = V.getOperand(BroadcastIdx);
7583
7584     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7585     // Only AVX2 has register broadcasts.
7586     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7587       return SDValue();
7588   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7589     // We can't broadcast from a vector register without AVX2, and we can only
7590     // broadcast from the zero-element of a vector register.
7591     return SDValue();
7592   }
7593
7594   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7595 }
7596
7597 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7598 // INSERTPS when the V1 elements are already in the correct locations
7599 // because otherwise we can just always use two SHUFPS instructions which
7600 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7601 // perform INSERTPS if a single V1 element is out of place and all V2
7602 // elements are zeroable.
7603 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7604                                             ArrayRef<int> Mask,
7605                                             SelectionDAG &DAG) {
7606   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7607   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7608   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7609   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7610
7611   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7612
7613   unsigned ZMask = 0;
7614   int V1DstIndex = -1;
7615   int V2DstIndex = -1;
7616   bool V1UsedInPlace = false;
7617
7618   for (int i = 0; i < 4; ++i) {
7619     // Synthesize a zero mask from the zeroable elements (includes undefs).
7620     if (Zeroable[i]) {
7621       ZMask |= 1 << i;
7622       continue;
7623     }
7624
7625     // Flag if we use any V1 inputs in place.
7626     if (i == Mask[i]) {
7627       V1UsedInPlace = true;
7628       continue;
7629     }
7630
7631     // We can only insert a single non-zeroable element.
7632     if (V1DstIndex != -1 || V2DstIndex != -1)
7633       return SDValue();
7634
7635     if (Mask[i] < 4) {
7636       // V1 input out of place for insertion.
7637       V1DstIndex = i;
7638     } else {
7639       // V2 input for insertion.
7640       V2DstIndex = i;
7641     }
7642   }
7643
7644   // Don't bother if we have no (non-zeroable) element for insertion.
7645   if (V1DstIndex == -1 && V2DstIndex == -1)
7646     return SDValue();
7647
7648   // Determine element insertion src/dst indices. The src index is from the
7649   // start of the inserted vector, not the start of the concatenated vector.
7650   unsigned V2SrcIndex = 0;
7651   if (V1DstIndex != -1) {
7652     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7653     // and don't use the original V2 at all.
7654     V2SrcIndex = Mask[V1DstIndex];
7655     V2DstIndex = V1DstIndex;
7656     V2 = V1;
7657   } else {
7658     V2SrcIndex = Mask[V2DstIndex] - 4;
7659   }
7660
7661   // If no V1 inputs are used in place, then the result is created only from
7662   // the zero mask and the V2 insertion - so remove V1 dependency.
7663   if (!V1UsedInPlace)
7664     V1 = DAG.getUNDEF(MVT::v4f32);
7665
7666   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7667   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7668
7669   // Insert the V2 element into the desired position.
7670   SDLoc DL(Op);
7671   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7672                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7673 }
7674
7675 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7676 /// UNPCK instruction.
7677 ///
7678 /// This specifically targets cases where we end up with alternating between
7679 /// the two inputs, and so can permute them into something that feeds a single
7680 /// UNPCK instruction. Note that this routine only targets integer vectors
7681 /// because for floating point vectors we have a generalized SHUFPS lowering
7682 /// strategy that handles everything that doesn't *exactly* match an unpack,
7683 /// making this clever lowering unnecessary.
7684 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7685                                           SDValue V2, ArrayRef<int> Mask,
7686                                           SelectionDAG &DAG) {
7687   assert(!VT.isFloatingPoint() &&
7688          "This routine only supports integer vectors.");
7689   assert(!isSingleInputShuffleMask(Mask) &&
7690          "This routine should only be used when blending two inputs.");
7691   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7692
7693   int Size = Mask.size();
7694
7695   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7696     return M >= 0 && M % Size < Size / 2;
7697   });
7698   int NumHiInputs = std::count_if(
7699       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7700
7701   bool UnpackLo = NumLoInputs >= NumHiInputs;
7702
7703   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7704     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7705     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7706
7707     for (int i = 0; i < Size; ++i) {
7708       if (Mask[i] < 0)
7709         continue;
7710
7711       // Each element of the unpack contains Scale elements from this mask.
7712       int UnpackIdx = i / Scale;
7713
7714       // We only handle the case where V1 feeds the first slots of the unpack.
7715       // We rely on canonicalization to ensure this is the case.
7716       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7717         return SDValue();
7718
7719       // Setup the mask for this input. The indexing is tricky as we have to
7720       // handle the unpack stride.
7721       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7722       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7723           Mask[i] % Size;
7724     }
7725
7726     // If we will have to shuffle both inputs to use the unpack, check whether
7727     // we can just unpack first and shuffle the result. If so, skip this unpack.
7728     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7729         !isNoopShuffleMask(V2Mask))
7730       return SDValue();
7731
7732     // Shuffle the inputs into place.
7733     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7734     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7735
7736     // Cast the inputs to the type we will use to unpack them.
7737     V1 = DAG.getBitcast(UnpackVT, V1);
7738     V2 = DAG.getBitcast(UnpackVT, V2);
7739
7740     // Unpack the inputs and cast the result back to the desired type.
7741     return DAG.getBitcast(
7742         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7743                         UnpackVT, V1, V2));
7744   };
7745
7746   // We try each unpack from the largest to the smallest to try and find one
7747   // that fits this mask.
7748   int OrigNumElements = VT.getVectorNumElements();
7749   int OrigScalarSize = VT.getScalarSizeInBits();
7750   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7751     int Scale = ScalarSize / OrigScalarSize;
7752     int NumElements = OrigNumElements / Scale;
7753     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7754     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7755       return Unpack;
7756   }
7757
7758   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7759   // initial unpack.
7760   if (NumLoInputs == 0 || NumHiInputs == 0) {
7761     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7762            "We have to have *some* inputs!");
7763     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7764
7765     // FIXME: We could consider the total complexity of the permute of each
7766     // possible unpacking. Or at the least we should consider how many
7767     // half-crossings are created.
7768     // FIXME: We could consider commuting the unpacks.
7769
7770     SmallVector<int, 32> PermMask;
7771     PermMask.assign(Size, -1);
7772     for (int i = 0; i < Size; ++i) {
7773       if (Mask[i] < 0)
7774         continue;
7775
7776       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7777
7778       PermMask[i] =
7779           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7780     }
7781     return DAG.getVectorShuffle(
7782         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7783                             DL, VT, V1, V2),
7784         DAG.getUNDEF(VT), PermMask);
7785   }
7786
7787   return SDValue();
7788 }
7789
7790 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7791 ///
7792 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7793 /// support for floating point shuffles but not integer shuffles. These
7794 /// instructions will incur a domain crossing penalty on some chips though so
7795 /// it is better to avoid lowering through this for integer vectors where
7796 /// possible.
7797 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7798                                        const X86Subtarget *Subtarget,
7799                                        SelectionDAG &DAG) {
7800   SDLoc DL(Op);
7801   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7802   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7803   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7804   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7805   ArrayRef<int> Mask = SVOp->getMask();
7806   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7807
7808   if (isSingleInputShuffleMask(Mask)) {
7809     // Use low duplicate instructions for masks that match their pattern.
7810     if (Subtarget->hasSSE3())
7811       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7812         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7813
7814     // Straight shuffle of a single input vector. Simulate this by using the
7815     // single input as both of the "inputs" to this instruction..
7816     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7817
7818     if (Subtarget->hasAVX()) {
7819       // If we have AVX, we can use VPERMILPS which will allow folding a load
7820       // into the shuffle.
7821       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7822                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7823     }
7824
7825     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7826                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7827   }
7828   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7829   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7830
7831   // If we have a single input, insert that into V1 if we can do so cheaply.
7832   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7833     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7834             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7835       return Insertion;
7836     // Try inverting the insertion since for v2 masks it is easy to do and we
7837     // can't reliably sort the mask one way or the other.
7838     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7839                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7840     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7841             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7842       return Insertion;
7843   }
7844
7845   // Try to use one of the special instruction patterns to handle two common
7846   // blend patterns if a zero-blend above didn't work.
7847   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7848       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7849     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7850       // We can either use a special instruction to load over the low double or
7851       // to move just the low double.
7852       return DAG.getNode(
7853           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7854           DL, MVT::v2f64, V2,
7855           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7856
7857   if (Subtarget->hasSSE41())
7858     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7859                                                   Subtarget, DAG))
7860       return Blend;
7861
7862   // Use dedicated unpack instructions for masks that match their pattern.
7863   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7864     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7865   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7866     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7867
7868   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7869   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7870                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7871 }
7872
7873 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7874 ///
7875 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7876 /// the integer unit to minimize domain crossing penalties. However, for blends
7877 /// it falls back to the floating point shuffle operation with appropriate bit
7878 /// casting.
7879 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7880                                        const X86Subtarget *Subtarget,
7881                                        SelectionDAG &DAG) {
7882   SDLoc DL(Op);
7883   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7884   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7885   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7886   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7887   ArrayRef<int> Mask = SVOp->getMask();
7888   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7889
7890   if (isSingleInputShuffleMask(Mask)) {
7891     // Check for being able to broadcast a single element.
7892     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7893                                                           Mask, Subtarget, DAG))
7894       return Broadcast;
7895
7896     // Straight shuffle of a single input vector. For everything from SSE2
7897     // onward this has a single fast instruction with no scary immediates.
7898     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7899     V1 = DAG.getBitcast(MVT::v4i32, V1);
7900     int WidenedMask[4] = {
7901         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7902         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7903     return DAG.getBitcast(
7904         MVT::v2i64,
7905         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7906                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7907   }
7908   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7909   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7910   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7911   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7912
7913   // If we have a blend of two PACKUS operations an the blend aligns with the
7914   // low and half halves, we can just merge the PACKUS operations. This is
7915   // particularly important as it lets us merge shuffles that this routine itself
7916   // creates.
7917   auto GetPackNode = [](SDValue V) {
7918     while (V.getOpcode() == ISD::BITCAST)
7919       V = V.getOperand(0);
7920
7921     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7922   };
7923   if (SDValue V1Pack = GetPackNode(V1))
7924     if (SDValue V2Pack = GetPackNode(V2))
7925       return DAG.getBitcast(MVT::v2i64,
7926                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7927                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7928                                                      : V1Pack.getOperand(1),
7929                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7930                                                      : V2Pack.getOperand(1)));
7931
7932   // Try to use shift instructions.
7933   if (SDValue Shift =
7934           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7935     return Shift;
7936
7937   // When loading a scalar and then shuffling it into a vector we can often do
7938   // the insertion cheaply.
7939   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7940           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7941     return Insertion;
7942   // Try inverting the insertion since for v2 masks it is easy to do and we
7943   // can't reliably sort the mask one way or the other.
7944   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7945   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7946           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7947     return Insertion;
7948
7949   // We have different paths for blend lowering, but they all must use the
7950   // *exact* same predicate.
7951   bool IsBlendSupported = Subtarget->hasSSE41();
7952   if (IsBlendSupported)
7953     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7954                                                   Subtarget, DAG))
7955       return Blend;
7956
7957   // Use dedicated unpack instructions for masks that match their pattern.
7958   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7959     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7960   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7961     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7962
7963   // Try to use byte rotation instructions.
7964   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7965   if (Subtarget->hasSSSE3())
7966     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7967             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7968       return Rotate;
7969
7970   // If we have direct support for blends, we should lower by decomposing into
7971   // a permute. That will be faster than the domain cross.
7972   if (IsBlendSupported)
7973     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7974                                                       Mask, DAG);
7975
7976   // We implement this with SHUFPD which is pretty lame because it will likely
7977   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7978   // However, all the alternatives are still more cycles and newer chips don't
7979   // have this problem. It would be really nice if x86 had better shuffles here.
7980   V1 = DAG.getBitcast(MVT::v2f64, V1);
7981   V2 = DAG.getBitcast(MVT::v2f64, V2);
7982   return DAG.getBitcast(MVT::v2i64,
7983                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7984 }
7985
7986 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7987 ///
7988 /// This is used to disable more specialized lowerings when the shufps lowering
7989 /// will happen to be efficient.
7990 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7991   // This routine only handles 128-bit shufps.
7992   assert(Mask.size() == 4 && "Unsupported mask size!");
7993
7994   // To lower with a single SHUFPS we need to have the low half and high half
7995   // each requiring a single input.
7996   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7997     return false;
7998   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7999     return false;
8000
8001   return true;
8002 }
8003
8004 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8005 ///
8006 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8007 /// It makes no assumptions about whether this is the *best* lowering, it simply
8008 /// uses it.
8009 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8010                                             ArrayRef<int> Mask, SDValue V1,
8011                                             SDValue V2, SelectionDAG &DAG) {
8012   SDValue LowV = V1, HighV = V2;
8013   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8014
8015   int NumV2Elements =
8016       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8017
8018   if (NumV2Elements == 1) {
8019     int V2Index =
8020         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8021         Mask.begin();
8022
8023     // Compute the index adjacent to V2Index and in the same half by toggling
8024     // the low bit.
8025     int V2AdjIndex = V2Index ^ 1;
8026
8027     if (Mask[V2AdjIndex] == -1) {
8028       // Handles all the cases where we have a single V2 element and an undef.
8029       // This will only ever happen in the high lanes because we commute the
8030       // vector otherwise.
8031       if (V2Index < 2)
8032         std::swap(LowV, HighV);
8033       NewMask[V2Index] -= 4;
8034     } else {
8035       // Handle the case where the V2 element ends up adjacent to a V1 element.
8036       // To make this work, blend them together as the first step.
8037       int V1Index = V2AdjIndex;
8038       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8039       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8040                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8041
8042       // Now proceed to reconstruct the final blend as we have the necessary
8043       // high or low half formed.
8044       if (V2Index < 2) {
8045         LowV = V2;
8046         HighV = V1;
8047       } else {
8048         HighV = V2;
8049       }
8050       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8051       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8052     }
8053   } else if (NumV2Elements == 2) {
8054     if (Mask[0] < 4 && Mask[1] < 4) {
8055       // Handle the easy case where we have V1 in the low lanes and V2 in the
8056       // high lanes.
8057       NewMask[2] -= 4;
8058       NewMask[3] -= 4;
8059     } else if (Mask[2] < 4 && Mask[3] < 4) {
8060       // We also handle the reversed case because this utility may get called
8061       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8062       // arrange things in the right direction.
8063       NewMask[0] -= 4;
8064       NewMask[1] -= 4;
8065       HighV = V1;
8066       LowV = V2;
8067     } else {
8068       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8069       // trying to place elements directly, just blend them and set up the final
8070       // shuffle to place them.
8071
8072       // The first two blend mask elements are for V1, the second two are for
8073       // V2.
8074       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8075                           Mask[2] < 4 ? Mask[2] : Mask[3],
8076                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8077                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8078       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8079                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8080
8081       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8082       // a blend.
8083       LowV = HighV = V1;
8084       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8085       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8086       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8087       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8088     }
8089   }
8090   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8091                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8092 }
8093
8094 /// \brief Lower 4-lane 32-bit floating point shuffles.
8095 ///
8096 /// Uses instructions exclusively from the floating point unit to minimize
8097 /// domain crossing penalties, as these are sufficient to implement all v4f32
8098 /// shuffles.
8099 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8100                                        const X86Subtarget *Subtarget,
8101                                        SelectionDAG &DAG) {
8102   SDLoc DL(Op);
8103   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8104   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8105   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8106   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8107   ArrayRef<int> Mask = SVOp->getMask();
8108   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8109
8110   int NumV2Elements =
8111       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8112
8113   if (NumV2Elements == 0) {
8114     // Check for being able to broadcast a single element.
8115     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8116                                                           Mask, Subtarget, DAG))
8117       return Broadcast;
8118
8119     // Use even/odd duplicate instructions for masks that match their pattern.
8120     if (Subtarget->hasSSE3()) {
8121       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8122         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8123       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8124         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8125     }
8126
8127     if (Subtarget->hasAVX()) {
8128       // If we have AVX, we can use VPERMILPS which will allow folding a load
8129       // into the shuffle.
8130       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8131                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8132     }
8133
8134     // Otherwise, use a straight shuffle of a single input vector. We pass the
8135     // input vector to both operands to simulate this with a SHUFPS.
8136     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8137                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8138   }
8139
8140   // There are special ways we can lower some single-element blends. However, we
8141   // have custom ways we can lower more complex single-element blends below that
8142   // we defer to if both this and BLENDPS fail to match, so restrict this to
8143   // when the V2 input is targeting element 0 of the mask -- that is the fast
8144   // case here.
8145   if (NumV2Elements == 1 && Mask[0] >= 4)
8146     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8147                                                          Mask, Subtarget, DAG))
8148       return V;
8149
8150   if (Subtarget->hasSSE41()) {
8151     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8152                                                   Subtarget, DAG))
8153       return Blend;
8154
8155     // Use INSERTPS if we can complete the shuffle efficiently.
8156     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8157       return V;
8158
8159     if (!isSingleSHUFPSMask(Mask))
8160       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8161               DL, MVT::v4f32, V1, V2, Mask, DAG))
8162         return BlendPerm;
8163   }
8164
8165   // Use dedicated unpack instructions for masks that match their pattern.
8166   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8167     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8168   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8169     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8170   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8171     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8172   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8173     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8174
8175   // Otherwise fall back to a SHUFPS lowering strategy.
8176   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8177 }
8178
8179 /// \brief Lower 4-lane i32 vector shuffles.
8180 ///
8181 /// We try to handle these with integer-domain shuffles where we can, but for
8182 /// blends we use the floating point domain blend instructions.
8183 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8184                                        const X86Subtarget *Subtarget,
8185                                        SelectionDAG &DAG) {
8186   SDLoc DL(Op);
8187   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8188   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8189   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8190   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8191   ArrayRef<int> Mask = SVOp->getMask();
8192   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8193
8194   // Whenever we can lower this as a zext, that instruction is strictly faster
8195   // than any alternative. It also allows us to fold memory operands into the
8196   // shuffle in many cases.
8197   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8198                                                          Mask, Subtarget, DAG))
8199     return ZExt;
8200
8201   int NumV2Elements =
8202       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8203
8204   if (NumV2Elements == 0) {
8205     // Check for being able to broadcast a single element.
8206     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8207                                                           Mask, Subtarget, DAG))
8208       return Broadcast;
8209
8210     // Straight shuffle of a single input vector. For everything from SSE2
8211     // onward this has a single fast instruction with no scary immediates.
8212     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8213     // but we aren't actually going to use the UNPCK instruction because doing
8214     // so prevents folding a load into this instruction or making a copy.
8215     const int UnpackLoMask[] = {0, 0, 1, 1};
8216     const int UnpackHiMask[] = {2, 2, 3, 3};
8217     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8218       Mask = UnpackLoMask;
8219     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8220       Mask = UnpackHiMask;
8221
8222     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8223                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8224   }
8225
8226   // Try to use shift instructions.
8227   if (SDValue Shift =
8228           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8229     return Shift;
8230
8231   // There are special ways we can lower some single-element blends.
8232   if (NumV2Elements == 1)
8233     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8234                                                          Mask, Subtarget, DAG))
8235       return V;
8236
8237   // We have different paths for blend lowering, but they all must use the
8238   // *exact* same predicate.
8239   bool IsBlendSupported = Subtarget->hasSSE41();
8240   if (IsBlendSupported)
8241     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8242                                                   Subtarget, DAG))
8243       return Blend;
8244
8245   if (SDValue Masked =
8246           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8247     return Masked;
8248
8249   // Use dedicated unpack instructions for masks that match their pattern.
8250   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8251     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8252   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8253     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8254   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8255     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8256   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8257     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8258
8259   // Try to use byte rotation instructions.
8260   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8261   if (Subtarget->hasSSSE3())
8262     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8263             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8264       return Rotate;
8265
8266   // If we have direct support for blends, we should lower by decomposing into
8267   // a permute. That will be faster than the domain cross.
8268   if (IsBlendSupported)
8269     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8270                                                       Mask, DAG);
8271
8272   // Try to lower by permuting the inputs into an unpack instruction.
8273   if (SDValue Unpack =
8274           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8275     return Unpack;
8276
8277   // We implement this with SHUFPS because it can blend from two vectors.
8278   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8279   // up the inputs, bypassing domain shift penalties that we would encur if we
8280   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8281   // relevant.
8282   return DAG.getBitcast(
8283       MVT::v4i32,
8284       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8285                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8286 }
8287
8288 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8289 /// shuffle lowering, and the most complex part.
8290 ///
8291 /// The lowering strategy is to try to form pairs of input lanes which are
8292 /// targeted at the same half of the final vector, and then use a dword shuffle
8293 /// to place them onto the right half, and finally unpack the paired lanes into
8294 /// their final position.
8295 ///
8296 /// The exact breakdown of how to form these dword pairs and align them on the
8297 /// correct sides is really tricky. See the comments within the function for
8298 /// more of the details.
8299 ///
8300 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8301 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8302 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8303 /// vector, form the analogous 128-bit 8-element Mask.
8304 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8305     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8306     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8307   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8308   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8309
8310   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8311   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8312   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8313
8314   SmallVector<int, 4> LoInputs;
8315   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8316                [](int M) { return M >= 0; });
8317   std::sort(LoInputs.begin(), LoInputs.end());
8318   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8319   SmallVector<int, 4> HiInputs;
8320   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8321                [](int M) { return M >= 0; });
8322   std::sort(HiInputs.begin(), HiInputs.end());
8323   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8324   int NumLToL =
8325       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8326   int NumHToL = LoInputs.size() - NumLToL;
8327   int NumLToH =
8328       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8329   int NumHToH = HiInputs.size() - NumLToH;
8330   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8331   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8332   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8333   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8334
8335   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8336   // such inputs we can swap two of the dwords across the half mark and end up
8337   // with <=2 inputs to each half in each half. Once there, we can fall through
8338   // to the generic code below. For example:
8339   //
8340   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8341   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8342   //
8343   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8344   // and an existing 2-into-2 on the other half. In this case we may have to
8345   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8346   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8347   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8348   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8349   // half than the one we target for fixing) will be fixed when we re-enter this
8350   // path. We will also combine away any sequence of PSHUFD instructions that
8351   // result into a single instruction. Here is an example of the tricky case:
8352   //
8353   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8354   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8355   //
8356   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8357   //
8358   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8359   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8360   //
8361   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8362   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8363   //
8364   // The result is fine to be handled by the generic logic.
8365   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8366                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8367                           int AOffset, int BOffset) {
8368     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8369            "Must call this with A having 3 or 1 inputs from the A half.");
8370     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8371            "Must call this with B having 1 or 3 inputs from the B half.");
8372     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8373            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8374
8375     bool ThreeAInputs = AToAInputs.size() == 3;
8376
8377     // Compute the index of dword with only one word among the three inputs in
8378     // a half by taking the sum of the half with three inputs and subtracting
8379     // the sum of the actual three inputs. The difference is the remaining
8380     // slot.
8381     int ADWord, BDWord;
8382     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8383     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8384     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8385     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8386     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8387     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8388     int TripleNonInputIdx =
8389         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8390     TripleDWord = TripleNonInputIdx / 2;
8391
8392     // We use xor with one to compute the adjacent DWord to whichever one the
8393     // OneInput is in.
8394     OneInputDWord = (OneInput / 2) ^ 1;
8395
8396     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8397     // and BToA inputs. If there is also such a problem with the BToB and AToB
8398     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8399     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8400     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8401     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8402       // Compute how many inputs will be flipped by swapping these DWords. We
8403       // need
8404       // to balance this to ensure we don't form a 3-1 shuffle in the other
8405       // half.
8406       int NumFlippedAToBInputs =
8407           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8408           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8409       int NumFlippedBToBInputs =
8410           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8411           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8412       if ((NumFlippedAToBInputs == 1 &&
8413            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8414           (NumFlippedBToBInputs == 1 &&
8415            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8416         // We choose whether to fix the A half or B half based on whether that
8417         // half has zero flipped inputs. At zero, we may not be able to fix it
8418         // with that half. We also bias towards fixing the B half because that
8419         // will more commonly be the high half, and we have to bias one way.
8420         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8421                                                        ArrayRef<int> Inputs) {
8422           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8423           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8424                                          PinnedIdx ^ 1) != Inputs.end();
8425           // Determine whether the free index is in the flipped dword or the
8426           // unflipped dword based on where the pinned index is. We use this bit
8427           // in an xor to conditionally select the adjacent dword.
8428           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8429           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8430                                              FixFreeIdx) != Inputs.end();
8431           if (IsFixIdxInput == IsFixFreeIdxInput)
8432             FixFreeIdx += 1;
8433           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8434                                         FixFreeIdx) != Inputs.end();
8435           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8436                  "We need to be changing the number of flipped inputs!");
8437           int PSHUFHalfMask[] = {0, 1, 2, 3};
8438           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8439           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8440                           MVT::v8i16, V,
8441                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8442
8443           for (int &M : Mask)
8444             if (M != -1 && M == FixIdx)
8445               M = FixFreeIdx;
8446             else if (M != -1 && M == FixFreeIdx)
8447               M = FixIdx;
8448         };
8449         if (NumFlippedBToBInputs != 0) {
8450           int BPinnedIdx =
8451               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8452           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8453         } else {
8454           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8455           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8456           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8457         }
8458       }
8459     }
8460
8461     int PSHUFDMask[] = {0, 1, 2, 3};
8462     PSHUFDMask[ADWord] = BDWord;
8463     PSHUFDMask[BDWord] = ADWord;
8464     V = DAG.getBitcast(
8465         VT,
8466         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8467                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8468
8469     // Adjust the mask to match the new locations of A and B.
8470     for (int &M : Mask)
8471       if (M != -1 && M/2 == ADWord)
8472         M = 2 * BDWord + M % 2;
8473       else if (M != -1 && M/2 == BDWord)
8474         M = 2 * ADWord + M % 2;
8475
8476     // Recurse back into this routine to re-compute state now that this isn't
8477     // a 3 and 1 problem.
8478     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8479                                                      DAG);
8480   };
8481   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8482     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8483   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8484     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8485
8486   // At this point there are at most two inputs to the low and high halves from
8487   // each half. That means the inputs can always be grouped into dwords and
8488   // those dwords can then be moved to the correct half with a dword shuffle.
8489   // We use at most one low and one high word shuffle to collect these paired
8490   // inputs into dwords, and finally a dword shuffle to place them.
8491   int PSHUFLMask[4] = {-1, -1, -1, -1};
8492   int PSHUFHMask[4] = {-1, -1, -1, -1};
8493   int PSHUFDMask[4] = {-1, -1, -1, -1};
8494
8495   // First fix the masks for all the inputs that are staying in their
8496   // original halves. This will then dictate the targets of the cross-half
8497   // shuffles.
8498   auto fixInPlaceInputs =
8499       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8500                     MutableArrayRef<int> SourceHalfMask,
8501                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8502     if (InPlaceInputs.empty())
8503       return;
8504     if (InPlaceInputs.size() == 1) {
8505       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8506           InPlaceInputs[0] - HalfOffset;
8507       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8508       return;
8509     }
8510     if (IncomingInputs.empty()) {
8511       // Just fix all of the in place inputs.
8512       for (int Input : InPlaceInputs) {
8513         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8514         PSHUFDMask[Input / 2] = Input / 2;
8515       }
8516       return;
8517     }
8518
8519     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8520     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8521         InPlaceInputs[0] - HalfOffset;
8522     // Put the second input next to the first so that they are packed into
8523     // a dword. We find the adjacent index by toggling the low bit.
8524     int AdjIndex = InPlaceInputs[0] ^ 1;
8525     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8526     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8527     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8528   };
8529   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8530   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8531
8532   // Now gather the cross-half inputs and place them into a free dword of
8533   // their target half.
8534   // FIXME: This operation could almost certainly be simplified dramatically to
8535   // look more like the 3-1 fixing operation.
8536   auto moveInputsToRightHalf = [&PSHUFDMask](
8537       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8538       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8539       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8540       int DestOffset) {
8541     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8542       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8543     };
8544     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8545                                                int Word) {
8546       int LowWord = Word & ~1;
8547       int HighWord = Word | 1;
8548       return isWordClobbered(SourceHalfMask, LowWord) ||
8549              isWordClobbered(SourceHalfMask, HighWord);
8550     };
8551
8552     if (IncomingInputs.empty())
8553       return;
8554
8555     if (ExistingInputs.empty()) {
8556       // Map any dwords with inputs from them into the right half.
8557       for (int Input : IncomingInputs) {
8558         // If the source half mask maps over the inputs, turn those into
8559         // swaps and use the swapped lane.
8560         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8561           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8562             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8563                 Input - SourceOffset;
8564             // We have to swap the uses in our half mask in one sweep.
8565             for (int &M : HalfMask)
8566               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8567                 M = Input;
8568               else if (M == Input)
8569                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8570           } else {
8571             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8572                        Input - SourceOffset &&
8573                    "Previous placement doesn't match!");
8574           }
8575           // Note that this correctly re-maps both when we do a swap and when
8576           // we observe the other side of the swap above. We rely on that to
8577           // avoid swapping the members of the input list directly.
8578           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8579         }
8580
8581         // Map the input's dword into the correct half.
8582         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8583           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8584         else
8585           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8586                      Input / 2 &&
8587                  "Previous placement doesn't match!");
8588       }
8589
8590       // And just directly shift any other-half mask elements to be same-half
8591       // as we will have mirrored the dword containing the element into the
8592       // same position within that half.
8593       for (int &M : HalfMask)
8594         if (M >= SourceOffset && M < SourceOffset + 4) {
8595           M = M - SourceOffset + DestOffset;
8596           assert(M >= 0 && "This should never wrap below zero!");
8597         }
8598       return;
8599     }
8600
8601     // Ensure we have the input in a viable dword of its current half. This
8602     // is particularly tricky because the original position may be clobbered
8603     // by inputs being moved and *staying* in that half.
8604     if (IncomingInputs.size() == 1) {
8605       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8606         int InputFixed = std::find(std::begin(SourceHalfMask),
8607                                    std::end(SourceHalfMask), -1) -
8608                          std::begin(SourceHalfMask) + SourceOffset;
8609         SourceHalfMask[InputFixed - SourceOffset] =
8610             IncomingInputs[0] - SourceOffset;
8611         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8612                      InputFixed);
8613         IncomingInputs[0] = InputFixed;
8614       }
8615     } else if (IncomingInputs.size() == 2) {
8616       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8617           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8618         // We have two non-adjacent or clobbered inputs we need to extract from
8619         // the source half. To do this, we need to map them into some adjacent
8620         // dword slot in the source mask.
8621         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8622                               IncomingInputs[1] - SourceOffset};
8623
8624         // If there is a free slot in the source half mask adjacent to one of
8625         // the inputs, place the other input in it. We use (Index XOR 1) to
8626         // compute an adjacent index.
8627         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8628             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8629           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8630           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8631           InputsFixed[1] = InputsFixed[0] ^ 1;
8632         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8633                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8634           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8635           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8636           InputsFixed[0] = InputsFixed[1] ^ 1;
8637         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8638                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8639           // The two inputs are in the same DWord but it is clobbered and the
8640           // adjacent DWord isn't used at all. Move both inputs to the free
8641           // slot.
8642           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8643           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8644           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8645           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8646         } else {
8647           // The only way we hit this point is if there is no clobbering
8648           // (because there are no off-half inputs to this half) and there is no
8649           // free slot adjacent to one of the inputs. In this case, we have to
8650           // swap an input with a non-input.
8651           for (int i = 0; i < 4; ++i)
8652             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8653                    "We can't handle any clobbers here!");
8654           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8655                  "Cannot have adjacent inputs here!");
8656
8657           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8658           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8659
8660           // We also have to update the final source mask in this case because
8661           // it may need to undo the above swap.
8662           for (int &M : FinalSourceHalfMask)
8663             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8664               M = InputsFixed[1] + SourceOffset;
8665             else if (M == InputsFixed[1] + SourceOffset)
8666               M = (InputsFixed[0] ^ 1) + SourceOffset;
8667
8668           InputsFixed[1] = InputsFixed[0] ^ 1;
8669         }
8670
8671         // Point everything at the fixed inputs.
8672         for (int &M : HalfMask)
8673           if (M == IncomingInputs[0])
8674             M = InputsFixed[0] + SourceOffset;
8675           else if (M == IncomingInputs[1])
8676             M = InputsFixed[1] + SourceOffset;
8677
8678         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8679         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8680       }
8681     } else {
8682       llvm_unreachable("Unhandled input size!");
8683     }
8684
8685     // Now hoist the DWord down to the right half.
8686     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8687     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8688     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8689     for (int &M : HalfMask)
8690       for (int Input : IncomingInputs)
8691         if (M == Input)
8692           M = FreeDWord * 2 + Input % 2;
8693   };
8694   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8695                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8696   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8697                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8698
8699   // Now enact all the shuffles we've computed to move the inputs into their
8700   // target half.
8701   if (!isNoopShuffleMask(PSHUFLMask))
8702     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8703                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8704   if (!isNoopShuffleMask(PSHUFHMask))
8705     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8706                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8707   if (!isNoopShuffleMask(PSHUFDMask))
8708     V = DAG.getBitcast(
8709         VT,
8710         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8711                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8712
8713   // At this point, each half should contain all its inputs, and we can then
8714   // just shuffle them into their final position.
8715   assert(std::count_if(LoMask.begin(), LoMask.end(),
8716                        [](int M) { return M >= 4; }) == 0 &&
8717          "Failed to lift all the high half inputs to the low mask!");
8718   assert(std::count_if(HiMask.begin(), HiMask.end(),
8719                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8720          "Failed to lift all the low half inputs to the high mask!");
8721
8722   // Do a half shuffle for the low mask.
8723   if (!isNoopShuffleMask(LoMask))
8724     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8725                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8726
8727   // Do a half shuffle with the high mask after shifting its values down.
8728   for (int &M : HiMask)
8729     if (M >= 0)
8730       M -= 4;
8731   if (!isNoopShuffleMask(HiMask))
8732     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8733                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8734
8735   return V;
8736 }
8737
8738 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8739 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8740                                           SDValue V2, ArrayRef<int> Mask,
8741                                           SelectionDAG &DAG, bool &V1InUse,
8742                                           bool &V2InUse) {
8743   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8744   SDValue V1Mask[16];
8745   SDValue V2Mask[16];
8746   V1InUse = false;
8747   V2InUse = false;
8748
8749   int Size = Mask.size();
8750   int Scale = 16 / Size;
8751   for (int i = 0; i < 16; ++i) {
8752     if (Mask[i / Scale] == -1) {
8753       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8754     } else {
8755       const int ZeroMask = 0x80;
8756       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8757                                           : ZeroMask;
8758       int V2Idx = Mask[i / Scale] < Size
8759                       ? ZeroMask
8760                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8761       if (Zeroable[i / Scale])
8762         V1Idx = V2Idx = ZeroMask;
8763       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8764       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8765       V1InUse |= (ZeroMask != V1Idx);
8766       V2InUse |= (ZeroMask != V2Idx);
8767     }
8768   }
8769
8770   if (V1InUse)
8771     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8772                      DAG.getBitcast(MVT::v16i8, V1),
8773                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8774   if (V2InUse)
8775     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8776                      DAG.getBitcast(MVT::v16i8, V2),
8777                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8778
8779   // If we need shuffled inputs from both, blend the two.
8780   SDValue V;
8781   if (V1InUse && V2InUse)
8782     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8783   else
8784     V = V1InUse ? V1 : V2;
8785
8786   // Cast the result back to the correct type.
8787   return DAG.getBitcast(VT, V);
8788 }
8789
8790 /// \brief Generic lowering of 8-lane i16 shuffles.
8791 ///
8792 /// This handles both single-input shuffles and combined shuffle/blends with
8793 /// two inputs. The single input shuffles are immediately delegated to
8794 /// a dedicated lowering routine.
8795 ///
8796 /// The blends are lowered in one of three fundamental ways. If there are few
8797 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8798 /// of the input is significantly cheaper when lowered as an interleaving of
8799 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8800 /// halves of the inputs separately (making them have relatively few inputs)
8801 /// and then concatenate them.
8802 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8803                                        const X86Subtarget *Subtarget,
8804                                        SelectionDAG &DAG) {
8805   SDLoc DL(Op);
8806   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8807   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8808   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8809   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8810   ArrayRef<int> OrigMask = SVOp->getMask();
8811   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8812                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8813   MutableArrayRef<int> Mask(MaskStorage);
8814
8815   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8816
8817   // Whenever we can lower this as a zext, that instruction is strictly faster
8818   // than any alternative.
8819   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8820           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8821     return ZExt;
8822
8823   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8824   (void)isV1;
8825   auto isV2 = [](int M) { return M >= 8; };
8826
8827   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8828
8829   if (NumV2Inputs == 0) {
8830     // Check for being able to broadcast a single element.
8831     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8832                                                           Mask, Subtarget, DAG))
8833       return Broadcast;
8834
8835     // Try to use shift instructions.
8836     if (SDValue Shift =
8837             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8838       return Shift;
8839
8840     // Use dedicated unpack instructions for masks that match their pattern.
8841     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8842       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8843     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8844       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8845
8846     // Try to use byte rotation instructions.
8847     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8848                                                         Mask, Subtarget, DAG))
8849       return Rotate;
8850
8851     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8852                                                      Subtarget, DAG);
8853   }
8854
8855   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8856          "All single-input shuffles should be canonicalized to be V1-input "
8857          "shuffles.");
8858
8859   // Try to use shift instructions.
8860   if (SDValue Shift =
8861           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8862     return Shift;
8863
8864   // See if we can use SSE4A Extraction / Insertion.
8865   if (Subtarget->hasSSE4A())
8866     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8867       return V;
8868
8869   // There are special ways we can lower some single-element blends.
8870   if (NumV2Inputs == 1)
8871     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8872                                                          Mask, Subtarget, DAG))
8873       return V;
8874
8875   // We have different paths for blend lowering, but they all must use the
8876   // *exact* same predicate.
8877   bool IsBlendSupported = Subtarget->hasSSE41();
8878   if (IsBlendSupported)
8879     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8880                                                   Subtarget, DAG))
8881       return Blend;
8882
8883   if (SDValue Masked =
8884           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8885     return Masked;
8886
8887   // Use dedicated unpack instructions for masks that match their pattern.
8888   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8889     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8890   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8891     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8892
8893   // Try to use byte rotation instructions.
8894   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8895           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8896     return Rotate;
8897
8898   if (SDValue BitBlend =
8899           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8900     return BitBlend;
8901
8902   if (SDValue Unpack =
8903           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8904     return Unpack;
8905
8906   // If we can't directly blend but can use PSHUFB, that will be better as it
8907   // can both shuffle and set up the inefficient blend.
8908   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8909     bool V1InUse, V2InUse;
8910     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8911                                       V1InUse, V2InUse);
8912   }
8913
8914   // We can always bit-blend if we have to so the fallback strategy is to
8915   // decompose into single-input permutes and blends.
8916   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8917                                                       Mask, DAG);
8918 }
8919
8920 /// \brief Check whether a compaction lowering can be done by dropping even
8921 /// elements and compute how many times even elements must be dropped.
8922 ///
8923 /// This handles shuffles which take every Nth element where N is a power of
8924 /// two. Example shuffle masks:
8925 ///
8926 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8927 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8928 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8929 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8930 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8931 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8932 ///
8933 /// Any of these lanes can of course be undef.
8934 ///
8935 /// This routine only supports N <= 3.
8936 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8937 /// for larger N.
8938 ///
8939 /// \returns N above, or the number of times even elements must be dropped if
8940 /// there is such a number. Otherwise returns zero.
8941 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8942   // Figure out whether we're looping over two inputs or just one.
8943   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8944
8945   // The modulus for the shuffle vector entries is based on whether this is
8946   // a single input or not.
8947   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8948   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8949          "We should only be called with masks with a power-of-2 size!");
8950
8951   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8952
8953   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8954   // and 2^3 simultaneously. This is because we may have ambiguity with
8955   // partially undef inputs.
8956   bool ViableForN[3] = {true, true, true};
8957
8958   for (int i = 0, e = Mask.size(); i < e; ++i) {
8959     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8960     // want.
8961     if (Mask[i] == -1)
8962       continue;
8963
8964     bool IsAnyViable = false;
8965     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8966       if (ViableForN[j]) {
8967         uint64_t N = j + 1;
8968
8969         // The shuffle mask must be equal to (i * 2^N) % M.
8970         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8971           IsAnyViable = true;
8972         else
8973           ViableForN[j] = false;
8974       }
8975     // Early exit if we exhaust the possible powers of two.
8976     if (!IsAnyViable)
8977       break;
8978   }
8979
8980   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8981     if (ViableForN[j])
8982       return j + 1;
8983
8984   // Return 0 as there is no viable power of two.
8985   return 0;
8986 }
8987
8988 /// \brief Generic lowering of v16i8 shuffles.
8989 ///
8990 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8991 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8992 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8993 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8994 /// back together.
8995 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8996                                        const X86Subtarget *Subtarget,
8997                                        SelectionDAG &DAG) {
8998   SDLoc DL(Op);
8999   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9000   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9001   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9003   ArrayRef<int> Mask = SVOp->getMask();
9004   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9005
9006   // Try to use shift instructions.
9007   if (SDValue Shift =
9008           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9009     return Shift;
9010
9011   // Try to use byte rotation instructions.
9012   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9013           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9014     return Rotate;
9015
9016   // Try to use a zext lowering.
9017   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9018           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9019     return ZExt;
9020
9021   // See if we can use SSE4A Extraction / Insertion.
9022   if (Subtarget->hasSSE4A())
9023     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9024       return V;
9025
9026   int NumV2Elements =
9027       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9028
9029   // For single-input shuffles, there are some nicer lowering tricks we can use.
9030   if (NumV2Elements == 0) {
9031     // Check for being able to broadcast a single element.
9032     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9033                                                           Mask, Subtarget, DAG))
9034       return Broadcast;
9035
9036     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9037     // Notably, this handles splat and partial-splat shuffles more efficiently.
9038     // However, it only makes sense if the pre-duplication shuffle simplifies
9039     // things significantly. Currently, this means we need to be able to
9040     // express the pre-duplication shuffle as an i16 shuffle.
9041     //
9042     // FIXME: We should check for other patterns which can be widened into an
9043     // i16 shuffle as well.
9044     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9045       for (int i = 0; i < 16; i += 2)
9046         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9047           return false;
9048
9049       return true;
9050     };
9051     auto tryToWidenViaDuplication = [&]() -> SDValue {
9052       if (!canWidenViaDuplication(Mask))
9053         return SDValue();
9054       SmallVector<int, 4> LoInputs;
9055       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9056                    [](int M) { return M >= 0 && M < 8; });
9057       std::sort(LoInputs.begin(), LoInputs.end());
9058       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9059                      LoInputs.end());
9060       SmallVector<int, 4> HiInputs;
9061       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9062                    [](int M) { return M >= 8; });
9063       std::sort(HiInputs.begin(), HiInputs.end());
9064       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9065                      HiInputs.end());
9066
9067       bool TargetLo = LoInputs.size() >= HiInputs.size();
9068       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9069       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9070
9071       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9072       SmallDenseMap<int, int, 8> LaneMap;
9073       for (int I : InPlaceInputs) {
9074         PreDupI16Shuffle[I/2] = I/2;
9075         LaneMap[I] = I;
9076       }
9077       int j = TargetLo ? 0 : 4, je = j + 4;
9078       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9079         // Check if j is already a shuffle of this input. This happens when
9080         // there are two adjacent bytes after we move the low one.
9081         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9082           // If we haven't yet mapped the input, search for a slot into which
9083           // we can map it.
9084           while (j < je && PreDupI16Shuffle[j] != -1)
9085             ++j;
9086
9087           if (j == je)
9088             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9089             return SDValue();
9090
9091           // Map this input with the i16 shuffle.
9092           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9093         }
9094
9095         // Update the lane map based on the mapping we ended up with.
9096         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9097       }
9098       V1 = DAG.getBitcast(
9099           MVT::v16i8,
9100           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9101                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9102
9103       // Unpack the bytes to form the i16s that will be shuffled into place.
9104       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9105                        MVT::v16i8, V1, V1);
9106
9107       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9108       for (int i = 0; i < 16; ++i)
9109         if (Mask[i] != -1) {
9110           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9111           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9112           if (PostDupI16Shuffle[i / 2] == -1)
9113             PostDupI16Shuffle[i / 2] = MappedMask;
9114           else
9115             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9116                    "Conflicting entrties in the original shuffle!");
9117         }
9118       return DAG.getBitcast(
9119           MVT::v16i8,
9120           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9121                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9122     };
9123     if (SDValue V = tryToWidenViaDuplication())
9124       return V;
9125   }
9126
9127   if (SDValue Masked =
9128           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9129     return Masked;
9130
9131   // Use dedicated unpack instructions for masks that match their pattern.
9132   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9133                                          0, 16, 1, 17, 2, 18, 3, 19,
9134                                          // High half.
9135                                          4, 20, 5, 21, 6, 22, 7, 23}))
9136     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9137   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9138                                          8, 24, 9, 25, 10, 26, 11, 27,
9139                                          // High half.
9140                                          12, 28, 13, 29, 14, 30, 15, 31}))
9141     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9142
9143   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9144   // with PSHUFB. It is important to do this before we attempt to generate any
9145   // blends but after all of the single-input lowerings. If the single input
9146   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9147   // want to preserve that and we can DAG combine any longer sequences into
9148   // a PSHUFB in the end. But once we start blending from multiple inputs,
9149   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9150   // and there are *very* few patterns that would actually be faster than the
9151   // PSHUFB approach because of its ability to zero lanes.
9152   //
9153   // FIXME: The only exceptions to the above are blends which are exact
9154   // interleavings with direct instructions supporting them. We currently don't
9155   // handle those well here.
9156   if (Subtarget->hasSSSE3()) {
9157     bool V1InUse = false;
9158     bool V2InUse = false;
9159
9160     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9161                                                 DAG, V1InUse, V2InUse);
9162
9163     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9164     // do so. This avoids using them to handle blends-with-zero which is
9165     // important as a single pshufb is significantly faster for that.
9166     if (V1InUse && V2InUse) {
9167       if (Subtarget->hasSSE41())
9168         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9169                                                       Mask, Subtarget, DAG))
9170           return Blend;
9171
9172       // We can use an unpack to do the blending rather than an or in some
9173       // cases. Even though the or may be (very minorly) more efficient, we
9174       // preference this lowering because there are common cases where part of
9175       // the complexity of the shuffles goes away when we do the final blend as
9176       // an unpack.
9177       // FIXME: It might be worth trying to detect if the unpack-feeding
9178       // shuffles will both be pshufb, in which case we shouldn't bother with
9179       // this.
9180       if (SDValue Unpack =
9181               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9182         return Unpack;
9183     }
9184
9185     return PSHUFB;
9186   }
9187
9188   // There are special ways we can lower some single-element blends.
9189   if (NumV2Elements == 1)
9190     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9191                                                          Mask, Subtarget, DAG))
9192       return V;
9193
9194   if (SDValue BitBlend =
9195           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9196     return BitBlend;
9197
9198   // Check whether a compaction lowering can be done. This handles shuffles
9199   // which take every Nth element for some even N. See the helper function for
9200   // details.
9201   //
9202   // We special case these as they can be particularly efficiently handled with
9203   // the PACKUSB instruction on x86 and they show up in common patterns of
9204   // rearranging bytes to truncate wide elements.
9205   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9206     // NumEvenDrops is the power of two stride of the elements. Another way of
9207     // thinking about it is that we need to drop the even elements this many
9208     // times to get the original input.
9209     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9210
9211     // First we need to zero all the dropped bytes.
9212     assert(NumEvenDrops <= 3 &&
9213            "No support for dropping even elements more than 3 times.");
9214     // We use the mask type to pick which bytes are preserved based on how many
9215     // elements are dropped.
9216     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9217     SDValue ByteClearMask = DAG.getBitcast(
9218         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9219     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9220     if (!IsSingleInput)
9221       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9222
9223     // Now pack things back together.
9224     V1 = DAG.getBitcast(MVT::v8i16, V1);
9225     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9226     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9227     for (int i = 1; i < NumEvenDrops; ++i) {
9228       Result = DAG.getBitcast(MVT::v8i16, Result);
9229       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9230     }
9231
9232     return Result;
9233   }
9234
9235   // Handle multi-input cases by blending single-input shuffles.
9236   if (NumV2Elements > 0)
9237     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9238                                                       Mask, DAG);
9239
9240   // The fallback path for single-input shuffles widens this into two v8i16
9241   // vectors with unpacks, shuffles those, and then pulls them back together
9242   // with a pack.
9243   SDValue V = V1;
9244
9245   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9246   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9247   for (int i = 0; i < 16; ++i)
9248     if (Mask[i] >= 0)
9249       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9250
9251   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9252
9253   SDValue VLoHalf, VHiHalf;
9254   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9255   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9256   // i16s.
9257   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9258                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9259       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9260                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9261     // Use a mask to drop the high bytes.
9262     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9263     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9264                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9265
9266     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9267     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9268
9269     // Squash the masks to point directly into VLoHalf.
9270     for (int &M : LoBlendMask)
9271       if (M >= 0)
9272         M /= 2;
9273     for (int &M : HiBlendMask)
9274       if (M >= 0)
9275         M /= 2;
9276   } else {
9277     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9278     // VHiHalf so that we can blend them as i16s.
9279     VLoHalf = DAG.getBitcast(
9280         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9281     VHiHalf = DAG.getBitcast(
9282         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9283   }
9284
9285   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9286   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9287
9288   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9289 }
9290
9291 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9292 ///
9293 /// This routine breaks down the specific type of 128-bit shuffle and
9294 /// dispatches to the lowering routines accordingly.
9295 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9296                                         MVT VT, const X86Subtarget *Subtarget,
9297                                         SelectionDAG &DAG) {
9298   switch (VT.SimpleTy) {
9299   case MVT::v2i64:
9300     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9301   case MVT::v2f64:
9302     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9303   case MVT::v4i32:
9304     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9305   case MVT::v4f32:
9306     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9307   case MVT::v8i16:
9308     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9309   case MVT::v16i8:
9310     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9311
9312   default:
9313     llvm_unreachable("Unimplemented!");
9314   }
9315 }
9316
9317 /// \brief Helper function to test whether a shuffle mask could be
9318 /// simplified by widening the elements being shuffled.
9319 ///
9320 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9321 /// leaves it in an unspecified state.
9322 ///
9323 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9324 /// shuffle masks. The latter have the special property of a '-2' representing
9325 /// a zero-ed lane of a vector.
9326 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9327                                     SmallVectorImpl<int> &WidenedMask) {
9328   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9329     // If both elements are undef, its trivial.
9330     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9331       WidenedMask.push_back(SM_SentinelUndef);
9332       continue;
9333     }
9334
9335     // Check for an undef mask and a mask value properly aligned to fit with
9336     // a pair of values. If we find such a case, use the non-undef mask's value.
9337     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9338       WidenedMask.push_back(Mask[i + 1] / 2);
9339       continue;
9340     }
9341     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9342       WidenedMask.push_back(Mask[i] / 2);
9343       continue;
9344     }
9345
9346     // When zeroing, we need to spread the zeroing across both lanes to widen.
9347     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9348       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9349           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9350         WidenedMask.push_back(SM_SentinelZero);
9351         continue;
9352       }
9353       return false;
9354     }
9355
9356     // Finally check if the two mask values are adjacent and aligned with
9357     // a pair.
9358     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9359       WidenedMask.push_back(Mask[i] / 2);
9360       continue;
9361     }
9362
9363     // Otherwise we can't safely widen the elements used in this shuffle.
9364     return false;
9365   }
9366   assert(WidenedMask.size() == Mask.size() / 2 &&
9367          "Incorrect size of mask after widening the elements!");
9368
9369   return true;
9370 }
9371
9372 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9373 ///
9374 /// This routine just extracts two subvectors, shuffles them independently, and
9375 /// then concatenates them back together. This should work effectively with all
9376 /// AVX vector shuffle types.
9377 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9378                                           SDValue V2, ArrayRef<int> Mask,
9379                                           SelectionDAG &DAG) {
9380   assert(VT.getSizeInBits() >= 256 &&
9381          "Only for 256-bit or wider vector shuffles!");
9382   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9383   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9384
9385   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9386   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9387
9388   int NumElements = VT.getVectorNumElements();
9389   int SplitNumElements = NumElements / 2;
9390   MVT ScalarVT = VT.getScalarType();
9391   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9392
9393   // Rather than splitting build-vectors, just build two narrower build
9394   // vectors. This helps shuffling with splats and zeros.
9395   auto SplitVector = [&](SDValue V) {
9396     while (V.getOpcode() == ISD::BITCAST)
9397       V = V->getOperand(0);
9398
9399     MVT OrigVT = V.getSimpleValueType();
9400     int OrigNumElements = OrigVT.getVectorNumElements();
9401     int OrigSplitNumElements = OrigNumElements / 2;
9402     MVT OrigScalarVT = OrigVT.getScalarType();
9403     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9404
9405     SDValue LoV, HiV;
9406
9407     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9408     if (!BV) {
9409       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9410                         DAG.getIntPtrConstant(0, DL));
9411       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9412                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9413     } else {
9414
9415       SmallVector<SDValue, 16> LoOps, HiOps;
9416       for (int i = 0; i < OrigSplitNumElements; ++i) {
9417         LoOps.push_back(BV->getOperand(i));
9418         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9419       }
9420       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9421       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9422     }
9423     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9424                           DAG.getBitcast(SplitVT, HiV));
9425   };
9426
9427   SDValue LoV1, HiV1, LoV2, HiV2;
9428   std::tie(LoV1, HiV1) = SplitVector(V1);
9429   std::tie(LoV2, HiV2) = SplitVector(V2);
9430
9431   // Now create two 4-way blends of these half-width vectors.
9432   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9433     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9434     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9435     for (int i = 0; i < SplitNumElements; ++i) {
9436       int M = HalfMask[i];
9437       if (M >= NumElements) {
9438         if (M >= NumElements + SplitNumElements)
9439           UseHiV2 = true;
9440         else
9441           UseLoV2 = true;
9442         V2BlendMask.push_back(M - NumElements);
9443         V1BlendMask.push_back(-1);
9444         BlendMask.push_back(SplitNumElements + i);
9445       } else if (M >= 0) {
9446         if (M >= SplitNumElements)
9447           UseHiV1 = true;
9448         else
9449           UseLoV1 = true;
9450         V2BlendMask.push_back(-1);
9451         V1BlendMask.push_back(M);
9452         BlendMask.push_back(i);
9453       } else {
9454         V2BlendMask.push_back(-1);
9455         V1BlendMask.push_back(-1);
9456         BlendMask.push_back(-1);
9457       }
9458     }
9459
9460     // Because the lowering happens after all combining takes place, we need to
9461     // manually combine these blend masks as much as possible so that we create
9462     // a minimal number of high-level vector shuffle nodes.
9463
9464     // First try just blending the halves of V1 or V2.
9465     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9466       return DAG.getUNDEF(SplitVT);
9467     if (!UseLoV2 && !UseHiV2)
9468       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9469     if (!UseLoV1 && !UseHiV1)
9470       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9471
9472     SDValue V1Blend, V2Blend;
9473     if (UseLoV1 && UseHiV1) {
9474       V1Blend =
9475         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9476     } else {
9477       // We only use half of V1 so map the usage down into the final blend mask.
9478       V1Blend = UseLoV1 ? LoV1 : HiV1;
9479       for (int i = 0; i < SplitNumElements; ++i)
9480         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9481           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9482     }
9483     if (UseLoV2 && UseHiV2) {
9484       V2Blend =
9485         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9486     } else {
9487       // We only use half of V2 so map the usage down into the final blend mask.
9488       V2Blend = UseLoV2 ? LoV2 : HiV2;
9489       for (int i = 0; i < SplitNumElements; ++i)
9490         if (BlendMask[i] >= SplitNumElements)
9491           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9492     }
9493     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9494   };
9495   SDValue Lo = HalfBlend(LoMask);
9496   SDValue Hi = HalfBlend(HiMask);
9497   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9498 }
9499
9500 /// \brief Either split a vector in halves or decompose the shuffles and the
9501 /// blend.
9502 ///
9503 /// This is provided as a good fallback for many lowerings of non-single-input
9504 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9505 /// between splitting the shuffle into 128-bit components and stitching those
9506 /// back together vs. extracting the single-input shuffles and blending those
9507 /// results.
9508 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9509                                                 SDValue V2, ArrayRef<int> Mask,
9510                                                 SelectionDAG &DAG) {
9511   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9512                                             "lower single-input shuffles as it "
9513                                             "could then recurse on itself.");
9514   int Size = Mask.size();
9515
9516   // If this can be modeled as a broadcast of two elements followed by a blend,
9517   // prefer that lowering. This is especially important because broadcasts can
9518   // often fold with memory operands.
9519   auto DoBothBroadcast = [&] {
9520     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9521     for (int M : Mask)
9522       if (M >= Size) {
9523         if (V2BroadcastIdx == -1)
9524           V2BroadcastIdx = M - Size;
9525         else if (M - Size != V2BroadcastIdx)
9526           return false;
9527       } else if (M >= 0) {
9528         if (V1BroadcastIdx == -1)
9529           V1BroadcastIdx = M;
9530         else if (M != V1BroadcastIdx)
9531           return false;
9532       }
9533     return true;
9534   };
9535   if (DoBothBroadcast())
9536     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9537                                                       DAG);
9538
9539   // If the inputs all stem from a single 128-bit lane of each input, then we
9540   // split them rather than blending because the split will decompose to
9541   // unusually few instructions.
9542   int LaneCount = VT.getSizeInBits() / 128;
9543   int LaneSize = Size / LaneCount;
9544   SmallBitVector LaneInputs[2];
9545   LaneInputs[0].resize(LaneCount, false);
9546   LaneInputs[1].resize(LaneCount, false);
9547   for (int i = 0; i < Size; ++i)
9548     if (Mask[i] >= 0)
9549       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9550   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9551     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9552
9553   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9554   // that the decomposed single-input shuffles don't end up here.
9555   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9556 }
9557
9558 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9559 /// a permutation and blend of those lanes.
9560 ///
9561 /// This essentially blends the out-of-lane inputs to each lane into the lane
9562 /// from a permuted copy of the vector. This lowering strategy results in four
9563 /// instructions in the worst case for a single-input cross lane shuffle which
9564 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9565 /// of. Special cases for each particular shuffle pattern should be handled
9566 /// prior to trying this lowering.
9567 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9568                                                        SDValue V1, SDValue V2,
9569                                                        ArrayRef<int> Mask,
9570                                                        SelectionDAG &DAG) {
9571   // FIXME: This should probably be generalized for 512-bit vectors as well.
9572   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9573   int LaneSize = Mask.size() / 2;
9574
9575   // If there are only inputs from one 128-bit lane, splitting will in fact be
9576   // less expensive. The flags track whether the given lane contains an element
9577   // that crosses to another lane.
9578   bool LaneCrossing[2] = {false, false};
9579   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9580     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9581       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9582   if (!LaneCrossing[0] || !LaneCrossing[1])
9583     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9584
9585   if (isSingleInputShuffleMask(Mask)) {
9586     SmallVector<int, 32> FlippedBlendMask;
9587     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9588       FlippedBlendMask.push_back(
9589           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9590                                   ? Mask[i]
9591                                   : Mask[i] % LaneSize +
9592                                         (i / LaneSize) * LaneSize + Size));
9593
9594     // Flip the vector, and blend the results which should now be in-lane. The
9595     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9596     // 5 for the high source. The value 3 selects the high half of source 2 and
9597     // the value 2 selects the low half of source 2. We only use source 2 to
9598     // allow folding it into a memory operand.
9599     unsigned PERMMask = 3 | 2 << 4;
9600     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9601                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9602     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9603   }
9604
9605   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9606   // will be handled by the above logic and a blend of the results, much like
9607   // other patterns in AVX.
9608   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9609 }
9610
9611 /// \brief Handle lowering 2-lane 128-bit shuffles.
9612 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9613                                         SDValue V2, ArrayRef<int> Mask,
9614                                         const X86Subtarget *Subtarget,
9615                                         SelectionDAG &DAG) {
9616   // TODO: If minimizing size and one of the inputs is a zero vector and the
9617   // the zero vector has only one use, we could use a VPERM2X128 to save the
9618   // instruction bytes needed to explicitly generate the zero vector.
9619
9620   // Blends are faster and handle all the non-lane-crossing cases.
9621   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9622                                                 Subtarget, DAG))
9623     return Blend;
9624
9625   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9626   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9627
9628   // If either input operand is a zero vector, use VPERM2X128 because its mask
9629   // allows us to replace the zero input with an implicit zero.
9630   if (!IsV1Zero && !IsV2Zero) {
9631     // Check for patterns which can be matched with a single insert of a 128-bit
9632     // subvector.
9633     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9634     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9635       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9636                                    VT.getVectorNumElements() / 2);
9637       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9638                                 DAG.getIntPtrConstant(0, DL));
9639       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9640                                 OnlyUsesV1 ? V1 : V2,
9641                                 DAG.getIntPtrConstant(0, DL));
9642       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9643     }
9644   }
9645
9646   // Otherwise form a 128-bit permutation. After accounting for undefs,
9647   // convert the 64-bit shuffle mask selection values into 128-bit
9648   // selection bits by dividing the indexes by 2 and shifting into positions
9649   // defined by a vperm2*128 instruction's immediate control byte.
9650
9651   // The immediate permute control byte looks like this:
9652   //    [1:0] - select 128 bits from sources for low half of destination
9653   //    [2]   - ignore
9654   //    [3]   - zero low half of destination
9655   //    [5:4] - select 128 bits from sources for high half of destination
9656   //    [6]   - ignore
9657   //    [7]   - zero high half of destination
9658
9659   int MaskLO = Mask[0];
9660   if (MaskLO == SM_SentinelUndef)
9661     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9662
9663   int MaskHI = Mask[2];
9664   if (MaskHI == SM_SentinelUndef)
9665     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9666
9667   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9668
9669   // If either input is a zero vector, replace it with an undef input.
9670   // Shuffle mask values <  4 are selecting elements of V1.
9671   // Shuffle mask values >= 4 are selecting elements of V2.
9672   // Adjust each half of the permute mask by clearing the half that was
9673   // selecting the zero vector and setting the zero mask bit.
9674   if (IsV1Zero) {
9675     V1 = DAG.getUNDEF(VT);
9676     if (MaskLO < 4)
9677       PermMask = (PermMask & 0xf0) | 0x08;
9678     if (MaskHI < 4)
9679       PermMask = (PermMask & 0x0f) | 0x80;
9680   }
9681   if (IsV2Zero) {
9682     V2 = DAG.getUNDEF(VT);
9683     if (MaskLO >= 4)
9684       PermMask = (PermMask & 0xf0) | 0x08;
9685     if (MaskHI >= 4)
9686       PermMask = (PermMask & 0x0f) | 0x80;
9687   }
9688
9689   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9690                      DAG.getConstant(PermMask, DL, MVT::i8));
9691 }
9692
9693 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9694 /// shuffling each lane.
9695 ///
9696 /// This will only succeed when the result of fixing the 128-bit lanes results
9697 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9698 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9699 /// the lane crosses early and then use simpler shuffles within each lane.
9700 ///
9701 /// FIXME: It might be worthwhile at some point to support this without
9702 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9703 /// in x86 only floating point has interesting non-repeating shuffles, and even
9704 /// those are still *marginally* more expensive.
9705 static SDValue lowerVectorShuffleByMerging128BitLanes(
9706     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9707     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9708   assert(!isSingleInputShuffleMask(Mask) &&
9709          "This is only useful with multiple inputs.");
9710
9711   int Size = Mask.size();
9712   int LaneSize = 128 / VT.getScalarSizeInBits();
9713   int NumLanes = Size / LaneSize;
9714   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9715
9716   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9717   // check whether the in-128-bit lane shuffles share a repeating pattern.
9718   SmallVector<int, 4> Lanes;
9719   Lanes.resize(NumLanes, -1);
9720   SmallVector<int, 4> InLaneMask;
9721   InLaneMask.resize(LaneSize, -1);
9722   for (int i = 0; i < Size; ++i) {
9723     if (Mask[i] < 0)
9724       continue;
9725
9726     int j = i / LaneSize;
9727
9728     if (Lanes[j] < 0) {
9729       // First entry we've seen for this lane.
9730       Lanes[j] = Mask[i] / LaneSize;
9731     } else if (Lanes[j] != Mask[i] / LaneSize) {
9732       // This doesn't match the lane selected previously!
9733       return SDValue();
9734     }
9735
9736     // Check that within each lane we have a consistent shuffle mask.
9737     int k = i % LaneSize;
9738     if (InLaneMask[k] < 0) {
9739       InLaneMask[k] = Mask[i] % LaneSize;
9740     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9741       // This doesn't fit a repeating in-lane mask.
9742       return SDValue();
9743     }
9744   }
9745
9746   // First shuffle the lanes into place.
9747   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9748                                 VT.getSizeInBits() / 64);
9749   SmallVector<int, 8> LaneMask;
9750   LaneMask.resize(NumLanes * 2, -1);
9751   for (int i = 0; i < NumLanes; ++i)
9752     if (Lanes[i] >= 0) {
9753       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9754       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9755     }
9756
9757   V1 = DAG.getBitcast(LaneVT, V1);
9758   V2 = DAG.getBitcast(LaneVT, V2);
9759   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9760
9761   // Cast it back to the type we actually want.
9762   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9763
9764   // Now do a simple shuffle that isn't lane crossing.
9765   SmallVector<int, 8> NewMask;
9766   NewMask.resize(Size, -1);
9767   for (int i = 0; i < Size; ++i)
9768     if (Mask[i] >= 0)
9769       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9770   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9771          "Must not introduce lane crosses at this point!");
9772
9773   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9774 }
9775
9776 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9777 /// given mask.
9778 ///
9779 /// This returns true if the elements from a particular input are already in the
9780 /// slot required by the given mask and require no permutation.
9781 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9782   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9783   int Size = Mask.size();
9784   for (int i = 0; i < Size; ++i)
9785     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9786       return false;
9787
9788   return true;
9789 }
9790
9791 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9792                                             ArrayRef<int> Mask, SDValue V1,
9793                                             SDValue V2, SelectionDAG &DAG) {
9794
9795   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9796   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9797   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9798   int NumElts = VT.getVectorNumElements();
9799   bool ShufpdMask = true;
9800   bool CommutableMask = true;
9801   unsigned Immediate = 0;
9802   for (int i = 0; i < NumElts; ++i) {
9803     if (Mask[i] < 0)
9804       continue;
9805     int Val = (i & 6) + NumElts * (i & 1);
9806     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9807     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9808       ShufpdMask = false;
9809     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9810       CommutableMask = false;
9811     Immediate |= (Mask[i] % 2) << i;
9812   }
9813   if (ShufpdMask)
9814     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9815                        DAG.getConstant(Immediate, DL, MVT::i8));
9816   if (CommutableMask)
9817     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9818                        DAG.getConstant(Immediate, DL, MVT::i8));
9819   return SDValue();
9820 }
9821
9822 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9823 ///
9824 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9825 /// isn't available.
9826 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9827                                        const X86Subtarget *Subtarget,
9828                                        SelectionDAG &DAG) {
9829   SDLoc DL(Op);
9830   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9831   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9833   ArrayRef<int> Mask = SVOp->getMask();
9834   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9835
9836   SmallVector<int, 4> WidenedMask;
9837   if (canWidenShuffleElements(Mask, WidenedMask))
9838     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9839                                     DAG);
9840
9841   if (isSingleInputShuffleMask(Mask)) {
9842     // Check for being able to broadcast a single element.
9843     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9844                                                           Mask, Subtarget, DAG))
9845       return Broadcast;
9846
9847     // Use low duplicate instructions for masks that match their pattern.
9848     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9849       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9850
9851     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9852       // Non-half-crossing single input shuffles can be lowerid with an
9853       // interleaved permutation.
9854       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9855                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9856       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9857                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9858     }
9859
9860     // With AVX2 we have direct support for this permutation.
9861     if (Subtarget->hasAVX2())
9862       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9863                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9864
9865     // Otherwise, fall back.
9866     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9867                                                    DAG);
9868   }
9869
9870   // X86 has dedicated unpack instructions that can handle specific blend
9871   // operations: UNPCKH and UNPCKL.
9872   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9873     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9874   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9875     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9876   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9877     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9878   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9879     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9880
9881   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9882                                                 Subtarget, DAG))
9883     return Blend;
9884
9885   // Check if the blend happens to exactly fit that of SHUFPD.
9886   if (SDValue Op =
9887       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9888     return Op;
9889
9890   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9891   // shuffle. However, if we have AVX2 and either inputs are already in place,
9892   // we will be able to shuffle even across lanes the other input in a single
9893   // instruction so skip this pattern.
9894   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9895                                  isShuffleMaskInputInPlace(1, Mask))))
9896     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9897             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9898       return Result;
9899
9900   // If we have AVX2 then we always want to lower with a blend because an v4 we
9901   // can fully permute the elements.
9902   if (Subtarget->hasAVX2())
9903     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9904                                                       Mask, DAG);
9905
9906   // Otherwise fall back on generic lowering.
9907   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9908 }
9909
9910 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9911 ///
9912 /// This routine is only called when we have AVX2 and thus a reasonable
9913 /// instruction set for v4i64 shuffling..
9914 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9915                                        const X86Subtarget *Subtarget,
9916                                        SelectionDAG &DAG) {
9917   SDLoc DL(Op);
9918   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9919   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9920   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9921   ArrayRef<int> Mask = SVOp->getMask();
9922   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9923   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9924
9925   SmallVector<int, 4> WidenedMask;
9926   if (canWidenShuffleElements(Mask, WidenedMask))
9927     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9928                                     DAG);
9929
9930   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9931                                                 Subtarget, DAG))
9932     return Blend;
9933
9934   // Check for being able to broadcast a single element.
9935   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9936                                                         Mask, Subtarget, DAG))
9937     return Broadcast;
9938
9939   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9940   // use lower latency instructions that will operate on both 128-bit lanes.
9941   SmallVector<int, 2> RepeatedMask;
9942   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9943     if (isSingleInputShuffleMask(Mask)) {
9944       int PSHUFDMask[] = {-1, -1, -1, -1};
9945       for (int i = 0; i < 2; ++i)
9946         if (RepeatedMask[i] >= 0) {
9947           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9948           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9949         }
9950       return DAG.getBitcast(
9951           MVT::v4i64,
9952           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9953                       DAG.getBitcast(MVT::v8i32, V1),
9954                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9955     }
9956   }
9957
9958   // AVX2 provides a direct instruction for permuting a single input across
9959   // lanes.
9960   if (isSingleInputShuffleMask(Mask))
9961     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9962                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9963
9964   // Try to use shift instructions.
9965   if (SDValue Shift =
9966           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9967     return Shift;
9968
9969   // Use dedicated unpack instructions for masks that match their pattern.
9970   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9971     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9972   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9973     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9974   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9975     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9976   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9977     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9978
9979   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9980   // shuffle. However, if we have AVX2 and either inputs are already in place,
9981   // we will be able to shuffle even across lanes the other input in a single
9982   // instruction so skip this pattern.
9983   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9984                                  isShuffleMaskInputInPlace(1, Mask))))
9985     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9986             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9987       return Result;
9988
9989   // Otherwise fall back on generic blend lowering.
9990   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9991                                                     Mask, DAG);
9992 }
9993
9994 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9995 ///
9996 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9997 /// isn't available.
9998 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9999                                        const X86Subtarget *Subtarget,
10000                                        SelectionDAG &DAG) {
10001   SDLoc DL(Op);
10002   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10003   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10004   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10005   ArrayRef<int> Mask = SVOp->getMask();
10006   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10007
10008   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10009                                                 Subtarget, DAG))
10010     return Blend;
10011
10012   // Check for being able to broadcast a single element.
10013   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10014                                                         Mask, Subtarget, DAG))
10015     return Broadcast;
10016
10017   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10018   // options to efficiently lower the shuffle.
10019   SmallVector<int, 4> RepeatedMask;
10020   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10021     assert(RepeatedMask.size() == 4 &&
10022            "Repeated masks must be half the mask width!");
10023
10024     // Use even/odd duplicate instructions for masks that match their pattern.
10025     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10026       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10027     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10028       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10029
10030     if (isSingleInputShuffleMask(Mask))
10031       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10032                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10033
10034     // Use dedicated unpack instructions for masks that match their pattern.
10035     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10036       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10037     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10038       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10039     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10040       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10041     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10042       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10043
10044     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10045     // have already handled any direct blends. We also need to squash the
10046     // repeated mask into a simulated v4f32 mask.
10047     for (int i = 0; i < 4; ++i)
10048       if (RepeatedMask[i] >= 8)
10049         RepeatedMask[i] -= 4;
10050     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10051   }
10052
10053   // If we have a single input shuffle with different shuffle patterns in the
10054   // two 128-bit lanes use the variable mask to VPERMILPS.
10055   if (isSingleInputShuffleMask(Mask)) {
10056     SDValue VPermMask[8];
10057     for (int i = 0; i < 8; ++i)
10058       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10059                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10060     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10061       return DAG.getNode(
10062           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10063           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10064
10065     if (Subtarget->hasAVX2())
10066       return DAG.getNode(
10067           X86ISD::VPERMV, DL, MVT::v8f32,
10068           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10069                                                  MVT::v8i32, VPermMask)),
10070           V1);
10071
10072     // Otherwise, fall back.
10073     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10074                                                    DAG);
10075   }
10076
10077   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10078   // shuffle.
10079   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10080           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10081     return Result;
10082
10083   // If we have AVX2 then we always want to lower with a blend because at v8 we
10084   // can fully permute the elements.
10085   if (Subtarget->hasAVX2())
10086     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10087                                                       Mask, DAG);
10088
10089   // Otherwise fall back on generic lowering.
10090   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10091 }
10092
10093 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10094 ///
10095 /// This routine is only called when we have AVX2 and thus a reasonable
10096 /// instruction set for v8i32 shuffling..
10097 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10098                                        const X86Subtarget *Subtarget,
10099                                        SelectionDAG &DAG) {
10100   SDLoc DL(Op);
10101   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10102   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10104   ArrayRef<int> Mask = SVOp->getMask();
10105   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10106   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10107
10108   // Whenever we can lower this as a zext, that instruction is strictly faster
10109   // than any alternative. It also allows us to fold memory operands into the
10110   // shuffle in many cases.
10111   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10112                                                          Mask, Subtarget, DAG))
10113     return ZExt;
10114
10115   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10116                                                 Subtarget, DAG))
10117     return Blend;
10118
10119   // Check for being able to broadcast a single element.
10120   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10121                                                         Mask, Subtarget, DAG))
10122     return Broadcast;
10123
10124   // If the shuffle mask is repeated in each 128-bit lane we can use more
10125   // efficient instructions that mirror the shuffles across the two 128-bit
10126   // lanes.
10127   SmallVector<int, 4> RepeatedMask;
10128   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10129     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10130     if (isSingleInputShuffleMask(Mask))
10131       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10132                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10133
10134     // Use dedicated unpack instructions for masks that match their pattern.
10135     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10136       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10137     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10138       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10139     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10140       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10141     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10142       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10143   }
10144
10145   // Try to use shift instructions.
10146   if (SDValue Shift =
10147           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10148     return Shift;
10149
10150   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10151           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10152     return Rotate;
10153
10154   // If the shuffle patterns aren't repeated but it is a single input, directly
10155   // generate a cross-lane VPERMD instruction.
10156   if (isSingleInputShuffleMask(Mask)) {
10157     SDValue VPermMask[8];
10158     for (int i = 0; i < 8; ++i)
10159       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10160                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10161     return DAG.getNode(
10162         X86ISD::VPERMV, DL, MVT::v8i32,
10163         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10164   }
10165
10166   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10167   // shuffle.
10168   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10169           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10170     return Result;
10171
10172   // Otherwise fall back on generic blend lowering.
10173   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10174                                                     Mask, DAG);
10175 }
10176
10177 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10178 ///
10179 /// This routine is only called when we have AVX2 and thus a reasonable
10180 /// instruction set for v16i16 shuffling..
10181 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10182                                         const X86Subtarget *Subtarget,
10183                                         SelectionDAG &DAG) {
10184   SDLoc DL(Op);
10185   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10186   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10187   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10188   ArrayRef<int> Mask = SVOp->getMask();
10189   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10190   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10191
10192   // Whenever we can lower this as a zext, that instruction is strictly faster
10193   // than any alternative. It also allows us to fold memory operands into the
10194   // shuffle in many cases.
10195   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10196                                                          Mask, Subtarget, DAG))
10197     return ZExt;
10198
10199   // Check for being able to broadcast a single element.
10200   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10201                                                         Mask, Subtarget, DAG))
10202     return Broadcast;
10203
10204   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10205                                                 Subtarget, DAG))
10206     return Blend;
10207
10208   // Use dedicated unpack instructions for masks that match their pattern.
10209   if (isShuffleEquivalent(V1, V2, Mask,
10210                           {// First 128-bit lane:
10211                            0, 16, 1, 17, 2, 18, 3, 19,
10212                            // Second 128-bit lane:
10213                            8, 24, 9, 25, 10, 26, 11, 27}))
10214     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10215   if (isShuffleEquivalent(V1, V2, Mask,
10216                           {// First 128-bit lane:
10217                            4, 20, 5, 21, 6, 22, 7, 23,
10218                            // Second 128-bit lane:
10219                            12, 28, 13, 29, 14, 30, 15, 31}))
10220     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10221
10222   // Try to use shift instructions.
10223   if (SDValue Shift =
10224           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10225     return Shift;
10226
10227   // Try to use byte rotation instructions.
10228   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10229           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10230     return Rotate;
10231
10232   if (isSingleInputShuffleMask(Mask)) {
10233     // There are no generalized cross-lane shuffle operations available on i16
10234     // element types.
10235     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10236       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10237                                                      Mask, DAG);
10238
10239     SmallVector<int, 8> RepeatedMask;
10240     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10241       // As this is a single-input shuffle, the repeated mask should be
10242       // a strictly valid v8i16 mask that we can pass through to the v8i16
10243       // lowering to handle even the v16 case.
10244       return lowerV8I16GeneralSingleInputVectorShuffle(
10245           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10246     }
10247
10248     SDValue PSHUFBMask[32];
10249     for (int i = 0; i < 16; ++i) {
10250       if (Mask[i] == -1) {
10251         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10252         continue;
10253       }
10254
10255       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10256       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10257       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10258       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10259     }
10260     return DAG.getBitcast(MVT::v16i16,
10261                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10262                                       DAG.getBitcast(MVT::v32i8, V1),
10263                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10264                                                   MVT::v32i8, PSHUFBMask)));
10265   }
10266
10267   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10268   // shuffle.
10269   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10270           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10271     return Result;
10272
10273   // Otherwise fall back on generic lowering.
10274   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10275 }
10276
10277 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10278 ///
10279 /// This routine is only called when we have AVX2 and thus a reasonable
10280 /// instruction set for v32i8 shuffling..
10281 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10282                                        const X86Subtarget *Subtarget,
10283                                        SelectionDAG &DAG) {
10284   SDLoc DL(Op);
10285   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10286   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10287   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10288   ArrayRef<int> Mask = SVOp->getMask();
10289   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10290   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10291
10292   // Whenever we can lower this as a zext, that instruction is strictly faster
10293   // than any alternative. It also allows us to fold memory operands into the
10294   // shuffle in many cases.
10295   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10296                                                          Mask, Subtarget, DAG))
10297     return ZExt;
10298
10299   // Check for being able to broadcast a single element.
10300   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10301                                                         Mask, Subtarget, DAG))
10302     return Broadcast;
10303
10304   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10305                                                 Subtarget, DAG))
10306     return Blend;
10307
10308   // Use dedicated unpack instructions for masks that match their pattern.
10309   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10310   // 256-bit lanes.
10311   if (isShuffleEquivalent(
10312           V1, V2, Mask,
10313           {// First 128-bit lane:
10314            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10315            // Second 128-bit lane:
10316            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10317     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10318   if (isShuffleEquivalent(
10319           V1, V2, Mask,
10320           {// First 128-bit lane:
10321            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10322            // Second 128-bit lane:
10323            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10324     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10325
10326   // Try to use shift instructions.
10327   if (SDValue Shift =
10328           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10329     return Shift;
10330
10331   // Try to use byte rotation instructions.
10332   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10333           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10334     return Rotate;
10335
10336   if (isSingleInputShuffleMask(Mask)) {
10337     // There are no generalized cross-lane shuffle operations available on i8
10338     // element types.
10339     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10340       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10341                                                      Mask, DAG);
10342
10343     SDValue PSHUFBMask[32];
10344     for (int i = 0; i < 32; ++i)
10345       PSHUFBMask[i] =
10346           Mask[i] < 0
10347               ? DAG.getUNDEF(MVT::i8)
10348               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10349                                 MVT::i8);
10350
10351     return DAG.getNode(
10352         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10353         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10354   }
10355
10356   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10357   // shuffle.
10358   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10359           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10360     return Result;
10361
10362   // Otherwise fall back on generic lowering.
10363   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10364 }
10365
10366 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10367 ///
10368 /// This routine either breaks down the specific type of a 256-bit x86 vector
10369 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10370 /// together based on the available instructions.
10371 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10372                                         MVT VT, const X86Subtarget *Subtarget,
10373                                         SelectionDAG &DAG) {
10374   SDLoc DL(Op);
10375   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10376   ArrayRef<int> Mask = SVOp->getMask();
10377
10378   // If we have a single input to the zero element, insert that into V1 if we
10379   // can do so cheaply.
10380   int NumElts = VT.getVectorNumElements();
10381   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10382     return M >= NumElts;
10383   });
10384
10385   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10386     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10387                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10388       return Insertion;
10389
10390   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10391   // check for those subtargets here and avoid much of the subtarget querying in
10392   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10393   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10394   // floating point types there eventually, just immediately cast everything to
10395   // a float and operate entirely in that domain.
10396   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10397     int ElementBits = VT.getScalarSizeInBits();
10398     if (ElementBits < 32)
10399       // No floating point type available, decompose into 128-bit vectors.
10400       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10401
10402     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10403                                 VT.getVectorNumElements());
10404     V1 = DAG.getBitcast(FpVT, V1);
10405     V2 = DAG.getBitcast(FpVT, V2);
10406     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10407   }
10408
10409   switch (VT.SimpleTy) {
10410   case MVT::v4f64:
10411     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10412   case MVT::v4i64:
10413     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10414   case MVT::v8f32:
10415     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10416   case MVT::v8i32:
10417     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10418   case MVT::v16i16:
10419     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10420   case MVT::v32i8:
10421     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10422
10423   default:
10424     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10425   }
10426 }
10427
10428 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10429 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10430                                        const X86Subtarget *Subtarget,
10431                                        SelectionDAG &DAG) {
10432   SDLoc DL(Op);
10433   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10434   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10435   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10436   ArrayRef<int> Mask = SVOp->getMask();
10437   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10438
10439   // X86 has dedicated unpack instructions that can handle specific blend
10440   // operations: UNPCKH and UNPCKL.
10441   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10442     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10443   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10444     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10445
10446   // FIXME: Implement direct support for this type!
10447   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10448 }
10449
10450 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10451 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10452                                        const X86Subtarget *Subtarget,
10453                                        SelectionDAG &DAG) {
10454   SDLoc DL(Op);
10455   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10456   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10457   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10458   ArrayRef<int> Mask = SVOp->getMask();
10459   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10460
10461   // Use dedicated unpack instructions for masks that match their pattern.
10462   if (isShuffleEquivalent(V1, V2, Mask,
10463                           {// First 128-bit lane.
10464                            0, 16, 1, 17, 4, 20, 5, 21,
10465                            // Second 128-bit lane.
10466                            8, 24, 9, 25, 12, 28, 13, 29}))
10467     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10468   if (isShuffleEquivalent(V1, V2, Mask,
10469                           {// First 128-bit lane.
10470                            2, 18, 3, 19, 6, 22, 7, 23,
10471                            // Second 128-bit lane.
10472                            10, 26, 11, 27, 14, 30, 15, 31}))
10473     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10474
10475   // FIXME: Implement direct support for this type!
10476   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10477 }
10478
10479 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10480 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10481                                        const X86Subtarget *Subtarget,
10482                                        SelectionDAG &DAG) {
10483   SDLoc DL(Op);
10484   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10485   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10487   ArrayRef<int> Mask = SVOp->getMask();
10488   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10489
10490   // X86 has dedicated unpack instructions that can handle specific blend
10491   // operations: UNPCKH and UNPCKL.
10492   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10493     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10494   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10495     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10496
10497   // FIXME: Implement direct support for this type!
10498   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10499 }
10500
10501 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10502 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10503                                        const X86Subtarget *Subtarget,
10504                                        SelectionDAG &DAG) {
10505   SDLoc DL(Op);
10506   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10507   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10508   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10509   ArrayRef<int> Mask = SVOp->getMask();
10510   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10511
10512   // Use dedicated unpack instructions for masks that match their pattern.
10513   if (isShuffleEquivalent(V1, V2, Mask,
10514                           {// First 128-bit lane.
10515                            0, 16, 1, 17, 4, 20, 5, 21,
10516                            // Second 128-bit lane.
10517                            8, 24, 9, 25, 12, 28, 13, 29}))
10518     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10519   if (isShuffleEquivalent(V1, V2, Mask,
10520                           {// First 128-bit lane.
10521                            2, 18, 3, 19, 6, 22, 7, 23,
10522                            // Second 128-bit lane.
10523                            10, 26, 11, 27, 14, 30, 15, 31}))
10524     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10525
10526   // FIXME: Implement direct support for this type!
10527   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10528 }
10529
10530 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10531 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10532                                         const X86Subtarget *Subtarget,
10533                                         SelectionDAG &DAG) {
10534   SDLoc DL(Op);
10535   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10536   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10538   ArrayRef<int> Mask = SVOp->getMask();
10539   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10540   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10541
10542   // FIXME: Implement direct support for this type!
10543   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10544 }
10545
10546 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10547 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10548                                        const X86Subtarget *Subtarget,
10549                                        SelectionDAG &DAG) {
10550   SDLoc DL(Op);
10551   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10552   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10554   ArrayRef<int> Mask = SVOp->getMask();
10555   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10556   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10557
10558   // FIXME: Implement direct support for this type!
10559   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10560 }
10561
10562 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10563 ///
10564 /// This routine either breaks down the specific type of a 512-bit x86 vector
10565 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10566 /// together based on the available instructions.
10567 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10568                                         MVT VT, const X86Subtarget *Subtarget,
10569                                         SelectionDAG &DAG) {
10570   SDLoc DL(Op);
10571   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10572   ArrayRef<int> Mask = SVOp->getMask();
10573   assert(Subtarget->hasAVX512() &&
10574          "Cannot lower 512-bit vectors w/ basic ISA!");
10575
10576   // Check for being able to broadcast a single element.
10577   if (SDValue Broadcast =
10578           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10579     return Broadcast;
10580
10581   // Dispatch to each element type for lowering. If we don't have supprot for
10582   // specific element type shuffles at 512 bits, immediately split them and
10583   // lower them. Each lowering routine of a given type is allowed to assume that
10584   // the requisite ISA extensions for that element type are available.
10585   switch (VT.SimpleTy) {
10586   case MVT::v8f64:
10587     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10588   case MVT::v16f32:
10589     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10590   case MVT::v8i64:
10591     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10592   case MVT::v16i32:
10593     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10594   case MVT::v32i16:
10595     if (Subtarget->hasBWI())
10596       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10597     break;
10598   case MVT::v64i8:
10599     if (Subtarget->hasBWI())
10600       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10601     break;
10602
10603   default:
10604     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10605   }
10606
10607   // Otherwise fall back on splitting.
10608   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10609 }
10610
10611 /// \brief Top-level lowering for x86 vector shuffles.
10612 ///
10613 /// This handles decomposition, canonicalization, and lowering of all x86
10614 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10615 /// above in helper routines. The canonicalization attempts to widen shuffles
10616 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10617 /// s.t. only one of the two inputs needs to be tested, etc.
10618 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10619                                   SelectionDAG &DAG) {
10620   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10621   ArrayRef<int> Mask = SVOp->getMask();
10622   SDValue V1 = Op.getOperand(0);
10623   SDValue V2 = Op.getOperand(1);
10624   MVT VT = Op.getSimpleValueType();
10625   int NumElements = VT.getVectorNumElements();
10626   SDLoc dl(Op);
10627
10628   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10629
10630   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10631   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10632   if (V1IsUndef && V2IsUndef)
10633     return DAG.getUNDEF(VT);
10634
10635   // When we create a shuffle node we put the UNDEF node to second operand,
10636   // but in some cases the first operand may be transformed to UNDEF.
10637   // In this case we should just commute the node.
10638   if (V1IsUndef)
10639     return DAG.getCommutedVectorShuffle(*SVOp);
10640
10641   // Check for non-undef masks pointing at an undef vector and make the masks
10642   // undef as well. This makes it easier to match the shuffle based solely on
10643   // the mask.
10644   if (V2IsUndef)
10645     for (int M : Mask)
10646       if (M >= NumElements) {
10647         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10648         for (int &M : NewMask)
10649           if (M >= NumElements)
10650             M = -1;
10651         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10652       }
10653
10654   // We actually see shuffles that are entirely re-arrangements of a set of
10655   // zero inputs. This mostly happens while decomposing complex shuffles into
10656   // simple ones. Directly lower these as a buildvector of zeros.
10657   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10658   if (Zeroable.all())
10659     return getZeroVector(VT, Subtarget, DAG, dl);
10660
10661   // Try to collapse shuffles into using a vector type with fewer elements but
10662   // wider element types. We cap this to not form integers or floating point
10663   // elements wider than 64 bits, but it might be interesting to form i128
10664   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10665   SmallVector<int, 16> WidenedMask;
10666   if (VT.getScalarSizeInBits() < 64 &&
10667       canWidenShuffleElements(Mask, WidenedMask)) {
10668     MVT NewEltVT = VT.isFloatingPoint()
10669                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10670                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10671     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10672     // Make sure that the new vector type is legal. For example, v2f64 isn't
10673     // legal on SSE1.
10674     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10675       V1 = DAG.getBitcast(NewVT, V1);
10676       V2 = DAG.getBitcast(NewVT, V2);
10677       return DAG.getBitcast(
10678           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10679     }
10680   }
10681
10682   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10683   for (int M : SVOp->getMask())
10684     if (M < 0)
10685       ++NumUndefElements;
10686     else if (M < NumElements)
10687       ++NumV1Elements;
10688     else
10689       ++NumV2Elements;
10690
10691   // Commute the shuffle as needed such that more elements come from V1 than
10692   // V2. This allows us to match the shuffle pattern strictly on how many
10693   // elements come from V1 without handling the symmetric cases.
10694   if (NumV2Elements > NumV1Elements)
10695     return DAG.getCommutedVectorShuffle(*SVOp);
10696
10697   // When the number of V1 and V2 elements are the same, try to minimize the
10698   // number of uses of V2 in the low half of the vector. When that is tied,
10699   // ensure that the sum of indices for V1 is equal to or lower than the sum
10700   // indices for V2. When those are equal, try to ensure that the number of odd
10701   // indices for V1 is lower than the number of odd indices for V2.
10702   if (NumV1Elements == NumV2Elements) {
10703     int LowV1Elements = 0, LowV2Elements = 0;
10704     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10705       if (M >= NumElements)
10706         ++LowV2Elements;
10707       else if (M >= 0)
10708         ++LowV1Elements;
10709     if (LowV2Elements > LowV1Elements) {
10710       return DAG.getCommutedVectorShuffle(*SVOp);
10711     } else if (LowV2Elements == LowV1Elements) {
10712       int SumV1Indices = 0, SumV2Indices = 0;
10713       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10714         if (SVOp->getMask()[i] >= NumElements)
10715           SumV2Indices += i;
10716         else if (SVOp->getMask()[i] >= 0)
10717           SumV1Indices += i;
10718       if (SumV2Indices < SumV1Indices) {
10719         return DAG.getCommutedVectorShuffle(*SVOp);
10720       } else if (SumV2Indices == SumV1Indices) {
10721         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10722         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10723           if (SVOp->getMask()[i] >= NumElements)
10724             NumV2OddIndices += i % 2;
10725           else if (SVOp->getMask()[i] >= 0)
10726             NumV1OddIndices += i % 2;
10727         if (NumV2OddIndices < NumV1OddIndices)
10728           return DAG.getCommutedVectorShuffle(*SVOp);
10729       }
10730     }
10731   }
10732
10733   // For each vector width, delegate to a specialized lowering routine.
10734   if (VT.getSizeInBits() == 128)
10735     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10736
10737   if (VT.getSizeInBits() == 256)
10738     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10739
10740   // Force AVX-512 vectors to be scalarized for now.
10741   // FIXME: Implement AVX-512 support!
10742   if (VT.getSizeInBits() == 512)
10743     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10744
10745   llvm_unreachable("Unimplemented!");
10746 }
10747
10748 // This function assumes its argument is a BUILD_VECTOR of constants or
10749 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10750 // true.
10751 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10752                                     unsigned &MaskValue) {
10753   MaskValue = 0;
10754   unsigned NumElems = BuildVector->getNumOperands();
10755   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10756   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10757   unsigned NumElemsInLane = NumElems / NumLanes;
10758
10759   // Blend for v16i16 should be symmetric for the both lanes.
10760   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10761     SDValue EltCond = BuildVector->getOperand(i);
10762     SDValue SndLaneEltCond =
10763         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10764
10765     int Lane1Cond = -1, Lane2Cond = -1;
10766     if (isa<ConstantSDNode>(EltCond))
10767       Lane1Cond = !isZero(EltCond);
10768     if (isa<ConstantSDNode>(SndLaneEltCond))
10769       Lane2Cond = !isZero(SndLaneEltCond);
10770
10771     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10772       // Lane1Cond != 0, means we want the first argument.
10773       // Lane1Cond == 0, means we want the second argument.
10774       // The encoding of this argument is 0 for the first argument, 1
10775       // for the second. Therefore, invert the condition.
10776       MaskValue |= !Lane1Cond << i;
10777     else if (Lane1Cond < 0)
10778       MaskValue |= !Lane2Cond << i;
10779     else
10780       return false;
10781   }
10782   return true;
10783 }
10784
10785 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10786 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10787                                            const X86Subtarget *Subtarget,
10788                                            SelectionDAG &DAG) {
10789   SDValue Cond = Op.getOperand(0);
10790   SDValue LHS = Op.getOperand(1);
10791   SDValue RHS = Op.getOperand(2);
10792   SDLoc dl(Op);
10793   MVT VT = Op.getSimpleValueType();
10794
10795   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10796     return SDValue();
10797   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10798
10799   // Only non-legal VSELECTs reach this lowering, convert those into generic
10800   // shuffles and re-use the shuffle lowering path for blends.
10801   SmallVector<int, 32> Mask;
10802   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10803     SDValue CondElt = CondBV->getOperand(i);
10804     Mask.push_back(
10805         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10806   }
10807   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10808 }
10809
10810 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10811   // A vselect where all conditions and data are constants can be optimized into
10812   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10813   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10814       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10815       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10816     return SDValue();
10817
10818   // Try to lower this to a blend-style vector shuffle. This can handle all
10819   // constant condition cases.
10820   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10821     return BlendOp;
10822
10823   // Variable blends are only legal from SSE4.1 onward.
10824   if (!Subtarget->hasSSE41())
10825     return SDValue();
10826
10827   // Only some types will be legal on some subtargets. If we can emit a legal
10828   // VSELECT-matching blend, return Op, and but if we need to expand, return
10829   // a null value.
10830   switch (Op.getSimpleValueType().SimpleTy) {
10831   default:
10832     // Most of the vector types have blends past SSE4.1.
10833     return Op;
10834
10835   case MVT::v32i8:
10836     // The byte blends for AVX vectors were introduced only in AVX2.
10837     if (Subtarget->hasAVX2())
10838       return Op;
10839
10840     return SDValue();
10841
10842   case MVT::v8i16:
10843   case MVT::v16i16:
10844     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10845     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10846       return Op;
10847
10848     // FIXME: We should custom lower this by fixing the condition and using i8
10849     // blends.
10850     return SDValue();
10851   }
10852 }
10853
10854 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10855   MVT VT = Op.getSimpleValueType();
10856   SDLoc dl(Op);
10857
10858   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10859     return SDValue();
10860
10861   if (VT.getSizeInBits() == 8) {
10862     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10863                                   Op.getOperand(0), Op.getOperand(1));
10864     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10865                                   DAG.getValueType(VT));
10866     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10867   }
10868
10869   if (VT.getSizeInBits() == 16) {
10870     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10871     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10872     if (Idx == 0)
10873       return DAG.getNode(
10874           ISD::TRUNCATE, dl, MVT::i16,
10875           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10876                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10877                       Op.getOperand(1)));
10878     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10879                                   Op.getOperand(0), Op.getOperand(1));
10880     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10881                                   DAG.getValueType(VT));
10882     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10883   }
10884
10885   if (VT == MVT::f32) {
10886     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10887     // the result back to FR32 register. It's only worth matching if the
10888     // result has a single use which is a store or a bitcast to i32.  And in
10889     // the case of a store, it's not worth it if the index is a constant 0,
10890     // because a MOVSSmr can be used instead, which is smaller and faster.
10891     if (!Op.hasOneUse())
10892       return SDValue();
10893     SDNode *User = *Op.getNode()->use_begin();
10894     if ((User->getOpcode() != ISD::STORE ||
10895          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10896           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10897         (User->getOpcode() != ISD::BITCAST ||
10898          User->getValueType(0) != MVT::i32))
10899       return SDValue();
10900     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10901                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10902                                   Op.getOperand(1));
10903     return DAG.getBitcast(MVT::f32, Extract);
10904   }
10905
10906   if (VT == MVT::i32 || VT == MVT::i64) {
10907     // ExtractPS/pextrq works with constant index.
10908     if (isa<ConstantSDNode>(Op.getOperand(1)))
10909       return Op;
10910   }
10911   return SDValue();
10912 }
10913
10914 /// Extract one bit from mask vector, like v16i1 or v8i1.
10915 /// AVX-512 feature.
10916 SDValue
10917 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10918   SDValue Vec = Op.getOperand(0);
10919   SDLoc dl(Vec);
10920   MVT VecVT = Vec.getSimpleValueType();
10921   SDValue Idx = Op.getOperand(1);
10922   MVT EltVT = Op.getSimpleValueType();
10923
10924   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10925   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10926          "Unexpected vector type in ExtractBitFromMaskVector");
10927
10928   // variable index can't be handled in mask registers,
10929   // extend vector to VR512
10930   if (!isa<ConstantSDNode>(Idx)) {
10931     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10932     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10933     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10934                               ExtVT.getVectorElementType(), Ext, Idx);
10935     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10936   }
10937
10938   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10939   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10940   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10941     rc = getRegClassFor(MVT::v16i1);
10942   unsigned MaxSift = rc->getSize()*8 - 1;
10943   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10944                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10945   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10946                     DAG.getConstant(MaxSift, dl, MVT::i8));
10947   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10948                        DAG.getIntPtrConstant(0, dl));
10949 }
10950
10951 SDValue
10952 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10953                                            SelectionDAG &DAG) const {
10954   SDLoc dl(Op);
10955   SDValue Vec = Op.getOperand(0);
10956   MVT VecVT = Vec.getSimpleValueType();
10957   SDValue Idx = Op.getOperand(1);
10958
10959   if (Op.getSimpleValueType() == MVT::i1)
10960     return ExtractBitFromMaskVector(Op, DAG);
10961
10962   if (!isa<ConstantSDNode>(Idx)) {
10963     if (VecVT.is512BitVector() ||
10964         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10965          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10966
10967       MVT MaskEltVT =
10968         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10969       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10970                                     MaskEltVT.getSizeInBits());
10971
10972       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10973       auto PtrVT = getPointerTy(DAG.getDataLayout());
10974       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10975                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10976                                  DAG.getConstant(0, dl, PtrVT));
10977       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10978       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10979                          DAG.getConstant(0, dl, PtrVT));
10980     }
10981     return SDValue();
10982   }
10983
10984   // If this is a 256-bit vector result, first extract the 128-bit vector and
10985   // then extract the element from the 128-bit vector.
10986   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10987
10988     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10989     // Get the 128-bit vector.
10990     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10991     MVT EltVT = VecVT.getVectorElementType();
10992
10993     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10994
10995     //if (IdxVal >= NumElems/2)
10996     //  IdxVal -= NumElems/2;
10997     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10998     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10999                        DAG.getConstant(IdxVal, dl, MVT::i32));
11000   }
11001
11002   assert(VecVT.is128BitVector() && "Unexpected vector length");
11003
11004   if (Subtarget->hasSSE41())
11005     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11006       return Res;
11007
11008   MVT VT = Op.getSimpleValueType();
11009   // TODO: handle v16i8.
11010   if (VT.getSizeInBits() == 16) {
11011     SDValue Vec = Op.getOperand(0);
11012     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11013     if (Idx == 0)
11014       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11015                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11016                                      DAG.getBitcast(MVT::v4i32, Vec),
11017                                      Op.getOperand(1)));
11018     // Transform it so it match pextrw which produces a 32-bit result.
11019     MVT EltVT = MVT::i32;
11020     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11021                                   Op.getOperand(0), Op.getOperand(1));
11022     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11023                                   DAG.getValueType(VT));
11024     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11025   }
11026
11027   if (VT.getSizeInBits() == 32) {
11028     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11029     if (Idx == 0)
11030       return Op;
11031
11032     // SHUFPS the element to the lowest double word, then movss.
11033     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11034     MVT VVT = Op.getOperand(0).getSimpleValueType();
11035     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11036                                        DAG.getUNDEF(VVT), Mask);
11037     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11038                        DAG.getIntPtrConstant(0, dl));
11039   }
11040
11041   if (VT.getSizeInBits() == 64) {
11042     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11043     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11044     //        to match extract_elt for f64.
11045     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11046     if (Idx == 0)
11047       return Op;
11048
11049     // UNPCKHPD the element to the lowest double word, then movsd.
11050     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11051     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11052     int Mask[2] = { 1, -1 };
11053     MVT VVT = Op.getOperand(0).getSimpleValueType();
11054     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11055                                        DAG.getUNDEF(VVT), Mask);
11056     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11057                        DAG.getIntPtrConstant(0, dl));
11058   }
11059
11060   return SDValue();
11061 }
11062
11063 /// Insert one bit to mask vector, like v16i1 or v8i1.
11064 /// AVX-512 feature.
11065 SDValue
11066 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11067   SDLoc dl(Op);
11068   SDValue Vec = Op.getOperand(0);
11069   SDValue Elt = Op.getOperand(1);
11070   SDValue Idx = Op.getOperand(2);
11071   MVT VecVT = Vec.getSimpleValueType();
11072
11073   if (!isa<ConstantSDNode>(Idx)) {
11074     // Non constant index. Extend source and destination,
11075     // insert element and then truncate the result.
11076     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11077     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11078     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11079       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11080       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11081     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11082   }
11083
11084   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11085   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11086   if (IdxVal)
11087     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11088                            DAG.getConstant(IdxVal, dl, MVT::i8));
11089   if (Vec.getOpcode() == ISD::UNDEF)
11090     return EltInVec;
11091   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11092 }
11093
11094 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11095                                                   SelectionDAG &DAG) const {
11096   MVT VT = Op.getSimpleValueType();
11097   MVT EltVT = VT.getVectorElementType();
11098
11099   if (EltVT == MVT::i1)
11100     return InsertBitToMaskVector(Op, DAG);
11101
11102   SDLoc dl(Op);
11103   SDValue N0 = Op.getOperand(0);
11104   SDValue N1 = Op.getOperand(1);
11105   SDValue N2 = Op.getOperand(2);
11106   if (!isa<ConstantSDNode>(N2))
11107     return SDValue();
11108   auto *N2C = cast<ConstantSDNode>(N2);
11109   unsigned IdxVal = N2C->getZExtValue();
11110
11111   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11112   // into that, and then insert the subvector back into the result.
11113   if (VT.is256BitVector() || VT.is512BitVector()) {
11114     // With a 256-bit vector, we can insert into the zero element efficiently
11115     // using a blend if we have AVX or AVX2 and the right data type.
11116     if (VT.is256BitVector() && IdxVal == 0) {
11117       // TODO: It is worthwhile to cast integer to floating point and back
11118       // and incur a domain crossing penalty if that's what we'll end up
11119       // doing anyway after extracting to a 128-bit vector.
11120       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11121           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11122         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11123         N2 = DAG.getIntPtrConstant(1, dl);
11124         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11125       }
11126     }
11127
11128     // Get the desired 128-bit vector chunk.
11129     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11130
11131     // Insert the element into the desired chunk.
11132     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11133     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11134
11135     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11136                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11137
11138     // Insert the changed part back into the bigger vector
11139     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11140   }
11141   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11142
11143   if (Subtarget->hasSSE41()) {
11144     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11145       unsigned Opc;
11146       if (VT == MVT::v8i16) {
11147         Opc = X86ISD::PINSRW;
11148       } else {
11149         assert(VT == MVT::v16i8);
11150         Opc = X86ISD::PINSRB;
11151       }
11152
11153       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11154       // argument.
11155       if (N1.getValueType() != MVT::i32)
11156         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11157       if (N2.getValueType() != MVT::i32)
11158         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11159       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11160     }
11161
11162     if (EltVT == MVT::f32) {
11163       // Bits [7:6] of the constant are the source select. This will always be
11164       //   zero here. The DAG Combiner may combine an extract_elt index into
11165       //   these bits. For example (insert (extract, 3), 2) could be matched by
11166       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11167       // Bits [5:4] of the constant are the destination select. This is the
11168       //   value of the incoming immediate.
11169       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11170       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11171
11172       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11173       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11174         // If this is an insertion of 32-bits into the low 32-bits of
11175         // a vector, we prefer to generate a blend with immediate rather
11176         // than an insertps. Blends are simpler operations in hardware and so
11177         // will always have equal or better performance than insertps.
11178         // But if optimizing for size and there's a load folding opportunity,
11179         // generate insertps because blendps does not have a 32-bit memory
11180         // operand form.
11181         N2 = DAG.getIntPtrConstant(1, dl);
11182         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11183         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11184       }
11185       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11186       // Create this as a scalar to vector..
11187       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11188       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11189     }
11190
11191     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11192       // PINSR* works with constant index.
11193       return Op;
11194     }
11195   }
11196
11197   if (EltVT == MVT::i8)
11198     return SDValue();
11199
11200   if (EltVT.getSizeInBits() == 16) {
11201     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11202     // as its second argument.
11203     if (N1.getValueType() != MVT::i32)
11204       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11205     if (N2.getValueType() != MVT::i32)
11206       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11207     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11208   }
11209   return SDValue();
11210 }
11211
11212 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11213   SDLoc dl(Op);
11214   MVT OpVT = Op.getSimpleValueType();
11215
11216   // If this is a 256-bit vector result, first insert into a 128-bit
11217   // vector and then insert into the 256-bit vector.
11218   if (!OpVT.is128BitVector()) {
11219     // Insert into a 128-bit vector.
11220     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11221     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11222                                  OpVT.getVectorNumElements() / SizeFactor);
11223
11224     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11225
11226     // Insert the 128-bit vector.
11227     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11228   }
11229
11230   if (OpVT == MVT::v1i64 &&
11231       Op.getOperand(0).getValueType() == MVT::i64)
11232     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11233
11234   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11235   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11236   return DAG.getBitcast(
11237       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11238 }
11239
11240 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11241 // a simple subregister reference or explicit instructions to grab
11242 // upper bits of a vector.
11243 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11244                                       SelectionDAG &DAG) {
11245   SDLoc dl(Op);
11246   SDValue In =  Op.getOperand(0);
11247   SDValue Idx = Op.getOperand(1);
11248   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11249   MVT ResVT   = Op.getSimpleValueType();
11250   MVT InVT    = In.getSimpleValueType();
11251
11252   if (Subtarget->hasFp256()) {
11253     if (ResVT.is128BitVector() &&
11254         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11255         isa<ConstantSDNode>(Idx)) {
11256       return Extract128BitVector(In, IdxVal, DAG, dl);
11257     }
11258     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11259         isa<ConstantSDNode>(Idx)) {
11260       return Extract256BitVector(In, IdxVal, DAG, dl);
11261     }
11262   }
11263   return SDValue();
11264 }
11265
11266 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11267 // simple superregister reference or explicit instructions to insert
11268 // the upper bits of a vector.
11269 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11270                                      SelectionDAG &DAG) {
11271   if (!Subtarget->hasAVX())
11272     return SDValue();
11273
11274   SDLoc dl(Op);
11275   SDValue Vec = Op.getOperand(0);
11276   SDValue SubVec = Op.getOperand(1);
11277   SDValue Idx = Op.getOperand(2);
11278
11279   if (!isa<ConstantSDNode>(Idx))
11280     return SDValue();
11281
11282   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11283   MVT OpVT = Op.getSimpleValueType();
11284   MVT SubVecVT = SubVec.getSimpleValueType();
11285
11286   // Fold two 16-byte subvector loads into one 32-byte load:
11287   // (insert_subvector (insert_subvector undef, (load addr), 0),
11288   //                   (load addr + 16), Elts/2)
11289   // --> load32 addr
11290   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11291       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11292       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11293     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11294     if (Idx2 && Idx2->getZExtValue() == 0) {
11295       SDValue SubVec2 = Vec.getOperand(1);
11296       // If needed, look through a bitcast to get to the load.
11297       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11298         SubVec2 = SubVec2.getOperand(0);
11299       
11300       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11301         bool Fast;
11302         unsigned Alignment = FirstLd->getAlignment();
11303         unsigned AS = FirstLd->getAddressSpace();
11304         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11305         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11306                                     OpVT, AS, Alignment, &Fast) && Fast) {
11307           SDValue Ops[] = { SubVec2, SubVec };
11308           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11309             return Ld;
11310         }
11311       }
11312     }
11313   }
11314
11315   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11316       SubVecVT.is128BitVector())
11317     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11318
11319   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11320     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11321
11322   if (OpVT.getVectorElementType() == MVT::i1) {
11323     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11324       return Op;
11325     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11326     SDValue Undef = DAG.getUNDEF(OpVT);
11327     unsigned NumElems = OpVT.getVectorNumElements();
11328     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11329
11330     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11331       // Zero upper bits of the Vec
11332       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11333       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11334
11335       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11336                                  SubVec, ZeroIdx);
11337       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11338       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11339     }
11340     if (IdxVal == 0) {
11341       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11342                                  SubVec, ZeroIdx);
11343       // Zero upper bits of the Vec2
11344       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11345       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11346       // Zero lower bits of the Vec
11347       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11348       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11349       // Merge them together
11350       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11351     }
11352   }
11353   return SDValue();
11354 }
11355
11356 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11357 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11358 // one of the above mentioned nodes. It has to be wrapped because otherwise
11359 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11360 // be used to form addressing mode. These wrapped nodes will be selected
11361 // into MOV32ri.
11362 SDValue
11363 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11364   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11365
11366   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11367   // global base reg.
11368   unsigned char OpFlag = 0;
11369   unsigned WrapperKind = X86ISD::Wrapper;
11370   CodeModel::Model M = DAG.getTarget().getCodeModel();
11371
11372   if (Subtarget->isPICStyleRIPRel() &&
11373       (M == CodeModel::Small || M == CodeModel::Kernel))
11374     WrapperKind = X86ISD::WrapperRIP;
11375   else if (Subtarget->isPICStyleGOT())
11376     OpFlag = X86II::MO_GOTOFF;
11377   else if (Subtarget->isPICStyleStubPIC())
11378     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11379
11380   auto PtrVT = getPointerTy(DAG.getDataLayout());
11381   SDValue Result = DAG.getTargetConstantPool(
11382       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11383   SDLoc DL(CP);
11384   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11385   // With PIC, the address is actually $g + Offset.
11386   if (OpFlag) {
11387     Result =
11388         DAG.getNode(ISD::ADD, DL, PtrVT,
11389                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11390   }
11391
11392   return Result;
11393 }
11394
11395 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11396   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11397
11398   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11399   // global base reg.
11400   unsigned char OpFlag = 0;
11401   unsigned WrapperKind = X86ISD::Wrapper;
11402   CodeModel::Model M = DAG.getTarget().getCodeModel();
11403
11404   if (Subtarget->isPICStyleRIPRel() &&
11405       (M == CodeModel::Small || M == CodeModel::Kernel))
11406     WrapperKind = X86ISD::WrapperRIP;
11407   else if (Subtarget->isPICStyleGOT())
11408     OpFlag = X86II::MO_GOTOFF;
11409   else if (Subtarget->isPICStyleStubPIC())
11410     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11411
11412   auto PtrVT = getPointerTy(DAG.getDataLayout());
11413   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11414   SDLoc DL(JT);
11415   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11416
11417   // With PIC, the address is actually $g + Offset.
11418   if (OpFlag)
11419     Result =
11420         DAG.getNode(ISD::ADD, DL, PtrVT,
11421                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11422
11423   return Result;
11424 }
11425
11426 SDValue
11427 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11428   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11429
11430   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11431   // global base reg.
11432   unsigned char OpFlag = 0;
11433   unsigned WrapperKind = X86ISD::Wrapper;
11434   CodeModel::Model M = DAG.getTarget().getCodeModel();
11435
11436   if (Subtarget->isPICStyleRIPRel() &&
11437       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11438     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11439       OpFlag = X86II::MO_GOTPCREL;
11440     WrapperKind = X86ISD::WrapperRIP;
11441   } else if (Subtarget->isPICStyleGOT()) {
11442     OpFlag = X86II::MO_GOT;
11443   } else if (Subtarget->isPICStyleStubPIC()) {
11444     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11445   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11446     OpFlag = X86II::MO_DARWIN_NONLAZY;
11447   }
11448
11449   auto PtrVT = getPointerTy(DAG.getDataLayout());
11450   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11451
11452   SDLoc DL(Op);
11453   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11454
11455   // With PIC, the address is actually $g + Offset.
11456   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11457       !Subtarget->is64Bit()) {
11458     Result =
11459         DAG.getNode(ISD::ADD, DL, PtrVT,
11460                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11461   }
11462
11463   // For symbols that require a load from a stub to get the address, emit the
11464   // load.
11465   if (isGlobalStubReference(OpFlag))
11466     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11467                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11468                          false, false, false, 0);
11469
11470   return Result;
11471 }
11472
11473 SDValue
11474 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11475   // Create the TargetBlockAddressAddress node.
11476   unsigned char OpFlags =
11477     Subtarget->ClassifyBlockAddressReference();
11478   CodeModel::Model M = DAG.getTarget().getCodeModel();
11479   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11480   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11481   SDLoc dl(Op);
11482   auto PtrVT = getPointerTy(DAG.getDataLayout());
11483   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11484
11485   if (Subtarget->isPICStyleRIPRel() &&
11486       (M == CodeModel::Small || M == CodeModel::Kernel))
11487     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11488   else
11489     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11490
11491   // With PIC, the address is actually $g + Offset.
11492   if (isGlobalRelativeToPICBase(OpFlags)) {
11493     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11494                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11495   }
11496
11497   return Result;
11498 }
11499
11500 SDValue
11501 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11502                                       int64_t Offset, SelectionDAG &DAG) const {
11503   // Create the TargetGlobalAddress node, folding in the constant
11504   // offset if it is legal.
11505   unsigned char OpFlags =
11506       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11507   CodeModel::Model M = DAG.getTarget().getCodeModel();
11508   auto PtrVT = getPointerTy(DAG.getDataLayout());
11509   SDValue Result;
11510   if (OpFlags == X86II::MO_NO_FLAG &&
11511       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11512     // A direct static reference to a global.
11513     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11514     Offset = 0;
11515   } else {
11516     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11517   }
11518
11519   if (Subtarget->isPICStyleRIPRel() &&
11520       (M == CodeModel::Small || M == CodeModel::Kernel))
11521     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11522   else
11523     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11524
11525   // With PIC, the address is actually $g + Offset.
11526   if (isGlobalRelativeToPICBase(OpFlags)) {
11527     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11528                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11529   }
11530
11531   // For globals that require a load from a stub to get the address, emit the
11532   // load.
11533   if (isGlobalStubReference(OpFlags))
11534     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11535                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11536                          false, false, false, 0);
11537
11538   // If there was a non-zero offset that we didn't fold, create an explicit
11539   // addition for it.
11540   if (Offset != 0)
11541     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11542                          DAG.getConstant(Offset, dl, PtrVT));
11543
11544   return Result;
11545 }
11546
11547 SDValue
11548 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11549   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11550   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11551   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11552 }
11553
11554 static SDValue
11555 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11556            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11557            unsigned char OperandFlags, bool LocalDynamic = false) {
11558   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11559   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11560   SDLoc dl(GA);
11561   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11562                                            GA->getValueType(0),
11563                                            GA->getOffset(),
11564                                            OperandFlags);
11565
11566   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11567                                            : X86ISD::TLSADDR;
11568
11569   if (InFlag) {
11570     SDValue Ops[] = { Chain,  TGA, *InFlag };
11571     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11572   } else {
11573     SDValue Ops[]  = { Chain, TGA };
11574     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11575   }
11576
11577   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11578   MFI->setAdjustsStack(true);
11579   MFI->setHasCalls(true);
11580
11581   SDValue Flag = Chain.getValue(1);
11582   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11583 }
11584
11585 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11586 static SDValue
11587 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11588                                 const EVT PtrVT) {
11589   SDValue InFlag;
11590   SDLoc dl(GA);  // ? function entry point might be better
11591   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11592                                    DAG.getNode(X86ISD::GlobalBaseReg,
11593                                                SDLoc(), PtrVT), InFlag);
11594   InFlag = Chain.getValue(1);
11595
11596   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11597 }
11598
11599 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11600 static SDValue
11601 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11602                                 const EVT PtrVT) {
11603   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11604                     X86::RAX, X86II::MO_TLSGD);
11605 }
11606
11607 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11608                                            SelectionDAG &DAG,
11609                                            const EVT PtrVT,
11610                                            bool is64Bit) {
11611   SDLoc dl(GA);
11612
11613   // Get the start address of the TLS block for this module.
11614   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11615       .getInfo<X86MachineFunctionInfo>();
11616   MFI->incNumLocalDynamicTLSAccesses();
11617
11618   SDValue Base;
11619   if (is64Bit) {
11620     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11621                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11622   } else {
11623     SDValue InFlag;
11624     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11625         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11626     InFlag = Chain.getValue(1);
11627     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11628                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11629   }
11630
11631   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11632   // of Base.
11633
11634   // Build x@dtpoff.
11635   unsigned char OperandFlags = X86II::MO_DTPOFF;
11636   unsigned WrapperKind = X86ISD::Wrapper;
11637   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11638                                            GA->getValueType(0),
11639                                            GA->getOffset(), OperandFlags);
11640   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11641
11642   // Add x@dtpoff with the base.
11643   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11644 }
11645
11646 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11647 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11648                                    const EVT PtrVT, TLSModel::Model model,
11649                                    bool is64Bit, bool isPIC) {
11650   SDLoc dl(GA);
11651
11652   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11653   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11654                                                          is64Bit ? 257 : 256));
11655
11656   SDValue ThreadPointer =
11657       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11658                   MachinePointerInfo(Ptr), false, false, false, 0);
11659
11660   unsigned char OperandFlags = 0;
11661   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11662   // initialexec.
11663   unsigned WrapperKind = X86ISD::Wrapper;
11664   if (model == TLSModel::LocalExec) {
11665     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11666   } else if (model == TLSModel::InitialExec) {
11667     if (is64Bit) {
11668       OperandFlags = X86II::MO_GOTTPOFF;
11669       WrapperKind = X86ISD::WrapperRIP;
11670     } else {
11671       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11672     }
11673   } else {
11674     llvm_unreachable("Unexpected model");
11675   }
11676
11677   // emit "addl x@ntpoff,%eax" (local exec)
11678   // or "addl x@indntpoff,%eax" (initial exec)
11679   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11680   SDValue TGA =
11681       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11682                                  GA->getOffset(), OperandFlags);
11683   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11684
11685   if (model == TLSModel::InitialExec) {
11686     if (isPIC && !is64Bit) {
11687       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11688                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11689                            Offset);
11690     }
11691
11692     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11693                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11694                          false, false, false, 0);
11695   }
11696
11697   // The address of the thread local variable is the add of the thread
11698   // pointer with the offset of the variable.
11699   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11700 }
11701
11702 SDValue
11703 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11704
11705   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11706   const GlobalValue *GV = GA->getGlobal();
11707   auto PtrVT = getPointerTy(DAG.getDataLayout());
11708
11709   if (Subtarget->isTargetELF()) {
11710     if (DAG.getTarget().Options.EmulatedTLS)
11711       return LowerToTLSEmulatedModel(GA, DAG);
11712     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11713     switch (model) {
11714       case TLSModel::GeneralDynamic:
11715         if (Subtarget->is64Bit())
11716           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11717         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11718       case TLSModel::LocalDynamic:
11719         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11720                                            Subtarget->is64Bit());
11721       case TLSModel::InitialExec:
11722       case TLSModel::LocalExec:
11723         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11724                                    DAG.getTarget().getRelocationModel() ==
11725                                        Reloc::PIC_);
11726     }
11727     llvm_unreachable("Unknown TLS model.");
11728   }
11729
11730   if (Subtarget->isTargetDarwin()) {
11731     // Darwin only has one model of TLS.  Lower to that.
11732     unsigned char OpFlag = 0;
11733     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11734                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11735
11736     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11737     // global base reg.
11738     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11739                  !Subtarget->is64Bit();
11740     if (PIC32)
11741       OpFlag = X86II::MO_TLVP_PIC_BASE;
11742     else
11743       OpFlag = X86II::MO_TLVP;
11744     SDLoc DL(Op);
11745     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11746                                                 GA->getValueType(0),
11747                                                 GA->getOffset(), OpFlag);
11748     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11749
11750     // With PIC32, the address is actually $g + Offset.
11751     if (PIC32)
11752       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11753                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11754                            Offset);
11755
11756     // Lowering the machine isd will make sure everything is in the right
11757     // location.
11758     SDValue Chain = DAG.getEntryNode();
11759     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11760     SDValue Args[] = { Chain, Offset };
11761     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11762
11763     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11764     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11765     MFI->setAdjustsStack(true);
11766
11767     // And our return value (tls address) is in the standard call return value
11768     // location.
11769     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11770     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11771   }
11772
11773   if (Subtarget->isTargetKnownWindowsMSVC() ||
11774       Subtarget->isTargetWindowsGNU()) {
11775     // Just use the implicit TLS architecture
11776     // Need to generate someting similar to:
11777     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11778     //                                  ; from TEB
11779     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11780     //   mov     rcx, qword [rdx+rcx*8]
11781     //   mov     eax, .tls$:tlsvar
11782     //   [rax+rcx] contains the address
11783     // Windows 64bit: gs:0x58
11784     // Windows 32bit: fs:__tls_array
11785
11786     SDLoc dl(GA);
11787     SDValue Chain = DAG.getEntryNode();
11788
11789     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11790     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11791     // use its literal value of 0x2C.
11792     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11793                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11794                                                              256)
11795                                         : Type::getInt32PtrTy(*DAG.getContext(),
11796                                                               257));
11797
11798     SDValue TlsArray = Subtarget->is64Bit()
11799                            ? DAG.getIntPtrConstant(0x58, dl)
11800                            : (Subtarget->isTargetWindowsGNU()
11801                                   ? DAG.getIntPtrConstant(0x2C, dl)
11802                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11803
11804     SDValue ThreadPointer =
11805         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11806                     false, false, 0);
11807
11808     SDValue res;
11809     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11810       res = ThreadPointer;
11811     } else {
11812       // Load the _tls_index variable
11813       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11814       if (Subtarget->is64Bit())
11815         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11816                              MachinePointerInfo(), MVT::i32, false, false,
11817                              false, 0);
11818       else
11819         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11820                           false, false, 0);
11821
11822       auto &DL = DAG.getDataLayout();
11823       SDValue Scale =
11824           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11825       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11826
11827       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11828     }
11829
11830     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11831                       false, 0);
11832
11833     // Get the offset of start of .tls section
11834     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11835                                              GA->getValueType(0),
11836                                              GA->getOffset(), X86II::MO_SECREL);
11837     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11838
11839     // The address of the thread local variable is the add of the thread
11840     // pointer with the offset of the variable.
11841     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11842   }
11843
11844   llvm_unreachable("TLS not implemented for this target.");
11845 }
11846
11847 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11848 /// and take a 2 x i32 value to shift plus a shift amount.
11849 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11850   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11851   MVT VT = Op.getSimpleValueType();
11852   unsigned VTBits = VT.getSizeInBits();
11853   SDLoc dl(Op);
11854   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11855   SDValue ShOpLo = Op.getOperand(0);
11856   SDValue ShOpHi = Op.getOperand(1);
11857   SDValue ShAmt  = Op.getOperand(2);
11858   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11859   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11860   // during isel.
11861   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11862                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11863   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11864                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11865                        : DAG.getConstant(0, dl, VT);
11866
11867   SDValue Tmp2, Tmp3;
11868   if (Op.getOpcode() == ISD::SHL_PARTS) {
11869     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11870     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11871   } else {
11872     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11873     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11874   }
11875
11876   // If the shift amount is larger or equal than the width of a part we can't
11877   // rely on the results of shld/shrd. Insert a test and select the appropriate
11878   // values for large shift amounts.
11879   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11880                                 DAG.getConstant(VTBits, dl, MVT::i8));
11881   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11882                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11883
11884   SDValue Hi, Lo;
11885   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11886   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11887   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11888
11889   if (Op.getOpcode() == ISD::SHL_PARTS) {
11890     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11891     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11892   } else {
11893     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11894     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11895   }
11896
11897   SDValue Ops[2] = { Lo, Hi };
11898   return DAG.getMergeValues(Ops, dl);
11899 }
11900
11901 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11902                                            SelectionDAG &DAG) const {
11903   SDValue Src = Op.getOperand(0);
11904   MVT SrcVT = Src.getSimpleValueType();
11905   MVT VT = Op.getSimpleValueType();
11906   SDLoc dl(Op);
11907
11908   if (SrcVT.isVector()) {
11909     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11910       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11911                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11912                          DAG.getUNDEF(SrcVT)));
11913     }
11914     if (SrcVT.getVectorElementType() == MVT::i1) {
11915       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11916       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11917                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11918     }
11919     return SDValue();
11920   }
11921
11922   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11923          "Unknown SINT_TO_FP to lower!");
11924
11925   // These are really Legal; return the operand so the caller accepts it as
11926   // Legal.
11927   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11928     return Op;
11929   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11930       Subtarget->is64Bit()) {
11931     return Op;
11932   }
11933
11934   unsigned Size = SrcVT.getSizeInBits()/8;
11935   MachineFunction &MF = DAG.getMachineFunction();
11936   auto PtrVT = getPointerTy(MF.getDataLayout());
11937   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11938   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11939   SDValue Chain = DAG.getStore(
11940       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11941       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11942       false, 0);
11943   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11944 }
11945
11946 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11947                                      SDValue StackSlot,
11948                                      SelectionDAG &DAG) const {
11949   // Build the FILD
11950   SDLoc DL(Op);
11951   SDVTList Tys;
11952   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11953   if (useSSE)
11954     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11955   else
11956     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11957
11958   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11959
11960   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11961   MachineMemOperand *MMO;
11962   if (FI) {
11963     int SSFI = FI->getIndex();
11964     MMO = DAG.getMachineFunction().getMachineMemOperand(
11965         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11966         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11967   } else {
11968     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11969     StackSlot = StackSlot.getOperand(1);
11970   }
11971   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11972   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11973                                            X86ISD::FILD, DL,
11974                                            Tys, Ops, SrcVT, MMO);
11975
11976   if (useSSE) {
11977     Chain = Result.getValue(1);
11978     SDValue InFlag = Result.getValue(2);
11979
11980     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11981     // shouldn't be necessary except that RFP cannot be live across
11982     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11983     MachineFunction &MF = DAG.getMachineFunction();
11984     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11985     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11986     auto PtrVT = getPointerTy(MF.getDataLayout());
11987     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11988     Tys = DAG.getVTList(MVT::Other);
11989     SDValue Ops[] = {
11990       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11991     };
11992     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11993         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11994         MachineMemOperand::MOStore, SSFISize, SSFISize);
11995
11996     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11997                                     Ops, Op.getValueType(), MMO);
11998     Result = DAG.getLoad(
11999         Op.getValueType(), DL, Chain, StackSlot,
12000         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12001         false, false, false, 0);
12002   }
12003
12004   return Result;
12005 }
12006
12007 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12008 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12009                                                SelectionDAG &DAG) const {
12010   // This algorithm is not obvious. Here it is what we're trying to output:
12011   /*
12012      movq       %rax,  %xmm0
12013      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12014      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12015      #ifdef __SSE3__
12016        haddpd   %xmm0, %xmm0
12017      #else
12018        pshufd   $0x4e, %xmm0, %xmm1
12019        addpd    %xmm1, %xmm0
12020      #endif
12021   */
12022
12023   SDLoc dl(Op);
12024   LLVMContext *Context = DAG.getContext();
12025
12026   // Build some magic constants.
12027   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12028   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12029   auto PtrVT = getPointerTy(DAG.getDataLayout());
12030   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12031
12032   SmallVector<Constant*,2> CV1;
12033   CV1.push_back(
12034     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12035                                       APInt(64, 0x4330000000000000ULL))));
12036   CV1.push_back(
12037     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12038                                       APInt(64, 0x4530000000000000ULL))));
12039   Constant *C1 = ConstantVector::get(CV1);
12040   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12041
12042   // Load the 64-bit value into an XMM register.
12043   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12044                             Op.getOperand(0));
12045   SDValue CLod0 =
12046       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12047                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12048                   false, false, false, 16);
12049   SDValue Unpck1 =
12050       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12051
12052   SDValue CLod1 =
12053       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12054                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12055                   false, false, false, 16);
12056   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12057   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12058   SDValue Result;
12059
12060   if (Subtarget->hasSSE3()) {
12061     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12062     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12063   } else {
12064     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12065     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12066                                            S2F, 0x4E, DAG);
12067     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12068                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12069   }
12070
12071   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12072                      DAG.getIntPtrConstant(0, dl));
12073 }
12074
12075 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12076 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12077                                                SelectionDAG &DAG) const {
12078   SDLoc dl(Op);
12079   // FP constant to bias correct the final result.
12080   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12081                                    MVT::f64);
12082
12083   // Load the 32-bit value into an XMM register.
12084   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12085                              Op.getOperand(0));
12086
12087   // Zero out the upper parts of the register.
12088   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12089
12090   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12091                      DAG.getBitcast(MVT::v2f64, Load),
12092                      DAG.getIntPtrConstant(0, dl));
12093
12094   // Or the load with the bias.
12095   SDValue Or = DAG.getNode(
12096       ISD::OR, dl, MVT::v2i64,
12097       DAG.getBitcast(MVT::v2i64,
12098                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12099       DAG.getBitcast(MVT::v2i64,
12100                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12101   Or =
12102       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12103                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12104
12105   // Subtract the bias.
12106   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12107
12108   // Handle final rounding.
12109   EVT DestVT = Op.getValueType();
12110
12111   if (DestVT.bitsLT(MVT::f64))
12112     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12113                        DAG.getIntPtrConstant(0, dl));
12114   if (DestVT.bitsGT(MVT::f64))
12115     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12116
12117   // Handle final rounding.
12118   return Sub;
12119 }
12120
12121 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12122                                      const X86Subtarget &Subtarget) {
12123   // The algorithm is the following:
12124   // #ifdef __SSE4_1__
12125   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12126   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12127   //                                 (uint4) 0x53000000, 0xaa);
12128   // #else
12129   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12130   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12131   // #endif
12132   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12133   //     return (float4) lo + fhi;
12134
12135   SDLoc DL(Op);
12136   SDValue V = Op->getOperand(0);
12137   EVT VecIntVT = V.getValueType();
12138   bool Is128 = VecIntVT == MVT::v4i32;
12139   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12140   // If we convert to something else than the supported type, e.g., to v4f64,
12141   // abort early.
12142   if (VecFloatVT != Op->getValueType(0))
12143     return SDValue();
12144
12145   unsigned NumElts = VecIntVT.getVectorNumElements();
12146   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12147          "Unsupported custom type");
12148   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12149
12150   // In the #idef/#else code, we have in common:
12151   // - The vector of constants:
12152   // -- 0x4b000000
12153   // -- 0x53000000
12154   // - A shift:
12155   // -- v >> 16
12156
12157   // Create the splat vector for 0x4b000000.
12158   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12159   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12160                            CstLow, CstLow, CstLow, CstLow};
12161   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12162                                   makeArrayRef(&CstLowArray[0], NumElts));
12163   // Create the splat vector for 0x53000000.
12164   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12165   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12166                             CstHigh, CstHigh, CstHigh, CstHigh};
12167   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12168                                    makeArrayRef(&CstHighArray[0], NumElts));
12169
12170   // Create the right shift.
12171   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12172   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12173                              CstShift, CstShift, CstShift, CstShift};
12174   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12175                                     makeArrayRef(&CstShiftArray[0], NumElts));
12176   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12177
12178   SDValue Low, High;
12179   if (Subtarget.hasSSE41()) {
12180     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12181     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12182     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12183     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12184     // Low will be bitcasted right away, so do not bother bitcasting back to its
12185     // original type.
12186     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12187                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12188     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12189     //                                 (uint4) 0x53000000, 0xaa);
12190     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12191     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12192     // High will be bitcasted right away, so do not bother bitcasting back to
12193     // its original type.
12194     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12195                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12196   } else {
12197     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12198     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12199                                      CstMask, CstMask, CstMask);
12200     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12201     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12202     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12203
12204     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12205     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12206   }
12207
12208   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12209   SDValue CstFAdd = DAG.getConstantFP(
12210       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12211   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12212                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12213   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12214                                    makeArrayRef(&CstFAddArray[0], NumElts));
12215
12216   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12217   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12218   SDValue FHigh =
12219       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12220   //     return (float4) lo + fhi;
12221   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12222   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12223 }
12224
12225 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12226                                                SelectionDAG &DAG) const {
12227   SDValue N0 = Op.getOperand(0);
12228   MVT SVT = N0.getSimpleValueType();
12229   SDLoc dl(Op);
12230
12231   switch (SVT.SimpleTy) {
12232   default:
12233     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12234   case MVT::v4i8:
12235   case MVT::v4i16:
12236   case MVT::v8i8:
12237   case MVT::v8i16: {
12238     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12239     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12240                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12241   }
12242   case MVT::v4i32:
12243   case MVT::v8i32:
12244     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12245   case MVT::v16i8:
12246   case MVT::v16i16:
12247     if (Subtarget->hasAVX512())
12248       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12249                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12250   }
12251   llvm_unreachable(nullptr);
12252 }
12253
12254 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12255                                            SelectionDAG &DAG) const {
12256   SDValue N0 = Op.getOperand(0);
12257   SDLoc dl(Op);
12258   auto PtrVT = getPointerTy(DAG.getDataLayout());
12259
12260   if (Op.getValueType().isVector())
12261     return lowerUINT_TO_FP_vec(Op, DAG);
12262
12263   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12264   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12265   // the optimization here.
12266   if (DAG.SignBitIsZero(N0))
12267     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12268
12269   MVT SrcVT = N0.getSimpleValueType();
12270   MVT DstVT = Op.getSimpleValueType();
12271   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12272     return LowerUINT_TO_FP_i64(Op, DAG);
12273   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12274     return LowerUINT_TO_FP_i32(Op, DAG);
12275   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12276     return SDValue();
12277
12278   // Make a 64-bit buffer, and use it to build an FILD.
12279   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12280   if (SrcVT == MVT::i32) {
12281     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12282     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12283     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12284                                   StackSlot, MachinePointerInfo(),
12285                                   false, false, 0);
12286     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12287                                   OffsetSlot, MachinePointerInfo(),
12288                                   false, false, 0);
12289     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12290     return Fild;
12291   }
12292
12293   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12294   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12295                                StackSlot, MachinePointerInfo(),
12296                                false, false, 0);
12297   // For i64 source, we need to add the appropriate power of 2 if the input
12298   // was negative.  This is the same as the optimization in
12299   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12300   // we must be careful to do the computation in x87 extended precision, not
12301   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12302   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12303   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12304       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12305       MachineMemOperand::MOLoad, 8, 8);
12306
12307   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12308   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12309   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12310                                          MVT::i64, MMO);
12311
12312   APInt FF(32, 0x5F800000ULL);
12313
12314   // Check whether the sign bit is set.
12315   SDValue SignSet = DAG.getSetCC(
12316       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12317       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12318
12319   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12320   SDValue FudgePtr = DAG.getConstantPool(
12321       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12322
12323   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12324   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12325   SDValue Four = DAG.getIntPtrConstant(4, dl);
12326   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12327                                Zero, Four);
12328   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12329
12330   // Load the value out, extending it from f32 to f80.
12331   // FIXME: Avoid the extend by constructing the right constant pool?
12332   SDValue Fudge = DAG.getExtLoad(
12333       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12334       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12335       false, false, false, 4);
12336   // Extend everything to 80 bits to force it to be done on x87.
12337   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12338   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12339                      DAG.getIntPtrConstant(0, dl));
12340 }
12341
12342 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12343 // is legal, or has an f16 source (which needs to be promoted to f32),
12344 // just return an <SDValue(), SDValue()> pair.
12345 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12346 // to i16, i32 or i64, and we lower it to a legal sequence.
12347 // If lowered to the final integer result we return a <result, SDValue()> pair.
12348 // Otherwise we lower it to a sequence ending with a FIST, return a
12349 // <FIST, StackSlot> pair, and the caller is responsible for loading
12350 // the final integer result from StackSlot.
12351 std::pair<SDValue,SDValue>
12352 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12353                                    bool IsSigned, bool IsReplace) const {
12354   SDLoc DL(Op);
12355
12356   EVT DstTy = Op.getValueType();
12357   EVT TheVT = Op.getOperand(0).getValueType();
12358   auto PtrVT = getPointerTy(DAG.getDataLayout());
12359
12360   if (TheVT == MVT::f16)
12361     // We need to promote the f16 to f32 before using the lowering
12362     // in this routine.
12363     return std::make_pair(SDValue(), SDValue());
12364
12365   assert((TheVT == MVT::f32 ||
12366           TheVT == MVT::f64 ||
12367           TheVT == MVT::f80) &&
12368          "Unexpected FP operand type in FP_TO_INTHelper");
12369
12370   // If using FIST to compute an unsigned i64, we'll need some fixup
12371   // to handle values above the maximum signed i64.  A FIST is always
12372   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12373   bool UnsignedFixup = !IsSigned &&
12374                        DstTy == MVT::i64 &&
12375                        (!Subtarget->is64Bit() ||
12376                         !isScalarFPTypeInSSEReg(TheVT));
12377
12378   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12379     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12380     // The low 32 bits of the fist result will have the correct uint32 result.
12381     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12382     DstTy = MVT::i64;
12383   }
12384
12385   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12386          DstTy.getSimpleVT() >= MVT::i16 &&
12387          "Unknown FP_TO_INT to lower!");
12388
12389   // These are really Legal.
12390   if (DstTy == MVT::i32 &&
12391       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12392     return std::make_pair(SDValue(), SDValue());
12393   if (Subtarget->is64Bit() &&
12394       DstTy == MVT::i64 &&
12395       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12396     return std::make_pair(SDValue(), SDValue());
12397
12398   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12399   // stack slot.
12400   MachineFunction &MF = DAG.getMachineFunction();
12401   unsigned MemSize = DstTy.getSizeInBits()/8;
12402   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12403   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12404
12405   unsigned Opc;
12406   switch (DstTy.getSimpleVT().SimpleTy) {
12407   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12408   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12409   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12410   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12411   }
12412
12413   SDValue Chain = DAG.getEntryNode();
12414   SDValue Value = Op.getOperand(0);
12415   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12416
12417   if (UnsignedFixup) {
12418     //
12419     // Conversion to unsigned i64 is implemented with a select,
12420     // depending on whether the source value fits in the range
12421     // of a signed i64.  Let Thresh be the FP equivalent of
12422     // 0x8000000000000000ULL.
12423     //
12424     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12425     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12426     //  Fist-to-mem64 FistSrc
12427     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12428     //  to XOR'ing the high 32 bits with Adjust.
12429     //
12430     // Being a power of 2, Thresh is exactly representable in all FP formats.
12431     // For X87 we'd like to use the smallest FP type for this constant, but
12432     // for DAG type consistency we have to match the FP operand type.
12433
12434     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12435     APFloat::opStatus Status = APFloat::opOK;
12436     bool LosesInfo = false;
12437     if (TheVT == MVT::f64)
12438       // The rounding mode is irrelevant as the conversion should be exact.
12439       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12440                               &LosesInfo);
12441     else if (TheVT == MVT::f80)
12442       Status = Thresh.convert(APFloat::x87DoubleExtended,
12443                               APFloat::rmNearestTiesToEven, &LosesInfo);
12444
12445     assert(Status == APFloat::opOK && !LosesInfo &&
12446            "FP conversion should have been exact");
12447
12448     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12449
12450     SDValue Cmp = DAG.getSetCC(DL,
12451                                getSetCCResultType(DAG.getDataLayout(),
12452                                                   *DAG.getContext(), TheVT),
12453                                Value, ThreshVal, ISD::SETLT);
12454     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12455                            DAG.getConstant(0, DL, MVT::i32),
12456                            DAG.getConstant(0x80000000, DL, MVT::i32));
12457     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12458     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12459                                               *DAG.getContext(), TheVT),
12460                        Value, ThreshVal, ISD::SETLT);
12461     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12462   }
12463
12464   // FIXME This causes a redundant load/store if the SSE-class value is already
12465   // in memory, such as if it is on the callstack.
12466   if (isScalarFPTypeInSSEReg(TheVT)) {
12467     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12468     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12469                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12470                          false, 0);
12471     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12472     SDValue Ops[] = {
12473       Chain, StackSlot, DAG.getValueType(TheVT)
12474     };
12475
12476     MachineMemOperand *MMO =
12477         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12478                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12479     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12480     Chain = Value.getValue(1);
12481     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12482     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12483   }
12484
12485   MachineMemOperand *MMO =
12486       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12487                               MachineMemOperand::MOStore, MemSize, MemSize);
12488
12489   if (UnsignedFixup) {
12490
12491     // Insert the FIST, load its result as two i32's,
12492     // and XOR the high i32 with Adjust.
12493
12494     SDValue FistOps[] = { Chain, Value, StackSlot };
12495     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12496                                            FistOps, DstTy, MMO);
12497
12498     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12499                                 MachinePointerInfo(),
12500                                 false, false, false, 0);
12501     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12502                                    DAG.getConstant(4, DL, PtrVT));
12503
12504     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12505                                  MachinePointerInfo(),
12506                                  false, false, false, 0);
12507     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12508
12509     if (Subtarget->is64Bit()) {
12510       // Join High32 and Low32 into a 64-bit result.
12511       // (High32 << 32) | Low32
12512       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12513       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12514       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12515                            DAG.getConstant(32, DL, MVT::i8));
12516       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12517       return std::make_pair(Result, SDValue());
12518     }
12519
12520     SDValue ResultOps[] = { Low32, High32 };
12521
12522     SDValue pair = IsReplace
12523       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12524       : DAG.getMergeValues(ResultOps, DL);
12525     return std::make_pair(pair, SDValue());
12526   } else {
12527     // Build the FP_TO_INT*_IN_MEM
12528     SDValue Ops[] = { Chain, Value, StackSlot };
12529     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12530                                            Ops, DstTy, MMO);
12531     return std::make_pair(FIST, StackSlot);
12532   }
12533 }
12534
12535 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12536                               const X86Subtarget *Subtarget) {
12537   MVT VT = Op->getSimpleValueType(0);
12538   SDValue In = Op->getOperand(0);
12539   MVT InVT = In.getSimpleValueType();
12540   SDLoc dl(Op);
12541
12542   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12543     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12544
12545   // Optimize vectors in AVX mode:
12546   //
12547   //   v8i16 -> v8i32
12548   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12549   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12550   //   Concat upper and lower parts.
12551   //
12552   //   v4i32 -> v4i64
12553   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12554   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12555   //   Concat upper and lower parts.
12556   //
12557
12558   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12559       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12560       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12561     return SDValue();
12562
12563   if (Subtarget->hasInt256())
12564     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12565
12566   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12567   SDValue Undef = DAG.getUNDEF(InVT);
12568   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12569   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12570   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12571
12572   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12573                              VT.getVectorNumElements()/2);
12574
12575   OpLo = DAG.getBitcast(HVT, OpLo);
12576   OpHi = DAG.getBitcast(HVT, OpHi);
12577
12578   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12579 }
12580
12581 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12582                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12583   MVT VT = Op->getSimpleValueType(0);
12584   SDValue In = Op->getOperand(0);
12585   MVT InVT = In.getSimpleValueType();
12586   SDLoc DL(Op);
12587   unsigned int NumElts = VT.getVectorNumElements();
12588   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12589     return SDValue();
12590
12591   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12592     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12593
12594   assert(InVT.getVectorElementType() == MVT::i1);
12595   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12596   SDValue One =
12597    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12598   SDValue Zero =
12599    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12600
12601   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12602   if (VT.is512BitVector())
12603     return V;
12604   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12605 }
12606
12607 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12608                                SelectionDAG &DAG) {
12609   if (Subtarget->hasFp256())
12610     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12611       return Res;
12612
12613   return SDValue();
12614 }
12615
12616 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12617                                 SelectionDAG &DAG) {
12618   SDLoc DL(Op);
12619   MVT VT = Op.getSimpleValueType();
12620   SDValue In = Op.getOperand(0);
12621   MVT SVT = In.getSimpleValueType();
12622
12623   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12624     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12625
12626   if (Subtarget->hasFp256())
12627     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12628       return Res;
12629
12630   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12631          VT.getVectorNumElements() != SVT.getVectorNumElements());
12632   return SDValue();
12633 }
12634
12635 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12636   SDLoc DL(Op);
12637   MVT VT = Op.getSimpleValueType();
12638   SDValue In = Op.getOperand(0);
12639   MVT InVT = In.getSimpleValueType();
12640
12641   if (VT == MVT::i1) {
12642     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12643            "Invalid scalar TRUNCATE operation");
12644     if (InVT.getSizeInBits() >= 32)
12645       return SDValue();
12646     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12647     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12648   }
12649   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12650          "Invalid TRUNCATE operation");
12651
12652   // move vector to mask - truncate solution for SKX
12653   if (VT.getVectorElementType() == MVT::i1) {
12654     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12655         Subtarget->hasBWI())
12656       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12657     if ((InVT.is256BitVector() || InVT.is128BitVector())
12658         && InVT.getScalarSizeInBits() <= 16 &&
12659         Subtarget->hasBWI() && Subtarget->hasVLX())
12660       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12661     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12662         Subtarget->hasDQI())
12663       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12664     if ((InVT.is256BitVector() || InVT.is128BitVector())
12665         && InVT.getScalarSizeInBits() >= 32 &&
12666         Subtarget->hasDQI() && Subtarget->hasVLX())
12667       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12668   }
12669
12670   if (VT.getVectorElementType() == MVT::i1) {
12671     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12672     unsigned NumElts = InVT.getVectorNumElements();
12673     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12674     if (InVT.getSizeInBits() < 512) {
12675       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12676       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12677       InVT = ExtVT;
12678     }
12679
12680     SDValue OneV =
12681      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12682     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12683     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12684   }
12685
12686   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12687   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12688       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12689     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12690
12691   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12692     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12693     if (Subtarget->hasInt256()) {
12694       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12695       In = DAG.getBitcast(MVT::v8i32, In);
12696       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12697                                 ShufMask);
12698       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12699                          DAG.getIntPtrConstant(0, DL));
12700     }
12701
12702     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12703                                DAG.getIntPtrConstant(0, DL));
12704     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12705                                DAG.getIntPtrConstant(2, DL));
12706     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12707     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12708     static const int ShufMask[] = {0, 2, 4, 6};
12709     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12710   }
12711
12712   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12713     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12714     if (Subtarget->hasInt256()) {
12715       In = DAG.getBitcast(MVT::v32i8, In);
12716
12717       SmallVector<SDValue,32> pshufbMask;
12718       for (unsigned i = 0; i < 2; ++i) {
12719         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12720         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12721         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12722         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12723         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12724         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12725         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12726         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12727         for (unsigned j = 0; j < 8; ++j)
12728           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12729       }
12730       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12731       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12732       In = DAG.getBitcast(MVT::v4i64, In);
12733
12734       static const int ShufMask[] = {0,  2,  -1,  -1};
12735       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12736                                 &ShufMask[0]);
12737       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12738                        DAG.getIntPtrConstant(0, DL));
12739       return DAG.getBitcast(VT, In);
12740     }
12741
12742     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12743                                DAG.getIntPtrConstant(0, DL));
12744
12745     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12746                                DAG.getIntPtrConstant(4, DL));
12747
12748     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12749     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12750
12751     // The PSHUFB mask:
12752     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12753                                    -1, -1, -1, -1, -1, -1, -1, -1};
12754
12755     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12756     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12757     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12758
12759     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12760     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12761
12762     // The MOVLHPS Mask:
12763     static const int ShufMask2[] = {0, 1, 4, 5};
12764     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12765     return DAG.getBitcast(MVT::v8i16, res);
12766   }
12767
12768   // Handle truncation of V256 to V128 using shuffles.
12769   if (!VT.is128BitVector() || !InVT.is256BitVector())
12770     return SDValue();
12771
12772   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12773
12774   unsigned NumElems = VT.getVectorNumElements();
12775   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12776
12777   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12778   // Prepare truncation shuffle mask
12779   for (unsigned i = 0; i != NumElems; ++i)
12780     MaskVec[i] = i * 2;
12781   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12782                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12783   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12784                      DAG.getIntPtrConstant(0, DL));
12785 }
12786
12787 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12788                                            SelectionDAG &DAG) const {
12789   assert(!Op.getSimpleValueType().isVector());
12790
12791   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12792     /*IsSigned=*/ true, /*IsReplace=*/ false);
12793   SDValue FIST = Vals.first, StackSlot = Vals.second;
12794   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12795   if (!FIST.getNode())
12796     return Op;
12797
12798   if (StackSlot.getNode())
12799     // Load the result.
12800     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12801                        FIST, StackSlot, MachinePointerInfo(),
12802                        false, false, false, 0);
12803
12804   // The node is the result.
12805   return FIST;
12806 }
12807
12808 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12809                                            SelectionDAG &DAG) const {
12810   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12811     /*IsSigned=*/ false, /*IsReplace=*/ false);
12812   SDValue FIST = Vals.first, StackSlot = Vals.second;
12813   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12814   if (!FIST.getNode())
12815     return Op;
12816
12817   if (StackSlot.getNode())
12818     // Load the result.
12819     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12820                        FIST, StackSlot, MachinePointerInfo(),
12821                        false, false, false, 0);
12822
12823   // The node is the result.
12824   return FIST;
12825 }
12826
12827 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12828   SDLoc DL(Op);
12829   MVT VT = Op.getSimpleValueType();
12830   SDValue In = Op.getOperand(0);
12831   MVT SVT = In.getSimpleValueType();
12832
12833   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12834
12835   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12836                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12837                                  In, DAG.getUNDEF(SVT)));
12838 }
12839
12840 /// The only differences between FABS and FNEG are the mask and the logic op.
12841 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12842 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12843   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12844          "Wrong opcode for lowering FABS or FNEG.");
12845
12846   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12847
12848   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12849   // into an FNABS. We'll lower the FABS after that if it is still in use.
12850   if (IsFABS)
12851     for (SDNode *User : Op->uses())
12852       if (User->getOpcode() == ISD::FNEG)
12853         return Op;
12854
12855   SDLoc dl(Op);
12856   MVT VT = Op.getSimpleValueType();
12857
12858   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12859   // decide if we should generate a 16-byte constant mask when we only need 4 or
12860   // 8 bytes for the scalar case.
12861
12862   MVT LogicVT;
12863   MVT EltVT;
12864   unsigned NumElts;
12865
12866   if (VT.isVector()) {
12867     LogicVT = VT;
12868     EltVT = VT.getVectorElementType();
12869     NumElts = VT.getVectorNumElements();
12870   } else {
12871     // There are no scalar bitwise logical SSE/AVX instructions, so we
12872     // generate a 16-byte vector constant and logic op even for the scalar case.
12873     // Using a 16-byte mask allows folding the load of the mask with
12874     // the logic op, so it can save (~4 bytes) on code size.
12875     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12876     EltVT = VT;
12877     NumElts = (VT == MVT::f64) ? 2 : 4;
12878   }
12879
12880   unsigned EltBits = EltVT.getSizeInBits();
12881   LLVMContext *Context = DAG.getContext();
12882   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12883   APInt MaskElt =
12884     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12885   Constant *C = ConstantInt::get(*Context, MaskElt);
12886   C = ConstantVector::getSplat(NumElts, C);
12887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12888   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12889   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12890   SDValue Mask =
12891       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12892                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12893                   false, false, false, Alignment);
12894
12895   SDValue Op0 = Op.getOperand(0);
12896   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12897   unsigned LogicOp =
12898     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12899   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12900
12901   if (VT.isVector())
12902     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12903
12904   // For the scalar case extend to a 128-bit vector, perform the logic op,
12905   // and extract the scalar result back out.
12906   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12907   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12908   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12909                      DAG.getIntPtrConstant(0, dl));
12910 }
12911
12912 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12914   LLVMContext *Context = DAG.getContext();
12915   SDValue Op0 = Op.getOperand(0);
12916   SDValue Op1 = Op.getOperand(1);
12917   SDLoc dl(Op);
12918   MVT VT = Op.getSimpleValueType();
12919   MVT SrcVT = Op1.getSimpleValueType();
12920
12921   // If second operand is smaller, extend it first.
12922   if (SrcVT.bitsLT(VT)) {
12923     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12924     SrcVT = VT;
12925   }
12926   // And if it is bigger, shrink it first.
12927   if (SrcVT.bitsGT(VT)) {
12928     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12929     SrcVT = VT;
12930   }
12931
12932   // At this point the operands and the result should have the same
12933   // type, and that won't be f80 since that is not custom lowered.
12934
12935   const fltSemantics &Sem =
12936       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12937   const unsigned SizeInBits = VT.getSizeInBits();
12938
12939   SmallVector<Constant *, 4> CV(
12940       VT == MVT::f64 ? 2 : 4,
12941       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12942
12943   // First, clear all bits but the sign bit from the second operand (sign).
12944   CV[0] = ConstantFP::get(*Context,
12945                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12946   Constant *C = ConstantVector::get(CV);
12947   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12948   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12949
12950   // Perform all logic operations as 16-byte vectors because there are no
12951   // scalar FP logic instructions in SSE. This allows load folding of the
12952   // constants into the logic instructions.
12953   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12954   SDValue Mask1 =
12955       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12956                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12957                   false, false, false, 16);
12958   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12959   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12960
12961   // Next, clear the sign bit from the first operand (magnitude).
12962   // If it's a constant, we can clear it here.
12963   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12964     APFloat APF = Op0CN->getValueAPF();
12965     // If the magnitude is a positive zero, the sign bit alone is enough.
12966     if (APF.isPosZero())
12967       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12968                          DAG.getIntPtrConstant(0, dl));
12969     APF.clearSign();
12970     CV[0] = ConstantFP::get(*Context, APF);
12971   } else {
12972     CV[0] = ConstantFP::get(
12973         *Context,
12974         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12975   }
12976   C = ConstantVector::get(CV);
12977   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12978   SDValue Val =
12979       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12980                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12981                   false, false, false, 16);
12982   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12983   if (!isa<ConstantFPSDNode>(Op0)) {
12984     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12985     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12986   }
12987   // OR the magnitude value with the sign bit.
12988   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12989   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12990                      DAG.getIntPtrConstant(0, dl));
12991 }
12992
12993 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12994   SDValue N0 = Op.getOperand(0);
12995   SDLoc dl(Op);
12996   MVT VT = Op.getSimpleValueType();
12997
12998   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12999   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13000                                   DAG.getConstant(1, dl, VT));
13001   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13002 }
13003
13004 // Check whether an OR'd tree is PTEST-able.
13005 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13006                                       SelectionDAG &DAG) {
13007   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13008
13009   if (!Subtarget->hasSSE41())
13010     return SDValue();
13011
13012   if (!Op->hasOneUse())
13013     return SDValue();
13014
13015   SDNode *N = Op.getNode();
13016   SDLoc DL(N);
13017
13018   SmallVector<SDValue, 8> Opnds;
13019   DenseMap<SDValue, unsigned> VecInMap;
13020   SmallVector<SDValue, 8> VecIns;
13021   EVT VT = MVT::Other;
13022
13023   // Recognize a special case where a vector is casted into wide integer to
13024   // test all 0s.
13025   Opnds.push_back(N->getOperand(0));
13026   Opnds.push_back(N->getOperand(1));
13027
13028   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13029     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13030     // BFS traverse all OR'd operands.
13031     if (I->getOpcode() == ISD::OR) {
13032       Opnds.push_back(I->getOperand(0));
13033       Opnds.push_back(I->getOperand(1));
13034       // Re-evaluate the number of nodes to be traversed.
13035       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13036       continue;
13037     }
13038
13039     // Quit if a non-EXTRACT_VECTOR_ELT
13040     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13041       return SDValue();
13042
13043     // Quit if without a constant index.
13044     SDValue Idx = I->getOperand(1);
13045     if (!isa<ConstantSDNode>(Idx))
13046       return SDValue();
13047
13048     SDValue ExtractedFromVec = I->getOperand(0);
13049     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13050     if (M == VecInMap.end()) {
13051       VT = ExtractedFromVec.getValueType();
13052       // Quit if not 128/256-bit vector.
13053       if (!VT.is128BitVector() && !VT.is256BitVector())
13054         return SDValue();
13055       // Quit if not the same type.
13056       if (VecInMap.begin() != VecInMap.end() &&
13057           VT != VecInMap.begin()->first.getValueType())
13058         return SDValue();
13059       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13060       VecIns.push_back(ExtractedFromVec);
13061     }
13062     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13063   }
13064
13065   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13066          "Not extracted from 128-/256-bit vector.");
13067
13068   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13069
13070   for (DenseMap<SDValue, unsigned>::const_iterator
13071         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13072     // Quit if not all elements are used.
13073     if (I->second != FullMask)
13074       return SDValue();
13075   }
13076
13077   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13078
13079   // Cast all vectors into TestVT for PTEST.
13080   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13081     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13082
13083   // If more than one full vectors are evaluated, OR them first before PTEST.
13084   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13085     // Each iteration will OR 2 nodes and append the result until there is only
13086     // 1 node left, i.e. the final OR'd value of all vectors.
13087     SDValue LHS = VecIns[Slot];
13088     SDValue RHS = VecIns[Slot + 1];
13089     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13090   }
13091
13092   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13093                      VecIns.back(), VecIns.back());
13094 }
13095
13096 /// \brief return true if \c Op has a use that doesn't just read flags.
13097 static bool hasNonFlagsUse(SDValue Op) {
13098   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13099        ++UI) {
13100     SDNode *User = *UI;
13101     unsigned UOpNo = UI.getOperandNo();
13102     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13103       // Look pass truncate.
13104       UOpNo = User->use_begin().getOperandNo();
13105       User = *User->use_begin();
13106     }
13107
13108     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13109         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13110       return true;
13111   }
13112   return false;
13113 }
13114
13115 /// Emit nodes that will be selected as "test Op0,Op0", or something
13116 /// equivalent.
13117 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13118                                     SelectionDAG &DAG) const {
13119   if (Op.getValueType() == MVT::i1) {
13120     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13121     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13122                        DAG.getConstant(0, dl, MVT::i8));
13123   }
13124   // CF and OF aren't always set the way we want. Determine which
13125   // of these we need.
13126   bool NeedCF = false;
13127   bool NeedOF = false;
13128   switch (X86CC) {
13129   default: break;
13130   case X86::COND_A: case X86::COND_AE:
13131   case X86::COND_B: case X86::COND_BE:
13132     NeedCF = true;
13133     break;
13134   case X86::COND_G: case X86::COND_GE:
13135   case X86::COND_L: case X86::COND_LE:
13136   case X86::COND_O: case X86::COND_NO: {
13137     // Check if we really need to set the
13138     // Overflow flag. If NoSignedWrap is present
13139     // that is not actually needed.
13140     switch (Op->getOpcode()) {
13141     case ISD::ADD:
13142     case ISD::SUB:
13143     case ISD::MUL:
13144     case ISD::SHL: {
13145       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13146       if (BinNode->Flags.hasNoSignedWrap())
13147         break;
13148     }
13149     default:
13150       NeedOF = true;
13151       break;
13152     }
13153     break;
13154   }
13155   }
13156   // See if we can use the EFLAGS value from the operand instead of
13157   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13158   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13159   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13160     // Emit a CMP with 0, which is the TEST pattern.
13161     //if (Op.getValueType() == MVT::i1)
13162     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13163     //                     DAG.getConstant(0, MVT::i1));
13164     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13165                        DAG.getConstant(0, dl, Op.getValueType()));
13166   }
13167   unsigned Opcode = 0;
13168   unsigned NumOperands = 0;
13169
13170   // Truncate operations may prevent the merge of the SETCC instruction
13171   // and the arithmetic instruction before it. Attempt to truncate the operands
13172   // of the arithmetic instruction and use a reduced bit-width instruction.
13173   bool NeedTruncation = false;
13174   SDValue ArithOp = Op;
13175   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13176     SDValue Arith = Op->getOperand(0);
13177     // Both the trunc and the arithmetic op need to have one user each.
13178     if (Arith->hasOneUse())
13179       switch (Arith.getOpcode()) {
13180         default: break;
13181         case ISD::ADD:
13182         case ISD::SUB:
13183         case ISD::AND:
13184         case ISD::OR:
13185         case ISD::XOR: {
13186           NeedTruncation = true;
13187           ArithOp = Arith;
13188         }
13189       }
13190   }
13191
13192   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13193   // which may be the result of a CAST.  We use the variable 'Op', which is the
13194   // non-casted variable when we check for possible users.
13195   switch (ArithOp.getOpcode()) {
13196   case ISD::ADD:
13197     // Due to an isel shortcoming, be conservative if this add is likely to be
13198     // selected as part of a load-modify-store instruction. When the root node
13199     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13200     // uses of other nodes in the match, such as the ADD in this case. This
13201     // leads to the ADD being left around and reselected, with the result being
13202     // two adds in the output.  Alas, even if none our users are stores, that
13203     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13204     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13205     // climbing the DAG back to the root, and it doesn't seem to be worth the
13206     // effort.
13207     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13208          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13209       if (UI->getOpcode() != ISD::CopyToReg &&
13210           UI->getOpcode() != ISD::SETCC &&
13211           UI->getOpcode() != ISD::STORE)
13212         goto default_case;
13213
13214     if (ConstantSDNode *C =
13215         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13216       // An add of one will be selected as an INC.
13217       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13218         Opcode = X86ISD::INC;
13219         NumOperands = 1;
13220         break;
13221       }
13222
13223       // An add of negative one (subtract of one) will be selected as a DEC.
13224       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13225         Opcode = X86ISD::DEC;
13226         NumOperands = 1;
13227         break;
13228       }
13229     }
13230
13231     // Otherwise use a regular EFLAGS-setting add.
13232     Opcode = X86ISD::ADD;
13233     NumOperands = 2;
13234     break;
13235   case ISD::SHL:
13236   case ISD::SRL:
13237     // If we have a constant logical shift that's only used in a comparison
13238     // against zero turn it into an equivalent AND. This allows turning it into
13239     // a TEST instruction later.
13240     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13241         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13242       EVT VT = Op.getValueType();
13243       unsigned BitWidth = VT.getSizeInBits();
13244       unsigned ShAmt = Op->getConstantOperandVal(1);
13245       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13246         break;
13247       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13248                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13249                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13250       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13251         break;
13252       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13253                                 DAG.getConstant(Mask, dl, VT));
13254       DAG.ReplaceAllUsesWith(Op, New);
13255       Op = New;
13256     }
13257     break;
13258
13259   case ISD::AND:
13260     // If the primary and result isn't used, don't bother using X86ISD::AND,
13261     // because a TEST instruction will be better.
13262     if (!hasNonFlagsUse(Op))
13263       break;
13264     // FALL THROUGH
13265   case ISD::SUB:
13266   case ISD::OR:
13267   case ISD::XOR:
13268     // Due to the ISEL shortcoming noted above, be conservative if this op is
13269     // likely to be selected as part of a load-modify-store instruction.
13270     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13271            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13272       if (UI->getOpcode() == ISD::STORE)
13273         goto default_case;
13274
13275     // Otherwise use a regular EFLAGS-setting instruction.
13276     switch (ArithOp.getOpcode()) {
13277     default: llvm_unreachable("unexpected operator!");
13278     case ISD::SUB: Opcode = X86ISD::SUB; break;
13279     case ISD::XOR: Opcode = X86ISD::XOR; break;
13280     case ISD::AND: Opcode = X86ISD::AND; break;
13281     case ISD::OR: {
13282       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13283         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13284         if (EFLAGS.getNode())
13285           return EFLAGS;
13286       }
13287       Opcode = X86ISD::OR;
13288       break;
13289     }
13290     }
13291
13292     NumOperands = 2;
13293     break;
13294   case X86ISD::ADD:
13295   case X86ISD::SUB:
13296   case X86ISD::INC:
13297   case X86ISD::DEC:
13298   case X86ISD::OR:
13299   case X86ISD::XOR:
13300   case X86ISD::AND:
13301     return SDValue(Op.getNode(), 1);
13302   default:
13303   default_case:
13304     break;
13305   }
13306
13307   // If we found that truncation is beneficial, perform the truncation and
13308   // update 'Op'.
13309   if (NeedTruncation) {
13310     EVT VT = Op.getValueType();
13311     SDValue WideVal = Op->getOperand(0);
13312     EVT WideVT = WideVal.getValueType();
13313     unsigned ConvertedOp = 0;
13314     // Use a target machine opcode to prevent further DAGCombine
13315     // optimizations that may separate the arithmetic operations
13316     // from the setcc node.
13317     switch (WideVal.getOpcode()) {
13318       default: break;
13319       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13320       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13321       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13322       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13323       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13324     }
13325
13326     if (ConvertedOp) {
13327       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13328       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13329         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13330         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13331         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13332       }
13333     }
13334   }
13335
13336   if (Opcode == 0)
13337     // Emit a CMP with 0, which is the TEST pattern.
13338     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13339                        DAG.getConstant(0, dl, Op.getValueType()));
13340
13341   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13342   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13343
13344   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13345   DAG.ReplaceAllUsesWith(Op, New);
13346   return SDValue(New.getNode(), 1);
13347 }
13348
13349 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13350 /// equivalent.
13351 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13352                                    SDLoc dl, SelectionDAG &DAG) const {
13353   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13354     if (C->getAPIntValue() == 0)
13355       return EmitTest(Op0, X86CC, dl, DAG);
13356
13357      if (Op0.getValueType() == MVT::i1)
13358        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13359   }
13360
13361   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13362        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13363     // Do the comparison at i32 if it's smaller, besides the Atom case.
13364     // This avoids subregister aliasing issues. Keep the smaller reference
13365     // if we're optimizing for size, however, as that'll allow better folding
13366     // of memory operations.
13367     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13368         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13369         !Subtarget->isAtom()) {
13370       unsigned ExtendOp =
13371           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13372       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13373       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13374     }
13375     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13376     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13377     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13378                               Op0, Op1);
13379     return SDValue(Sub.getNode(), 1);
13380   }
13381   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13382 }
13383
13384 /// Convert a comparison if required by the subtarget.
13385 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13386                                                  SelectionDAG &DAG) const {
13387   // If the subtarget does not support the FUCOMI instruction, floating-point
13388   // comparisons have to be converted.
13389   if (Subtarget->hasCMov() ||
13390       Cmp.getOpcode() != X86ISD::CMP ||
13391       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13392       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13393     return Cmp;
13394
13395   // The instruction selector will select an FUCOM instruction instead of
13396   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13397   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13398   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13399   SDLoc dl(Cmp);
13400   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13401   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13402   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13403                             DAG.getConstant(8, dl, MVT::i8));
13404   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13405   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13406 }
13407
13408 /// The minimum architected relative accuracy is 2^-12. We need one
13409 /// Newton-Raphson step to have a good float result (24 bits of precision).
13410 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13411                                             DAGCombinerInfo &DCI,
13412                                             unsigned &RefinementSteps,
13413                                             bool &UseOneConstNR) const {
13414   EVT VT = Op.getValueType();
13415   const char *RecipOp;
13416
13417   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13418   // TODO: Add support for AVX512 (v16f32).
13419   // It is likely not profitable to do this for f64 because a double-precision
13420   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13421   // instructions: convert to single, rsqrtss, convert back to double, refine
13422   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13423   // along with FMA, this could be a throughput win.
13424   if (VT == MVT::f32 && Subtarget->hasSSE1())
13425     RecipOp = "sqrtf";
13426   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13427            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13428     RecipOp = "vec-sqrtf";
13429   else
13430     return SDValue();
13431
13432   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13433   if (!Recips.isEnabled(RecipOp))
13434     return SDValue();
13435
13436   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13437   UseOneConstNR = false;
13438   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13439 }
13440
13441 /// The minimum architected relative accuracy is 2^-12. We need one
13442 /// Newton-Raphson step to have a good float result (24 bits of precision).
13443 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13444                                             DAGCombinerInfo &DCI,
13445                                             unsigned &RefinementSteps) const {
13446   EVT VT = Op.getValueType();
13447   const char *RecipOp;
13448
13449   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13450   // TODO: Add support for AVX512 (v16f32).
13451   // It is likely not profitable to do this for f64 because a double-precision
13452   // reciprocal estimate with refinement on x86 prior to FMA requires
13453   // 15 instructions: convert to single, rcpss, convert back to double, refine
13454   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13455   // along with FMA, this could be a throughput win.
13456   if (VT == MVT::f32 && Subtarget->hasSSE1())
13457     RecipOp = "divf";
13458   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13459            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13460     RecipOp = "vec-divf";
13461   else
13462     return SDValue();
13463
13464   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13465   if (!Recips.isEnabled(RecipOp))
13466     return SDValue();
13467
13468   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13469   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13470 }
13471
13472 /// If we have at least two divisions that use the same divisor, convert to
13473 /// multplication by a reciprocal. This may need to be adjusted for a given
13474 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13475 /// This is because we still need one division to calculate the reciprocal and
13476 /// then we need two multiplies by that reciprocal as replacements for the
13477 /// original divisions.
13478 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13479   return 2;
13480 }
13481
13482 static bool isAllOnes(SDValue V) {
13483   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13484   return C && C->isAllOnesValue();
13485 }
13486
13487 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13488 /// if it's possible.
13489 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13490                                      SDLoc dl, SelectionDAG &DAG) const {
13491   SDValue Op0 = And.getOperand(0);
13492   SDValue Op1 = And.getOperand(1);
13493   if (Op0.getOpcode() == ISD::TRUNCATE)
13494     Op0 = Op0.getOperand(0);
13495   if (Op1.getOpcode() == ISD::TRUNCATE)
13496     Op1 = Op1.getOperand(0);
13497
13498   SDValue LHS, RHS;
13499   if (Op1.getOpcode() == ISD::SHL)
13500     std::swap(Op0, Op1);
13501   if (Op0.getOpcode() == ISD::SHL) {
13502     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13503       if (And00C->getZExtValue() == 1) {
13504         // If we looked past a truncate, check that it's only truncating away
13505         // known zeros.
13506         unsigned BitWidth = Op0.getValueSizeInBits();
13507         unsigned AndBitWidth = And.getValueSizeInBits();
13508         if (BitWidth > AndBitWidth) {
13509           APInt Zeros, Ones;
13510           DAG.computeKnownBits(Op0, Zeros, Ones);
13511           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13512             return SDValue();
13513         }
13514         LHS = Op1;
13515         RHS = Op0.getOperand(1);
13516       }
13517   } else if (Op1.getOpcode() == ISD::Constant) {
13518     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13519     uint64_t AndRHSVal = AndRHS->getZExtValue();
13520     SDValue AndLHS = Op0;
13521
13522     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13523       LHS = AndLHS.getOperand(0);
13524       RHS = AndLHS.getOperand(1);
13525     }
13526
13527     // Use BT if the immediate can't be encoded in a TEST instruction.
13528     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13529       LHS = AndLHS;
13530       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13531     }
13532   }
13533
13534   if (LHS.getNode()) {
13535     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13536     // instruction.  Since the shift amount is in-range-or-undefined, we know
13537     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13538     // the encoding for the i16 version is larger than the i32 version.
13539     // Also promote i16 to i32 for performance / code size reason.
13540     if (LHS.getValueType() == MVT::i8 ||
13541         LHS.getValueType() == MVT::i16)
13542       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13543
13544     // If the operand types disagree, extend the shift amount to match.  Since
13545     // BT ignores high bits (like shifts) we can use anyextend.
13546     if (LHS.getValueType() != RHS.getValueType())
13547       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13548
13549     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13550     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13551     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13552                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13553   }
13554
13555   return SDValue();
13556 }
13557
13558 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13559 /// mask CMPs.
13560 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13561                               SDValue &Op1) {
13562   unsigned SSECC;
13563   bool Swap = false;
13564
13565   // SSE Condition code mapping:
13566   //  0 - EQ
13567   //  1 - LT
13568   //  2 - LE
13569   //  3 - UNORD
13570   //  4 - NEQ
13571   //  5 - NLT
13572   //  6 - NLE
13573   //  7 - ORD
13574   switch (SetCCOpcode) {
13575   default: llvm_unreachable("Unexpected SETCC condition");
13576   case ISD::SETOEQ:
13577   case ISD::SETEQ:  SSECC = 0; break;
13578   case ISD::SETOGT:
13579   case ISD::SETGT:  Swap = true; // Fallthrough
13580   case ISD::SETLT:
13581   case ISD::SETOLT: SSECC = 1; break;
13582   case ISD::SETOGE:
13583   case ISD::SETGE:  Swap = true; // Fallthrough
13584   case ISD::SETLE:
13585   case ISD::SETOLE: SSECC = 2; break;
13586   case ISD::SETUO:  SSECC = 3; break;
13587   case ISD::SETUNE:
13588   case ISD::SETNE:  SSECC = 4; break;
13589   case ISD::SETULE: Swap = true; // Fallthrough
13590   case ISD::SETUGE: SSECC = 5; break;
13591   case ISD::SETULT: Swap = true; // Fallthrough
13592   case ISD::SETUGT: SSECC = 6; break;
13593   case ISD::SETO:   SSECC = 7; break;
13594   case ISD::SETUEQ:
13595   case ISD::SETONE: SSECC = 8; break;
13596   }
13597   if (Swap)
13598     std::swap(Op0, Op1);
13599
13600   return SSECC;
13601 }
13602
13603 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13604 // ones, and then concatenate the result back.
13605 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13606   MVT VT = Op.getSimpleValueType();
13607
13608   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13609          "Unsupported value type for operation");
13610
13611   unsigned NumElems = VT.getVectorNumElements();
13612   SDLoc dl(Op);
13613   SDValue CC = Op.getOperand(2);
13614
13615   // Extract the LHS vectors
13616   SDValue LHS = Op.getOperand(0);
13617   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13618   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13619
13620   // Extract the RHS vectors
13621   SDValue RHS = Op.getOperand(1);
13622   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13623   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13624
13625   // Issue the operation on the smaller types and concatenate the result back
13626   MVT EltVT = VT.getVectorElementType();
13627   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13628   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13629                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13630                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13631 }
13632
13633 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13634   SDValue Op0 = Op.getOperand(0);
13635   SDValue Op1 = Op.getOperand(1);
13636   SDValue CC = Op.getOperand(2);
13637   MVT VT = Op.getSimpleValueType();
13638   SDLoc dl(Op);
13639
13640   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13641          "Unexpected type for boolean compare operation");
13642   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13643   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13644                                DAG.getConstant(-1, dl, VT));
13645   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13646                                DAG.getConstant(-1, dl, VT));
13647   switch (SetCCOpcode) {
13648   default: llvm_unreachable("Unexpected SETCC condition");
13649   case ISD::SETEQ:
13650     // (x == y) -> ~(x ^ y)
13651     return DAG.getNode(ISD::XOR, dl, VT,
13652                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13653                        DAG.getConstant(-1, dl, VT));
13654   case ISD::SETNE:
13655     // (x != y) -> (x ^ y)
13656     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13657   case ISD::SETUGT:
13658   case ISD::SETGT:
13659     // (x > y) -> (x & ~y)
13660     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13661   case ISD::SETULT:
13662   case ISD::SETLT:
13663     // (x < y) -> (~x & y)
13664     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13665   case ISD::SETULE:
13666   case ISD::SETLE:
13667     // (x <= y) -> (~x | y)
13668     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13669   case ISD::SETUGE:
13670   case ISD::SETGE:
13671     // (x >=y) -> (x | ~y)
13672     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13673   }
13674 }
13675
13676 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13677                                      const X86Subtarget *Subtarget) {
13678   SDValue Op0 = Op.getOperand(0);
13679   SDValue Op1 = Op.getOperand(1);
13680   SDValue CC = Op.getOperand(2);
13681   MVT VT = Op.getSimpleValueType();
13682   SDLoc dl(Op);
13683
13684   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13685          Op.getValueType().getScalarType() == MVT::i1 &&
13686          "Cannot set masked compare for this operation");
13687
13688   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13689   unsigned  Opc = 0;
13690   bool Unsigned = false;
13691   bool Swap = false;
13692   unsigned SSECC;
13693   switch (SetCCOpcode) {
13694   default: llvm_unreachable("Unexpected SETCC condition");
13695   case ISD::SETNE:  SSECC = 4; break;
13696   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13697   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13698   case ISD::SETLT:  Swap = true; //fall-through
13699   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13700   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13701   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13702   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13703   case ISD::SETULE: Unsigned = true; //fall-through
13704   case ISD::SETLE:  SSECC = 2; break;
13705   }
13706
13707   if (Swap)
13708     std::swap(Op0, Op1);
13709   if (Opc)
13710     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13711   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13712   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13713                      DAG.getConstant(SSECC, dl, MVT::i8));
13714 }
13715
13716 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13717 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13718 /// return an empty value.
13719 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13720 {
13721   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13722   if (!BV)
13723     return SDValue();
13724
13725   MVT VT = Op1.getSimpleValueType();
13726   MVT EVT = VT.getVectorElementType();
13727   unsigned n = VT.getVectorNumElements();
13728   SmallVector<SDValue, 8> ULTOp1;
13729
13730   for (unsigned i = 0; i < n; ++i) {
13731     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13732     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13733       return SDValue();
13734
13735     // Avoid underflow.
13736     APInt Val = Elt->getAPIntValue();
13737     if (Val == 0)
13738       return SDValue();
13739
13740     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13741   }
13742
13743   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13744 }
13745
13746 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13747                            SelectionDAG &DAG) {
13748   SDValue Op0 = Op.getOperand(0);
13749   SDValue Op1 = Op.getOperand(1);
13750   SDValue CC = Op.getOperand(2);
13751   MVT VT = Op.getSimpleValueType();
13752   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13753   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13754   SDLoc dl(Op);
13755
13756   if (isFP) {
13757 #ifndef NDEBUG
13758     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13759     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13760 #endif
13761
13762     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13763     unsigned Opc = X86ISD::CMPP;
13764     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13765       assert(VT.getVectorNumElements() <= 16);
13766       Opc = X86ISD::CMPM;
13767     }
13768     // In the two special cases we can't handle, emit two comparisons.
13769     if (SSECC == 8) {
13770       unsigned CC0, CC1;
13771       unsigned CombineOpc;
13772       if (SetCCOpcode == ISD::SETUEQ) {
13773         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13774       } else {
13775         assert(SetCCOpcode == ISD::SETONE);
13776         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13777       }
13778
13779       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13780                                  DAG.getConstant(CC0, dl, MVT::i8));
13781       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13782                                  DAG.getConstant(CC1, dl, MVT::i8));
13783       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13784     }
13785     // Handle all other FP comparisons here.
13786     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13787                        DAG.getConstant(SSECC, dl, MVT::i8));
13788   }
13789
13790   // Break 256-bit integer vector compare into smaller ones.
13791   if (VT.is256BitVector() && !Subtarget->hasInt256())
13792     return Lower256IntVSETCC(Op, DAG);
13793
13794   EVT OpVT = Op1.getValueType();
13795   if (OpVT.getVectorElementType() == MVT::i1)
13796     return LowerBoolVSETCC_AVX512(Op, DAG);
13797
13798   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13799   if (Subtarget->hasAVX512()) {
13800     if (Op1.getValueType().is512BitVector() ||
13801         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13802         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13803       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13804
13805     // In AVX-512 architecture setcc returns mask with i1 elements,
13806     // But there is no compare instruction for i8 and i16 elements in KNL.
13807     // We are not talking about 512-bit operands in this case, these
13808     // types are illegal.
13809     if (MaskResult &&
13810         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13811          OpVT.getVectorElementType().getSizeInBits() >= 8))
13812       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13813                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13814   }
13815
13816   // We are handling one of the integer comparisons here.  Since SSE only has
13817   // GT and EQ comparisons for integer, swapping operands and multiple
13818   // operations may be required for some comparisons.
13819   unsigned Opc;
13820   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13821   bool Subus = false;
13822
13823   switch (SetCCOpcode) {
13824   default: llvm_unreachable("Unexpected SETCC condition");
13825   case ISD::SETNE:  Invert = true;
13826   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13827   case ISD::SETLT:  Swap = true;
13828   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13829   case ISD::SETGE:  Swap = true;
13830   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13831                     Invert = true; break;
13832   case ISD::SETULT: Swap = true;
13833   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13834                     FlipSigns = true; break;
13835   case ISD::SETUGE: Swap = true;
13836   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13837                     FlipSigns = true; Invert = true; break;
13838   }
13839
13840   // Special case: Use min/max operations for SETULE/SETUGE
13841   MVT VET = VT.getVectorElementType();
13842   bool hasMinMax =
13843        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13844     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13845
13846   if (hasMinMax) {
13847     switch (SetCCOpcode) {
13848     default: break;
13849     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13850     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13851     }
13852
13853     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13854   }
13855
13856   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13857   if (!MinMax && hasSubus) {
13858     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13859     // Op0 u<= Op1:
13860     //   t = psubus Op0, Op1
13861     //   pcmpeq t, <0..0>
13862     switch (SetCCOpcode) {
13863     default: break;
13864     case ISD::SETULT: {
13865       // If the comparison is against a constant we can turn this into a
13866       // setule.  With psubus, setule does not require a swap.  This is
13867       // beneficial because the constant in the register is no longer
13868       // destructed as the destination so it can be hoisted out of a loop.
13869       // Only do this pre-AVX since vpcmp* is no longer destructive.
13870       if (Subtarget->hasAVX())
13871         break;
13872       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13873       if (ULEOp1.getNode()) {
13874         Op1 = ULEOp1;
13875         Subus = true; Invert = false; Swap = false;
13876       }
13877       break;
13878     }
13879     // Psubus is better than flip-sign because it requires no inversion.
13880     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13881     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13882     }
13883
13884     if (Subus) {
13885       Opc = X86ISD::SUBUS;
13886       FlipSigns = false;
13887     }
13888   }
13889
13890   if (Swap)
13891     std::swap(Op0, Op1);
13892
13893   // Check that the operation in question is available (most are plain SSE2,
13894   // but PCMPGTQ and PCMPEQQ have different requirements).
13895   if (VT == MVT::v2i64) {
13896     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13897       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13898
13899       // First cast everything to the right type.
13900       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13901       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13902
13903       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13904       // bits of the inputs before performing those operations. The lower
13905       // compare is always unsigned.
13906       SDValue SB;
13907       if (FlipSigns) {
13908         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13909       } else {
13910         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13911         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13912         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13913                          Sign, Zero, Sign, Zero);
13914       }
13915       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13916       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13917
13918       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13919       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13920       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13921
13922       // Create masks for only the low parts/high parts of the 64 bit integers.
13923       static const int MaskHi[] = { 1, 1, 3, 3 };
13924       static const int MaskLo[] = { 0, 0, 2, 2 };
13925       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13926       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13927       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13928
13929       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13930       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13931
13932       if (Invert)
13933         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13934
13935       return DAG.getBitcast(VT, Result);
13936     }
13937
13938     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13939       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13940       // pcmpeqd + pshufd + pand.
13941       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13942
13943       // First cast everything to the right type.
13944       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13945       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13946
13947       // Do the compare.
13948       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13949
13950       // Make sure the lower and upper halves are both all-ones.
13951       static const int Mask[] = { 1, 0, 3, 2 };
13952       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13953       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13954
13955       if (Invert)
13956         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13957
13958       return DAG.getBitcast(VT, Result);
13959     }
13960   }
13961
13962   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13963   // bits of the inputs before performing those operations.
13964   if (FlipSigns) {
13965     EVT EltVT = VT.getVectorElementType();
13966     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13967                                  VT);
13968     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13969     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13970   }
13971
13972   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13973
13974   // If the logical-not of the result is required, perform that now.
13975   if (Invert)
13976     Result = DAG.getNOT(dl, Result, VT);
13977
13978   if (MinMax)
13979     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13980
13981   if (Subus)
13982     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13983                          getZeroVector(VT, Subtarget, DAG, dl));
13984
13985   return Result;
13986 }
13987
13988 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13989
13990   MVT VT = Op.getSimpleValueType();
13991
13992   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13993
13994   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13995          && "SetCC type must be 8-bit or 1-bit integer");
13996   SDValue Op0 = Op.getOperand(0);
13997   SDValue Op1 = Op.getOperand(1);
13998   SDLoc dl(Op);
13999   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14000
14001   // Optimize to BT if possible.
14002   // Lower (X & (1 << N)) == 0 to BT(X, N).
14003   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14004   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14005   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14006       Op1.getOpcode() == ISD::Constant &&
14007       cast<ConstantSDNode>(Op1)->isNullValue() &&
14008       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14009     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14010     if (NewSetCC.getNode()) {
14011       if (VT == MVT::i1)
14012         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14013       return NewSetCC;
14014     }
14015   }
14016
14017   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14018   // these.
14019   if (Op1.getOpcode() == ISD::Constant &&
14020       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14021        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14022       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14023
14024     // If the input is a setcc, then reuse the input setcc or use a new one with
14025     // the inverted condition.
14026     if (Op0.getOpcode() == X86ISD::SETCC) {
14027       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14028       bool Invert = (CC == ISD::SETNE) ^
14029         cast<ConstantSDNode>(Op1)->isNullValue();
14030       if (!Invert)
14031         return Op0;
14032
14033       CCode = X86::GetOppositeBranchCondition(CCode);
14034       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14035                                   DAG.getConstant(CCode, dl, MVT::i8),
14036                                   Op0.getOperand(1));
14037       if (VT == MVT::i1)
14038         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14039       return SetCC;
14040     }
14041   }
14042   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14043       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14044       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14045
14046     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14047     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14048   }
14049
14050   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14051   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14052   if (X86CC == X86::COND_INVALID)
14053     return SDValue();
14054
14055   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14056   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14057   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14058                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14059   if (VT == MVT::i1)
14060     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14061   return SetCC;
14062 }
14063
14064 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14065 static bool isX86LogicalCmp(SDValue Op) {
14066   unsigned Opc = Op.getNode()->getOpcode();
14067   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14068       Opc == X86ISD::SAHF)
14069     return true;
14070   if (Op.getResNo() == 1 &&
14071       (Opc == X86ISD::ADD ||
14072        Opc == X86ISD::SUB ||
14073        Opc == X86ISD::ADC ||
14074        Opc == X86ISD::SBB ||
14075        Opc == X86ISD::SMUL ||
14076        Opc == X86ISD::UMUL ||
14077        Opc == X86ISD::INC ||
14078        Opc == X86ISD::DEC ||
14079        Opc == X86ISD::OR ||
14080        Opc == X86ISD::XOR ||
14081        Opc == X86ISD::AND))
14082     return true;
14083
14084   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14085     return true;
14086
14087   return false;
14088 }
14089
14090 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14091   if (V.getOpcode() != ISD::TRUNCATE)
14092     return false;
14093
14094   SDValue VOp0 = V.getOperand(0);
14095   unsigned InBits = VOp0.getValueSizeInBits();
14096   unsigned Bits = V.getValueSizeInBits();
14097   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14098 }
14099
14100 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14101   bool addTest = true;
14102   SDValue Cond  = Op.getOperand(0);
14103   SDValue Op1 = Op.getOperand(1);
14104   SDValue Op2 = Op.getOperand(2);
14105   SDLoc DL(Op);
14106   EVT VT = Op1.getValueType();
14107   SDValue CC;
14108
14109   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14110   // are available or VBLENDV if AVX is available.
14111   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14112   if (Cond.getOpcode() == ISD::SETCC &&
14113       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14114        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14115       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14116     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14117     int SSECC = translateX86FSETCC(
14118         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14119
14120     if (SSECC != 8) {
14121       if (Subtarget->hasAVX512()) {
14122         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14123                                   DAG.getConstant(SSECC, DL, MVT::i8));
14124         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14125       }
14126
14127       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14128                                 DAG.getConstant(SSECC, DL, MVT::i8));
14129
14130       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14131       // of 3 logic instructions for size savings and potentially speed.
14132       // Unfortunately, there is no scalar form of VBLENDV.
14133
14134       // If either operand is a constant, don't try this. We can expect to
14135       // optimize away at least one of the logic instructions later in that
14136       // case, so that sequence would be faster than a variable blend.
14137
14138       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14139       // uses XMM0 as the selection register. That may need just as many
14140       // instructions as the AND/ANDN/OR sequence due to register moves, so
14141       // don't bother.
14142
14143       if (Subtarget->hasAVX() &&
14144           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14145
14146         // Convert to vectors, do a VSELECT, and convert back to scalar.
14147         // All of the conversions should be optimized away.
14148
14149         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14150         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14151         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14152         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14153
14154         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14155         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14156
14157         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14158
14159         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14160                            VSel, DAG.getIntPtrConstant(0, DL));
14161       }
14162       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14163       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14164       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14165     }
14166   }
14167
14168   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14169     SDValue Op1Scalar;
14170     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14171       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14172     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14173       Op1Scalar = Op1.getOperand(0);
14174     SDValue Op2Scalar;
14175     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14176       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14177     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14178       Op2Scalar = Op2.getOperand(0);
14179     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14180       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14181                                       Op1Scalar.getValueType(),
14182                                       Cond, Op1Scalar, Op2Scalar);
14183       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14184         return DAG.getBitcast(VT, newSelect);
14185       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14186       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14187                          DAG.getIntPtrConstant(0, DL));
14188     }
14189   }
14190
14191   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14192     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14193     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14194                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14195     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14196                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14197     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14198                                     Cond, Op1, Op2);
14199     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14200   }
14201
14202   if (Cond.getOpcode() == ISD::SETCC) {
14203     SDValue NewCond = LowerSETCC(Cond, DAG);
14204     if (NewCond.getNode())
14205       Cond = NewCond;
14206   }
14207
14208   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14209   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14210   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14211   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14212   if (Cond.getOpcode() == X86ISD::SETCC &&
14213       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14214       isZero(Cond.getOperand(1).getOperand(1))) {
14215     SDValue Cmp = Cond.getOperand(1);
14216
14217     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14218
14219     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14220         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14221       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14222
14223       SDValue CmpOp0 = Cmp.getOperand(0);
14224       // Apply further optimizations for special cases
14225       // (select (x != 0), -1, 0) -> neg & sbb
14226       // (select (x == 0), 0, -1) -> neg & sbb
14227       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14228         if (YC->isNullValue() &&
14229             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14230           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14231           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14232                                     DAG.getConstant(0, DL,
14233                                                     CmpOp0.getValueType()),
14234                                     CmpOp0);
14235           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14236                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14237                                     SDValue(Neg.getNode(), 1));
14238           return Res;
14239         }
14240
14241       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14242                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14243       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14244
14245       SDValue Res =   // Res = 0 or -1.
14246         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14247                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14248
14249       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14250         Res = DAG.getNOT(DL, Res, Res.getValueType());
14251
14252       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14253       if (!N2C || !N2C->isNullValue())
14254         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14255       return Res;
14256     }
14257   }
14258
14259   // Look past (and (setcc_carry (cmp ...)), 1).
14260   if (Cond.getOpcode() == ISD::AND &&
14261       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14262     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14263     if (C && C->getAPIntValue() == 1)
14264       Cond = Cond.getOperand(0);
14265   }
14266
14267   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14268   // setting operand in place of the X86ISD::SETCC.
14269   unsigned CondOpcode = Cond.getOpcode();
14270   if (CondOpcode == X86ISD::SETCC ||
14271       CondOpcode == X86ISD::SETCC_CARRY) {
14272     CC = Cond.getOperand(0);
14273
14274     SDValue Cmp = Cond.getOperand(1);
14275     unsigned Opc = Cmp.getOpcode();
14276     MVT VT = Op.getSimpleValueType();
14277
14278     bool IllegalFPCMov = false;
14279     if (VT.isFloatingPoint() && !VT.isVector() &&
14280         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14281       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14282
14283     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14284         Opc == X86ISD::BT) { // FIXME
14285       Cond = Cmp;
14286       addTest = false;
14287     }
14288   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14289              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14290              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14291               Cond.getOperand(0).getValueType() != MVT::i8)) {
14292     SDValue LHS = Cond.getOperand(0);
14293     SDValue RHS = Cond.getOperand(1);
14294     unsigned X86Opcode;
14295     unsigned X86Cond;
14296     SDVTList VTs;
14297     switch (CondOpcode) {
14298     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14299     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14300     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14301     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14302     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14303     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14304     default: llvm_unreachable("unexpected overflowing operator");
14305     }
14306     if (CondOpcode == ISD::UMULO)
14307       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14308                           MVT::i32);
14309     else
14310       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14311
14312     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14313
14314     if (CondOpcode == ISD::UMULO)
14315       Cond = X86Op.getValue(2);
14316     else
14317       Cond = X86Op.getValue(1);
14318
14319     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14320     addTest = false;
14321   }
14322
14323   if (addTest) {
14324     // Look past the truncate if the high bits are known zero.
14325     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14326       Cond = Cond.getOperand(0);
14327
14328     // We know the result of AND is compared against zero. Try to match
14329     // it to BT.
14330     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14331       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14332       if (NewSetCC.getNode()) {
14333         CC = NewSetCC.getOperand(0);
14334         Cond = NewSetCC.getOperand(1);
14335         addTest = false;
14336       }
14337     }
14338   }
14339
14340   if (addTest) {
14341     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14342     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14343   }
14344
14345   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14346   // a <  b ?  0 : -1 -> RES = setcc_carry
14347   // a >= b ? -1 :  0 -> RES = setcc_carry
14348   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14349   if (Cond.getOpcode() == X86ISD::SUB) {
14350     Cond = ConvertCmpIfNecessary(Cond, DAG);
14351     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14352
14353     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14354         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14355       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14356                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14357                                 Cond);
14358       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14359         return DAG.getNOT(DL, Res, Res.getValueType());
14360       return Res;
14361     }
14362   }
14363
14364   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14365   // widen the cmov and push the truncate through. This avoids introducing a new
14366   // branch during isel and doesn't add any extensions.
14367   if (Op.getValueType() == MVT::i8 &&
14368       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14369     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14370     if (T1.getValueType() == T2.getValueType() &&
14371         // Blacklist CopyFromReg to avoid partial register stalls.
14372         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14373       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14374       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14375       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14376     }
14377   }
14378
14379   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14380   // condition is true.
14381   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14382   SDValue Ops[] = { Op2, Op1, CC, Cond };
14383   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14384 }
14385
14386 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14387                                        const X86Subtarget *Subtarget,
14388                                        SelectionDAG &DAG) {
14389   MVT VT = Op->getSimpleValueType(0);
14390   SDValue In = Op->getOperand(0);
14391   MVT InVT = In.getSimpleValueType();
14392   MVT VTElt = VT.getVectorElementType();
14393   MVT InVTElt = InVT.getVectorElementType();
14394   SDLoc dl(Op);
14395
14396   // SKX processor
14397   if ((InVTElt == MVT::i1) &&
14398       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14399         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14400
14401        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14402         VTElt.getSizeInBits() <= 16)) ||
14403
14404        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14405         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14406
14407        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14408         VTElt.getSizeInBits() >= 32))))
14409     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14410
14411   unsigned int NumElts = VT.getVectorNumElements();
14412
14413   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14414     return SDValue();
14415
14416   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14417     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14418       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14419     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14420   }
14421
14422   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14423   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14424   SDValue NegOne =
14425    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14426                    ExtVT);
14427   SDValue Zero =
14428    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14429
14430   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14431   if (VT.is512BitVector())
14432     return V;
14433   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14434 }
14435
14436 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14437                                              const X86Subtarget *Subtarget,
14438                                              SelectionDAG &DAG) {
14439   SDValue In = Op->getOperand(0);
14440   MVT VT = Op->getSimpleValueType(0);
14441   MVT InVT = In.getSimpleValueType();
14442   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14443
14444   MVT InSVT = InVT.getScalarType();
14445   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14446
14447   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14448     return SDValue();
14449   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14450     return SDValue();
14451
14452   SDLoc dl(Op);
14453
14454   // SSE41 targets can use the pmovsx* instructions directly.
14455   if (Subtarget->hasSSE41())
14456     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14457
14458   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14459   SDValue Curr = In;
14460   MVT CurrVT = InVT;
14461
14462   // As SRAI is only available on i16/i32 types, we expand only up to i32
14463   // and handle i64 separately.
14464   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14465     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14466     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14467     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14468     Curr = DAG.getBitcast(CurrVT, Curr);
14469   }
14470
14471   SDValue SignExt = Curr;
14472   if (CurrVT != InVT) {
14473     unsigned SignExtShift =
14474         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14475     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14476                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14477   }
14478
14479   if (CurrVT == VT)
14480     return SignExt;
14481
14482   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14483     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14484                                DAG.getConstant(31, dl, MVT::i8));
14485     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14486     return DAG.getBitcast(VT, Ext);
14487   }
14488
14489   return SDValue();
14490 }
14491
14492 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14493                                 SelectionDAG &DAG) {
14494   MVT VT = Op->getSimpleValueType(0);
14495   SDValue In = Op->getOperand(0);
14496   MVT InVT = In.getSimpleValueType();
14497   SDLoc dl(Op);
14498
14499   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14500     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14501
14502   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14503       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14504       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14505     return SDValue();
14506
14507   if (Subtarget->hasInt256())
14508     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14509
14510   // Optimize vectors in AVX mode
14511   // Sign extend  v8i16 to v8i32 and
14512   //              v4i32 to v4i64
14513   //
14514   // Divide input vector into two parts
14515   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14516   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14517   // concat the vectors to original VT
14518
14519   unsigned NumElems = InVT.getVectorNumElements();
14520   SDValue Undef = DAG.getUNDEF(InVT);
14521
14522   SmallVector<int,8> ShufMask1(NumElems, -1);
14523   for (unsigned i = 0; i != NumElems/2; ++i)
14524     ShufMask1[i] = i;
14525
14526   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14527
14528   SmallVector<int,8> ShufMask2(NumElems, -1);
14529   for (unsigned i = 0; i != NumElems/2; ++i)
14530     ShufMask2[i] = i + NumElems/2;
14531
14532   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14533
14534   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14535                                 VT.getVectorNumElements()/2);
14536
14537   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14538   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14539
14540   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14541 }
14542
14543 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14544 // may emit an illegal shuffle but the expansion is still better than scalar
14545 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14546 // we'll emit a shuffle and a arithmetic shift.
14547 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14548 // TODO: It is possible to support ZExt by zeroing the undef values during
14549 // the shuffle phase or after the shuffle.
14550 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14551                                  SelectionDAG &DAG) {
14552   MVT RegVT = Op.getSimpleValueType();
14553   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14554   assert(RegVT.isInteger() &&
14555          "We only custom lower integer vector sext loads.");
14556
14557   // Nothing useful we can do without SSE2 shuffles.
14558   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14559
14560   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14561   SDLoc dl(Ld);
14562   EVT MemVT = Ld->getMemoryVT();
14563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14564   unsigned RegSz = RegVT.getSizeInBits();
14565
14566   ISD::LoadExtType Ext = Ld->getExtensionType();
14567
14568   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14569          && "Only anyext and sext are currently implemented.");
14570   assert(MemVT != RegVT && "Cannot extend to the same type");
14571   assert(MemVT.isVector() && "Must load a vector from memory");
14572
14573   unsigned NumElems = RegVT.getVectorNumElements();
14574   unsigned MemSz = MemVT.getSizeInBits();
14575   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14576
14577   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14578     // The only way in which we have a legal 256-bit vector result but not the
14579     // integer 256-bit operations needed to directly lower a sextload is if we
14580     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14581     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14582     // correctly legalized. We do this late to allow the canonical form of
14583     // sextload to persist throughout the rest of the DAG combiner -- it wants
14584     // to fold together any extensions it can, and so will fuse a sign_extend
14585     // of an sextload into a sextload targeting a wider value.
14586     SDValue Load;
14587     if (MemSz == 128) {
14588       // Just switch this to a normal load.
14589       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14590                                        "it must be a legal 128-bit vector "
14591                                        "type!");
14592       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14593                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14594                   Ld->isInvariant(), Ld->getAlignment());
14595     } else {
14596       assert(MemSz < 128 &&
14597              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14598       // Do an sext load to a 128-bit vector type. We want to use the same
14599       // number of elements, but elements half as wide. This will end up being
14600       // recursively lowered by this routine, but will succeed as we definitely
14601       // have all the necessary features if we're using AVX1.
14602       EVT HalfEltVT =
14603           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14604       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14605       Load =
14606           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14607                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14608                          Ld->isNonTemporal(), Ld->isInvariant(),
14609                          Ld->getAlignment());
14610     }
14611
14612     // Replace chain users with the new chain.
14613     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14614     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14615
14616     // Finally, do a normal sign-extend to the desired register.
14617     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14618   }
14619
14620   // All sizes must be a power of two.
14621   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14622          "Non-power-of-two elements are not custom lowered!");
14623
14624   // Attempt to load the original value using scalar loads.
14625   // Find the largest scalar type that divides the total loaded size.
14626   MVT SclrLoadTy = MVT::i8;
14627   for (MVT Tp : MVT::integer_valuetypes()) {
14628     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14629       SclrLoadTy = Tp;
14630     }
14631   }
14632
14633   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14634   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14635       (64 <= MemSz))
14636     SclrLoadTy = MVT::f64;
14637
14638   // Calculate the number of scalar loads that we need to perform
14639   // in order to load our vector from memory.
14640   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14641
14642   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14643          "Can only lower sext loads with a single scalar load!");
14644
14645   unsigned loadRegZize = RegSz;
14646   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14647     loadRegZize = 128;
14648
14649   // Represent our vector as a sequence of elements which are the
14650   // largest scalar that we can load.
14651   EVT LoadUnitVecVT = EVT::getVectorVT(
14652       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14653
14654   // Represent the data using the same element type that is stored in
14655   // memory. In practice, we ''widen'' MemVT.
14656   EVT WideVecVT =
14657       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14658                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14659
14660   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14661          "Invalid vector type");
14662
14663   // We can't shuffle using an illegal type.
14664   assert(TLI.isTypeLegal(WideVecVT) &&
14665          "We only lower types that form legal widened vector types");
14666
14667   SmallVector<SDValue, 8> Chains;
14668   SDValue Ptr = Ld->getBasePtr();
14669   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14670                                       TLI.getPointerTy(DAG.getDataLayout()));
14671   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14672
14673   for (unsigned i = 0; i < NumLoads; ++i) {
14674     // Perform a single load.
14675     SDValue ScalarLoad =
14676         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14677                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14678                     Ld->getAlignment());
14679     Chains.push_back(ScalarLoad.getValue(1));
14680     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14681     // another round of DAGCombining.
14682     if (i == 0)
14683       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14684     else
14685       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14686                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14687
14688     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14689   }
14690
14691   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14692
14693   // Bitcast the loaded value to a vector of the original element type, in
14694   // the size of the target vector type.
14695   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14696   unsigned SizeRatio = RegSz / MemSz;
14697
14698   if (Ext == ISD::SEXTLOAD) {
14699     // If we have SSE4.1, we can directly emit a VSEXT node.
14700     if (Subtarget->hasSSE41()) {
14701       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14702       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14703       return Sext;
14704     }
14705
14706     // Otherwise we'll shuffle the small elements in the high bits of the
14707     // larger type and perform an arithmetic shift. If the shift is not legal
14708     // it's better to scalarize.
14709     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14710            "We can't implement a sext load without an arithmetic right shift!");
14711
14712     // Redistribute the loaded elements into the different locations.
14713     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14714     for (unsigned i = 0; i != NumElems; ++i)
14715       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14716
14717     SDValue Shuff = DAG.getVectorShuffle(
14718         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14719
14720     Shuff = DAG.getBitcast(RegVT, Shuff);
14721
14722     // Build the arithmetic shift.
14723     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14724                    MemVT.getVectorElementType().getSizeInBits();
14725     Shuff =
14726         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14727                     DAG.getConstant(Amt, dl, RegVT));
14728
14729     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14730     return Shuff;
14731   }
14732
14733   // Redistribute the loaded elements into the different locations.
14734   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14735   for (unsigned i = 0; i != NumElems; ++i)
14736     ShuffleVec[i * SizeRatio] = i;
14737
14738   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14739                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14740
14741   // Bitcast to the requested type.
14742   Shuff = DAG.getBitcast(RegVT, Shuff);
14743   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14744   return Shuff;
14745 }
14746
14747 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14748 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14749 // from the AND / OR.
14750 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14751   Opc = Op.getOpcode();
14752   if (Opc != ISD::OR && Opc != ISD::AND)
14753     return false;
14754   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14755           Op.getOperand(0).hasOneUse() &&
14756           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14757           Op.getOperand(1).hasOneUse());
14758 }
14759
14760 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14761 // 1 and that the SETCC node has a single use.
14762 static bool isXor1OfSetCC(SDValue Op) {
14763   if (Op.getOpcode() != ISD::XOR)
14764     return false;
14765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14766   if (N1C && N1C->getAPIntValue() == 1) {
14767     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14768       Op.getOperand(0).hasOneUse();
14769   }
14770   return false;
14771 }
14772
14773 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14774   bool addTest = true;
14775   SDValue Chain = Op.getOperand(0);
14776   SDValue Cond  = Op.getOperand(1);
14777   SDValue Dest  = Op.getOperand(2);
14778   SDLoc dl(Op);
14779   SDValue CC;
14780   bool Inverted = false;
14781
14782   if (Cond.getOpcode() == ISD::SETCC) {
14783     // Check for setcc([su]{add,sub,mul}o == 0).
14784     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14785         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14786         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14787         Cond.getOperand(0).getResNo() == 1 &&
14788         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14789          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14790          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14791          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14792          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14793          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14794       Inverted = true;
14795       Cond = Cond.getOperand(0);
14796     } else {
14797       SDValue NewCond = LowerSETCC(Cond, DAG);
14798       if (NewCond.getNode())
14799         Cond = NewCond;
14800     }
14801   }
14802 #if 0
14803   // FIXME: LowerXALUO doesn't handle these!!
14804   else if (Cond.getOpcode() == X86ISD::ADD  ||
14805            Cond.getOpcode() == X86ISD::SUB  ||
14806            Cond.getOpcode() == X86ISD::SMUL ||
14807            Cond.getOpcode() == X86ISD::UMUL)
14808     Cond = LowerXALUO(Cond, DAG);
14809 #endif
14810
14811   // Look pass (and (setcc_carry (cmp ...)), 1).
14812   if (Cond.getOpcode() == ISD::AND &&
14813       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14814     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14815     if (C && C->getAPIntValue() == 1)
14816       Cond = Cond.getOperand(0);
14817   }
14818
14819   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14820   // setting operand in place of the X86ISD::SETCC.
14821   unsigned CondOpcode = Cond.getOpcode();
14822   if (CondOpcode == X86ISD::SETCC ||
14823       CondOpcode == X86ISD::SETCC_CARRY) {
14824     CC = Cond.getOperand(0);
14825
14826     SDValue Cmp = Cond.getOperand(1);
14827     unsigned Opc = Cmp.getOpcode();
14828     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14829     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14830       Cond = Cmp;
14831       addTest = false;
14832     } else {
14833       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14834       default: break;
14835       case X86::COND_O:
14836       case X86::COND_B:
14837         // These can only come from an arithmetic instruction with overflow,
14838         // e.g. SADDO, UADDO.
14839         Cond = Cond.getNode()->getOperand(1);
14840         addTest = false;
14841         break;
14842       }
14843     }
14844   }
14845   CondOpcode = Cond.getOpcode();
14846   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14847       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14848       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14849        Cond.getOperand(0).getValueType() != MVT::i8)) {
14850     SDValue LHS = Cond.getOperand(0);
14851     SDValue RHS = Cond.getOperand(1);
14852     unsigned X86Opcode;
14853     unsigned X86Cond;
14854     SDVTList VTs;
14855     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14856     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14857     // X86ISD::INC).
14858     switch (CondOpcode) {
14859     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14860     case ISD::SADDO:
14861       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14862         if (C->isOne()) {
14863           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14864           break;
14865         }
14866       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14867     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14868     case ISD::SSUBO:
14869       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14870         if (C->isOne()) {
14871           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14872           break;
14873         }
14874       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14875     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14876     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14877     default: llvm_unreachable("unexpected overflowing operator");
14878     }
14879     if (Inverted)
14880       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14881     if (CondOpcode == ISD::UMULO)
14882       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14883                           MVT::i32);
14884     else
14885       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14886
14887     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14888
14889     if (CondOpcode == ISD::UMULO)
14890       Cond = X86Op.getValue(2);
14891     else
14892       Cond = X86Op.getValue(1);
14893
14894     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14895     addTest = false;
14896   } else {
14897     unsigned CondOpc;
14898     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14899       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14900       if (CondOpc == ISD::OR) {
14901         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14902         // two branches instead of an explicit OR instruction with a
14903         // separate test.
14904         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14905             isX86LogicalCmp(Cmp)) {
14906           CC = Cond.getOperand(0).getOperand(0);
14907           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14908                               Chain, Dest, CC, Cmp);
14909           CC = Cond.getOperand(1).getOperand(0);
14910           Cond = Cmp;
14911           addTest = false;
14912         }
14913       } else { // ISD::AND
14914         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14915         // two branches instead of an explicit AND instruction with a
14916         // separate test. However, we only do this if this block doesn't
14917         // have a fall-through edge, because this requires an explicit
14918         // jmp when the condition is false.
14919         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14920             isX86LogicalCmp(Cmp) &&
14921             Op.getNode()->hasOneUse()) {
14922           X86::CondCode CCode =
14923             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14924           CCode = X86::GetOppositeBranchCondition(CCode);
14925           CC = DAG.getConstant(CCode, dl, MVT::i8);
14926           SDNode *User = *Op.getNode()->use_begin();
14927           // Look for an unconditional branch following this conditional branch.
14928           // We need this because we need to reverse the successors in order
14929           // to implement FCMP_OEQ.
14930           if (User->getOpcode() == ISD::BR) {
14931             SDValue FalseBB = User->getOperand(1);
14932             SDNode *NewBR =
14933               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14934             assert(NewBR == User);
14935             (void)NewBR;
14936             Dest = FalseBB;
14937
14938             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14939                                 Chain, Dest, CC, Cmp);
14940             X86::CondCode CCode =
14941               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14942             CCode = X86::GetOppositeBranchCondition(CCode);
14943             CC = DAG.getConstant(CCode, dl, MVT::i8);
14944             Cond = Cmp;
14945             addTest = false;
14946           }
14947         }
14948       }
14949     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14950       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14951       // It should be transformed during dag combiner except when the condition
14952       // is set by a arithmetics with overflow node.
14953       X86::CondCode CCode =
14954         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14955       CCode = X86::GetOppositeBranchCondition(CCode);
14956       CC = DAG.getConstant(CCode, dl, MVT::i8);
14957       Cond = Cond.getOperand(0).getOperand(1);
14958       addTest = false;
14959     } else if (Cond.getOpcode() == ISD::SETCC &&
14960                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14961       // For FCMP_OEQ, we can emit
14962       // two branches instead of an explicit AND instruction with a
14963       // separate test. However, we only do this if this block doesn't
14964       // have a fall-through edge, because this requires an explicit
14965       // jmp when the condition is false.
14966       if (Op.getNode()->hasOneUse()) {
14967         SDNode *User = *Op.getNode()->use_begin();
14968         // Look for an unconditional branch following this conditional branch.
14969         // We need this because we need to reverse the successors in order
14970         // to implement FCMP_OEQ.
14971         if (User->getOpcode() == ISD::BR) {
14972           SDValue FalseBB = User->getOperand(1);
14973           SDNode *NewBR =
14974             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14975           assert(NewBR == User);
14976           (void)NewBR;
14977           Dest = FalseBB;
14978
14979           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14980                                     Cond.getOperand(0), Cond.getOperand(1));
14981           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14982           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14983           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14984                               Chain, Dest, CC, Cmp);
14985           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14986           Cond = Cmp;
14987           addTest = false;
14988         }
14989       }
14990     } else if (Cond.getOpcode() == ISD::SETCC &&
14991                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14992       // For FCMP_UNE, we can emit
14993       // two branches instead of an explicit AND instruction with a
14994       // separate test. However, we only do this if this block doesn't
14995       // have a fall-through edge, because this requires an explicit
14996       // jmp when the condition is false.
14997       if (Op.getNode()->hasOneUse()) {
14998         SDNode *User = *Op.getNode()->use_begin();
14999         // Look for an unconditional branch following this conditional branch.
15000         // We need this because we need to reverse the successors in order
15001         // to implement FCMP_UNE.
15002         if (User->getOpcode() == ISD::BR) {
15003           SDValue FalseBB = User->getOperand(1);
15004           SDNode *NewBR =
15005             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15006           assert(NewBR == User);
15007           (void)NewBR;
15008
15009           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15010                                     Cond.getOperand(0), Cond.getOperand(1));
15011           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15012           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15013           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15014                               Chain, Dest, CC, Cmp);
15015           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15016           Cond = Cmp;
15017           addTest = false;
15018           Dest = FalseBB;
15019         }
15020       }
15021     }
15022   }
15023
15024   if (addTest) {
15025     // Look pass the truncate if the high bits are known zero.
15026     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15027         Cond = Cond.getOperand(0);
15028
15029     // We know the result of AND is compared against zero. Try to match
15030     // it to BT.
15031     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15032       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15033       if (NewSetCC.getNode()) {
15034         CC = NewSetCC.getOperand(0);
15035         Cond = NewSetCC.getOperand(1);
15036         addTest = false;
15037       }
15038     }
15039   }
15040
15041   if (addTest) {
15042     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15043     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15044     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15045   }
15046   Cond = ConvertCmpIfNecessary(Cond, DAG);
15047   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15048                      Chain, Dest, CC, Cond);
15049 }
15050
15051 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15052 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15053 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15054 // that the guard pages used by the OS virtual memory manager are allocated in
15055 // correct sequence.
15056 SDValue
15057 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15058                                            SelectionDAG &DAG) const {
15059   MachineFunction &MF = DAG.getMachineFunction();
15060   bool SplitStack = MF.shouldSplitStack();
15061   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15062                SplitStack;
15063   SDLoc dl(Op);
15064
15065   if (!Lower) {
15066     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15067     SDNode* Node = Op.getNode();
15068
15069     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15070     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15071         " not tell us which reg is the stack pointer!");
15072     EVT VT = Node->getValueType(0);
15073     SDValue Tmp1 = SDValue(Node, 0);
15074     SDValue Tmp2 = SDValue(Node, 1);
15075     SDValue Tmp3 = Node->getOperand(2);
15076     SDValue Chain = Tmp1.getOperand(0);
15077
15078     // Chain the dynamic stack allocation so that it doesn't modify the stack
15079     // pointer when other instructions are using the stack.
15080     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15081         SDLoc(Node));
15082
15083     SDValue Size = Tmp2.getOperand(1);
15084     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15085     Chain = SP.getValue(1);
15086     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15087     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15088     unsigned StackAlign = TFI.getStackAlignment();
15089     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15090     if (Align > StackAlign)
15091       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15092           DAG.getConstant(-(uint64_t)Align, dl, VT));
15093     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15094
15095     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15096         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15097         SDLoc(Node));
15098
15099     SDValue Ops[2] = { Tmp1, Tmp2 };
15100     return DAG.getMergeValues(Ops, dl);
15101   }
15102
15103   // Get the inputs.
15104   SDValue Chain = Op.getOperand(0);
15105   SDValue Size  = Op.getOperand(1);
15106   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15107   EVT VT = Op.getNode()->getValueType(0);
15108
15109   bool Is64Bit = Subtarget->is64Bit();
15110   MVT SPTy = getPointerTy(DAG.getDataLayout());
15111
15112   if (SplitStack) {
15113     MachineRegisterInfo &MRI = MF.getRegInfo();
15114
15115     if (Is64Bit) {
15116       // The 64 bit implementation of segmented stacks needs to clobber both r10
15117       // r11. This makes it impossible to use it along with nested parameters.
15118       const Function *F = MF.getFunction();
15119
15120       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15121            I != E; ++I)
15122         if (I->hasNestAttr())
15123           report_fatal_error("Cannot use segmented stacks with functions that "
15124                              "have nested arguments.");
15125     }
15126
15127     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15128     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15129     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15130     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15131                                 DAG.getRegister(Vreg, SPTy));
15132     SDValue Ops1[2] = { Value, Chain };
15133     return DAG.getMergeValues(Ops1, dl);
15134   } else {
15135     SDValue Flag;
15136     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15137
15138     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15139     Flag = Chain.getValue(1);
15140     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15141
15142     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15143
15144     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15145     unsigned SPReg = RegInfo->getStackRegister();
15146     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15147     Chain = SP.getValue(1);
15148
15149     if (Align) {
15150       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15151                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15152       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15153     }
15154
15155     SDValue Ops1[2] = { SP, Chain };
15156     return DAG.getMergeValues(Ops1, dl);
15157   }
15158 }
15159
15160 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15161   MachineFunction &MF = DAG.getMachineFunction();
15162   auto PtrVT = getPointerTy(MF.getDataLayout());
15163   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15164
15165   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15166   SDLoc DL(Op);
15167
15168   if (!Subtarget->is64Bit() ||
15169       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15170     // vastart just stores the address of the VarArgsFrameIndex slot into the
15171     // memory location argument.
15172     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15173     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15174                         MachinePointerInfo(SV), false, false, 0);
15175   }
15176
15177   // __va_list_tag:
15178   //   gp_offset         (0 - 6 * 8)
15179   //   fp_offset         (48 - 48 + 8 * 16)
15180   //   overflow_arg_area (point to parameters coming in memory).
15181   //   reg_save_area
15182   SmallVector<SDValue, 8> MemOps;
15183   SDValue FIN = Op.getOperand(1);
15184   // Store gp_offset
15185   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15186                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15187                                                DL, MVT::i32),
15188                                FIN, MachinePointerInfo(SV), false, false, 0);
15189   MemOps.push_back(Store);
15190
15191   // Store fp_offset
15192   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15193   Store = DAG.getStore(Op.getOperand(0), DL,
15194                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15195                                        MVT::i32),
15196                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15197   MemOps.push_back(Store);
15198
15199   // Store ptr to overflow_arg_area
15200   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15201   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15202   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15203                        MachinePointerInfo(SV, 8),
15204                        false, false, 0);
15205   MemOps.push_back(Store);
15206
15207   // Store ptr to reg_save_area.
15208   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15209   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15210   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15211                        MachinePointerInfo(SV, 16), false, false, 0);
15212   MemOps.push_back(Store);
15213   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15214 }
15215
15216 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15217   assert(Subtarget->is64Bit() &&
15218          "LowerVAARG only handles 64-bit va_arg!");
15219   assert(Op.getNode()->getNumOperands() == 4);
15220
15221   MachineFunction &MF = DAG.getMachineFunction();
15222   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15223     // The Win64 ABI uses char* instead of a structure.
15224     return DAG.expandVAArg(Op.getNode());
15225
15226   SDValue Chain = Op.getOperand(0);
15227   SDValue SrcPtr = Op.getOperand(1);
15228   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15229   unsigned Align = Op.getConstantOperandVal(3);
15230   SDLoc dl(Op);
15231
15232   EVT ArgVT = Op.getNode()->getValueType(0);
15233   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15234   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15235   uint8_t ArgMode;
15236
15237   // Decide which area this value should be read from.
15238   // TODO: Implement the AMD64 ABI in its entirety. This simple
15239   // selection mechanism works only for the basic types.
15240   if (ArgVT == MVT::f80) {
15241     llvm_unreachable("va_arg for f80 not yet implemented");
15242   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15243     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15244   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15245     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15246   } else {
15247     llvm_unreachable("Unhandled argument type in LowerVAARG");
15248   }
15249
15250   if (ArgMode == 2) {
15251     // Sanity Check: Make sure using fp_offset makes sense.
15252     assert(!Subtarget->useSoftFloat() &&
15253            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15254            Subtarget->hasSSE1());
15255   }
15256
15257   // Insert VAARG_64 node into the DAG
15258   // VAARG_64 returns two values: Variable Argument Address, Chain
15259   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15260                        DAG.getConstant(ArgMode, dl, MVT::i8),
15261                        DAG.getConstant(Align, dl, MVT::i32)};
15262   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15263   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15264                                           VTs, InstOps, MVT::i64,
15265                                           MachinePointerInfo(SV),
15266                                           /*Align=*/0,
15267                                           /*Volatile=*/false,
15268                                           /*ReadMem=*/true,
15269                                           /*WriteMem=*/true);
15270   Chain = VAARG.getValue(1);
15271
15272   // Load the next argument and return it
15273   return DAG.getLoad(ArgVT, dl,
15274                      Chain,
15275                      VAARG,
15276                      MachinePointerInfo(),
15277                      false, false, false, 0);
15278 }
15279
15280 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15281                            SelectionDAG &DAG) {
15282   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15283   // where a va_list is still an i8*.
15284   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15285   if (Subtarget->isCallingConvWin64(
15286         DAG.getMachineFunction().getFunction()->getCallingConv()))
15287     // Probably a Win64 va_copy.
15288     return DAG.expandVACopy(Op.getNode());
15289
15290   SDValue Chain = Op.getOperand(0);
15291   SDValue DstPtr = Op.getOperand(1);
15292   SDValue SrcPtr = Op.getOperand(2);
15293   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15294   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15295   SDLoc DL(Op);
15296
15297   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15298                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15299                        false, false,
15300                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15301 }
15302
15303 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15304 // amount is a constant. Takes immediate version of shift as input.
15305 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15306                                           SDValue SrcOp, uint64_t ShiftAmt,
15307                                           SelectionDAG &DAG) {
15308   MVT ElementType = VT.getVectorElementType();
15309
15310   // Fold this packed shift into its first operand if ShiftAmt is 0.
15311   if (ShiftAmt == 0)
15312     return SrcOp;
15313
15314   // Check for ShiftAmt >= element width
15315   if (ShiftAmt >= ElementType.getSizeInBits()) {
15316     if (Opc == X86ISD::VSRAI)
15317       ShiftAmt = ElementType.getSizeInBits() - 1;
15318     else
15319       return DAG.getConstant(0, dl, VT);
15320   }
15321
15322   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15323          && "Unknown target vector shift-by-constant node");
15324
15325   // Fold this packed vector shift into a build vector if SrcOp is a
15326   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15327   if (VT == SrcOp.getSimpleValueType() &&
15328       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15329     SmallVector<SDValue, 8> Elts;
15330     unsigned NumElts = SrcOp->getNumOperands();
15331     ConstantSDNode *ND;
15332
15333     switch(Opc) {
15334     default: llvm_unreachable(nullptr);
15335     case X86ISD::VSHLI:
15336       for (unsigned i=0; i!=NumElts; ++i) {
15337         SDValue CurrentOp = SrcOp->getOperand(i);
15338         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15339           Elts.push_back(CurrentOp);
15340           continue;
15341         }
15342         ND = cast<ConstantSDNode>(CurrentOp);
15343         const APInt &C = ND->getAPIntValue();
15344         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15345       }
15346       break;
15347     case X86ISD::VSRLI:
15348       for (unsigned i=0; i!=NumElts; ++i) {
15349         SDValue CurrentOp = SrcOp->getOperand(i);
15350         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15351           Elts.push_back(CurrentOp);
15352           continue;
15353         }
15354         ND = cast<ConstantSDNode>(CurrentOp);
15355         const APInt &C = ND->getAPIntValue();
15356         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15357       }
15358       break;
15359     case X86ISD::VSRAI:
15360       for (unsigned i=0; i!=NumElts; ++i) {
15361         SDValue CurrentOp = SrcOp->getOperand(i);
15362         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15363           Elts.push_back(CurrentOp);
15364           continue;
15365         }
15366         ND = cast<ConstantSDNode>(CurrentOp);
15367         const APInt &C = ND->getAPIntValue();
15368         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15369       }
15370       break;
15371     }
15372
15373     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15374   }
15375
15376   return DAG.getNode(Opc, dl, VT, SrcOp,
15377                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15378 }
15379
15380 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15381 // may or may not be a constant. Takes immediate version of shift as input.
15382 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15383                                    SDValue SrcOp, SDValue ShAmt,
15384                                    SelectionDAG &DAG) {
15385   MVT SVT = ShAmt.getSimpleValueType();
15386   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15387
15388   // Catch shift-by-constant.
15389   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15390     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15391                                       CShAmt->getZExtValue(), DAG);
15392
15393   // Change opcode to non-immediate version
15394   switch (Opc) {
15395     default: llvm_unreachable("Unknown target vector shift node");
15396     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15397     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15398     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15399   }
15400
15401   const X86Subtarget &Subtarget =
15402       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15403   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15404       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15405     // Let the shuffle legalizer expand this shift amount node.
15406     SDValue Op0 = ShAmt.getOperand(0);
15407     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15408     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15409   } else {
15410     // Need to build a vector containing shift amount.
15411     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15412     SmallVector<SDValue, 4> ShOps;
15413     ShOps.push_back(ShAmt);
15414     if (SVT == MVT::i32) {
15415       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15416       ShOps.push_back(DAG.getUNDEF(SVT));
15417     }
15418     ShOps.push_back(DAG.getUNDEF(SVT));
15419
15420     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15421     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15422   }
15423
15424   // The return type has to be a 128-bit type with the same element
15425   // type as the input type.
15426   MVT EltVT = VT.getVectorElementType();
15427   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15428
15429   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15430   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15431 }
15432
15433 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15434 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15435 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15436 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15437                                     SDValue PreservedSrc,
15438                                     const X86Subtarget *Subtarget,
15439                                     SelectionDAG &DAG) {
15440     EVT VT = Op.getValueType();
15441     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15442                                   MVT::i1, VT.getVectorNumElements());
15443     SDValue VMask = SDValue();
15444     unsigned OpcodeSelect = ISD::VSELECT;
15445     SDLoc dl(Op);
15446
15447     assert(MaskVT.isSimple() && "invalid mask type");
15448
15449     if (isAllOnes(Mask))
15450       return Op;
15451
15452     if (MaskVT.bitsGT(Mask.getValueType())) {
15453       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15454                                          MaskVT.getSizeInBits());
15455       VMask = DAG.getBitcast(MaskVT,
15456                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15457     } else {
15458       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15459                                        Mask.getValueType().getSizeInBits());
15460       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15461       // are extracted by EXTRACT_SUBVECTOR.
15462       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15463                           DAG.getBitcast(BitcastVT, Mask),
15464                           DAG.getIntPtrConstant(0, dl));
15465     }
15466
15467     switch (Op.getOpcode()) {
15468       default: break;
15469       case X86ISD::PCMPEQM:
15470       case X86ISD::PCMPGTM:
15471       case X86ISD::CMPM:
15472       case X86ISD::CMPMU:
15473         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15474       case X86ISD::VTRUNC:
15475       case X86ISD::VTRUNCS:
15476       case X86ISD::VTRUNCUS:
15477         // We can't use ISD::VSELECT here because it is not always "Legal"
15478         // for the destination type. For example vpmovqb require only AVX512
15479         // and vselect that can operate on byte element type require BWI
15480         OpcodeSelect = X86ISD::SELECT;
15481         break;
15482     }
15483     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15484       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15485     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15486 }
15487
15488 /// \brief Creates an SDNode for a predicated scalar operation.
15489 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15490 /// The mask is coming as MVT::i8 and it should be truncated
15491 /// to MVT::i1 while lowering masking intrinsics.
15492 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15493 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15494 /// for a scalar instruction.
15495 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15496                                     SDValue PreservedSrc,
15497                                     const X86Subtarget *Subtarget,
15498                                     SelectionDAG &DAG) {
15499     if (isAllOnes(Mask))
15500       return Op;
15501
15502     EVT VT = Op.getValueType();
15503     SDLoc dl(Op);
15504     // The mask should be of type MVT::i1
15505     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15506
15507     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15508       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15509     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15510 }
15511
15512 static int getSEHRegistrationNodeSize(const Function *Fn) {
15513   if (!Fn->hasPersonalityFn())
15514     report_fatal_error(
15515         "querying registration node size for function without personality");
15516   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15517   // WinEHStatePass for the full struct definition.
15518   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15519   case EHPersonality::MSVC_X86SEH: return 24;
15520   case EHPersonality::MSVC_CXX: return 16;
15521   default: break;
15522   }
15523   report_fatal_error("can only recover FP for MSVC EH personality functions");
15524 }
15525
15526 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15527 /// function or when returning to a parent frame after catching an exception, we
15528 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15529 /// Here's the math:
15530 ///   RegNodeBase = EntryEBP - RegNodeSize
15531 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15532 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15533 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15534 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15535                                    SDValue EntryEBP) {
15536   MachineFunction &MF = DAG.getMachineFunction();
15537   SDLoc dl;
15538
15539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15540   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15541
15542   // It's possible that the parent function no longer has a personality function
15543   // if the exceptional code was optimized away, in which case we just return
15544   // the incoming EBP.
15545   if (!Fn->hasPersonalityFn())
15546     return EntryEBP;
15547
15548   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15549
15550   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15551   // registration.
15552   MCSymbol *OffsetSym =
15553       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15554           GlobalValue::getRealLinkageName(Fn->getName()));
15555   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15556   SDValue RegNodeFrameOffset =
15557       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15558
15559   // RegNodeBase = EntryEBP - RegNodeSize
15560   // ParentFP = RegNodeBase - RegNodeFrameOffset
15561   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15562                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15563   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15564 }
15565
15566 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15567                                        SelectionDAG &DAG) {
15568   SDLoc dl(Op);
15569   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15570   EVT VT = Op.getValueType();
15571   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15572   if (IntrData) {
15573     switch(IntrData->Type) {
15574     case INTR_TYPE_1OP:
15575       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15576     case INTR_TYPE_2OP:
15577       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15578         Op.getOperand(2));
15579     case INTR_TYPE_3OP:
15580       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15581         Op.getOperand(2), Op.getOperand(3));
15582     case INTR_TYPE_4OP:
15583       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15584         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15585     case INTR_TYPE_1OP_MASK_RM: {
15586       SDValue Src = Op.getOperand(1);
15587       SDValue PassThru = Op.getOperand(2);
15588       SDValue Mask = Op.getOperand(3);
15589       SDValue RoundingMode;
15590       // We allways add rounding mode to the Node.
15591       // If the rounding mode is not specified, we add the
15592       // "current direction" mode.
15593       if (Op.getNumOperands() == 4)
15594         RoundingMode =
15595           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15596       else
15597         RoundingMode = Op.getOperand(4);
15598       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15599       if (IntrWithRoundingModeOpcode != 0)
15600         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15601             X86::STATIC_ROUNDING::CUR_DIRECTION)
15602           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15603                                       dl, Op.getValueType(), Src, RoundingMode),
15604                                       Mask, PassThru, Subtarget, DAG);
15605       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15606                                               RoundingMode),
15607                                   Mask, PassThru, Subtarget, DAG);
15608     }
15609     case INTR_TYPE_1OP_MASK: {
15610       SDValue Src = Op.getOperand(1);
15611       SDValue PassThru = Op.getOperand(2);
15612       SDValue Mask = Op.getOperand(3);
15613       // We add rounding mode to the Node when
15614       //   - RM Opcode is specified and
15615       //   - RM is not "current direction".
15616       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15617       if (IntrWithRoundingModeOpcode != 0) {
15618         SDValue Rnd = Op.getOperand(4);
15619         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15620         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15621           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15622                                       dl, Op.getValueType(),
15623                                       Src, Rnd),
15624                                       Mask, PassThru, Subtarget, DAG);
15625         }
15626       }
15627       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15628                                   Mask, PassThru, Subtarget, DAG);
15629     }
15630     case INTR_TYPE_SCALAR_MASK_RM: {
15631       SDValue Src1 = Op.getOperand(1);
15632       SDValue Src2 = Op.getOperand(2);
15633       SDValue Src0 = Op.getOperand(3);
15634       SDValue Mask = Op.getOperand(4);
15635       // There are 2 kinds of intrinsics in this group:
15636       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15637       // (2) With rounding mode and sae - 7 operands.
15638       if (Op.getNumOperands() == 6) {
15639         SDValue Sae  = Op.getOperand(5);
15640         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15641         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15642                                                 Sae),
15643                                     Mask, Src0, Subtarget, DAG);
15644       }
15645       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15646       SDValue RoundingMode  = Op.getOperand(5);
15647       SDValue Sae  = Op.getOperand(6);
15648       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15649                                               RoundingMode, Sae),
15650                                   Mask, Src0, Subtarget, DAG);
15651     }
15652     case INTR_TYPE_2OP_MASK: {
15653       SDValue Src1 = Op.getOperand(1);
15654       SDValue Src2 = Op.getOperand(2);
15655       SDValue PassThru = Op.getOperand(3);
15656       SDValue Mask = Op.getOperand(4);
15657       // We specify 2 possible opcodes for intrinsics with rounding modes.
15658       // First, we check if the intrinsic may have non-default rounding mode,
15659       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15660       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15661       if (IntrWithRoundingModeOpcode != 0) {
15662         SDValue Rnd = Op.getOperand(5);
15663         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15664         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15665           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15666                                       dl, Op.getValueType(),
15667                                       Src1, Src2, Rnd),
15668                                       Mask, PassThru, Subtarget, DAG);
15669         }
15670       }
15671       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15672                                               Src1,Src2),
15673                                   Mask, PassThru, Subtarget, DAG);
15674     }
15675     case INTR_TYPE_2OP_MASK_RM: {
15676       SDValue Src1 = Op.getOperand(1);
15677       SDValue Src2 = Op.getOperand(2);
15678       SDValue PassThru = Op.getOperand(3);
15679       SDValue Mask = Op.getOperand(4);
15680       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15681       // First, we check if the intrinsic have rounding mode (6 operands),
15682       // if not, we set rounding mode to "current".
15683       SDValue Rnd;
15684       if (Op.getNumOperands() == 6)
15685         Rnd = Op.getOperand(5);
15686       else
15687         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15688       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15689                                               Src1, Src2, Rnd),
15690                                   Mask, PassThru, Subtarget, DAG);
15691     }
15692     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15693       SDValue Src1 = Op.getOperand(1);
15694       SDValue Src2 = Op.getOperand(2);
15695       SDValue Src3 = Op.getOperand(3);
15696       SDValue PassThru = Op.getOperand(4);
15697       SDValue Mask = Op.getOperand(5);
15698       SDValue Sae  = Op.getOperand(6);
15699
15700       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15701                                               Src2, Src3, Sae),
15702                                   Mask, PassThru, Subtarget, DAG);
15703     }
15704     case INTR_TYPE_3OP_MASK_RM: {
15705       SDValue Src1 = Op.getOperand(1);
15706       SDValue Src2 = Op.getOperand(2);
15707       SDValue Imm = Op.getOperand(3);
15708       SDValue PassThru = Op.getOperand(4);
15709       SDValue Mask = Op.getOperand(5);
15710       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15711       // First, we check if the intrinsic have rounding mode (7 operands),
15712       // if not, we set rounding mode to "current".
15713       SDValue Rnd;
15714       if (Op.getNumOperands() == 7)
15715         Rnd = Op.getOperand(6);
15716       else
15717         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15718       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15719         Src1, Src2, Imm, Rnd),
15720         Mask, PassThru, Subtarget, DAG);
15721     }
15722     case INTR_TYPE_3OP_IMM8_MASK:
15723     case INTR_TYPE_3OP_MASK: {
15724       SDValue Src1 = Op.getOperand(1);
15725       SDValue Src2 = Op.getOperand(2);
15726       SDValue Src3 = Op.getOperand(3);
15727       SDValue PassThru = Op.getOperand(4);
15728       SDValue Mask = Op.getOperand(5);
15729
15730       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15731         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15732       // We specify 2 possible opcodes for intrinsics with rounding modes.
15733       // First, we check if the intrinsic may have non-default rounding mode,
15734       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15735       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15736       if (IntrWithRoundingModeOpcode != 0) {
15737         SDValue Rnd = Op.getOperand(6);
15738         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15739         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15740           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15741                                       dl, Op.getValueType(),
15742                                       Src1, Src2, Src3, Rnd),
15743                                       Mask, PassThru, Subtarget, DAG);
15744         }
15745       }
15746       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15747                                               Src1, Src2, Src3),
15748                                   Mask, PassThru, Subtarget, DAG);
15749     }
15750     case VPERM_3OP_MASKZ:
15751     case VPERM_3OP_MASK:
15752     case FMA_OP_MASK3:
15753     case FMA_OP_MASKZ:
15754     case FMA_OP_MASK: {
15755       SDValue Src1 = Op.getOperand(1);
15756       SDValue Src2 = Op.getOperand(2);
15757       SDValue Src3 = Op.getOperand(3);
15758       SDValue Mask = Op.getOperand(4);
15759       EVT VT = Op.getValueType();
15760       SDValue PassThru = SDValue();
15761
15762       // set PassThru element
15763       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15764         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15765       else if (IntrData->Type == FMA_OP_MASK3)
15766         PassThru = Src3;
15767       else
15768         PassThru = Src1;
15769
15770       // We specify 2 possible opcodes for intrinsics with rounding modes.
15771       // First, we check if the intrinsic may have non-default rounding mode,
15772       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15773       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15774       if (IntrWithRoundingModeOpcode != 0) {
15775         SDValue Rnd = Op.getOperand(5);
15776         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15777             X86::STATIC_ROUNDING::CUR_DIRECTION)
15778           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15779                                                   dl, Op.getValueType(),
15780                                                   Src1, Src2, Src3, Rnd),
15781                                       Mask, PassThru, Subtarget, DAG);
15782       }
15783       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15784                                               dl, Op.getValueType(),
15785                                               Src1, Src2, Src3),
15786                                   Mask, PassThru, Subtarget, DAG);
15787     }
15788     case CMP_MASK:
15789     case CMP_MASK_CC: {
15790       // Comparison intrinsics with masks.
15791       // Example of transformation:
15792       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15793       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15794       // (i8 (bitcast
15795       //   (v8i1 (insert_subvector undef,
15796       //           (v2i1 (and (PCMPEQM %a, %b),
15797       //                      (extract_subvector
15798       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15799       EVT VT = Op.getOperand(1).getValueType();
15800       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15801                                     VT.getVectorNumElements());
15802       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15803       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15804                                        Mask.getValueType().getSizeInBits());
15805       SDValue Cmp;
15806       if (IntrData->Type == CMP_MASK_CC) {
15807         SDValue CC = Op.getOperand(3);
15808         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15809         // We specify 2 possible opcodes for intrinsics with rounding modes.
15810         // First, we check if the intrinsic may have non-default rounding mode,
15811         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15812         if (IntrData->Opc1 != 0) {
15813           SDValue Rnd = Op.getOperand(5);
15814           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15815               X86::STATIC_ROUNDING::CUR_DIRECTION)
15816             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15817                               Op.getOperand(2), CC, Rnd);
15818         }
15819         //default rounding mode
15820         if(!Cmp.getNode())
15821             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15822                               Op.getOperand(2), CC);
15823
15824       } else {
15825         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15826         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15827                           Op.getOperand(2));
15828       }
15829       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15830                                              DAG.getTargetConstant(0, dl,
15831                                                                    MaskVT),
15832                                              Subtarget, DAG);
15833       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15834                                 DAG.getUNDEF(BitcastVT), CmpMask,
15835                                 DAG.getIntPtrConstant(0, dl));
15836       return DAG.getBitcast(Op.getValueType(), Res);
15837     }
15838     case COMI: { // Comparison intrinsics
15839       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15840       SDValue LHS = Op.getOperand(1);
15841       SDValue RHS = Op.getOperand(2);
15842       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15843       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15844       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15845       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15846                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15847       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15848     }
15849     case VSHIFT:
15850       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15851                                  Op.getOperand(1), Op.getOperand(2), DAG);
15852     case VSHIFT_MASK:
15853       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15854                                                       Op.getSimpleValueType(),
15855                                                       Op.getOperand(1),
15856                                                       Op.getOperand(2), DAG),
15857                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15858                                   DAG);
15859     case COMPRESS_EXPAND_IN_REG: {
15860       SDValue Mask = Op.getOperand(3);
15861       SDValue DataToCompress = Op.getOperand(1);
15862       SDValue PassThru = Op.getOperand(2);
15863       if (isAllOnes(Mask)) // return data as is
15864         return Op.getOperand(1);
15865
15866       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15867                                               DataToCompress),
15868                                   Mask, PassThru, Subtarget, DAG);
15869     }
15870     case BLEND: {
15871       SDValue Mask = Op.getOperand(3);
15872       EVT VT = Op.getValueType();
15873       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15874                                     VT.getVectorNumElements());
15875       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15876                                        Mask.getValueType().getSizeInBits());
15877       SDLoc dl(Op);
15878       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15879                                   DAG.getBitcast(BitcastVT, Mask),
15880                                   DAG.getIntPtrConstant(0, dl));
15881       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15882                          Op.getOperand(2));
15883     }
15884     default:
15885       break;
15886     }
15887   }
15888
15889   switch (IntNo) {
15890   default: return SDValue();    // Don't custom lower most intrinsics.
15891
15892   case Intrinsic::x86_avx2_permd:
15893   case Intrinsic::x86_avx2_permps:
15894     // Operands intentionally swapped. Mask is last operand to intrinsic,
15895     // but second operand for node/instruction.
15896     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15897                        Op.getOperand(2), Op.getOperand(1));
15898
15899   // ptest and testp intrinsics. The intrinsic these come from are designed to
15900   // return an integer value, not just an instruction so lower it to the ptest
15901   // or testp pattern and a setcc for the result.
15902   case Intrinsic::x86_sse41_ptestz:
15903   case Intrinsic::x86_sse41_ptestc:
15904   case Intrinsic::x86_sse41_ptestnzc:
15905   case Intrinsic::x86_avx_ptestz_256:
15906   case Intrinsic::x86_avx_ptestc_256:
15907   case Intrinsic::x86_avx_ptestnzc_256:
15908   case Intrinsic::x86_avx_vtestz_ps:
15909   case Intrinsic::x86_avx_vtestc_ps:
15910   case Intrinsic::x86_avx_vtestnzc_ps:
15911   case Intrinsic::x86_avx_vtestz_pd:
15912   case Intrinsic::x86_avx_vtestc_pd:
15913   case Intrinsic::x86_avx_vtestnzc_pd:
15914   case Intrinsic::x86_avx_vtestz_ps_256:
15915   case Intrinsic::x86_avx_vtestc_ps_256:
15916   case Intrinsic::x86_avx_vtestnzc_ps_256:
15917   case Intrinsic::x86_avx_vtestz_pd_256:
15918   case Intrinsic::x86_avx_vtestc_pd_256:
15919   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15920     bool IsTestPacked = false;
15921     unsigned X86CC;
15922     switch (IntNo) {
15923     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15924     case Intrinsic::x86_avx_vtestz_ps:
15925     case Intrinsic::x86_avx_vtestz_pd:
15926     case Intrinsic::x86_avx_vtestz_ps_256:
15927     case Intrinsic::x86_avx_vtestz_pd_256:
15928       IsTestPacked = true; // Fallthrough
15929     case Intrinsic::x86_sse41_ptestz:
15930     case Intrinsic::x86_avx_ptestz_256:
15931       // ZF = 1
15932       X86CC = X86::COND_E;
15933       break;
15934     case Intrinsic::x86_avx_vtestc_ps:
15935     case Intrinsic::x86_avx_vtestc_pd:
15936     case Intrinsic::x86_avx_vtestc_ps_256:
15937     case Intrinsic::x86_avx_vtestc_pd_256:
15938       IsTestPacked = true; // Fallthrough
15939     case Intrinsic::x86_sse41_ptestc:
15940     case Intrinsic::x86_avx_ptestc_256:
15941       // CF = 1
15942       X86CC = X86::COND_B;
15943       break;
15944     case Intrinsic::x86_avx_vtestnzc_ps:
15945     case Intrinsic::x86_avx_vtestnzc_pd:
15946     case Intrinsic::x86_avx_vtestnzc_ps_256:
15947     case Intrinsic::x86_avx_vtestnzc_pd_256:
15948       IsTestPacked = true; // Fallthrough
15949     case Intrinsic::x86_sse41_ptestnzc:
15950     case Intrinsic::x86_avx_ptestnzc_256:
15951       // ZF and CF = 0
15952       X86CC = X86::COND_A;
15953       break;
15954     }
15955
15956     SDValue LHS = Op.getOperand(1);
15957     SDValue RHS = Op.getOperand(2);
15958     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15959     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15960     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15961     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15962     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15963   }
15964   case Intrinsic::x86_avx512_kortestz_w:
15965   case Intrinsic::x86_avx512_kortestc_w: {
15966     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15967     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15968     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15969     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15970     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15971     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15972     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15973   }
15974
15975   case Intrinsic::x86_sse42_pcmpistria128:
15976   case Intrinsic::x86_sse42_pcmpestria128:
15977   case Intrinsic::x86_sse42_pcmpistric128:
15978   case Intrinsic::x86_sse42_pcmpestric128:
15979   case Intrinsic::x86_sse42_pcmpistrio128:
15980   case Intrinsic::x86_sse42_pcmpestrio128:
15981   case Intrinsic::x86_sse42_pcmpistris128:
15982   case Intrinsic::x86_sse42_pcmpestris128:
15983   case Intrinsic::x86_sse42_pcmpistriz128:
15984   case Intrinsic::x86_sse42_pcmpestriz128: {
15985     unsigned Opcode;
15986     unsigned X86CC;
15987     switch (IntNo) {
15988     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15989     case Intrinsic::x86_sse42_pcmpistria128:
15990       Opcode = X86ISD::PCMPISTRI;
15991       X86CC = X86::COND_A;
15992       break;
15993     case Intrinsic::x86_sse42_pcmpestria128:
15994       Opcode = X86ISD::PCMPESTRI;
15995       X86CC = X86::COND_A;
15996       break;
15997     case Intrinsic::x86_sse42_pcmpistric128:
15998       Opcode = X86ISD::PCMPISTRI;
15999       X86CC = X86::COND_B;
16000       break;
16001     case Intrinsic::x86_sse42_pcmpestric128:
16002       Opcode = X86ISD::PCMPESTRI;
16003       X86CC = X86::COND_B;
16004       break;
16005     case Intrinsic::x86_sse42_pcmpistrio128:
16006       Opcode = X86ISD::PCMPISTRI;
16007       X86CC = X86::COND_O;
16008       break;
16009     case Intrinsic::x86_sse42_pcmpestrio128:
16010       Opcode = X86ISD::PCMPESTRI;
16011       X86CC = X86::COND_O;
16012       break;
16013     case Intrinsic::x86_sse42_pcmpistris128:
16014       Opcode = X86ISD::PCMPISTRI;
16015       X86CC = X86::COND_S;
16016       break;
16017     case Intrinsic::x86_sse42_pcmpestris128:
16018       Opcode = X86ISD::PCMPESTRI;
16019       X86CC = X86::COND_S;
16020       break;
16021     case Intrinsic::x86_sse42_pcmpistriz128:
16022       Opcode = X86ISD::PCMPISTRI;
16023       X86CC = X86::COND_E;
16024       break;
16025     case Intrinsic::x86_sse42_pcmpestriz128:
16026       Opcode = X86ISD::PCMPESTRI;
16027       X86CC = X86::COND_E;
16028       break;
16029     }
16030     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16031     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16032     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16033     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16034                                 DAG.getConstant(X86CC, dl, MVT::i8),
16035                                 SDValue(PCMP.getNode(), 1));
16036     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16037   }
16038
16039   case Intrinsic::x86_sse42_pcmpistri128:
16040   case Intrinsic::x86_sse42_pcmpestri128: {
16041     unsigned Opcode;
16042     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16043       Opcode = X86ISD::PCMPISTRI;
16044     else
16045       Opcode = X86ISD::PCMPESTRI;
16046
16047     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16048     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16049     return DAG.getNode(Opcode, dl, VTs, NewOps);
16050   }
16051
16052   case Intrinsic::x86_seh_lsda: {
16053     // Compute the symbol for the LSDA. We know it'll get emitted later.
16054     MachineFunction &MF = DAG.getMachineFunction();
16055     SDValue Op1 = Op.getOperand(1);
16056     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16057     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16058         GlobalValue::getRealLinkageName(Fn->getName()));
16059
16060     // Generate a simple absolute symbol reference. This intrinsic is only
16061     // supported on 32-bit Windows, which isn't PIC.
16062     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16063     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16064   }
16065
16066   case Intrinsic::x86_seh_recoverfp: {
16067     SDValue FnOp = Op.getOperand(1);
16068     SDValue IncomingFPOp = Op.getOperand(2);
16069     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16070     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16071     if (!Fn)
16072       report_fatal_error(
16073           "llvm.x86.seh.recoverfp must take a function as the first argument");
16074     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16075   }
16076
16077   case Intrinsic::localaddress: {
16078     // Returns one of the stack, base, or frame pointer registers, depending on
16079     // which is used to reference local variables.
16080     MachineFunction &MF = DAG.getMachineFunction();
16081     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16082     unsigned Reg;
16083     if (RegInfo->hasBasePointer(MF))
16084       Reg = RegInfo->getBaseRegister();
16085     else // This function handles the SP or FP case.
16086       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16087     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16088   }
16089   }
16090 }
16091
16092 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16093                               SDValue Src, SDValue Mask, SDValue Base,
16094                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16095                               const X86Subtarget * Subtarget) {
16096   SDLoc dl(Op);
16097   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16098   if (!C)
16099     llvm_unreachable("Invalid scale type");
16100   unsigned ScaleVal = C->getZExtValue();
16101   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16102     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16103
16104   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16105   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16106                              Index.getSimpleValueType().getVectorNumElements());
16107   SDValue MaskInReg;
16108   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16109   if (MaskC)
16110     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16111   else {
16112     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16113                                      Mask.getValueType().getSizeInBits());
16114
16115     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16116     // are extracted by EXTRACT_SUBVECTOR.
16117     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16118                             DAG.getBitcast(BitcastVT, Mask),
16119                             DAG.getIntPtrConstant(0, dl));
16120   }
16121   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16122   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16123   SDValue Segment = DAG.getRegister(0, MVT::i32);
16124   if (Src.getOpcode() == ISD::UNDEF)
16125     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16126   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16127   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16128   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16129   return DAG.getMergeValues(RetOps, dl);
16130 }
16131
16132 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16133                                SDValue Src, SDValue Mask, SDValue Base,
16134                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16135   SDLoc dl(Op);
16136   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16137   if (!C)
16138     llvm_unreachable("Invalid scale type");
16139   unsigned ScaleVal = C->getZExtValue();
16140   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16141     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16142
16143   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16144   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16145   SDValue Segment = DAG.getRegister(0, MVT::i32);
16146   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16147                              Index.getSimpleValueType().getVectorNumElements());
16148   SDValue MaskInReg;
16149   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16150   if (MaskC)
16151     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16152   else {
16153     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16154                                      Mask.getValueType().getSizeInBits());
16155
16156     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16157     // are extracted by EXTRACT_SUBVECTOR.
16158     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16159                             DAG.getBitcast(BitcastVT, Mask),
16160                             DAG.getIntPtrConstant(0, dl));
16161   }
16162   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16163   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16164   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16165   return SDValue(Res, 1);
16166 }
16167
16168 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16169                                SDValue Mask, SDValue Base, SDValue Index,
16170                                SDValue ScaleOp, SDValue Chain) {
16171   SDLoc dl(Op);
16172   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16173   assert(C && "Invalid scale type");
16174   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16175   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16176   SDValue Segment = DAG.getRegister(0, MVT::i32);
16177   EVT MaskVT =
16178     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16179   SDValue MaskInReg;
16180   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16181   if (MaskC)
16182     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16183   else
16184     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16185   //SDVTList VTs = DAG.getVTList(MVT::Other);
16186   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16187   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16188   return SDValue(Res, 0);
16189 }
16190
16191 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16192 // read performance monitor counters (x86_rdpmc).
16193 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16194                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16195                               SmallVectorImpl<SDValue> &Results) {
16196   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16197   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16198   SDValue LO, HI;
16199
16200   // The ECX register is used to select the index of the performance counter
16201   // to read.
16202   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16203                                    N->getOperand(2));
16204   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16205
16206   // Reads the content of a 64-bit performance counter and returns it in the
16207   // registers EDX:EAX.
16208   if (Subtarget->is64Bit()) {
16209     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16210     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16211                             LO.getValue(2));
16212   } else {
16213     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16214     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16215                             LO.getValue(2));
16216   }
16217   Chain = HI.getValue(1);
16218
16219   if (Subtarget->is64Bit()) {
16220     // The EAX register is loaded with the low-order 32 bits. The EDX register
16221     // is loaded with the supported high-order bits of the counter.
16222     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16223                               DAG.getConstant(32, DL, MVT::i8));
16224     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16225     Results.push_back(Chain);
16226     return;
16227   }
16228
16229   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16230   SDValue Ops[] = { LO, HI };
16231   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16232   Results.push_back(Pair);
16233   Results.push_back(Chain);
16234 }
16235
16236 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16237 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16238 // also used to custom lower READCYCLECOUNTER nodes.
16239 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16240                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16241                               SmallVectorImpl<SDValue> &Results) {
16242   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16243   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16244   SDValue LO, HI;
16245
16246   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16247   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16248   // and the EAX register is loaded with the low-order 32 bits.
16249   if (Subtarget->is64Bit()) {
16250     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16251     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16252                             LO.getValue(2));
16253   } else {
16254     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16255     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16256                             LO.getValue(2));
16257   }
16258   SDValue Chain = HI.getValue(1);
16259
16260   if (Opcode == X86ISD::RDTSCP_DAG) {
16261     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16262
16263     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16264     // the ECX register. Add 'ecx' explicitly to the chain.
16265     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16266                                      HI.getValue(2));
16267     // Explicitly store the content of ECX at the location passed in input
16268     // to the 'rdtscp' intrinsic.
16269     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16270                          MachinePointerInfo(), false, false, 0);
16271   }
16272
16273   if (Subtarget->is64Bit()) {
16274     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16275     // the EAX register is loaded with the low-order 32 bits.
16276     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16277                               DAG.getConstant(32, DL, MVT::i8));
16278     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16279     Results.push_back(Chain);
16280     return;
16281   }
16282
16283   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16284   SDValue Ops[] = { LO, HI };
16285   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16286   Results.push_back(Pair);
16287   Results.push_back(Chain);
16288 }
16289
16290 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16291                                      SelectionDAG &DAG) {
16292   SmallVector<SDValue, 2> Results;
16293   SDLoc DL(Op);
16294   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16295                           Results);
16296   return DAG.getMergeValues(Results, DL);
16297 }
16298
16299 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16300                                     SelectionDAG &DAG) {
16301   MachineFunction &MF = DAG.getMachineFunction();
16302   const Function *Fn = MF.getFunction();
16303   SDLoc dl(Op);
16304   SDValue Chain = Op.getOperand(0);
16305
16306   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16307          "using llvm.x86.seh.restoreframe requires a frame pointer");
16308
16309   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16310   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16311
16312   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16313   unsigned FrameReg =
16314       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16315   unsigned SPReg = RegInfo->getStackRegister();
16316   unsigned SlotSize = RegInfo->getSlotSize();
16317
16318   // Get incoming EBP.
16319   SDValue IncomingEBP =
16320       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16321
16322   // SP is saved in the first field of every registration node, so load
16323   // [EBP-RegNodeSize] into SP.
16324   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16325   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16326                                DAG.getConstant(-RegNodeSize, dl, VT));
16327   SDValue NewSP =
16328       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16329                   false, VT.getScalarSizeInBits() / 8);
16330   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16331
16332   if (!RegInfo->needsStackRealignment(MF)) {
16333     // Adjust EBP to point back to the original frame position.
16334     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16335     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16336   } else {
16337     assert(RegInfo->hasBasePointer(MF) &&
16338            "functions with Win32 EH must use frame or base pointer register");
16339
16340     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16341     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16342     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16343
16344     // Reload the spilled EBP value, now that the stack and base pointers are
16345     // set up.
16346     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16347     X86FI->setHasSEHFramePtrSave(true);
16348     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16349     X86FI->setSEHFramePtrSaveIndex(FI);
16350     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16351                                 MachinePointerInfo(), false, false, false,
16352                                 VT.getScalarSizeInBits() / 8);
16353     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16354   }
16355
16356   return Chain;
16357 }
16358
16359 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16360 /// return truncate Store/MaskedStore Node
16361 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16362                                                SelectionDAG &DAG,
16363                                                MVT ElementType) {
16364   SDLoc dl(Op);
16365   SDValue Mask = Op.getOperand(4);
16366   SDValue DataToTruncate = Op.getOperand(3);
16367   SDValue Addr = Op.getOperand(2);
16368   SDValue Chain = Op.getOperand(0);
16369
16370   EVT VT  = DataToTruncate.getValueType();
16371   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16372                              ElementType, VT.getVectorNumElements());
16373
16374   if (isAllOnes(Mask)) // return just a truncate store
16375     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16376                              MachinePointerInfo(), SVT, false, false,
16377                              SVT.getScalarSizeInBits()/8);
16378
16379   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16380                                 MVT::i1, VT.getVectorNumElements());
16381   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16382                                    Mask.getValueType().getSizeInBits());
16383   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16384   // are extracted by EXTRACT_SUBVECTOR.
16385   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16386                               DAG.getBitcast(BitcastVT, Mask),
16387                               DAG.getIntPtrConstant(0, dl));
16388
16389   MachineMemOperand *MMO = DAG.getMachineFunction().
16390     getMachineMemOperand(MachinePointerInfo(),
16391                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16392                          SVT.getScalarSizeInBits()/8);
16393
16394   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16395                             VMask, SVT, MMO, true);
16396 }
16397
16398 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16399                                       SelectionDAG &DAG) {
16400   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16401
16402   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16403   if (!IntrData) {
16404     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16405       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16406     return SDValue();
16407   }
16408
16409   SDLoc dl(Op);
16410   switch(IntrData->Type) {
16411   default:
16412     llvm_unreachable("Unknown Intrinsic Type");
16413     break;
16414   case RDSEED:
16415   case RDRAND: {
16416     // Emit the node with the right value type.
16417     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16418     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16419
16420     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16421     // Otherwise return the value from Rand, which is always 0, casted to i32.
16422     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16423                       DAG.getConstant(1, dl, Op->getValueType(1)),
16424                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16425                       SDValue(Result.getNode(), 1) };
16426     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16427                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16428                                   Ops);
16429
16430     // Return { result, isValid, chain }.
16431     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16432                        SDValue(Result.getNode(), 2));
16433   }
16434   case GATHER: {
16435   //gather(v1, mask, index, base, scale);
16436     SDValue Chain = Op.getOperand(0);
16437     SDValue Src   = Op.getOperand(2);
16438     SDValue Base  = Op.getOperand(3);
16439     SDValue Index = Op.getOperand(4);
16440     SDValue Mask  = Op.getOperand(5);
16441     SDValue Scale = Op.getOperand(6);
16442     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16443                          Chain, Subtarget);
16444   }
16445   case SCATTER: {
16446   //scatter(base, mask, index, v1, scale);
16447     SDValue Chain = Op.getOperand(0);
16448     SDValue Base  = Op.getOperand(2);
16449     SDValue Mask  = Op.getOperand(3);
16450     SDValue Index = Op.getOperand(4);
16451     SDValue Src   = Op.getOperand(5);
16452     SDValue Scale = Op.getOperand(6);
16453     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16454                           Scale, Chain);
16455   }
16456   case PREFETCH: {
16457     SDValue Hint = Op.getOperand(6);
16458     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16459     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16460     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16461     SDValue Chain = Op.getOperand(0);
16462     SDValue Mask  = Op.getOperand(2);
16463     SDValue Index = Op.getOperand(3);
16464     SDValue Base  = Op.getOperand(4);
16465     SDValue Scale = Op.getOperand(5);
16466     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16467   }
16468   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16469   case RDTSC: {
16470     SmallVector<SDValue, 2> Results;
16471     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16472                             Results);
16473     return DAG.getMergeValues(Results, dl);
16474   }
16475   // Read Performance Monitoring Counters.
16476   case RDPMC: {
16477     SmallVector<SDValue, 2> Results;
16478     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16479     return DAG.getMergeValues(Results, dl);
16480   }
16481   // XTEST intrinsics.
16482   case XTEST: {
16483     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16484     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16485     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16486                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16487                                 InTrans);
16488     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16489     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16490                        Ret, SDValue(InTrans.getNode(), 1));
16491   }
16492   // ADC/ADCX/SBB
16493   case ADX: {
16494     SmallVector<SDValue, 2> Results;
16495     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16496     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16497     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16498                                 DAG.getConstant(-1, dl, MVT::i8));
16499     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16500                               Op.getOperand(4), GenCF.getValue(1));
16501     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16502                                  Op.getOperand(5), MachinePointerInfo(),
16503                                  false, false, 0);
16504     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16505                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16506                                 Res.getValue(1));
16507     Results.push_back(SetCC);
16508     Results.push_back(Store);
16509     return DAG.getMergeValues(Results, dl);
16510   }
16511   case COMPRESS_TO_MEM: {
16512     SDLoc dl(Op);
16513     SDValue Mask = Op.getOperand(4);
16514     SDValue DataToCompress = Op.getOperand(3);
16515     SDValue Addr = Op.getOperand(2);
16516     SDValue Chain = Op.getOperand(0);
16517
16518     EVT VT = DataToCompress.getValueType();
16519     if (isAllOnes(Mask)) // return just a store
16520       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16521                           MachinePointerInfo(), false, false,
16522                           VT.getScalarSizeInBits()/8);
16523
16524     SDValue Compressed =
16525       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16526                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16527     return DAG.getStore(Chain, dl, Compressed, Addr,
16528                         MachinePointerInfo(), false, false,
16529                         VT.getScalarSizeInBits()/8);
16530   }
16531   case TRUNCATE_TO_MEM_VI8:
16532     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16533   case TRUNCATE_TO_MEM_VI16:
16534     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16535   case TRUNCATE_TO_MEM_VI32:
16536     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16537   case EXPAND_FROM_MEM: {
16538     SDLoc dl(Op);
16539     SDValue Mask = Op.getOperand(4);
16540     SDValue PassThru = Op.getOperand(3);
16541     SDValue Addr = Op.getOperand(2);
16542     SDValue Chain = Op.getOperand(0);
16543     EVT VT = Op.getValueType();
16544
16545     if (isAllOnes(Mask)) // return just a load
16546       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16547                          false, VT.getScalarSizeInBits()/8);
16548
16549     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16550                                        false, false, false,
16551                                        VT.getScalarSizeInBits()/8);
16552
16553     SDValue Results[] = {
16554       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16555                            Mask, PassThru, Subtarget, DAG), Chain};
16556     return DAG.getMergeValues(Results, dl);
16557   }
16558   }
16559 }
16560
16561 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16562                                            SelectionDAG &DAG) const {
16563   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16564   MFI->setReturnAddressIsTaken(true);
16565
16566   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16567     return SDValue();
16568
16569   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16570   SDLoc dl(Op);
16571   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16572
16573   if (Depth > 0) {
16574     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16575     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16576     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16577     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16578                        DAG.getNode(ISD::ADD, dl, PtrVT,
16579                                    FrameAddr, Offset),
16580                        MachinePointerInfo(), false, false, false, 0);
16581   }
16582
16583   // Just load the return address.
16584   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16585   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16586                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16587 }
16588
16589 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16590   MachineFunction &MF = DAG.getMachineFunction();
16591   MachineFrameInfo *MFI = MF.getFrameInfo();
16592   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16593   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16594   EVT VT = Op.getValueType();
16595
16596   MFI->setFrameAddressIsTaken(true);
16597
16598   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16599     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16600     // is not possible to crawl up the stack without looking at the unwind codes
16601     // simultaneously.
16602     int FrameAddrIndex = FuncInfo->getFAIndex();
16603     if (!FrameAddrIndex) {
16604       // Set up a frame object for the return address.
16605       unsigned SlotSize = RegInfo->getSlotSize();
16606       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16607           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16608       FuncInfo->setFAIndex(FrameAddrIndex);
16609     }
16610     return DAG.getFrameIndex(FrameAddrIndex, VT);
16611   }
16612
16613   unsigned FrameReg =
16614       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16615   SDLoc dl(Op);  // FIXME probably not meaningful
16616   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16617   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16618           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16619          "Invalid Frame Register!");
16620   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16621   while (Depth--)
16622     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16623                             MachinePointerInfo(),
16624                             false, false, false, 0);
16625   return FrameAddr;
16626 }
16627
16628 // FIXME? Maybe this could be a TableGen attribute on some registers and
16629 // this table could be generated automatically from RegInfo.
16630 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16631                                               SelectionDAG &DAG) const {
16632   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16633   const MachineFunction &MF = DAG.getMachineFunction();
16634
16635   unsigned Reg = StringSwitch<unsigned>(RegName)
16636                        .Case("esp", X86::ESP)
16637                        .Case("rsp", X86::RSP)
16638                        .Case("ebp", X86::EBP)
16639                        .Case("rbp", X86::RBP)
16640                        .Default(0);
16641
16642   if (Reg == X86::EBP || Reg == X86::RBP) {
16643     if (!TFI.hasFP(MF))
16644       report_fatal_error("register " + StringRef(RegName) +
16645                          " is allocatable: function has no frame pointer");
16646 #ifndef NDEBUG
16647     else {
16648       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16649       unsigned FrameReg =
16650           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16651       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16652              "Invalid Frame Register!");
16653     }
16654 #endif
16655   }
16656
16657   if (Reg)
16658     return Reg;
16659
16660   report_fatal_error("Invalid register name global variable");
16661 }
16662
16663 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16664                                                      SelectionDAG &DAG) const {
16665   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16666   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16667 }
16668
16669 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16670   SDValue Chain     = Op.getOperand(0);
16671   SDValue Offset    = Op.getOperand(1);
16672   SDValue Handler   = Op.getOperand(2);
16673   SDLoc dl      (Op);
16674
16675   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16676   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16677   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16678   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16679           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16680          "Invalid Frame Register!");
16681   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16682   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16683
16684   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16685                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16686                                                        dl));
16687   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16688   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16689                        false, false, 0);
16690   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16691
16692   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16693                      DAG.getRegister(StoreAddrReg, PtrVT));
16694 }
16695
16696 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16697   SDValue Chain = Op.getOperand(0);
16698   SDValue Dest = Op.getOperand(1);
16699   SDLoc DL(Op);
16700
16701   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16702   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16703
16704   // Load the address of the destination block.
16705   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16706   SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16707   unsigned WrapperKind =
16708       Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16709   SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16710   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16711   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16712                      DAG.getRegister(ReturnReg, PtrVT));
16713 }
16714
16715 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16716                                                SelectionDAG &DAG) const {
16717   SDLoc DL(Op);
16718   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16719                      DAG.getVTList(MVT::i32, MVT::Other),
16720                      Op.getOperand(0), Op.getOperand(1));
16721 }
16722
16723 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16724                                                 SelectionDAG &DAG) const {
16725   SDLoc DL(Op);
16726   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16727                      Op.getOperand(0), Op.getOperand(1));
16728 }
16729
16730 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16731   return Op.getOperand(0);
16732 }
16733
16734 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16735                                                 SelectionDAG &DAG) const {
16736   SDValue Root = Op.getOperand(0);
16737   SDValue Trmp = Op.getOperand(1); // trampoline
16738   SDValue FPtr = Op.getOperand(2); // nested function
16739   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16740   SDLoc dl (Op);
16741
16742   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16743   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16744
16745   if (Subtarget->is64Bit()) {
16746     SDValue OutChains[6];
16747
16748     // Large code-model.
16749     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16750     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16751
16752     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16753     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16754
16755     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16756
16757     // Load the pointer to the nested function into R11.
16758     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16759     SDValue Addr = Trmp;
16760     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16761                                 Addr, MachinePointerInfo(TrmpAddr),
16762                                 false, false, 0);
16763
16764     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16765                        DAG.getConstant(2, dl, MVT::i64));
16766     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16767                                 MachinePointerInfo(TrmpAddr, 2),
16768                                 false, false, 2);
16769
16770     // Load the 'nest' parameter value into R10.
16771     // R10 is specified in X86CallingConv.td
16772     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16773     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16774                        DAG.getConstant(10, dl, MVT::i64));
16775     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16776                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16777                                 false, false, 0);
16778
16779     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16780                        DAG.getConstant(12, dl, MVT::i64));
16781     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16782                                 MachinePointerInfo(TrmpAddr, 12),
16783                                 false, false, 2);
16784
16785     // Jump to the nested function.
16786     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16787     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16788                        DAG.getConstant(20, dl, MVT::i64));
16789     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16790                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16791                                 false, false, 0);
16792
16793     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16794     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16795                        DAG.getConstant(22, dl, MVT::i64));
16796     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16797                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16798                                 false, false, 0);
16799
16800     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16801   } else {
16802     const Function *Func =
16803       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16804     CallingConv::ID CC = Func->getCallingConv();
16805     unsigned NestReg;
16806
16807     switch (CC) {
16808     default:
16809       llvm_unreachable("Unsupported calling convention");
16810     case CallingConv::C:
16811     case CallingConv::X86_StdCall: {
16812       // Pass 'nest' parameter in ECX.
16813       // Must be kept in sync with X86CallingConv.td
16814       NestReg = X86::ECX;
16815
16816       // Check that ECX wasn't needed by an 'inreg' parameter.
16817       FunctionType *FTy = Func->getFunctionType();
16818       const AttributeSet &Attrs = Func->getAttributes();
16819
16820       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16821         unsigned InRegCount = 0;
16822         unsigned Idx = 1;
16823
16824         for (FunctionType::param_iterator I = FTy->param_begin(),
16825              E = FTy->param_end(); I != E; ++I, ++Idx)
16826           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16827             auto &DL = DAG.getDataLayout();
16828             // FIXME: should only count parameters that are lowered to integers.
16829             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16830           }
16831
16832         if (InRegCount > 2) {
16833           report_fatal_error("Nest register in use - reduce number of inreg"
16834                              " parameters!");
16835         }
16836       }
16837       break;
16838     }
16839     case CallingConv::X86_FastCall:
16840     case CallingConv::X86_ThisCall:
16841     case CallingConv::Fast:
16842       // Pass 'nest' parameter in EAX.
16843       // Must be kept in sync with X86CallingConv.td
16844       NestReg = X86::EAX;
16845       break;
16846     }
16847
16848     SDValue OutChains[4];
16849     SDValue Addr, Disp;
16850
16851     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16852                        DAG.getConstant(10, dl, MVT::i32));
16853     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16854
16855     // This is storing the opcode for MOV32ri.
16856     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16857     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16858     OutChains[0] = DAG.getStore(Root, dl,
16859                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16860                                 Trmp, MachinePointerInfo(TrmpAddr),
16861                                 false, false, 0);
16862
16863     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16864                        DAG.getConstant(1, dl, MVT::i32));
16865     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16866                                 MachinePointerInfo(TrmpAddr, 1),
16867                                 false, false, 1);
16868
16869     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16870     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16871                        DAG.getConstant(5, dl, MVT::i32));
16872     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16873                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16874                                 false, false, 1);
16875
16876     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16877                        DAG.getConstant(6, dl, MVT::i32));
16878     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16879                                 MachinePointerInfo(TrmpAddr, 6),
16880                                 false, false, 1);
16881
16882     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16883   }
16884 }
16885
16886 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16887                                             SelectionDAG &DAG) const {
16888   /*
16889    The rounding mode is in bits 11:10 of FPSR, and has the following
16890    settings:
16891      00 Round to nearest
16892      01 Round to -inf
16893      10 Round to +inf
16894      11 Round to 0
16895
16896   FLT_ROUNDS, on the other hand, expects the following:
16897     -1 Undefined
16898      0 Round to 0
16899      1 Round to nearest
16900      2 Round to +inf
16901      3 Round to -inf
16902
16903   To perform the conversion, we do:
16904     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16905   */
16906
16907   MachineFunction &MF = DAG.getMachineFunction();
16908   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16909   unsigned StackAlignment = TFI.getStackAlignment();
16910   MVT VT = Op.getSimpleValueType();
16911   SDLoc DL(Op);
16912
16913   // Save FP Control Word to stack slot
16914   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16915   SDValue StackSlot =
16916       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16917
16918   MachineMemOperand *MMO =
16919       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16920                               MachineMemOperand::MOStore, 2, 2);
16921
16922   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16923   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16924                                           DAG.getVTList(MVT::Other),
16925                                           Ops, MVT::i16, MMO);
16926
16927   // Load FP Control Word from stack slot
16928   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16929                             MachinePointerInfo(), false, false, false, 0);
16930
16931   // Transform as necessary
16932   SDValue CWD1 =
16933     DAG.getNode(ISD::SRL, DL, MVT::i16,
16934                 DAG.getNode(ISD::AND, DL, MVT::i16,
16935                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16936                 DAG.getConstant(11, DL, MVT::i8));
16937   SDValue CWD2 =
16938     DAG.getNode(ISD::SRL, DL, MVT::i16,
16939                 DAG.getNode(ISD::AND, DL, MVT::i16,
16940                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16941                 DAG.getConstant(9, DL, MVT::i8));
16942
16943   SDValue RetVal =
16944     DAG.getNode(ISD::AND, DL, MVT::i16,
16945                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16946                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16947                             DAG.getConstant(1, DL, MVT::i16)),
16948                 DAG.getConstant(3, DL, MVT::i16));
16949
16950   return DAG.getNode((VT.getSizeInBits() < 16 ?
16951                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16952 }
16953
16954 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16955   MVT VT = Op.getSimpleValueType();
16956   EVT OpVT = VT;
16957   unsigned NumBits = VT.getSizeInBits();
16958   SDLoc dl(Op);
16959
16960   Op = Op.getOperand(0);
16961   if (VT == MVT::i8) {
16962     // Zero extend to i32 since there is not an i8 bsr.
16963     OpVT = MVT::i32;
16964     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16965   }
16966
16967   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16968   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16969   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16970
16971   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16972   SDValue Ops[] = {
16973     Op,
16974     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16975     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16976     Op.getValue(1)
16977   };
16978   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16979
16980   // Finally xor with NumBits-1.
16981   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16982                    DAG.getConstant(NumBits - 1, dl, OpVT));
16983
16984   if (VT == MVT::i8)
16985     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16986   return Op;
16987 }
16988
16989 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16990   MVT VT = Op.getSimpleValueType();
16991   EVT OpVT = VT;
16992   unsigned NumBits = VT.getSizeInBits();
16993   SDLoc dl(Op);
16994
16995   Op = Op.getOperand(0);
16996   if (VT == MVT::i8) {
16997     // Zero extend to i32 since there is not an i8 bsr.
16998     OpVT = MVT::i32;
16999     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17000   }
17001
17002   // Issue a bsr (scan bits in reverse).
17003   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17004   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17005
17006   // And xor with NumBits-1.
17007   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17008                    DAG.getConstant(NumBits - 1, dl, OpVT));
17009
17010   if (VT == MVT::i8)
17011     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17012   return Op;
17013 }
17014
17015 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17016   MVT VT = Op.getSimpleValueType();
17017   unsigned NumBits = VT.getSizeInBits();
17018   SDLoc dl(Op);
17019   Op = Op.getOperand(0);
17020
17021   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17022   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17023   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17024
17025   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17026   SDValue Ops[] = {
17027     Op,
17028     DAG.getConstant(NumBits, dl, VT),
17029     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17030     Op.getValue(1)
17031   };
17032   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17033 }
17034
17035 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17036 // ones, and then concatenate the result back.
17037 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17038   MVT VT = Op.getSimpleValueType();
17039
17040   assert(VT.is256BitVector() && VT.isInteger() &&
17041          "Unsupported value type for operation");
17042
17043   unsigned NumElems = VT.getVectorNumElements();
17044   SDLoc dl(Op);
17045
17046   // Extract the LHS vectors
17047   SDValue LHS = Op.getOperand(0);
17048   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17049   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17050
17051   // Extract the RHS vectors
17052   SDValue RHS = Op.getOperand(1);
17053   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17054   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17055
17056   MVT EltVT = VT.getVectorElementType();
17057   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17058
17059   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17060                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17061                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17062 }
17063
17064 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17065   if (Op.getValueType() == MVT::i1)
17066     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17067                        Op.getOperand(0), Op.getOperand(1));
17068   assert(Op.getSimpleValueType().is256BitVector() &&
17069          Op.getSimpleValueType().isInteger() &&
17070          "Only handle AVX 256-bit vector integer operation");
17071   return Lower256IntArith(Op, DAG);
17072 }
17073
17074 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17075   if (Op.getValueType() == MVT::i1)
17076     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17077                        Op.getOperand(0), Op.getOperand(1));
17078   assert(Op.getSimpleValueType().is256BitVector() &&
17079          Op.getSimpleValueType().isInteger() &&
17080          "Only handle AVX 256-bit vector integer operation");
17081   return Lower256IntArith(Op, DAG);
17082 }
17083
17084 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17085   assert(Op.getSimpleValueType().is256BitVector() &&
17086          Op.getSimpleValueType().isInteger() &&
17087          "Only handle AVX 256-bit vector integer operation");
17088   return Lower256IntArith(Op, DAG);
17089 }
17090
17091 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17092                         SelectionDAG &DAG) {
17093   SDLoc dl(Op);
17094   MVT VT = Op.getSimpleValueType();
17095
17096   if (VT == MVT::i1)
17097     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17098
17099   // Decompose 256-bit ops into smaller 128-bit ops.
17100   if (VT.is256BitVector() && !Subtarget->hasInt256())
17101     return Lower256IntArith(Op, DAG);
17102
17103   SDValue A = Op.getOperand(0);
17104   SDValue B = Op.getOperand(1);
17105
17106   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17107   // pairs, multiply and truncate.
17108   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17109     if (Subtarget->hasInt256()) {
17110       if (VT == MVT::v32i8) {
17111         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17112         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17113         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17114         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17115         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17116         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17117         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17118         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17119                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17120                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17121       }
17122
17123       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17124       return DAG.getNode(
17125           ISD::TRUNCATE, dl, VT,
17126           DAG.getNode(ISD::MUL, dl, ExVT,
17127                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17128                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17129     }
17130
17131     assert(VT == MVT::v16i8 &&
17132            "Pre-AVX2 support only supports v16i8 multiplication");
17133     MVT ExVT = MVT::v8i16;
17134
17135     // Extract the lo parts and sign extend to i16
17136     SDValue ALo, BLo;
17137     if (Subtarget->hasSSE41()) {
17138       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17139       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17140     } else {
17141       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17142                               -1, 4, -1, 5, -1, 6, -1, 7};
17143       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17144       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17145       ALo = DAG.getBitcast(ExVT, ALo);
17146       BLo = DAG.getBitcast(ExVT, BLo);
17147       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17148       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17149     }
17150
17151     // Extract the hi parts and sign extend to i16
17152     SDValue AHi, BHi;
17153     if (Subtarget->hasSSE41()) {
17154       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17155                               -1, -1, -1, -1, -1, -1, -1, -1};
17156       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17157       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17158       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17159       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17160     } else {
17161       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17162                               -1, 12, -1, 13, -1, 14, -1, 15};
17163       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17164       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17165       AHi = DAG.getBitcast(ExVT, AHi);
17166       BHi = DAG.getBitcast(ExVT, BHi);
17167       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17168       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17169     }
17170
17171     // Multiply, mask the lower 8bits of the lo/hi results and pack
17172     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17173     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17174     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17175     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17176     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17177   }
17178
17179   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17180   if (VT == MVT::v4i32) {
17181     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17182            "Should not custom lower when pmuldq is available!");
17183
17184     // Extract the odd parts.
17185     static const int UnpackMask[] = { 1, -1, 3, -1 };
17186     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17187     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17188
17189     // Multiply the even parts.
17190     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17191     // Now multiply odd parts.
17192     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17193
17194     Evens = DAG.getBitcast(VT, Evens);
17195     Odds = DAG.getBitcast(VT, Odds);
17196
17197     // Merge the two vectors back together with a shuffle. This expands into 2
17198     // shuffles.
17199     static const int ShufMask[] = { 0, 4, 2, 6 };
17200     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17201   }
17202
17203   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17204          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17205
17206   //  Ahi = psrlqi(a, 32);
17207   //  Bhi = psrlqi(b, 32);
17208   //
17209   //  AloBlo = pmuludq(a, b);
17210   //  AloBhi = pmuludq(a, Bhi);
17211   //  AhiBlo = pmuludq(Ahi, b);
17212
17213   //  AloBhi = psllqi(AloBhi, 32);
17214   //  AhiBlo = psllqi(AhiBlo, 32);
17215   //  return AloBlo + AloBhi + AhiBlo;
17216
17217   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17218   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17219
17220   SDValue AhiBlo = Ahi;
17221   SDValue AloBhi = Bhi;
17222   // Bit cast to 32-bit vectors for MULUDQ
17223   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17224                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17225   A = DAG.getBitcast(MulVT, A);
17226   B = DAG.getBitcast(MulVT, B);
17227   Ahi = DAG.getBitcast(MulVT, Ahi);
17228   Bhi = DAG.getBitcast(MulVT, Bhi);
17229
17230   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17231   // After shifting right const values the result may be all-zero.
17232   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17233     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17234     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17235   }
17236   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17237     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17238     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17239   }
17240
17241   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17242   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17243 }
17244
17245 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17246   assert(Subtarget->isTargetWin64() && "Unexpected target");
17247   EVT VT = Op.getValueType();
17248   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17249          "Unexpected return type for lowering");
17250
17251   RTLIB::Libcall LC;
17252   bool isSigned;
17253   switch (Op->getOpcode()) {
17254   default: llvm_unreachable("Unexpected request for libcall!");
17255   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17256   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17257   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17258   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17259   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17260   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17261   }
17262
17263   SDLoc dl(Op);
17264   SDValue InChain = DAG.getEntryNode();
17265
17266   TargetLowering::ArgListTy Args;
17267   TargetLowering::ArgListEntry Entry;
17268   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17269     EVT ArgVT = Op->getOperand(i).getValueType();
17270     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17271            "Unexpected argument type for lowering");
17272     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17273     Entry.Node = StackPtr;
17274     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17275                            false, false, 16);
17276     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17277     Entry.Ty = PointerType::get(ArgTy,0);
17278     Entry.isSExt = false;
17279     Entry.isZExt = false;
17280     Args.push_back(Entry);
17281   }
17282
17283   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17284                                          getPointerTy(DAG.getDataLayout()));
17285
17286   TargetLowering::CallLoweringInfo CLI(DAG);
17287   CLI.setDebugLoc(dl).setChain(InChain)
17288     .setCallee(getLibcallCallingConv(LC),
17289                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17290                Callee, std::move(Args), 0)
17291     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17292
17293   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17294   return DAG.getBitcast(VT, CallInfo.first);
17295 }
17296
17297 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17298                              SelectionDAG &DAG) {
17299   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17300   EVT VT = Op0.getValueType();
17301   SDLoc dl(Op);
17302
17303   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17304          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17305
17306   // PMULxD operations multiply each even value (starting at 0) of LHS with
17307   // the related value of RHS and produce a widen result.
17308   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17309   // => <2 x i64> <ae|cg>
17310   //
17311   // In other word, to have all the results, we need to perform two PMULxD:
17312   // 1. one with the even values.
17313   // 2. one with the odd values.
17314   // To achieve #2, with need to place the odd values at an even position.
17315   //
17316   // Place the odd value at an even position (basically, shift all values 1
17317   // step to the left):
17318   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17319   // <a|b|c|d> => <b|undef|d|undef>
17320   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17321   // <e|f|g|h> => <f|undef|h|undef>
17322   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17323
17324   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17325   // ints.
17326   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17327   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17328   unsigned Opcode =
17329       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17330   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17331   // => <2 x i64> <ae|cg>
17332   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17333   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17334   // => <2 x i64> <bf|dh>
17335   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17336
17337   // Shuffle it back into the right order.
17338   SDValue Highs, Lows;
17339   if (VT == MVT::v8i32) {
17340     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17341     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17342     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17343     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17344   } else {
17345     const int HighMask[] = {1, 5, 3, 7};
17346     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17347     const int LowMask[] = {0, 4, 2, 6};
17348     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17349   }
17350
17351   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17352   // unsigned multiply.
17353   if (IsSigned && !Subtarget->hasSSE41()) {
17354     SDValue ShAmt = DAG.getConstant(
17355         31, dl,
17356         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17357     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17358                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17359     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17360                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17361
17362     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17363     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17364   }
17365
17366   // The first result of MUL_LOHI is actually the low value, followed by the
17367   // high value.
17368   SDValue Ops[] = {Lows, Highs};
17369   return DAG.getMergeValues(Ops, dl);
17370 }
17371
17372 // Return true if the required (according to Opcode) shift-imm form is natively
17373 // supported by the Subtarget
17374 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17375                                         unsigned Opcode) {
17376   if (VT.getScalarSizeInBits() < 16)
17377     return false;
17378
17379   if (VT.is512BitVector() &&
17380       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17381     return true;
17382
17383   bool LShift = VT.is128BitVector() ||
17384     (VT.is256BitVector() && Subtarget->hasInt256());
17385
17386   bool AShift = LShift && (Subtarget->hasVLX() ||
17387     (VT != MVT::v2i64 && VT != MVT::v4i64));
17388   return (Opcode == ISD::SRA) ? AShift : LShift;
17389 }
17390
17391 // The shift amount is a variable, but it is the same for all vector lanes.
17392 // These instructions are defined together with shift-immediate.
17393 static
17394 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17395                                       unsigned Opcode) {
17396   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17397 }
17398
17399 // Return true if the required (according to Opcode) variable-shift form is
17400 // natively supported by the Subtarget
17401 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17402                                     unsigned Opcode) {
17403
17404   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17405     return false;
17406
17407   // vXi16 supported only on AVX-512, BWI
17408   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17409     return false;
17410
17411   if (VT.is512BitVector() || Subtarget->hasVLX())
17412     return true;
17413
17414   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17415   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17416   return (Opcode == ISD::SRA) ? AShift : LShift;
17417 }
17418
17419 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17420                                          const X86Subtarget *Subtarget) {
17421   MVT VT = Op.getSimpleValueType();
17422   SDLoc dl(Op);
17423   SDValue R = Op.getOperand(0);
17424   SDValue Amt = Op.getOperand(1);
17425
17426   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17427     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17428
17429   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17430     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17431     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17432     SDValue Ex = DAG.getBitcast(ExVT, R);
17433
17434     if (ShiftAmt >= 32) {
17435       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17436       SDValue Upper =
17437           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17438       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17439                                                  ShiftAmt - 32, DAG);
17440       if (VT == MVT::v2i64)
17441         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17442       if (VT == MVT::v4i64)
17443         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17444                                   {9, 1, 11, 3, 13, 5, 15, 7});
17445     } else {
17446       // SRA upper i32, SHL whole i64 and select lower i32.
17447       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17448                                                  ShiftAmt, DAG);
17449       SDValue Lower =
17450           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17451       Lower = DAG.getBitcast(ExVT, Lower);
17452       if (VT == MVT::v2i64)
17453         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17454       if (VT == MVT::v4i64)
17455         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17456                                   {8, 1, 10, 3, 12, 5, 14, 7});
17457     }
17458     return DAG.getBitcast(VT, Ex);
17459   };
17460
17461   // Optimize shl/srl/sra with constant shift amount.
17462   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17463     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17464       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17465
17466       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17467         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17468
17469       // i64 SRA needs to be performed as partial shifts.
17470       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17471           Op.getOpcode() == ISD::SRA)
17472         return ArithmeticShiftRight64(ShiftAmt);
17473
17474       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17475         unsigned NumElts = VT.getVectorNumElements();
17476         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17477
17478         if (Op.getOpcode() == ISD::SHL) {
17479           // Simple i8 add case
17480           if (ShiftAmt == 1)
17481             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17482
17483           // Make a large shift.
17484           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17485                                                    R, ShiftAmt, DAG);
17486           SHL = DAG.getBitcast(VT, SHL);
17487           // Zero out the rightmost bits.
17488           SmallVector<SDValue, 32> V(
17489               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17490           return DAG.getNode(ISD::AND, dl, VT, SHL,
17491                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17492         }
17493         if (Op.getOpcode() == ISD::SRL) {
17494           // Make a large shift.
17495           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17496                                                    R, ShiftAmt, DAG);
17497           SRL = DAG.getBitcast(VT, SRL);
17498           // Zero out the leftmost bits.
17499           SmallVector<SDValue, 32> V(
17500               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17501           return DAG.getNode(ISD::AND, dl, VT, SRL,
17502                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17503         }
17504         if (Op.getOpcode() == ISD::SRA) {
17505           if (ShiftAmt == 7) {
17506             // ashr(R, 7)  === cmp_slt(R, 0)
17507             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17508             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17509           }
17510
17511           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17512           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17513           SmallVector<SDValue, 32> V(NumElts,
17514                                      DAG.getConstant(128 >> ShiftAmt, dl,
17515                                                      MVT::i8));
17516           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17517           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17518           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17519           return Res;
17520         }
17521         llvm_unreachable("Unknown shift opcode.");
17522       }
17523     }
17524   }
17525
17526   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17527   if (!Subtarget->is64Bit() &&
17528       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17529
17530     // Peek through any splat that was introduced for i64 shift vectorization.
17531     int SplatIndex = -1;
17532     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17533       if (SVN->isSplat()) {
17534         SplatIndex = SVN->getSplatIndex();
17535         Amt = Amt.getOperand(0);
17536         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17537                "Splat shuffle referencing second operand");
17538       }
17539
17540     if (Amt.getOpcode() != ISD::BITCAST ||
17541         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17542       return SDValue();
17543
17544     Amt = Amt.getOperand(0);
17545     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17546                      VT.getVectorNumElements();
17547     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17548     uint64_t ShiftAmt = 0;
17549     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17550     for (unsigned i = 0; i != Ratio; ++i) {
17551       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17552       if (!C)
17553         return SDValue();
17554       // 6 == Log2(64)
17555       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17556     }
17557
17558     // Check remaining shift amounts (if not a splat).
17559     if (SplatIndex < 0) {
17560       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17561         uint64_t ShAmt = 0;
17562         for (unsigned j = 0; j != Ratio; ++j) {
17563           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17564           if (!C)
17565             return SDValue();
17566           // 6 == Log2(64)
17567           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17568         }
17569         if (ShAmt != ShiftAmt)
17570           return SDValue();
17571       }
17572     }
17573
17574     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17575       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17576
17577     if (Op.getOpcode() == ISD::SRA)
17578       return ArithmeticShiftRight64(ShiftAmt);
17579   }
17580
17581   return SDValue();
17582 }
17583
17584 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17585                                         const X86Subtarget* Subtarget) {
17586   MVT VT = Op.getSimpleValueType();
17587   SDLoc dl(Op);
17588   SDValue R = Op.getOperand(0);
17589   SDValue Amt = Op.getOperand(1);
17590
17591   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17592     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17593
17594   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17595     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17596
17597   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17598     SDValue BaseShAmt;
17599     EVT EltVT = VT.getVectorElementType();
17600
17601     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17602       // Check if this build_vector node is doing a splat.
17603       // If so, then set BaseShAmt equal to the splat value.
17604       BaseShAmt = BV->getSplatValue();
17605       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17606         BaseShAmt = SDValue();
17607     } else {
17608       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17609         Amt = Amt.getOperand(0);
17610
17611       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17612       if (SVN && SVN->isSplat()) {
17613         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17614         SDValue InVec = Amt.getOperand(0);
17615         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17616           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17617                  "Unexpected shuffle index found!");
17618           BaseShAmt = InVec.getOperand(SplatIdx);
17619         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17620            if (ConstantSDNode *C =
17621                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17622              if (C->getZExtValue() == SplatIdx)
17623                BaseShAmt = InVec.getOperand(1);
17624            }
17625         }
17626
17627         if (!BaseShAmt)
17628           // Avoid introducing an extract element from a shuffle.
17629           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17630                                   DAG.getIntPtrConstant(SplatIdx, dl));
17631       }
17632     }
17633
17634     if (BaseShAmt.getNode()) {
17635       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17636       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17637         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17638       else if (EltVT.bitsLT(MVT::i32))
17639         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17640
17641       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17642     }
17643   }
17644
17645   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17646   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17647       Amt.getOpcode() == ISD::BITCAST &&
17648       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17649     Amt = Amt.getOperand(0);
17650     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17651                      VT.getVectorNumElements();
17652     std::vector<SDValue> Vals(Ratio);
17653     for (unsigned i = 0; i != Ratio; ++i)
17654       Vals[i] = Amt.getOperand(i);
17655     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17656       for (unsigned j = 0; j != Ratio; ++j)
17657         if (Vals[j] != Amt.getOperand(i + j))
17658           return SDValue();
17659     }
17660
17661     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17662       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17663   }
17664   return SDValue();
17665 }
17666
17667 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17668                           SelectionDAG &DAG) {
17669   MVT VT = Op.getSimpleValueType();
17670   SDLoc dl(Op);
17671   SDValue R = Op.getOperand(0);
17672   SDValue Amt = Op.getOperand(1);
17673
17674   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17675   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17676
17677   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17678     return V;
17679
17680   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17681       return V;
17682
17683   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17684     return Op;
17685
17686   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17687   // shifts per-lane and then shuffle the partial results back together.
17688   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17689     // Splat the shift amounts so the scalar shifts above will catch it.
17690     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17691     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17692     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17693     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17694     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17695   }
17696
17697   // i64 vector arithmetic shift can be emulated with the transform:
17698   // M = lshr(SIGN_BIT, Amt)
17699   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17700   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17701       Op.getOpcode() == ISD::SRA) {
17702     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17703     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17704     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17705     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17706     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17707     return R;
17708   }
17709
17710   // If possible, lower this packed shift into a vector multiply instead of
17711   // expanding it into a sequence of scalar shifts.
17712   // Do this only if the vector shift count is a constant build_vector.
17713   if (Op.getOpcode() == ISD::SHL &&
17714       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17715        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17716       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17717     SmallVector<SDValue, 8> Elts;
17718     EVT SVT = VT.getScalarType();
17719     unsigned SVTBits = SVT.getSizeInBits();
17720     const APInt &One = APInt(SVTBits, 1);
17721     unsigned NumElems = VT.getVectorNumElements();
17722
17723     for (unsigned i=0; i !=NumElems; ++i) {
17724       SDValue Op = Amt->getOperand(i);
17725       if (Op->getOpcode() == ISD::UNDEF) {
17726         Elts.push_back(Op);
17727         continue;
17728       }
17729
17730       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17731       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17732       uint64_t ShAmt = C.getZExtValue();
17733       if (ShAmt >= SVTBits) {
17734         Elts.push_back(DAG.getUNDEF(SVT));
17735         continue;
17736       }
17737       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17738     }
17739     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17740     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17741   }
17742
17743   // Lower SHL with variable shift amount.
17744   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17745     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17746
17747     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17748                      DAG.getConstant(0x3f800000U, dl, VT));
17749     Op = DAG.getBitcast(MVT::v4f32, Op);
17750     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17751     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17752   }
17753
17754   // If possible, lower this shift as a sequence of two shifts by
17755   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17756   // Example:
17757   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17758   //
17759   // Could be rewritten as:
17760   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17761   //
17762   // The advantage is that the two shifts from the example would be
17763   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17764   // the vector shift into four scalar shifts plus four pairs of vector
17765   // insert/extract.
17766   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17767       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17768     unsigned TargetOpcode = X86ISD::MOVSS;
17769     bool CanBeSimplified;
17770     // The splat value for the first packed shift (the 'X' from the example).
17771     SDValue Amt1 = Amt->getOperand(0);
17772     // The splat value for the second packed shift (the 'Y' from the example).
17773     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17774                                         Amt->getOperand(2);
17775
17776     // See if it is possible to replace this node with a sequence of
17777     // two shifts followed by a MOVSS/MOVSD
17778     if (VT == MVT::v4i32) {
17779       // Check if it is legal to use a MOVSS.
17780       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17781                         Amt2 == Amt->getOperand(3);
17782       if (!CanBeSimplified) {
17783         // Otherwise, check if we can still simplify this node using a MOVSD.
17784         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17785                           Amt->getOperand(2) == Amt->getOperand(3);
17786         TargetOpcode = X86ISD::MOVSD;
17787         Amt2 = Amt->getOperand(2);
17788       }
17789     } else {
17790       // Do similar checks for the case where the machine value type
17791       // is MVT::v8i16.
17792       CanBeSimplified = Amt1 == Amt->getOperand(1);
17793       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17794         CanBeSimplified = Amt2 == Amt->getOperand(i);
17795
17796       if (!CanBeSimplified) {
17797         TargetOpcode = X86ISD::MOVSD;
17798         CanBeSimplified = true;
17799         Amt2 = Amt->getOperand(4);
17800         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17801           CanBeSimplified = Amt1 == Amt->getOperand(i);
17802         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17803           CanBeSimplified = Amt2 == Amt->getOperand(j);
17804       }
17805     }
17806
17807     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17808         isa<ConstantSDNode>(Amt2)) {
17809       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17810       EVT CastVT = MVT::v4i32;
17811       SDValue Splat1 =
17812         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17813       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17814       SDValue Splat2 =
17815         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17816       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17817       if (TargetOpcode == X86ISD::MOVSD)
17818         CastVT = MVT::v2i64;
17819       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17820       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17821       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17822                                             BitCast1, DAG);
17823       return DAG.getBitcast(VT, Result);
17824     }
17825   }
17826
17827   // v4i32 Non Uniform Shifts.
17828   // If the shift amount is constant we can shift each lane using the SSE2
17829   // immediate shifts, else we need to zero-extend each lane to the lower i64
17830   // and shift using the SSE2 variable shifts.
17831   // The separate results can then be blended together.
17832   if (VT == MVT::v4i32) {
17833     unsigned Opc = Op.getOpcode();
17834     SDValue Amt0, Amt1, Amt2, Amt3;
17835     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17836       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17837       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17838       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17839       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17840     } else {
17841       // ISD::SHL is handled above but we include it here for completeness.
17842       switch (Opc) {
17843       default:
17844         llvm_unreachable("Unknown target vector shift node");
17845       case ISD::SHL:
17846         Opc = X86ISD::VSHL;
17847         break;
17848       case ISD::SRL:
17849         Opc = X86ISD::VSRL;
17850         break;
17851       case ISD::SRA:
17852         Opc = X86ISD::VSRA;
17853         break;
17854       }
17855       // The SSE2 shifts use the lower i64 as the same shift amount for
17856       // all lanes and the upper i64 is ignored. These shuffle masks
17857       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17858       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17859       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17860       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17861       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17862       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17863     }
17864
17865     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17866     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17867     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17868     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17869     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17870     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17871     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17872   }
17873
17874   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17875     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17876     unsigned ShiftOpcode = Op->getOpcode();
17877
17878     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17879       // On SSE41 targets we make use of the fact that VSELECT lowers
17880       // to PBLENDVB which selects bytes based just on the sign bit.
17881       if (Subtarget->hasSSE41()) {
17882         V0 = DAG.getBitcast(VT, V0);
17883         V1 = DAG.getBitcast(VT, V1);
17884         Sel = DAG.getBitcast(VT, Sel);
17885         return DAG.getBitcast(SelVT,
17886                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17887       }
17888       // On pre-SSE41 targets we test for the sign bit by comparing to
17889       // zero - a negative value will set all bits of the lanes to true
17890       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17891       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17892       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17893       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17894     };
17895
17896     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17897     // We can safely do this using i16 shifts as we're only interested in
17898     // the 3 lower bits of each byte.
17899     Amt = DAG.getBitcast(ExtVT, Amt);
17900     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17901     Amt = DAG.getBitcast(VT, Amt);
17902
17903     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17904       // r = VSELECT(r, shift(r, 4), a);
17905       SDValue M =
17906           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17907       R = SignBitSelect(VT, Amt, M, R);
17908
17909       // a += a
17910       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17911
17912       // r = VSELECT(r, shift(r, 2), a);
17913       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17914       R = SignBitSelect(VT, Amt, M, R);
17915
17916       // a += a
17917       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17918
17919       // return VSELECT(r, shift(r, 1), a);
17920       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17921       R = SignBitSelect(VT, Amt, M, R);
17922       return R;
17923     }
17924
17925     if (Op->getOpcode() == ISD::SRA) {
17926       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17927       // so we can correctly sign extend. We don't care what happens to the
17928       // lower byte.
17929       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17930       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17931       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17932       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17933       ALo = DAG.getBitcast(ExtVT, ALo);
17934       AHi = DAG.getBitcast(ExtVT, AHi);
17935       RLo = DAG.getBitcast(ExtVT, RLo);
17936       RHi = DAG.getBitcast(ExtVT, RHi);
17937
17938       // r = VSELECT(r, shift(r, 4), a);
17939       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17940                                 DAG.getConstant(4, dl, ExtVT));
17941       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17942                                 DAG.getConstant(4, dl, ExtVT));
17943       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17944       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17945
17946       // a += a
17947       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17948       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17949
17950       // r = VSELECT(r, shift(r, 2), a);
17951       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17952                         DAG.getConstant(2, dl, ExtVT));
17953       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17954                         DAG.getConstant(2, dl, ExtVT));
17955       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17956       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17957
17958       // a += a
17959       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17960       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17961
17962       // r = VSELECT(r, shift(r, 1), a);
17963       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17964                         DAG.getConstant(1, dl, ExtVT));
17965       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17966                         DAG.getConstant(1, dl, ExtVT));
17967       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17968       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17969
17970       // Logical shift the result back to the lower byte, leaving a zero upper
17971       // byte
17972       // meaning that we can safely pack with PACKUSWB.
17973       RLo =
17974           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17975       RHi =
17976           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17977       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17978     }
17979   }
17980
17981   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17982   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17983   // solution better.
17984   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17985     MVT ExtVT = MVT::v8i32;
17986     unsigned ExtOpc =
17987         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17988     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17989     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17990     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17991                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17992   }
17993
17994   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17995     MVT ExtVT = MVT::v8i32;
17996     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17997     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17998     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17999     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18000     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18001     ALo = DAG.getBitcast(ExtVT, ALo);
18002     AHi = DAG.getBitcast(ExtVT, AHi);
18003     RLo = DAG.getBitcast(ExtVT, RLo);
18004     RHi = DAG.getBitcast(ExtVT, RHi);
18005     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18006     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18007     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18008     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18009     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18010   }
18011
18012   if (VT == MVT::v8i16) {
18013     unsigned ShiftOpcode = Op->getOpcode();
18014
18015     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18016       // On SSE41 targets we make use of the fact that VSELECT lowers
18017       // to PBLENDVB which selects bytes based just on the sign bit.
18018       if (Subtarget->hasSSE41()) {
18019         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18020         V0 = DAG.getBitcast(ExtVT, V0);
18021         V1 = DAG.getBitcast(ExtVT, V1);
18022         Sel = DAG.getBitcast(ExtVT, Sel);
18023         return DAG.getBitcast(
18024             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18025       }
18026       // On pre-SSE41 targets we splat the sign bit - a negative value will
18027       // set all bits of the lanes to true and VSELECT uses that in
18028       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18029       SDValue C =
18030           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18031       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18032     };
18033
18034     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18035     if (Subtarget->hasSSE41()) {
18036       // On SSE41 targets we need to replicate the shift mask in both
18037       // bytes for PBLENDVB.
18038       Amt = DAG.getNode(
18039           ISD::OR, dl, VT,
18040           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18041           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18042     } else {
18043       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18044     }
18045
18046     // r = VSELECT(r, shift(r, 8), a);
18047     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18048     R = SignBitSelect(Amt, M, R);
18049
18050     // a += a
18051     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18052
18053     // r = VSELECT(r, shift(r, 4), a);
18054     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18055     R = SignBitSelect(Amt, M, R);
18056
18057     // a += a
18058     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18059
18060     // r = VSELECT(r, shift(r, 2), a);
18061     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18062     R = SignBitSelect(Amt, M, R);
18063
18064     // a += a
18065     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18066
18067     // return VSELECT(r, shift(r, 1), a);
18068     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18069     R = SignBitSelect(Amt, M, R);
18070     return R;
18071   }
18072
18073   // Decompose 256-bit shifts into smaller 128-bit shifts.
18074   if (VT.is256BitVector()) {
18075     unsigned NumElems = VT.getVectorNumElements();
18076     MVT EltVT = VT.getVectorElementType();
18077     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18078
18079     // Extract the two vectors
18080     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18081     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18082
18083     // Recreate the shift amount vectors
18084     SDValue Amt1, Amt2;
18085     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18086       // Constant shift amount
18087       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18088       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18089       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18090
18091       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18092       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18093     } else {
18094       // Variable shift amount
18095       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18096       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18097     }
18098
18099     // Issue new vector shifts for the smaller types
18100     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18101     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18102
18103     // Concatenate the result back
18104     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18105   }
18106
18107   return SDValue();
18108 }
18109
18110 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18111   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18112   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18113   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18114   // has only one use.
18115   SDNode *N = Op.getNode();
18116   SDValue LHS = N->getOperand(0);
18117   SDValue RHS = N->getOperand(1);
18118   unsigned BaseOp = 0;
18119   unsigned Cond = 0;
18120   SDLoc DL(Op);
18121   switch (Op.getOpcode()) {
18122   default: llvm_unreachable("Unknown ovf instruction!");
18123   case ISD::SADDO:
18124     // A subtract of one will be selected as a INC. Note that INC doesn't
18125     // set CF, so we can't do this for UADDO.
18126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18127       if (C->isOne()) {
18128         BaseOp = X86ISD::INC;
18129         Cond = X86::COND_O;
18130         break;
18131       }
18132     BaseOp = X86ISD::ADD;
18133     Cond = X86::COND_O;
18134     break;
18135   case ISD::UADDO:
18136     BaseOp = X86ISD::ADD;
18137     Cond = X86::COND_B;
18138     break;
18139   case ISD::SSUBO:
18140     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18141     // set CF, so we can't do this for USUBO.
18142     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18143       if (C->isOne()) {
18144         BaseOp = X86ISD::DEC;
18145         Cond = X86::COND_O;
18146         break;
18147       }
18148     BaseOp = X86ISD::SUB;
18149     Cond = X86::COND_O;
18150     break;
18151   case ISD::USUBO:
18152     BaseOp = X86ISD::SUB;
18153     Cond = X86::COND_B;
18154     break;
18155   case ISD::SMULO:
18156     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18157     Cond = X86::COND_O;
18158     break;
18159   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18160     if (N->getValueType(0) == MVT::i8) {
18161       BaseOp = X86ISD::UMUL8;
18162       Cond = X86::COND_O;
18163       break;
18164     }
18165     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18166                                  MVT::i32);
18167     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18168
18169     SDValue SetCC =
18170       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18171                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18172                   SDValue(Sum.getNode(), 2));
18173
18174     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18175   }
18176   }
18177
18178   // Also sets EFLAGS.
18179   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18180   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18181
18182   SDValue SetCC =
18183     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18184                 DAG.getConstant(Cond, DL, MVT::i32),
18185                 SDValue(Sum.getNode(), 1));
18186
18187   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18188 }
18189
18190 /// Returns true if the operand type is exactly twice the native width, and
18191 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18192 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18193 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18194 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18195   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18196
18197   if (OpWidth == 64)
18198     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18199   else if (OpWidth == 128)
18200     return Subtarget->hasCmpxchg16b();
18201   else
18202     return false;
18203 }
18204
18205 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18206   return needsCmpXchgNb(SI->getValueOperand()->getType());
18207 }
18208
18209 // Note: this turns large loads into lock cmpxchg8b/16b.
18210 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18211 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18212   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18213   return needsCmpXchgNb(PTy->getElementType());
18214 }
18215
18216 TargetLoweringBase::AtomicRMWExpansionKind
18217 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18218   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18219   Type *MemType = AI->getType();
18220
18221   // If the operand is too big, we must see if cmpxchg8/16b is available
18222   // and default to library calls otherwise.
18223   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18224     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18225                                    : AtomicRMWExpansionKind::None;
18226   }
18227
18228   AtomicRMWInst::BinOp Op = AI->getOperation();
18229   switch (Op) {
18230   default:
18231     llvm_unreachable("Unknown atomic operation");
18232   case AtomicRMWInst::Xchg:
18233   case AtomicRMWInst::Add:
18234   case AtomicRMWInst::Sub:
18235     // It's better to use xadd, xsub or xchg for these in all cases.
18236     return AtomicRMWExpansionKind::None;
18237   case AtomicRMWInst::Or:
18238   case AtomicRMWInst::And:
18239   case AtomicRMWInst::Xor:
18240     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18241     // prefix to a normal instruction for these operations.
18242     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18243                             : AtomicRMWExpansionKind::None;
18244   case AtomicRMWInst::Nand:
18245   case AtomicRMWInst::Max:
18246   case AtomicRMWInst::Min:
18247   case AtomicRMWInst::UMax:
18248   case AtomicRMWInst::UMin:
18249     // These always require a non-trivial set of data operations on x86. We must
18250     // use a cmpxchg loop.
18251     return AtomicRMWExpansionKind::CmpXChg;
18252   }
18253 }
18254
18255 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18256   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18257   // no-sse2). There isn't any reason to disable it if the target processor
18258   // supports it.
18259   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18260 }
18261
18262 LoadInst *
18263 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18264   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18265   Type *MemType = AI->getType();
18266   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18267   // there is no benefit in turning such RMWs into loads, and it is actually
18268   // harmful as it introduces a mfence.
18269   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18270     return nullptr;
18271
18272   auto Builder = IRBuilder<>(AI);
18273   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18274   auto SynchScope = AI->getSynchScope();
18275   // We must restrict the ordering to avoid generating loads with Release or
18276   // ReleaseAcquire orderings.
18277   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18278   auto Ptr = AI->getPointerOperand();
18279
18280   // Before the load we need a fence. Here is an example lifted from
18281   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18282   // is required:
18283   // Thread 0:
18284   //   x.store(1, relaxed);
18285   //   r1 = y.fetch_add(0, release);
18286   // Thread 1:
18287   //   y.fetch_add(42, acquire);
18288   //   r2 = x.load(relaxed);
18289   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18290   // lowered to just a load without a fence. A mfence flushes the store buffer,
18291   // making the optimization clearly correct.
18292   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18293   // otherwise, we might be able to be more aggressive on relaxed idempotent
18294   // rmw. In practice, they do not look useful, so we don't try to be
18295   // especially clever.
18296   if (SynchScope == SingleThread)
18297     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18298     // the IR level, so we must wrap it in an intrinsic.
18299     return nullptr;
18300
18301   if (!hasMFENCE(*Subtarget))
18302     // FIXME: it might make sense to use a locked operation here but on a
18303     // different cache-line to prevent cache-line bouncing. In practice it
18304     // is probably a small win, and x86 processors without mfence are rare
18305     // enough that we do not bother.
18306     return nullptr;
18307
18308   Function *MFence =
18309       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18310   Builder.CreateCall(MFence, {});
18311
18312   // Finally we can emit the atomic load.
18313   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18314           AI->getType()->getPrimitiveSizeInBits());
18315   Loaded->setAtomic(Order, SynchScope);
18316   AI->replaceAllUsesWith(Loaded);
18317   AI->eraseFromParent();
18318   return Loaded;
18319 }
18320
18321 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18322                                  SelectionDAG &DAG) {
18323   SDLoc dl(Op);
18324   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18325     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18326   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18327     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18328
18329   // The only fence that needs an instruction is a sequentially-consistent
18330   // cross-thread fence.
18331   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18332     if (hasMFENCE(*Subtarget))
18333       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18334
18335     SDValue Chain = Op.getOperand(0);
18336     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18337     SDValue Ops[] = {
18338       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18339       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18340       DAG.getRegister(0, MVT::i32),            // Index
18341       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18342       DAG.getRegister(0, MVT::i32),            // Segment.
18343       Zero,
18344       Chain
18345     };
18346     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18347     return SDValue(Res, 0);
18348   }
18349
18350   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18351   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18352 }
18353
18354 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18355                              SelectionDAG &DAG) {
18356   MVT T = Op.getSimpleValueType();
18357   SDLoc DL(Op);
18358   unsigned Reg = 0;
18359   unsigned size = 0;
18360   switch(T.SimpleTy) {
18361   default: llvm_unreachable("Invalid value type!");
18362   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18363   case MVT::i16: Reg = X86::AX;  size = 2; break;
18364   case MVT::i32: Reg = X86::EAX; size = 4; break;
18365   case MVT::i64:
18366     assert(Subtarget->is64Bit() && "Node not type legal!");
18367     Reg = X86::RAX; size = 8;
18368     break;
18369   }
18370   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18371                                   Op.getOperand(2), SDValue());
18372   SDValue Ops[] = { cpIn.getValue(0),
18373                     Op.getOperand(1),
18374                     Op.getOperand(3),
18375                     DAG.getTargetConstant(size, DL, MVT::i8),
18376                     cpIn.getValue(1) };
18377   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18378   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18379   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18380                                            Ops, T, MMO);
18381
18382   SDValue cpOut =
18383     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18384   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18385                                       MVT::i32, cpOut.getValue(2));
18386   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18387                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18388                                 EFLAGS);
18389
18390   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18391   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18392   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18393   return SDValue();
18394 }
18395
18396 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18397                             SelectionDAG &DAG) {
18398   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18399   MVT DstVT = Op.getSimpleValueType();
18400
18401   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18402     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18403     if (DstVT != MVT::f64)
18404       // This conversion needs to be expanded.
18405       return SDValue();
18406
18407     SDValue InVec = Op->getOperand(0);
18408     SDLoc dl(Op);
18409     unsigned NumElts = SrcVT.getVectorNumElements();
18410     EVT SVT = SrcVT.getVectorElementType();
18411
18412     // Widen the vector in input in the case of MVT::v2i32.
18413     // Example: from MVT::v2i32 to MVT::v4i32.
18414     SmallVector<SDValue, 16> Elts;
18415     for (unsigned i = 0, e = NumElts; i != e; ++i)
18416       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18417                                  DAG.getIntPtrConstant(i, dl)));
18418
18419     // Explicitly mark the extra elements as Undef.
18420     Elts.append(NumElts, DAG.getUNDEF(SVT));
18421
18422     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18423     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18424     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18425     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18426                        DAG.getIntPtrConstant(0, dl));
18427   }
18428
18429   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18430          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18431   assert((DstVT == MVT::i64 ||
18432           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18433          "Unexpected custom BITCAST");
18434   // i64 <=> MMX conversions are Legal.
18435   if (SrcVT==MVT::i64 && DstVT.isVector())
18436     return Op;
18437   if (DstVT==MVT::i64 && SrcVT.isVector())
18438     return Op;
18439   // MMX <=> MMX conversions are Legal.
18440   if (SrcVT.isVector() && DstVT.isVector())
18441     return Op;
18442   // All other conversions need to be expanded.
18443   return SDValue();
18444 }
18445
18446 /// Compute the horizontal sum of bytes in V for the elements of VT.
18447 ///
18448 /// Requires V to be a byte vector and VT to be an integer vector type with
18449 /// wider elements than V's type. The width of the elements of VT determines
18450 /// how many bytes of V are summed horizontally to produce each element of the
18451 /// result.
18452 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18453                                       const X86Subtarget *Subtarget,
18454                                       SelectionDAG &DAG) {
18455   SDLoc DL(V);
18456   MVT ByteVecVT = V.getSimpleValueType();
18457   MVT EltVT = VT.getVectorElementType();
18458   int NumElts = VT.getVectorNumElements();
18459   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18460          "Expected value to have byte element type.");
18461   assert(EltVT != MVT::i8 &&
18462          "Horizontal byte sum only makes sense for wider elements!");
18463   unsigned VecSize = VT.getSizeInBits();
18464   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18465
18466   // PSADBW instruction horizontally add all bytes and leave the result in i64
18467   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18468   if (EltVT == MVT::i64) {
18469     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18470     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18471     return DAG.getBitcast(VT, V);
18472   }
18473
18474   if (EltVT == MVT::i32) {
18475     // We unpack the low half and high half into i32s interleaved with zeros so
18476     // that we can use PSADBW to horizontally sum them. The most useful part of
18477     // this is that it lines up the results of two PSADBW instructions to be
18478     // two v2i64 vectors which concatenated are the 4 population counts. We can
18479     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18480     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18481     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18482     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18483
18484     // Do the horizontal sums into two v2i64s.
18485     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18486     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18487                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18488     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18489                        DAG.getBitcast(ByteVecVT, High), Zeros);
18490
18491     // Merge them together.
18492     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18493     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18494                     DAG.getBitcast(ShortVecVT, Low),
18495                     DAG.getBitcast(ShortVecVT, High));
18496
18497     return DAG.getBitcast(VT, V);
18498   }
18499
18500   // The only element type left is i16.
18501   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18502
18503   // To obtain pop count for each i16 element starting from the pop count for
18504   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18505   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18506   // directly supported.
18507   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18508   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18509   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18510   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18511                   DAG.getBitcast(ByteVecVT, V));
18512   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18513 }
18514
18515 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18516                                         const X86Subtarget *Subtarget,
18517                                         SelectionDAG &DAG) {
18518   MVT VT = Op.getSimpleValueType();
18519   MVT EltVT = VT.getVectorElementType();
18520   unsigned VecSize = VT.getSizeInBits();
18521
18522   // Implement a lookup table in register by using an algorithm based on:
18523   // http://wm.ite.pl/articles/sse-popcount.html
18524   //
18525   // The general idea is that every lower byte nibble in the input vector is an
18526   // index into a in-register pre-computed pop count table. We then split up the
18527   // input vector in two new ones: (1) a vector with only the shifted-right
18528   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18529   // masked out higher ones) for each byte. PSHUB is used separately with both
18530   // to index the in-register table. Next, both are added and the result is a
18531   // i8 vector where each element contains the pop count for input byte.
18532   //
18533   // To obtain the pop count for elements != i8, we follow up with the same
18534   // approach and use additional tricks as described below.
18535   //
18536   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18537                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18538                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18539                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18540
18541   int NumByteElts = VecSize / 8;
18542   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18543   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18544   SmallVector<SDValue, 16> LUTVec;
18545   for (int i = 0; i < NumByteElts; ++i)
18546     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18547   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18548   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18549                                   DAG.getConstant(0x0F, DL, MVT::i8));
18550   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18551
18552   // High nibbles
18553   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18554   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18555   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18556
18557   // Low nibbles
18558   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18559
18560   // The input vector is used as the shuffle mask that index elements into the
18561   // LUT. After counting low and high nibbles, add the vector to obtain the
18562   // final pop count per i8 element.
18563   SDValue HighPopCnt =
18564       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18565   SDValue LowPopCnt =
18566       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18567   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18568
18569   if (EltVT == MVT::i8)
18570     return PopCnt;
18571
18572   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18573 }
18574
18575 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18576                                        const X86Subtarget *Subtarget,
18577                                        SelectionDAG &DAG) {
18578   MVT VT = Op.getSimpleValueType();
18579   assert(VT.is128BitVector() &&
18580          "Only 128-bit vector bitmath lowering supported.");
18581
18582   int VecSize = VT.getSizeInBits();
18583   MVT EltVT = VT.getVectorElementType();
18584   int Len = EltVT.getSizeInBits();
18585
18586   // This is the vectorized version of the "best" algorithm from
18587   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18588   // with a minor tweak to use a series of adds + shifts instead of vector
18589   // multiplications. Implemented for all integer vector types. We only use
18590   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18591   // much faster, even faster than using native popcnt instructions.
18592
18593   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18594     MVT VT = V.getSimpleValueType();
18595     SmallVector<SDValue, 32> Shifters(
18596         VT.getVectorNumElements(),
18597         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18598     return DAG.getNode(OpCode, DL, VT, V,
18599                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18600   };
18601   auto GetMask = [&](SDValue V, APInt Mask) {
18602     MVT VT = V.getSimpleValueType();
18603     SmallVector<SDValue, 32> Masks(
18604         VT.getVectorNumElements(),
18605         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18606     return DAG.getNode(ISD::AND, DL, VT, V,
18607                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18608   };
18609
18610   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18611   // x86, so set the SRL type to have elements at least i16 wide. This is
18612   // correct because all of our SRLs are followed immediately by a mask anyways
18613   // that handles any bits that sneak into the high bits of the byte elements.
18614   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18615
18616   SDValue V = Op;
18617
18618   // v = v - ((v >> 1) & 0x55555555...)
18619   SDValue Srl =
18620       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18621   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18622   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18623
18624   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18625   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18626   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18627   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18628   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18629
18630   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18631   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18632   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18633   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18634
18635   // At this point, V contains the byte-wise population count, and we are
18636   // merely doing a horizontal sum if necessary to get the wider element
18637   // counts.
18638   if (EltVT == MVT::i8)
18639     return V;
18640
18641   return LowerHorizontalByteSum(
18642       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18643       DAG);
18644 }
18645
18646 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18647                                 SelectionDAG &DAG) {
18648   MVT VT = Op.getSimpleValueType();
18649   // FIXME: Need to add AVX-512 support here!
18650   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18651          "Unknown CTPOP type to handle");
18652   SDLoc DL(Op.getNode());
18653   SDValue Op0 = Op.getOperand(0);
18654
18655   if (!Subtarget->hasSSSE3()) {
18656     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18657     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18658     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18659   }
18660
18661   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18662     unsigned NumElems = VT.getVectorNumElements();
18663
18664     // Extract each 128-bit vector, compute pop count and concat the result.
18665     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18666     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18667
18668     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18669                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18670                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18671   }
18672
18673   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18674 }
18675
18676 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18677                           SelectionDAG &DAG) {
18678   assert(Op.getValueType().isVector() &&
18679          "We only do custom lowering for vector population count.");
18680   return LowerVectorCTPOP(Op, Subtarget, DAG);
18681 }
18682
18683 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18684   SDNode *Node = Op.getNode();
18685   SDLoc dl(Node);
18686   EVT T = Node->getValueType(0);
18687   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18688                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18689   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18690                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18691                        Node->getOperand(0),
18692                        Node->getOperand(1), negOp,
18693                        cast<AtomicSDNode>(Node)->getMemOperand(),
18694                        cast<AtomicSDNode>(Node)->getOrdering(),
18695                        cast<AtomicSDNode>(Node)->getSynchScope());
18696 }
18697
18698 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18699   SDNode *Node = Op.getNode();
18700   SDLoc dl(Node);
18701   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18702
18703   // Convert seq_cst store -> xchg
18704   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18705   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18706   //        (The only way to get a 16-byte store is cmpxchg16b)
18707   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18708   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18709       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18710     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18711                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18712                                  Node->getOperand(0),
18713                                  Node->getOperand(1), Node->getOperand(2),
18714                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18715                                  cast<AtomicSDNode>(Node)->getOrdering(),
18716                                  cast<AtomicSDNode>(Node)->getSynchScope());
18717     return Swap.getValue(1);
18718   }
18719   // Other atomic stores have a simple pattern.
18720   return Op;
18721 }
18722
18723 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18724   EVT VT = Op.getNode()->getSimpleValueType(0);
18725
18726   // Let legalize expand this if it isn't a legal type yet.
18727   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18728     return SDValue();
18729
18730   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18731
18732   unsigned Opc;
18733   bool ExtraOp = false;
18734   switch (Op.getOpcode()) {
18735   default: llvm_unreachable("Invalid code");
18736   case ISD::ADDC: Opc = X86ISD::ADD; break;
18737   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18738   case ISD::SUBC: Opc = X86ISD::SUB; break;
18739   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18740   }
18741
18742   if (!ExtraOp)
18743     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18744                        Op.getOperand(1));
18745   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18746                      Op.getOperand(1), Op.getOperand(2));
18747 }
18748
18749 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18750                             SelectionDAG &DAG) {
18751   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18752
18753   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18754   // which returns the values as { float, float } (in XMM0) or
18755   // { double, double } (which is returned in XMM0, XMM1).
18756   SDLoc dl(Op);
18757   SDValue Arg = Op.getOperand(0);
18758   EVT ArgVT = Arg.getValueType();
18759   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18760
18761   TargetLowering::ArgListTy Args;
18762   TargetLowering::ArgListEntry Entry;
18763
18764   Entry.Node = Arg;
18765   Entry.Ty = ArgTy;
18766   Entry.isSExt = false;
18767   Entry.isZExt = false;
18768   Args.push_back(Entry);
18769
18770   bool isF64 = ArgVT == MVT::f64;
18771   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18772   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18773   // the results are returned via SRet in memory.
18774   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18775   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18776   SDValue Callee =
18777       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18778
18779   Type *RetTy = isF64
18780     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18781     : (Type*)VectorType::get(ArgTy, 4);
18782
18783   TargetLowering::CallLoweringInfo CLI(DAG);
18784   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18785     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18786
18787   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18788
18789   if (isF64)
18790     // Returned in xmm0 and xmm1.
18791     return CallResult.first;
18792
18793   // Returned in bits 0:31 and 32:64 xmm0.
18794   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18795                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18796   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18797                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18798   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18799   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18800 }
18801
18802 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18803                              SelectionDAG &DAG) {
18804   assert(Subtarget->hasAVX512() &&
18805          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18806
18807   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18808   EVT VT = N->getValue().getValueType();
18809   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18810   SDLoc dl(Op);
18811
18812   // X86 scatter kills mask register, so its type should be added to
18813   // the list of return values
18814   if (N->getNumValues() == 1) {
18815     SDValue Index = N->getIndex();
18816     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18817         !Index.getValueType().is512BitVector())
18818       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18819
18820     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18821     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18822                       N->getOperand(3), Index };
18823
18824     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18825     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18826     return SDValue(NewScatter.getNode(), 0);
18827   }
18828   return Op;
18829 }
18830
18831 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18832                             SelectionDAG &DAG) {
18833   assert(Subtarget->hasAVX512() &&
18834          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18835
18836   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18837   EVT VT = Op.getValueType();
18838   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18839   SDLoc dl(Op);
18840
18841   SDValue Index = N->getIndex();
18842   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18843       !Index.getValueType().is512BitVector()) {
18844     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18845     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18846                       N->getOperand(3), Index };
18847     DAG.UpdateNodeOperands(N, Ops);
18848   }
18849   return Op;
18850 }
18851
18852 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18853                                                     SelectionDAG &DAG) const {
18854   // TODO: Eventually, the lowering of these nodes should be informed by or
18855   // deferred to the GC strategy for the function in which they appear. For
18856   // now, however, they must be lowered to something. Since they are logically
18857   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18858   // require special handling for these nodes), lower them as literal NOOPs for
18859   // the time being.
18860   SmallVector<SDValue, 2> Ops;
18861
18862   Ops.push_back(Op.getOperand(0));
18863   if (Op->getGluedNode())
18864     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18865
18866   SDLoc OpDL(Op);
18867   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18868   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18869
18870   return NOOP;
18871 }
18872
18873 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18874                                                   SelectionDAG &DAG) const {
18875   // TODO: Eventually, the lowering of these nodes should be informed by or
18876   // deferred to the GC strategy for the function in which they appear. For
18877   // now, however, they must be lowered to something. Since they are logically
18878   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18879   // require special handling for these nodes), lower them as literal NOOPs for
18880   // the time being.
18881   SmallVector<SDValue, 2> Ops;
18882
18883   Ops.push_back(Op.getOperand(0));
18884   if (Op->getGluedNode())
18885     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18886
18887   SDLoc OpDL(Op);
18888   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18889   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18890
18891   return NOOP;
18892 }
18893
18894 /// LowerOperation - Provide custom lowering hooks for some operations.
18895 ///
18896 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18897   switch (Op.getOpcode()) {
18898   default: llvm_unreachable("Should not custom lower this!");
18899   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18900   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18901     return LowerCMP_SWAP(Op, Subtarget, DAG);
18902   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18903   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18904   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18905   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18906   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18907   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18908   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18909   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18910   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18911   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18912   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18913   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18914   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18915   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18916   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18917   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18918   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18919   case ISD::SHL_PARTS:
18920   case ISD::SRA_PARTS:
18921   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18922   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18923   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18924   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18925   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18926   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18927   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18928   case ISD::SIGN_EXTEND_VECTOR_INREG:
18929     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18930   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18931   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18932   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18933   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18934   case ISD::FABS:
18935   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18936   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18937   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18938   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18939   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18940   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18941   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18942   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18943   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18944   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18945   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18946   case ISD::INTRINSIC_VOID:
18947   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18948   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18949   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18950   case ISD::FRAME_TO_ARGS_OFFSET:
18951                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18952   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18953   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18954   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
18955   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18956   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18957   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18958   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18959   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18960   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18961   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18962   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18963   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18964   case ISD::UMUL_LOHI:
18965   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18966   case ISD::SRA:
18967   case ISD::SRL:
18968   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18969   case ISD::SADDO:
18970   case ISD::UADDO:
18971   case ISD::SSUBO:
18972   case ISD::USUBO:
18973   case ISD::SMULO:
18974   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18975   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18976   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18977   case ISD::ADDC:
18978   case ISD::ADDE:
18979   case ISD::SUBC:
18980   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18981   case ISD::ADD:                return LowerADD(Op, DAG);
18982   case ISD::SUB:                return LowerSUB(Op, DAG);
18983   case ISD::SMAX:
18984   case ISD::SMIN:
18985   case ISD::UMAX:
18986   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18987   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18988   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18989   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18990   case ISD::GC_TRANSITION_START:
18991                                 return LowerGC_TRANSITION_START(Op, DAG);
18992   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18993   }
18994 }
18995
18996 /// ReplaceNodeResults - Replace a node with an illegal result type
18997 /// with a new node built out of custom code.
18998 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18999                                            SmallVectorImpl<SDValue>&Results,
19000                                            SelectionDAG &DAG) const {
19001   SDLoc dl(N);
19002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19003   switch (N->getOpcode()) {
19004   default:
19005     llvm_unreachable("Do not know how to custom type legalize this operation!");
19006   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19007   case X86ISD::FMINC:
19008   case X86ISD::FMIN:
19009   case X86ISD::FMAXC:
19010   case X86ISD::FMAX: {
19011     EVT VT = N->getValueType(0);
19012     if (VT != MVT::v2f32)
19013       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19014     SDValue UNDEF = DAG.getUNDEF(VT);
19015     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19016                               N->getOperand(0), UNDEF);
19017     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19018                               N->getOperand(1), UNDEF);
19019     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19020     return;
19021   }
19022   case ISD::SIGN_EXTEND_INREG:
19023   case ISD::ADDC:
19024   case ISD::ADDE:
19025   case ISD::SUBC:
19026   case ISD::SUBE:
19027     // We don't want to expand or promote these.
19028     return;
19029   case ISD::SDIV:
19030   case ISD::UDIV:
19031   case ISD::SREM:
19032   case ISD::UREM:
19033   case ISD::SDIVREM:
19034   case ISD::UDIVREM: {
19035     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19036     Results.push_back(V);
19037     return;
19038   }
19039   case ISD::FP_TO_SINT:
19040   case ISD::FP_TO_UINT: {
19041     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19042
19043     std::pair<SDValue,SDValue> Vals =
19044         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19045     SDValue FIST = Vals.first, StackSlot = Vals.second;
19046     if (FIST.getNode()) {
19047       EVT VT = N->getValueType(0);
19048       // Return a load from the stack slot.
19049       if (StackSlot.getNode())
19050         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19051                                       MachinePointerInfo(),
19052                                       false, false, false, 0));
19053       else
19054         Results.push_back(FIST);
19055     }
19056     return;
19057   }
19058   case ISD::UINT_TO_FP: {
19059     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19060     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19061         N->getValueType(0) != MVT::v2f32)
19062       return;
19063     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19064                                  N->getOperand(0));
19065     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19066                                      MVT::f64);
19067     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19068     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19069                              DAG.getBitcast(MVT::v2i64, VBias));
19070     Or = DAG.getBitcast(MVT::v2f64, Or);
19071     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19072     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19073     return;
19074   }
19075   case ISD::FP_ROUND: {
19076     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19077         return;
19078     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19079     Results.push_back(V);
19080     return;
19081   }
19082   case ISD::FP_EXTEND: {
19083     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19084     // No other ValueType for FP_EXTEND should reach this point.
19085     assert(N->getValueType(0) == MVT::v2f32 &&
19086            "Do not know how to legalize this Node");
19087     return;
19088   }
19089   case ISD::INTRINSIC_W_CHAIN: {
19090     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19091     switch (IntNo) {
19092     default : llvm_unreachable("Do not know how to custom type "
19093                                "legalize this intrinsic operation!");
19094     case Intrinsic::x86_rdtsc:
19095       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19096                                      Results);
19097     case Intrinsic::x86_rdtscp:
19098       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19099                                      Results);
19100     case Intrinsic::x86_rdpmc:
19101       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19102     }
19103   }
19104   case ISD::READCYCLECOUNTER: {
19105     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19106                                    Results);
19107   }
19108   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19109     EVT T = N->getValueType(0);
19110     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19111     bool Regs64bit = T == MVT::i128;
19112     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19113     SDValue cpInL, cpInH;
19114     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19115                         DAG.getConstant(0, dl, HalfT));
19116     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19117                         DAG.getConstant(1, dl, HalfT));
19118     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19119                              Regs64bit ? X86::RAX : X86::EAX,
19120                              cpInL, SDValue());
19121     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19122                              Regs64bit ? X86::RDX : X86::EDX,
19123                              cpInH, cpInL.getValue(1));
19124     SDValue swapInL, swapInH;
19125     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19126                           DAG.getConstant(0, dl, HalfT));
19127     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19128                           DAG.getConstant(1, dl, HalfT));
19129     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19130                                Regs64bit ? X86::RBX : X86::EBX,
19131                                swapInL, cpInH.getValue(1));
19132     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19133                                Regs64bit ? X86::RCX : X86::ECX,
19134                                swapInH, swapInL.getValue(1));
19135     SDValue Ops[] = { swapInH.getValue(0),
19136                       N->getOperand(1),
19137                       swapInH.getValue(1) };
19138     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19139     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19140     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19141                                   X86ISD::LCMPXCHG8_DAG;
19142     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19143     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19144                                         Regs64bit ? X86::RAX : X86::EAX,
19145                                         HalfT, Result.getValue(1));
19146     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19147                                         Regs64bit ? X86::RDX : X86::EDX,
19148                                         HalfT, cpOutL.getValue(2));
19149     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19150
19151     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19152                                         MVT::i32, cpOutH.getValue(2));
19153     SDValue Success =
19154         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19155                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19156     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19157
19158     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19159     Results.push_back(Success);
19160     Results.push_back(EFLAGS.getValue(1));
19161     return;
19162   }
19163   case ISD::ATOMIC_SWAP:
19164   case ISD::ATOMIC_LOAD_ADD:
19165   case ISD::ATOMIC_LOAD_SUB:
19166   case ISD::ATOMIC_LOAD_AND:
19167   case ISD::ATOMIC_LOAD_OR:
19168   case ISD::ATOMIC_LOAD_XOR:
19169   case ISD::ATOMIC_LOAD_NAND:
19170   case ISD::ATOMIC_LOAD_MIN:
19171   case ISD::ATOMIC_LOAD_MAX:
19172   case ISD::ATOMIC_LOAD_UMIN:
19173   case ISD::ATOMIC_LOAD_UMAX:
19174   case ISD::ATOMIC_LOAD: {
19175     // Delegate to generic TypeLegalization. Situations we can really handle
19176     // should have already been dealt with by AtomicExpandPass.cpp.
19177     break;
19178   }
19179   case ISD::BITCAST: {
19180     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19181     EVT DstVT = N->getValueType(0);
19182     EVT SrcVT = N->getOperand(0)->getValueType(0);
19183
19184     if (SrcVT != MVT::f64 ||
19185         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19186       return;
19187
19188     unsigned NumElts = DstVT.getVectorNumElements();
19189     EVT SVT = DstVT.getVectorElementType();
19190     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19191     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19192                                    MVT::v2f64, N->getOperand(0));
19193     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19194
19195     if (ExperimentalVectorWideningLegalization) {
19196       // If we are legalizing vectors by widening, we already have the desired
19197       // legal vector type, just return it.
19198       Results.push_back(ToVecInt);
19199       return;
19200     }
19201
19202     SmallVector<SDValue, 8> Elts;
19203     for (unsigned i = 0, e = NumElts; i != e; ++i)
19204       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19205                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19206
19207     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19208   }
19209   }
19210 }
19211
19212 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19213   switch ((X86ISD::NodeType)Opcode) {
19214   case X86ISD::FIRST_NUMBER:       break;
19215   case X86ISD::BSF:                return "X86ISD::BSF";
19216   case X86ISD::BSR:                return "X86ISD::BSR";
19217   case X86ISD::SHLD:               return "X86ISD::SHLD";
19218   case X86ISD::SHRD:               return "X86ISD::SHRD";
19219   case X86ISD::FAND:               return "X86ISD::FAND";
19220   case X86ISD::FANDN:              return "X86ISD::FANDN";
19221   case X86ISD::FOR:                return "X86ISD::FOR";
19222   case X86ISD::FXOR:               return "X86ISD::FXOR";
19223   case X86ISD::FILD:               return "X86ISD::FILD";
19224   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19225   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19226   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19227   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19228   case X86ISD::FLD:                return "X86ISD::FLD";
19229   case X86ISD::FST:                return "X86ISD::FST";
19230   case X86ISD::CALL:               return "X86ISD::CALL";
19231   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19232   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19233   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19234   case X86ISD::BT:                 return "X86ISD::BT";
19235   case X86ISD::CMP:                return "X86ISD::CMP";
19236   case X86ISD::COMI:               return "X86ISD::COMI";
19237   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19238   case X86ISD::CMPM:               return "X86ISD::CMPM";
19239   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19240   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19241   case X86ISD::SETCC:              return "X86ISD::SETCC";
19242   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19243   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19244   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19245   case X86ISD::CMOV:               return "X86ISD::CMOV";
19246   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19247   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19248   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19249   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19250   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19251   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19252   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19253   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19254   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19255   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19256   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19257   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19258   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19259   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19260   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19261   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19262   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19263   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19264   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19265   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19266   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19267   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19268   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19269   case X86ISD::HADD:               return "X86ISD::HADD";
19270   case X86ISD::HSUB:               return "X86ISD::HSUB";
19271   case X86ISD::FHADD:              return "X86ISD::FHADD";
19272   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19273   case X86ISD::ABS:                return "X86ISD::ABS";
19274   case X86ISD::FMAX:               return "X86ISD::FMAX";
19275   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19276   case X86ISD::FMIN:               return "X86ISD::FMIN";
19277   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19278   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19279   case X86ISD::FMINC:              return "X86ISD::FMINC";
19280   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19281   case X86ISD::FRCP:               return "X86ISD::FRCP";
19282   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19283   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19284   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19285   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19286   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19287   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19288   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19289   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19290   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19291   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19292   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19293   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19294   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19295   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19296   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19297   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19298   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19299   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19300   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19301   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19302   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19303   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19304   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19305   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19306   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19307   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19308   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19309   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19310   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19311   case X86ISD::VSHL:               return "X86ISD::VSHL";
19312   case X86ISD::VSRL:               return "X86ISD::VSRL";
19313   case X86ISD::VSRA:               return "X86ISD::VSRA";
19314   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19315   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19316   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19317   case X86ISD::CMPP:               return "X86ISD::CMPP";
19318   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19319   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19320   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19321   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19322   case X86ISD::ADD:                return "X86ISD::ADD";
19323   case X86ISD::SUB:                return "X86ISD::SUB";
19324   case X86ISD::ADC:                return "X86ISD::ADC";
19325   case X86ISD::SBB:                return "X86ISD::SBB";
19326   case X86ISD::SMUL:               return "X86ISD::SMUL";
19327   case X86ISD::UMUL:               return "X86ISD::UMUL";
19328   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19329   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19330   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19331   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19332   case X86ISD::INC:                return "X86ISD::INC";
19333   case X86ISD::DEC:                return "X86ISD::DEC";
19334   case X86ISD::OR:                 return "X86ISD::OR";
19335   case X86ISD::XOR:                return "X86ISD::XOR";
19336   case X86ISD::AND:                return "X86ISD::AND";
19337   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19338   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19339   case X86ISD::PTEST:              return "X86ISD::PTEST";
19340   case X86ISD::TESTP:              return "X86ISD::TESTP";
19341   case X86ISD::TESTM:              return "X86ISD::TESTM";
19342   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19343   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19344   case X86ISD::KTEST:              return "X86ISD::KTEST";
19345   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19346   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19347   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19348   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19349   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19350   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19351   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19352   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19353   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19354   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19355   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19356   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19357   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19358   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19359   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19360   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19361   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19362   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19363   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19364   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19365   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19366   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19367   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19368   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19369   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19370   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19371   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19372   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19373   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19374   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19375   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19376   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19377   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19378   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19379   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19380   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19381   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19382   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19383   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19384   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19385   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19386   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19387   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19388   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19389   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19390   case X86ISD::SAHF:               return "X86ISD::SAHF";
19391   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19392   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19393   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19394   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19395   case X86ISD::FMADD:              return "X86ISD::FMADD";
19396   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19397   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19398   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19399   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19400   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19401   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19402   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19403   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19404   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19405   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19406   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19407   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19408   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19409   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19410   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19411   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19412   case X86ISD::XTEST:              return "X86ISD::XTEST";
19413   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19414   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19415   case X86ISD::SELECT:             return "X86ISD::SELECT";
19416   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19417   case X86ISD::RCP28:              return "X86ISD::RCP28";
19418   case X86ISD::EXP2:               return "X86ISD::EXP2";
19419   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19420   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19421   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19422   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19423   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19424   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19425   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19426   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19427   case X86ISD::ADDS:               return "X86ISD::ADDS";
19428   case X86ISD::SUBS:               return "X86ISD::SUBS";
19429   case X86ISD::AVG:                return "X86ISD::AVG";
19430   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19431   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19432   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19433   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19434   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19435   }
19436   return nullptr;
19437 }
19438
19439 // isLegalAddressingMode - Return true if the addressing mode represented
19440 // by AM is legal for this target, for a load/store of the specified type.
19441 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19442                                               const AddrMode &AM, Type *Ty,
19443                                               unsigned AS) const {
19444   // X86 supports extremely general addressing modes.
19445   CodeModel::Model M = getTargetMachine().getCodeModel();
19446   Reloc::Model R = getTargetMachine().getRelocationModel();
19447
19448   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19449   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19450     return false;
19451
19452   if (AM.BaseGV) {
19453     unsigned GVFlags =
19454       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19455
19456     // If a reference to this global requires an extra load, we can't fold it.
19457     if (isGlobalStubReference(GVFlags))
19458       return false;
19459
19460     // If BaseGV requires a register for the PIC base, we cannot also have a
19461     // BaseReg specified.
19462     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19463       return false;
19464
19465     // If lower 4G is not available, then we must use rip-relative addressing.
19466     if ((M != CodeModel::Small || R != Reloc::Static) &&
19467         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19468       return false;
19469   }
19470
19471   switch (AM.Scale) {
19472   case 0:
19473   case 1:
19474   case 2:
19475   case 4:
19476   case 8:
19477     // These scales always work.
19478     break;
19479   case 3:
19480   case 5:
19481   case 9:
19482     // These scales are formed with basereg+scalereg.  Only accept if there is
19483     // no basereg yet.
19484     if (AM.HasBaseReg)
19485       return false;
19486     break;
19487   default:  // Other stuff never works.
19488     return false;
19489   }
19490
19491   return true;
19492 }
19493
19494 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19495   unsigned Bits = Ty->getScalarSizeInBits();
19496
19497   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19498   // particularly cheaper than those without.
19499   if (Bits == 8)
19500     return false;
19501
19502   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19503   // variable shifts just as cheap as scalar ones.
19504   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19505     return false;
19506
19507   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19508   // fully general vector.
19509   return true;
19510 }
19511
19512 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19513   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19514     return false;
19515   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19516   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19517   return NumBits1 > NumBits2;
19518 }
19519
19520 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19521   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19522     return false;
19523
19524   if (!isTypeLegal(EVT::getEVT(Ty1)))
19525     return false;
19526
19527   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19528
19529   // Assuming the caller doesn't have a zeroext or signext return parameter,
19530   // truncation all the way down to i1 is valid.
19531   return true;
19532 }
19533
19534 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19535   return isInt<32>(Imm);
19536 }
19537
19538 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19539   // Can also use sub to handle negated immediates.
19540   return isInt<32>(Imm);
19541 }
19542
19543 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19544   if (!VT1.isInteger() || !VT2.isInteger())
19545     return false;
19546   unsigned NumBits1 = VT1.getSizeInBits();
19547   unsigned NumBits2 = VT2.getSizeInBits();
19548   return NumBits1 > NumBits2;
19549 }
19550
19551 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19552   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19553   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19554 }
19555
19556 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19557   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19558   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19559 }
19560
19561 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19562   EVT VT1 = Val.getValueType();
19563   if (isZExtFree(VT1, VT2))
19564     return true;
19565
19566   if (Val.getOpcode() != ISD::LOAD)
19567     return false;
19568
19569   if (!VT1.isSimple() || !VT1.isInteger() ||
19570       !VT2.isSimple() || !VT2.isInteger())
19571     return false;
19572
19573   switch (VT1.getSimpleVT().SimpleTy) {
19574   default: break;
19575   case MVT::i8:
19576   case MVT::i16:
19577   case MVT::i32:
19578     // X86 has 8, 16, and 32-bit zero-extending loads.
19579     return true;
19580   }
19581
19582   return false;
19583 }
19584
19585 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19586
19587 bool
19588 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19589   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19590     return false;
19591
19592   VT = VT.getScalarType();
19593
19594   if (!VT.isSimple())
19595     return false;
19596
19597   switch (VT.getSimpleVT().SimpleTy) {
19598   case MVT::f32:
19599   case MVT::f64:
19600     return true;
19601   default:
19602     break;
19603   }
19604
19605   return false;
19606 }
19607
19608 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19609   // i16 instructions are longer (0x66 prefix) and potentially slower.
19610   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19611 }
19612
19613 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19614 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19615 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19616 /// are assumed to be legal.
19617 bool
19618 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19619                                       EVT VT) const {
19620   if (!VT.isSimple())
19621     return false;
19622
19623   // Not for i1 vectors
19624   if (VT.getScalarType() == MVT::i1)
19625     return false;
19626
19627   // Very little shuffling can be done for 64-bit vectors right now.
19628   if (VT.getSizeInBits() == 64)
19629     return false;
19630
19631   // We only care that the types being shuffled are legal. The lowering can
19632   // handle any possible shuffle mask that results.
19633   return isTypeLegal(VT.getSimpleVT());
19634 }
19635
19636 bool
19637 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19638                                           EVT VT) const {
19639   // Just delegate to the generic legality, clear masks aren't special.
19640   return isShuffleMaskLegal(Mask, VT);
19641 }
19642
19643 //===----------------------------------------------------------------------===//
19644 //                           X86 Scheduler Hooks
19645 //===----------------------------------------------------------------------===//
19646
19647 /// Utility function to emit xbegin specifying the start of an RTM region.
19648 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19649                                      const TargetInstrInfo *TII) {
19650   DebugLoc DL = MI->getDebugLoc();
19651
19652   const BasicBlock *BB = MBB->getBasicBlock();
19653   MachineFunction::iterator I = MBB;
19654   ++I;
19655
19656   // For the v = xbegin(), we generate
19657   //
19658   // thisMBB:
19659   //  xbegin sinkMBB
19660   //
19661   // mainMBB:
19662   //  eax = -1
19663   //
19664   // sinkMBB:
19665   //  v = eax
19666
19667   MachineBasicBlock *thisMBB = MBB;
19668   MachineFunction *MF = MBB->getParent();
19669   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19670   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19671   MF->insert(I, mainMBB);
19672   MF->insert(I, sinkMBB);
19673
19674   // Transfer the remainder of BB and its successor edges to sinkMBB.
19675   sinkMBB->splice(sinkMBB->begin(), MBB,
19676                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19677   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19678
19679   // thisMBB:
19680   //  xbegin sinkMBB
19681   //  # fallthrough to mainMBB
19682   //  # abortion to sinkMBB
19683   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19684   thisMBB->addSuccessor(mainMBB);
19685   thisMBB->addSuccessor(sinkMBB);
19686
19687   // mainMBB:
19688   //  EAX = -1
19689   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19690   mainMBB->addSuccessor(sinkMBB);
19691
19692   // sinkMBB:
19693   // EAX is live into the sinkMBB
19694   sinkMBB->addLiveIn(X86::EAX);
19695   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19696           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19697     .addReg(X86::EAX);
19698
19699   MI->eraseFromParent();
19700   return sinkMBB;
19701 }
19702
19703 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19704 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19705 // in the .td file.
19706 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19707                                        const TargetInstrInfo *TII) {
19708   unsigned Opc;
19709   switch (MI->getOpcode()) {
19710   default: llvm_unreachable("illegal opcode!");
19711   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19712   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19713   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19714   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19715   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19716   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19717   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19718   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19719   }
19720
19721   DebugLoc dl = MI->getDebugLoc();
19722   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19723
19724   unsigned NumArgs = MI->getNumOperands();
19725   for (unsigned i = 1; i < NumArgs; ++i) {
19726     MachineOperand &Op = MI->getOperand(i);
19727     if (!(Op.isReg() && Op.isImplicit()))
19728       MIB.addOperand(Op);
19729   }
19730   if (MI->hasOneMemOperand())
19731     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19732
19733   BuildMI(*BB, MI, dl,
19734     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19735     .addReg(X86::XMM0);
19736
19737   MI->eraseFromParent();
19738   return BB;
19739 }
19740
19741 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19742 // defs in an instruction pattern
19743 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19744                                        const TargetInstrInfo *TII) {
19745   unsigned Opc;
19746   switch (MI->getOpcode()) {
19747   default: llvm_unreachable("illegal opcode!");
19748   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19749   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19750   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19751   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19752   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19753   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19754   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19755   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19756   }
19757
19758   DebugLoc dl = MI->getDebugLoc();
19759   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19760
19761   unsigned NumArgs = MI->getNumOperands(); // remove the results
19762   for (unsigned i = 1; i < NumArgs; ++i) {
19763     MachineOperand &Op = MI->getOperand(i);
19764     if (!(Op.isReg() && Op.isImplicit()))
19765       MIB.addOperand(Op);
19766   }
19767   if (MI->hasOneMemOperand())
19768     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19769
19770   BuildMI(*BB, MI, dl,
19771     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19772     .addReg(X86::ECX);
19773
19774   MI->eraseFromParent();
19775   return BB;
19776 }
19777
19778 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19779                                       const X86Subtarget *Subtarget) {
19780   DebugLoc dl = MI->getDebugLoc();
19781   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19782   // Address into RAX/EAX, other two args into ECX, EDX.
19783   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19784   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19785   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19786   for (int i = 0; i < X86::AddrNumOperands; ++i)
19787     MIB.addOperand(MI->getOperand(i));
19788
19789   unsigned ValOps = X86::AddrNumOperands;
19790   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19791     .addReg(MI->getOperand(ValOps).getReg());
19792   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19793     .addReg(MI->getOperand(ValOps+1).getReg());
19794
19795   // The instruction doesn't actually take any operands though.
19796   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19797
19798   MI->eraseFromParent(); // The pseudo is gone now.
19799   return BB;
19800 }
19801
19802 MachineBasicBlock *
19803 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19804                                                  MachineBasicBlock *MBB) const {
19805   // Emit va_arg instruction on X86-64.
19806
19807   // Operands to this pseudo-instruction:
19808   // 0  ) Output        : destination address (reg)
19809   // 1-5) Input         : va_list address (addr, i64mem)
19810   // 6  ) ArgSize       : Size (in bytes) of vararg type
19811   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19812   // 8  ) Align         : Alignment of type
19813   // 9  ) EFLAGS (implicit-def)
19814
19815   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19816   static_assert(X86::AddrNumOperands == 5,
19817                 "VAARG_64 assumes 5 address operands");
19818
19819   unsigned DestReg = MI->getOperand(0).getReg();
19820   MachineOperand &Base = MI->getOperand(1);
19821   MachineOperand &Scale = MI->getOperand(2);
19822   MachineOperand &Index = MI->getOperand(3);
19823   MachineOperand &Disp = MI->getOperand(4);
19824   MachineOperand &Segment = MI->getOperand(5);
19825   unsigned ArgSize = MI->getOperand(6).getImm();
19826   unsigned ArgMode = MI->getOperand(7).getImm();
19827   unsigned Align = MI->getOperand(8).getImm();
19828
19829   // Memory Reference
19830   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19831   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19832   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19833
19834   // Machine Information
19835   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19836   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19837   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19838   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19839   DebugLoc DL = MI->getDebugLoc();
19840
19841   // struct va_list {
19842   //   i32   gp_offset
19843   //   i32   fp_offset
19844   //   i64   overflow_area (address)
19845   //   i64   reg_save_area (address)
19846   // }
19847   // sizeof(va_list) = 24
19848   // alignment(va_list) = 8
19849
19850   unsigned TotalNumIntRegs = 6;
19851   unsigned TotalNumXMMRegs = 8;
19852   bool UseGPOffset = (ArgMode == 1);
19853   bool UseFPOffset = (ArgMode == 2);
19854   unsigned MaxOffset = TotalNumIntRegs * 8 +
19855                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19856
19857   /* Align ArgSize to a multiple of 8 */
19858   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19859   bool NeedsAlign = (Align > 8);
19860
19861   MachineBasicBlock *thisMBB = MBB;
19862   MachineBasicBlock *overflowMBB;
19863   MachineBasicBlock *offsetMBB;
19864   MachineBasicBlock *endMBB;
19865
19866   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19867   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19868   unsigned OffsetReg = 0;
19869
19870   if (!UseGPOffset && !UseFPOffset) {
19871     // If we only pull from the overflow region, we don't create a branch.
19872     // We don't need to alter control flow.
19873     OffsetDestReg = 0; // unused
19874     OverflowDestReg = DestReg;
19875
19876     offsetMBB = nullptr;
19877     overflowMBB = thisMBB;
19878     endMBB = thisMBB;
19879   } else {
19880     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19881     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19882     // If not, pull from overflow_area. (branch to overflowMBB)
19883     //
19884     //       thisMBB
19885     //         |     .
19886     //         |        .
19887     //     offsetMBB   overflowMBB
19888     //         |        .
19889     //         |     .
19890     //        endMBB
19891
19892     // Registers for the PHI in endMBB
19893     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19894     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19895
19896     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19897     MachineFunction *MF = MBB->getParent();
19898     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19899     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19900     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19901
19902     MachineFunction::iterator MBBIter = MBB;
19903     ++MBBIter;
19904
19905     // Insert the new basic blocks
19906     MF->insert(MBBIter, offsetMBB);
19907     MF->insert(MBBIter, overflowMBB);
19908     MF->insert(MBBIter, endMBB);
19909
19910     // Transfer the remainder of MBB and its successor edges to endMBB.
19911     endMBB->splice(endMBB->begin(), thisMBB,
19912                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19913     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19914
19915     // Make offsetMBB and overflowMBB successors of thisMBB
19916     thisMBB->addSuccessor(offsetMBB);
19917     thisMBB->addSuccessor(overflowMBB);
19918
19919     // endMBB is a successor of both offsetMBB and overflowMBB
19920     offsetMBB->addSuccessor(endMBB);
19921     overflowMBB->addSuccessor(endMBB);
19922
19923     // Load the offset value into a register
19924     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19925     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19926       .addOperand(Base)
19927       .addOperand(Scale)
19928       .addOperand(Index)
19929       .addDisp(Disp, UseFPOffset ? 4 : 0)
19930       .addOperand(Segment)
19931       .setMemRefs(MMOBegin, MMOEnd);
19932
19933     // Check if there is enough room left to pull this argument.
19934     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19935       .addReg(OffsetReg)
19936       .addImm(MaxOffset + 8 - ArgSizeA8);
19937
19938     // Branch to "overflowMBB" if offset >= max
19939     // Fall through to "offsetMBB" otherwise
19940     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19941       .addMBB(overflowMBB);
19942   }
19943
19944   // In offsetMBB, emit code to use the reg_save_area.
19945   if (offsetMBB) {
19946     assert(OffsetReg != 0);
19947
19948     // Read the reg_save_area address.
19949     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19950     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19951       .addOperand(Base)
19952       .addOperand(Scale)
19953       .addOperand(Index)
19954       .addDisp(Disp, 16)
19955       .addOperand(Segment)
19956       .setMemRefs(MMOBegin, MMOEnd);
19957
19958     // Zero-extend the offset
19959     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19960       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19961         .addImm(0)
19962         .addReg(OffsetReg)
19963         .addImm(X86::sub_32bit);
19964
19965     // Add the offset to the reg_save_area to get the final address.
19966     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19967       .addReg(OffsetReg64)
19968       .addReg(RegSaveReg);
19969
19970     // Compute the offset for the next argument
19971     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19972     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19973       .addReg(OffsetReg)
19974       .addImm(UseFPOffset ? 16 : 8);
19975
19976     // Store it back into the va_list.
19977     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19978       .addOperand(Base)
19979       .addOperand(Scale)
19980       .addOperand(Index)
19981       .addDisp(Disp, UseFPOffset ? 4 : 0)
19982       .addOperand(Segment)
19983       .addReg(NextOffsetReg)
19984       .setMemRefs(MMOBegin, MMOEnd);
19985
19986     // Jump to endMBB
19987     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19988       .addMBB(endMBB);
19989   }
19990
19991   //
19992   // Emit code to use overflow area
19993   //
19994
19995   // Load the overflow_area address into a register.
19996   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19997   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19998     .addOperand(Base)
19999     .addOperand(Scale)
20000     .addOperand(Index)
20001     .addDisp(Disp, 8)
20002     .addOperand(Segment)
20003     .setMemRefs(MMOBegin, MMOEnd);
20004
20005   // If we need to align it, do so. Otherwise, just copy the address
20006   // to OverflowDestReg.
20007   if (NeedsAlign) {
20008     // Align the overflow address
20009     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20010     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20011
20012     // aligned_addr = (addr + (align-1)) & ~(align-1)
20013     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20014       .addReg(OverflowAddrReg)
20015       .addImm(Align-1);
20016
20017     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20018       .addReg(TmpReg)
20019       .addImm(~(uint64_t)(Align-1));
20020   } else {
20021     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20022       .addReg(OverflowAddrReg);
20023   }
20024
20025   // Compute the next overflow address after this argument.
20026   // (the overflow address should be kept 8-byte aligned)
20027   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20028   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20029     .addReg(OverflowDestReg)
20030     .addImm(ArgSizeA8);
20031
20032   // Store the new overflow address.
20033   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20034     .addOperand(Base)
20035     .addOperand(Scale)
20036     .addOperand(Index)
20037     .addDisp(Disp, 8)
20038     .addOperand(Segment)
20039     .addReg(NextAddrReg)
20040     .setMemRefs(MMOBegin, MMOEnd);
20041
20042   // If we branched, emit the PHI to the front of endMBB.
20043   if (offsetMBB) {
20044     BuildMI(*endMBB, endMBB->begin(), DL,
20045             TII->get(X86::PHI), DestReg)
20046       .addReg(OffsetDestReg).addMBB(offsetMBB)
20047       .addReg(OverflowDestReg).addMBB(overflowMBB);
20048   }
20049
20050   // Erase the pseudo instruction
20051   MI->eraseFromParent();
20052
20053   return endMBB;
20054 }
20055
20056 MachineBasicBlock *
20057 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20058                                                  MachineInstr *MI,
20059                                                  MachineBasicBlock *MBB) const {
20060   // Emit code to save XMM registers to the stack. The ABI says that the
20061   // number of registers to save is given in %al, so it's theoretically
20062   // possible to do an indirect jump trick to avoid saving all of them,
20063   // however this code takes a simpler approach and just executes all
20064   // of the stores if %al is non-zero. It's less code, and it's probably
20065   // easier on the hardware branch predictor, and stores aren't all that
20066   // expensive anyway.
20067
20068   // Create the new basic blocks. One block contains all the XMM stores,
20069   // and one block is the final destination regardless of whether any
20070   // stores were performed.
20071   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20072   MachineFunction *F = MBB->getParent();
20073   MachineFunction::iterator MBBIter = MBB;
20074   ++MBBIter;
20075   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20076   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20077   F->insert(MBBIter, XMMSaveMBB);
20078   F->insert(MBBIter, EndMBB);
20079
20080   // Transfer the remainder of MBB and its successor edges to EndMBB.
20081   EndMBB->splice(EndMBB->begin(), MBB,
20082                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20083   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20084
20085   // The original block will now fall through to the XMM save block.
20086   MBB->addSuccessor(XMMSaveMBB);
20087   // The XMMSaveMBB will fall through to the end block.
20088   XMMSaveMBB->addSuccessor(EndMBB);
20089
20090   // Now add the instructions.
20091   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20092   DebugLoc DL = MI->getDebugLoc();
20093
20094   unsigned CountReg = MI->getOperand(0).getReg();
20095   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20096   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20097
20098   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20099     // If %al is 0, branch around the XMM save block.
20100     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20101     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20102     MBB->addSuccessor(EndMBB);
20103   }
20104
20105   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20106   // that was just emitted, but clearly shouldn't be "saved".
20107   assert((MI->getNumOperands() <= 3 ||
20108           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20109           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20110          && "Expected last argument to be EFLAGS");
20111   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20112   // In the XMM save block, save all the XMM argument registers.
20113   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20114     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20115     MachineMemOperand *MMO = F->getMachineMemOperand(
20116         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20117         MachineMemOperand::MOStore,
20118         /*Size=*/16, /*Align=*/16);
20119     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20120       .addFrameIndex(RegSaveFrameIndex)
20121       .addImm(/*Scale=*/1)
20122       .addReg(/*IndexReg=*/0)
20123       .addImm(/*Disp=*/Offset)
20124       .addReg(/*Segment=*/0)
20125       .addReg(MI->getOperand(i).getReg())
20126       .addMemOperand(MMO);
20127   }
20128
20129   MI->eraseFromParent();   // The pseudo instruction is gone now.
20130
20131   return EndMBB;
20132 }
20133
20134 // The EFLAGS operand of SelectItr might be missing a kill marker
20135 // because there were multiple uses of EFLAGS, and ISel didn't know
20136 // which to mark. Figure out whether SelectItr should have had a
20137 // kill marker, and set it if it should. Returns the correct kill
20138 // marker value.
20139 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20140                                      MachineBasicBlock* BB,
20141                                      const TargetRegisterInfo* TRI) {
20142   // Scan forward through BB for a use/def of EFLAGS.
20143   MachineBasicBlock::iterator miI(std::next(SelectItr));
20144   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20145     const MachineInstr& mi = *miI;
20146     if (mi.readsRegister(X86::EFLAGS))
20147       return false;
20148     if (mi.definesRegister(X86::EFLAGS))
20149       break; // Should have kill-flag - update below.
20150   }
20151
20152   // If we hit the end of the block, check whether EFLAGS is live into a
20153   // successor.
20154   if (miI == BB->end()) {
20155     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20156                                           sEnd = BB->succ_end();
20157          sItr != sEnd; ++sItr) {
20158       MachineBasicBlock* succ = *sItr;
20159       if (succ->isLiveIn(X86::EFLAGS))
20160         return false;
20161     }
20162   }
20163
20164   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20165   // out. SelectMI should have a kill flag on EFLAGS.
20166   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20167   return true;
20168 }
20169
20170 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20171 // together with other CMOV pseudo-opcodes into a single basic-block with
20172 // conditional jump around it.
20173 static bool isCMOVPseudo(MachineInstr *MI) {
20174   switch (MI->getOpcode()) {
20175   case X86::CMOV_FR32:
20176   case X86::CMOV_FR64:
20177   case X86::CMOV_GR8:
20178   case X86::CMOV_GR16:
20179   case X86::CMOV_GR32:
20180   case X86::CMOV_RFP32:
20181   case X86::CMOV_RFP64:
20182   case X86::CMOV_RFP80:
20183   case X86::CMOV_V2F64:
20184   case X86::CMOV_V2I64:
20185   case X86::CMOV_V4F32:
20186   case X86::CMOV_V4F64:
20187   case X86::CMOV_V4I64:
20188   case X86::CMOV_V16F32:
20189   case X86::CMOV_V8F32:
20190   case X86::CMOV_V8F64:
20191   case X86::CMOV_V8I64:
20192   case X86::CMOV_V8I1:
20193   case X86::CMOV_V16I1:
20194   case X86::CMOV_V32I1:
20195   case X86::CMOV_V64I1:
20196     return true;
20197
20198   default:
20199     return false;
20200   }
20201 }
20202
20203 MachineBasicBlock *
20204 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20205                                      MachineBasicBlock *BB) const {
20206   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20207   DebugLoc DL = MI->getDebugLoc();
20208
20209   // To "insert" a SELECT_CC instruction, we actually have to insert the
20210   // diamond control-flow pattern.  The incoming instruction knows the
20211   // destination vreg to set, the condition code register to branch on, the
20212   // true/false values to select between, and a branch opcode to use.
20213   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20214   MachineFunction::iterator It = BB;
20215   ++It;
20216
20217   //  thisMBB:
20218   //  ...
20219   //   TrueVal = ...
20220   //   cmpTY ccX, r1, r2
20221   //   bCC copy1MBB
20222   //   fallthrough --> copy0MBB
20223   MachineBasicBlock *thisMBB = BB;
20224   MachineFunction *F = BB->getParent();
20225
20226   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20227   // as described above, by inserting a BB, and then making a PHI at the join
20228   // point to select the true and false operands of the CMOV in the PHI.
20229   //
20230   // The code also handles two different cases of multiple CMOV opcodes
20231   // in a row.
20232   //
20233   // Case 1:
20234   // In this case, there are multiple CMOVs in a row, all which are based on
20235   // the same condition setting (or the exact opposite condition setting).
20236   // In this case we can lower all the CMOVs using a single inserted BB, and
20237   // then make a number of PHIs at the join point to model the CMOVs. The only
20238   // trickiness here, is that in a case like:
20239   //
20240   // t2 = CMOV cond1 t1, f1
20241   // t3 = CMOV cond1 t2, f2
20242   //
20243   // when rewriting this into PHIs, we have to perform some renaming on the
20244   // temps since you cannot have a PHI operand refer to a PHI result earlier
20245   // in the same block.  The "simple" but wrong lowering would be:
20246   //
20247   // t2 = PHI t1(BB1), f1(BB2)
20248   // t3 = PHI t2(BB1), f2(BB2)
20249   //
20250   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20251   // renaming is to note that on the path through BB1, t2 is really just a
20252   // copy of t1, and do that renaming, properly generating:
20253   //
20254   // t2 = PHI t1(BB1), f1(BB2)
20255   // t3 = PHI t1(BB1), f2(BB2)
20256   //
20257   // Case 2, we lower cascaded CMOVs such as
20258   //
20259   //   (CMOV (CMOV F, T, cc1), T, cc2)
20260   //
20261   // to two successives branches.  For that, we look for another CMOV as the
20262   // following instruction.
20263   //
20264   // Without this, we would add a PHI between the two jumps, which ends up
20265   // creating a few copies all around. For instance, for
20266   //
20267   //    (sitofp (zext (fcmp une)))
20268   //
20269   // we would generate:
20270   //
20271   //         ucomiss %xmm1, %xmm0
20272   //         movss  <1.0f>, %xmm0
20273   //         movaps  %xmm0, %xmm1
20274   //         jne     .LBB5_2
20275   //         xorps   %xmm1, %xmm1
20276   // .LBB5_2:
20277   //         jp      .LBB5_4
20278   //         movaps  %xmm1, %xmm0
20279   // .LBB5_4:
20280   //         retq
20281   //
20282   // because this custom-inserter would have generated:
20283   //
20284   //   A
20285   //   | \
20286   //   |  B
20287   //   | /
20288   //   C
20289   //   | \
20290   //   |  D
20291   //   | /
20292   //   E
20293   //
20294   // A: X = ...; Y = ...
20295   // B: empty
20296   // C: Z = PHI [X, A], [Y, B]
20297   // D: empty
20298   // E: PHI [X, C], [Z, D]
20299   //
20300   // If we lower both CMOVs in a single step, we can instead generate:
20301   //
20302   //   A
20303   //   | \
20304   //   |  C
20305   //   | /|
20306   //   |/ |
20307   //   |  |
20308   //   |  D
20309   //   | /
20310   //   E
20311   //
20312   // A: X = ...; Y = ...
20313   // D: empty
20314   // E: PHI [X, A], [X, C], [Y, D]
20315   //
20316   // Which, in our sitofp/fcmp example, gives us something like:
20317   //
20318   //         ucomiss %xmm1, %xmm0
20319   //         movss  <1.0f>, %xmm0
20320   //         jne     .LBB5_4
20321   //         jp      .LBB5_4
20322   //         xorps   %xmm0, %xmm0
20323   // .LBB5_4:
20324   //         retq
20325   //
20326   MachineInstr *CascadedCMOV = nullptr;
20327   MachineInstr *LastCMOV = MI;
20328   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20329   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20330   MachineBasicBlock::iterator NextMIIt =
20331       std::next(MachineBasicBlock::iterator(MI));
20332
20333   // Check for case 1, where there are multiple CMOVs with the same condition
20334   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20335   // number of jumps the most.
20336
20337   if (isCMOVPseudo(MI)) {
20338     // See if we have a string of CMOVS with the same condition.
20339     while (NextMIIt != BB->end() &&
20340            isCMOVPseudo(NextMIIt) &&
20341            (NextMIIt->getOperand(3).getImm() == CC ||
20342             NextMIIt->getOperand(3).getImm() == OppCC)) {
20343       LastCMOV = &*NextMIIt;
20344       ++NextMIIt;
20345     }
20346   }
20347
20348   // This checks for case 2, but only do this if we didn't already find
20349   // case 1, as indicated by LastCMOV == MI.
20350   if (LastCMOV == MI &&
20351       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20352       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20353       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20354     CascadedCMOV = &*NextMIIt;
20355   }
20356
20357   MachineBasicBlock *jcc1MBB = nullptr;
20358
20359   // If we have a cascaded CMOV, we lower it to two successive branches to
20360   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20361   if (CascadedCMOV) {
20362     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20363     F->insert(It, jcc1MBB);
20364     jcc1MBB->addLiveIn(X86::EFLAGS);
20365   }
20366
20367   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20368   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20369   F->insert(It, copy0MBB);
20370   F->insert(It, sinkMBB);
20371
20372   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20373   // live into the sink and copy blocks.
20374   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20375
20376   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20377   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20378       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20379     copy0MBB->addLiveIn(X86::EFLAGS);
20380     sinkMBB->addLiveIn(X86::EFLAGS);
20381   }
20382
20383   // Transfer the remainder of BB and its successor edges to sinkMBB.
20384   sinkMBB->splice(sinkMBB->begin(), BB,
20385                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20386   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20387
20388   // Add the true and fallthrough blocks as its successors.
20389   if (CascadedCMOV) {
20390     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20391     BB->addSuccessor(jcc1MBB);
20392
20393     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20394     // jump to the sinkMBB.
20395     jcc1MBB->addSuccessor(copy0MBB);
20396     jcc1MBB->addSuccessor(sinkMBB);
20397   } else {
20398     BB->addSuccessor(copy0MBB);
20399   }
20400
20401   // The true block target of the first (or only) branch is always sinkMBB.
20402   BB->addSuccessor(sinkMBB);
20403
20404   // Create the conditional branch instruction.
20405   unsigned Opc = X86::GetCondBranchFromCond(CC);
20406   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20407
20408   if (CascadedCMOV) {
20409     unsigned Opc2 = X86::GetCondBranchFromCond(
20410         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20411     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20412   }
20413
20414   //  copy0MBB:
20415   //   %FalseValue = ...
20416   //   # fallthrough to sinkMBB
20417   copy0MBB->addSuccessor(sinkMBB);
20418
20419   //  sinkMBB:
20420   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20421   //  ...
20422   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20423   MachineBasicBlock::iterator MIItEnd =
20424     std::next(MachineBasicBlock::iterator(LastCMOV));
20425   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20426   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20427   MachineInstrBuilder MIB;
20428
20429   // As we are creating the PHIs, we have to be careful if there is more than
20430   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20431   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20432   // That also means that PHI construction must work forward from earlier to
20433   // later, and that the code must maintain a mapping from earlier PHI's
20434   // destination registers, and the registers that went into the PHI.
20435
20436   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20437     unsigned DestReg = MIIt->getOperand(0).getReg();
20438     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20439     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20440
20441     // If this CMOV we are generating is the opposite condition from
20442     // the jump we generated, then we have to swap the operands for the
20443     // PHI that is going to be generated.
20444     if (MIIt->getOperand(3).getImm() == OppCC)
20445         std::swap(Op1Reg, Op2Reg);
20446
20447     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20448       Op1Reg = RegRewriteTable[Op1Reg].first;
20449
20450     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20451       Op2Reg = RegRewriteTable[Op2Reg].second;
20452
20453     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20454                   TII->get(X86::PHI), DestReg)
20455           .addReg(Op1Reg).addMBB(copy0MBB)
20456           .addReg(Op2Reg).addMBB(thisMBB);
20457
20458     // Add this PHI to the rewrite table.
20459     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20460   }
20461
20462   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20463   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20464   if (CascadedCMOV) {
20465     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20466     // Copy the PHI result to the register defined by the second CMOV.
20467     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20468             DL, TII->get(TargetOpcode::COPY),
20469             CascadedCMOV->getOperand(0).getReg())
20470         .addReg(MI->getOperand(0).getReg());
20471     CascadedCMOV->eraseFromParent();
20472   }
20473
20474   // Now remove the CMOV(s).
20475   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20476     (MIIt++)->eraseFromParent();
20477
20478   return sinkMBB;
20479 }
20480
20481 MachineBasicBlock *
20482 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20483                                        MachineBasicBlock *BB) const {
20484   // Combine the following atomic floating-point modification pattern:
20485   //   a.store(reg OP a.load(acquire), release)
20486   // Transform them into:
20487   //   OPss (%gpr), %xmm
20488   //   movss %xmm, (%gpr)
20489   // Or sd equivalent for 64-bit operations.
20490   unsigned MOp, FOp;
20491   switch (MI->getOpcode()) {
20492   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20493   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20494   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20495   }
20496   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20497   DebugLoc DL = MI->getDebugLoc();
20498   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20499   unsigned MSrc = MI->getOperand(0).getReg();
20500   unsigned VSrc = MI->getOperand(5).getReg();
20501   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20502                                 .addReg(/*Base=*/MSrc)
20503                                 .addImm(/*Scale=*/1)
20504                                 .addReg(/*Index=*/0)
20505                                 .addImm(0)
20506                                 .addReg(0);
20507   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20508                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20509                           .addReg(VSrc)
20510                           .addReg(/*Base=*/MSrc)
20511                           .addImm(/*Scale=*/1)
20512                           .addReg(/*Index=*/0)
20513                           .addImm(/*Disp=*/0)
20514                           .addReg(/*Segment=*/0);
20515   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20516   MI->eraseFromParent(); // The pseudo instruction is gone now.
20517   return BB;
20518 }
20519
20520 MachineBasicBlock *
20521 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20522                                         MachineBasicBlock *BB) const {
20523   MachineFunction *MF = BB->getParent();
20524   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20525   DebugLoc DL = MI->getDebugLoc();
20526   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20527
20528   assert(MF->shouldSplitStack());
20529
20530   const bool Is64Bit = Subtarget->is64Bit();
20531   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20532
20533   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20534   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20535
20536   // BB:
20537   //  ... [Till the alloca]
20538   // If stacklet is not large enough, jump to mallocMBB
20539   //
20540   // bumpMBB:
20541   //  Allocate by subtracting from RSP
20542   //  Jump to continueMBB
20543   //
20544   // mallocMBB:
20545   //  Allocate by call to runtime
20546   //
20547   // continueMBB:
20548   //  ...
20549   //  [rest of original BB]
20550   //
20551
20552   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20553   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20554   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20555
20556   MachineRegisterInfo &MRI = MF->getRegInfo();
20557   const TargetRegisterClass *AddrRegClass =
20558       getRegClassFor(getPointerTy(MF->getDataLayout()));
20559
20560   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20561     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20562     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20563     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20564     sizeVReg = MI->getOperand(1).getReg(),
20565     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20566
20567   MachineFunction::iterator MBBIter = BB;
20568   ++MBBIter;
20569
20570   MF->insert(MBBIter, bumpMBB);
20571   MF->insert(MBBIter, mallocMBB);
20572   MF->insert(MBBIter, continueMBB);
20573
20574   continueMBB->splice(continueMBB->begin(), BB,
20575                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20576   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20577
20578   // Add code to the main basic block to check if the stack limit has been hit,
20579   // and if so, jump to mallocMBB otherwise to bumpMBB.
20580   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20581   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20582     .addReg(tmpSPVReg).addReg(sizeVReg);
20583   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20584     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20585     .addReg(SPLimitVReg);
20586   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20587
20588   // bumpMBB simply decreases the stack pointer, since we know the current
20589   // stacklet has enough space.
20590   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20591     .addReg(SPLimitVReg);
20592   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20593     .addReg(SPLimitVReg);
20594   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20595
20596   // Calls into a routine in libgcc to allocate more space from the heap.
20597   const uint32_t *RegMask =
20598       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20599   if (IsLP64) {
20600     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20601       .addReg(sizeVReg);
20602     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20603       .addExternalSymbol("__morestack_allocate_stack_space")
20604       .addRegMask(RegMask)
20605       .addReg(X86::RDI, RegState::Implicit)
20606       .addReg(X86::RAX, RegState::ImplicitDefine);
20607   } else if (Is64Bit) {
20608     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20609       .addReg(sizeVReg);
20610     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20611       .addExternalSymbol("__morestack_allocate_stack_space")
20612       .addRegMask(RegMask)
20613       .addReg(X86::EDI, RegState::Implicit)
20614       .addReg(X86::EAX, RegState::ImplicitDefine);
20615   } else {
20616     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20617       .addImm(12);
20618     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20619     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20620       .addExternalSymbol("__morestack_allocate_stack_space")
20621       .addRegMask(RegMask)
20622       .addReg(X86::EAX, RegState::ImplicitDefine);
20623   }
20624
20625   if (!Is64Bit)
20626     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20627       .addImm(16);
20628
20629   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20630     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20631   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20632
20633   // Set up the CFG correctly.
20634   BB->addSuccessor(bumpMBB);
20635   BB->addSuccessor(mallocMBB);
20636   mallocMBB->addSuccessor(continueMBB);
20637   bumpMBB->addSuccessor(continueMBB);
20638
20639   // Take care of the PHI nodes.
20640   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20641           MI->getOperand(0).getReg())
20642     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20643     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20644
20645   // Delete the original pseudo instruction.
20646   MI->eraseFromParent();
20647
20648   // And we're done.
20649   return continueMBB;
20650 }
20651
20652 MachineBasicBlock *
20653 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20654                                         MachineBasicBlock *BB) const {
20655   DebugLoc DL = MI->getDebugLoc();
20656
20657   assert(!Subtarget->isTargetMachO());
20658
20659   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20660                                                     DL);
20661
20662   MI->eraseFromParent();   // The pseudo instruction is gone now.
20663   return BB;
20664 }
20665
20666 MachineBasicBlock *
20667 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20668                                       MachineBasicBlock *BB) const {
20669   // This is pretty easy.  We're taking the value that we received from
20670   // our load from the relocation, sticking it in either RDI (x86-64)
20671   // or EAX and doing an indirect call.  The return value will then
20672   // be in the normal return register.
20673   MachineFunction *F = BB->getParent();
20674   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20675   DebugLoc DL = MI->getDebugLoc();
20676
20677   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20678   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20679
20680   // Get a register mask for the lowered call.
20681   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20682   // proper register mask.
20683   const uint32_t *RegMask =
20684       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20685   if (Subtarget->is64Bit()) {
20686     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20687                                       TII->get(X86::MOV64rm), X86::RDI)
20688     .addReg(X86::RIP)
20689     .addImm(0).addReg(0)
20690     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20691                       MI->getOperand(3).getTargetFlags())
20692     .addReg(0);
20693     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20694     addDirectMem(MIB, X86::RDI);
20695     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20696   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20697     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20698                                       TII->get(X86::MOV32rm), X86::EAX)
20699     .addReg(0)
20700     .addImm(0).addReg(0)
20701     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20702                       MI->getOperand(3).getTargetFlags())
20703     .addReg(0);
20704     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20705     addDirectMem(MIB, X86::EAX);
20706     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20707   } else {
20708     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20709                                       TII->get(X86::MOV32rm), X86::EAX)
20710     .addReg(TII->getGlobalBaseReg(F))
20711     .addImm(0).addReg(0)
20712     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20713                       MI->getOperand(3).getTargetFlags())
20714     .addReg(0);
20715     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20716     addDirectMem(MIB, X86::EAX);
20717     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20718   }
20719
20720   MI->eraseFromParent(); // The pseudo instruction is gone now.
20721   return BB;
20722 }
20723
20724 MachineBasicBlock *
20725 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20726                                     MachineBasicBlock *MBB) const {
20727   DebugLoc DL = MI->getDebugLoc();
20728   MachineFunction *MF = MBB->getParent();
20729   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20730   MachineRegisterInfo &MRI = MF->getRegInfo();
20731
20732   const BasicBlock *BB = MBB->getBasicBlock();
20733   MachineFunction::iterator I = MBB;
20734   ++I;
20735
20736   // Memory Reference
20737   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20738   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20739
20740   unsigned DstReg;
20741   unsigned MemOpndSlot = 0;
20742
20743   unsigned CurOp = 0;
20744
20745   DstReg = MI->getOperand(CurOp++).getReg();
20746   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20747   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20748   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20749   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20750
20751   MemOpndSlot = CurOp;
20752
20753   MVT PVT = getPointerTy(MF->getDataLayout());
20754   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20755          "Invalid Pointer Size!");
20756
20757   // For v = setjmp(buf), we generate
20758   //
20759   // thisMBB:
20760   //  buf[LabelOffset] = restoreMBB
20761   //  SjLjSetup restoreMBB
20762   //
20763   // mainMBB:
20764   //  v_main = 0
20765   //
20766   // sinkMBB:
20767   //  v = phi(main, restore)
20768   //
20769   // restoreMBB:
20770   //  if base pointer being used, load it from frame
20771   //  v_restore = 1
20772
20773   MachineBasicBlock *thisMBB = MBB;
20774   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20775   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20776   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20777   MF->insert(I, mainMBB);
20778   MF->insert(I, sinkMBB);
20779   MF->push_back(restoreMBB);
20780
20781   MachineInstrBuilder MIB;
20782
20783   // Transfer the remainder of BB and its successor edges to sinkMBB.
20784   sinkMBB->splice(sinkMBB->begin(), MBB,
20785                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20786   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20787
20788   // thisMBB:
20789   unsigned PtrStoreOpc = 0;
20790   unsigned LabelReg = 0;
20791   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20792   Reloc::Model RM = MF->getTarget().getRelocationModel();
20793   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20794                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20795
20796   // Prepare IP either in reg or imm.
20797   if (!UseImmLabel) {
20798     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20799     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20800     LabelReg = MRI.createVirtualRegister(PtrRC);
20801     if (Subtarget->is64Bit()) {
20802       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20803               .addReg(X86::RIP)
20804               .addImm(0)
20805               .addReg(0)
20806               .addMBB(restoreMBB)
20807               .addReg(0);
20808     } else {
20809       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20810       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20811               .addReg(XII->getGlobalBaseReg(MF))
20812               .addImm(0)
20813               .addReg(0)
20814               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20815               .addReg(0);
20816     }
20817   } else
20818     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20819   // Store IP
20820   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20821   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20822     if (i == X86::AddrDisp)
20823       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20824     else
20825       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20826   }
20827   if (!UseImmLabel)
20828     MIB.addReg(LabelReg);
20829   else
20830     MIB.addMBB(restoreMBB);
20831   MIB.setMemRefs(MMOBegin, MMOEnd);
20832   // Setup
20833   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20834           .addMBB(restoreMBB);
20835
20836   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20837   MIB.addRegMask(RegInfo->getNoPreservedMask());
20838   thisMBB->addSuccessor(mainMBB);
20839   thisMBB->addSuccessor(restoreMBB);
20840
20841   // mainMBB:
20842   //  EAX = 0
20843   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20844   mainMBB->addSuccessor(sinkMBB);
20845
20846   // sinkMBB:
20847   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20848           TII->get(X86::PHI), DstReg)
20849     .addReg(mainDstReg).addMBB(mainMBB)
20850     .addReg(restoreDstReg).addMBB(restoreMBB);
20851
20852   // restoreMBB:
20853   if (RegInfo->hasBasePointer(*MF)) {
20854     const bool Uses64BitFramePtr =
20855         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20856     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20857     X86FI->setRestoreBasePointer(MF);
20858     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20859     unsigned BasePtr = RegInfo->getBaseRegister();
20860     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20861     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20862                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20863       .setMIFlag(MachineInstr::FrameSetup);
20864   }
20865   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20866   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20867   restoreMBB->addSuccessor(sinkMBB);
20868
20869   MI->eraseFromParent();
20870   return sinkMBB;
20871 }
20872
20873 MachineBasicBlock *
20874 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20875                                      MachineBasicBlock *MBB) const {
20876   DebugLoc DL = MI->getDebugLoc();
20877   MachineFunction *MF = MBB->getParent();
20878   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20879   MachineRegisterInfo &MRI = MF->getRegInfo();
20880
20881   // Memory Reference
20882   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20883   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20884
20885   MVT PVT = getPointerTy(MF->getDataLayout());
20886   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20887          "Invalid Pointer Size!");
20888
20889   const TargetRegisterClass *RC =
20890     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20891   unsigned Tmp = MRI.createVirtualRegister(RC);
20892   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20893   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20894   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20895   unsigned SP = RegInfo->getStackRegister();
20896
20897   MachineInstrBuilder MIB;
20898
20899   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20900   const int64_t SPOffset = 2 * PVT.getStoreSize();
20901
20902   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20903   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20904
20905   // Reload FP
20906   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20907   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20908     MIB.addOperand(MI->getOperand(i));
20909   MIB.setMemRefs(MMOBegin, MMOEnd);
20910   // Reload IP
20911   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20912   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20913     if (i == X86::AddrDisp)
20914       MIB.addDisp(MI->getOperand(i), LabelOffset);
20915     else
20916       MIB.addOperand(MI->getOperand(i));
20917   }
20918   MIB.setMemRefs(MMOBegin, MMOEnd);
20919   // Reload SP
20920   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20921   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20922     if (i == X86::AddrDisp)
20923       MIB.addDisp(MI->getOperand(i), SPOffset);
20924     else
20925       MIB.addOperand(MI->getOperand(i));
20926   }
20927   MIB.setMemRefs(MMOBegin, MMOEnd);
20928   // Jump
20929   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20930
20931   MI->eraseFromParent();
20932   return MBB;
20933 }
20934
20935 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20936 // accumulator loops. Writing back to the accumulator allows the coalescer
20937 // to remove extra copies in the loop.
20938 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20939 MachineBasicBlock *
20940 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20941                                  MachineBasicBlock *MBB) const {
20942   MachineOperand &AddendOp = MI->getOperand(3);
20943
20944   // Bail out early if the addend isn't a register - we can't switch these.
20945   if (!AddendOp.isReg())
20946     return MBB;
20947
20948   MachineFunction &MF = *MBB->getParent();
20949   MachineRegisterInfo &MRI = MF.getRegInfo();
20950
20951   // Check whether the addend is defined by a PHI:
20952   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20953   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20954   if (!AddendDef.isPHI())
20955     return MBB;
20956
20957   // Look for the following pattern:
20958   // loop:
20959   //   %addend = phi [%entry, 0], [%loop, %result]
20960   //   ...
20961   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20962
20963   // Replace with:
20964   //   loop:
20965   //   %addend = phi [%entry, 0], [%loop, %result]
20966   //   ...
20967   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20968
20969   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20970     assert(AddendDef.getOperand(i).isReg());
20971     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20972     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20973     if (&PHISrcInst == MI) {
20974       // Found a matching instruction.
20975       unsigned NewFMAOpc = 0;
20976       switch (MI->getOpcode()) {
20977         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20978         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20979         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20980         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20981         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20982         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20983         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20984         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20985         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20986         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20987         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20988         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20989         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20990         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20991         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20992         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20993         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20994         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20995         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20996         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20997
20998         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20999         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21000         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21001         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21002         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21003         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21004         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21005         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21006         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21007         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21008         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21009         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21010         default: llvm_unreachable("Unrecognized FMA variant.");
21011       }
21012
21013       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21014       MachineInstrBuilder MIB =
21015         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21016         .addOperand(MI->getOperand(0))
21017         .addOperand(MI->getOperand(3))
21018         .addOperand(MI->getOperand(2))
21019         .addOperand(MI->getOperand(1));
21020       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21021       MI->eraseFromParent();
21022     }
21023   }
21024
21025   return MBB;
21026 }
21027
21028 MachineBasicBlock *
21029 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21030                                                MachineBasicBlock *BB) const {
21031   switch (MI->getOpcode()) {
21032   default: llvm_unreachable("Unexpected instr type to insert");
21033   case X86::TAILJMPd64:
21034   case X86::TAILJMPr64:
21035   case X86::TAILJMPm64:
21036   case X86::TAILJMPd64_REX:
21037   case X86::TAILJMPr64_REX:
21038   case X86::TAILJMPm64_REX:
21039     llvm_unreachable("TAILJMP64 would not be touched here.");
21040   case X86::TCRETURNdi64:
21041   case X86::TCRETURNri64:
21042   case X86::TCRETURNmi64:
21043     return BB;
21044   case X86::WIN_ALLOCA:
21045     return EmitLoweredWinAlloca(MI, BB);
21046   case X86::SEG_ALLOCA_32:
21047   case X86::SEG_ALLOCA_64:
21048     return EmitLoweredSegAlloca(MI, BB);
21049   case X86::TLSCall_32:
21050   case X86::TLSCall_64:
21051     return EmitLoweredTLSCall(MI, BB);
21052   case X86::CMOV_FR32:
21053   case X86::CMOV_FR64:
21054   case X86::CMOV_GR8:
21055   case X86::CMOV_GR16:
21056   case X86::CMOV_GR32:
21057   case X86::CMOV_RFP32:
21058   case X86::CMOV_RFP64:
21059   case X86::CMOV_RFP80:
21060   case X86::CMOV_V2F64:
21061   case X86::CMOV_V2I64:
21062   case X86::CMOV_V4F32:
21063   case X86::CMOV_V4F64:
21064   case X86::CMOV_V4I64:
21065   case X86::CMOV_V16F32:
21066   case X86::CMOV_V8F32:
21067   case X86::CMOV_V8F64:
21068   case X86::CMOV_V8I64:
21069   case X86::CMOV_V8I1:
21070   case X86::CMOV_V16I1:
21071   case X86::CMOV_V32I1:
21072   case X86::CMOV_V64I1:
21073     return EmitLoweredSelect(MI, BB);
21074
21075   case X86::RELEASE_FADD32mr:
21076   case X86::RELEASE_FADD64mr:
21077     return EmitLoweredAtomicFP(MI, BB);
21078
21079   case X86::FP32_TO_INT16_IN_MEM:
21080   case X86::FP32_TO_INT32_IN_MEM:
21081   case X86::FP32_TO_INT64_IN_MEM:
21082   case X86::FP64_TO_INT16_IN_MEM:
21083   case X86::FP64_TO_INT32_IN_MEM:
21084   case X86::FP64_TO_INT64_IN_MEM:
21085   case X86::FP80_TO_INT16_IN_MEM:
21086   case X86::FP80_TO_INT32_IN_MEM:
21087   case X86::FP80_TO_INT64_IN_MEM: {
21088     MachineFunction *F = BB->getParent();
21089     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21090     DebugLoc DL = MI->getDebugLoc();
21091
21092     // Change the floating point control register to use "round towards zero"
21093     // mode when truncating to an integer value.
21094     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21095     addFrameReference(BuildMI(*BB, MI, DL,
21096                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21097
21098     // Load the old value of the high byte of the control word...
21099     unsigned OldCW =
21100       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21101     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21102                       CWFrameIdx);
21103
21104     // Set the high part to be round to zero...
21105     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21106       .addImm(0xC7F);
21107
21108     // Reload the modified control word now...
21109     addFrameReference(BuildMI(*BB, MI, DL,
21110                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21111
21112     // Restore the memory image of control word to original value
21113     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21114       .addReg(OldCW);
21115
21116     // Get the X86 opcode to use.
21117     unsigned Opc;
21118     switch (MI->getOpcode()) {
21119     default: llvm_unreachable("illegal opcode!");
21120     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21121     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21122     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21123     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21124     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21125     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21126     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21127     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21128     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21129     }
21130
21131     X86AddressMode AM;
21132     MachineOperand &Op = MI->getOperand(0);
21133     if (Op.isReg()) {
21134       AM.BaseType = X86AddressMode::RegBase;
21135       AM.Base.Reg = Op.getReg();
21136     } else {
21137       AM.BaseType = X86AddressMode::FrameIndexBase;
21138       AM.Base.FrameIndex = Op.getIndex();
21139     }
21140     Op = MI->getOperand(1);
21141     if (Op.isImm())
21142       AM.Scale = Op.getImm();
21143     Op = MI->getOperand(2);
21144     if (Op.isImm())
21145       AM.IndexReg = Op.getImm();
21146     Op = MI->getOperand(3);
21147     if (Op.isGlobal()) {
21148       AM.GV = Op.getGlobal();
21149     } else {
21150       AM.Disp = Op.getImm();
21151     }
21152     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21153                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21154
21155     // Reload the original control word now.
21156     addFrameReference(BuildMI(*BB, MI, DL,
21157                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21158
21159     MI->eraseFromParent();   // The pseudo instruction is gone now.
21160     return BB;
21161   }
21162     // String/text processing lowering.
21163   case X86::PCMPISTRM128REG:
21164   case X86::VPCMPISTRM128REG:
21165   case X86::PCMPISTRM128MEM:
21166   case X86::VPCMPISTRM128MEM:
21167   case X86::PCMPESTRM128REG:
21168   case X86::VPCMPESTRM128REG:
21169   case X86::PCMPESTRM128MEM:
21170   case X86::VPCMPESTRM128MEM:
21171     assert(Subtarget->hasSSE42() &&
21172            "Target must have SSE4.2 or AVX features enabled");
21173     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21174
21175   // String/text processing lowering.
21176   case X86::PCMPISTRIREG:
21177   case X86::VPCMPISTRIREG:
21178   case X86::PCMPISTRIMEM:
21179   case X86::VPCMPISTRIMEM:
21180   case X86::PCMPESTRIREG:
21181   case X86::VPCMPESTRIREG:
21182   case X86::PCMPESTRIMEM:
21183   case X86::VPCMPESTRIMEM:
21184     assert(Subtarget->hasSSE42() &&
21185            "Target must have SSE4.2 or AVX features enabled");
21186     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21187
21188   // Thread synchronization.
21189   case X86::MONITOR:
21190     return EmitMonitor(MI, BB, Subtarget);
21191
21192   // xbegin
21193   case X86::XBEGIN:
21194     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21195
21196   case X86::VASTART_SAVE_XMM_REGS:
21197     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21198
21199   case X86::VAARG_64:
21200     return EmitVAARG64WithCustomInserter(MI, BB);
21201
21202   case X86::EH_SjLj_SetJmp32:
21203   case X86::EH_SjLj_SetJmp64:
21204     return emitEHSjLjSetJmp(MI, BB);
21205
21206   case X86::EH_SjLj_LongJmp32:
21207   case X86::EH_SjLj_LongJmp64:
21208     return emitEHSjLjLongJmp(MI, BB);
21209
21210   case TargetOpcode::STATEPOINT:
21211     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21212     // this point in the process.  We diverge later.
21213     return emitPatchPoint(MI, BB);
21214
21215   case TargetOpcode::STACKMAP:
21216   case TargetOpcode::PATCHPOINT:
21217     return emitPatchPoint(MI, BB);
21218
21219   case X86::VFMADDPDr213r:
21220   case X86::VFMADDPSr213r:
21221   case X86::VFMADDSDr213r:
21222   case X86::VFMADDSSr213r:
21223   case X86::VFMSUBPDr213r:
21224   case X86::VFMSUBPSr213r:
21225   case X86::VFMSUBSDr213r:
21226   case X86::VFMSUBSSr213r:
21227   case X86::VFNMADDPDr213r:
21228   case X86::VFNMADDPSr213r:
21229   case X86::VFNMADDSDr213r:
21230   case X86::VFNMADDSSr213r:
21231   case X86::VFNMSUBPDr213r:
21232   case X86::VFNMSUBPSr213r:
21233   case X86::VFNMSUBSDr213r:
21234   case X86::VFNMSUBSSr213r:
21235   case X86::VFMADDSUBPDr213r:
21236   case X86::VFMADDSUBPSr213r:
21237   case X86::VFMSUBADDPDr213r:
21238   case X86::VFMSUBADDPSr213r:
21239   case X86::VFMADDPDr213rY:
21240   case X86::VFMADDPSr213rY:
21241   case X86::VFMSUBPDr213rY:
21242   case X86::VFMSUBPSr213rY:
21243   case X86::VFNMADDPDr213rY:
21244   case X86::VFNMADDPSr213rY:
21245   case X86::VFNMSUBPDr213rY:
21246   case X86::VFNMSUBPSr213rY:
21247   case X86::VFMADDSUBPDr213rY:
21248   case X86::VFMADDSUBPSr213rY:
21249   case X86::VFMSUBADDPDr213rY:
21250   case X86::VFMSUBADDPSr213rY:
21251     return emitFMA3Instr(MI, BB);
21252   }
21253 }
21254
21255 //===----------------------------------------------------------------------===//
21256 //                           X86 Optimization Hooks
21257 //===----------------------------------------------------------------------===//
21258
21259 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21260                                                       APInt &KnownZero,
21261                                                       APInt &KnownOne,
21262                                                       const SelectionDAG &DAG,
21263                                                       unsigned Depth) const {
21264   unsigned BitWidth = KnownZero.getBitWidth();
21265   unsigned Opc = Op.getOpcode();
21266   assert((Opc >= ISD::BUILTIN_OP_END ||
21267           Opc == ISD::INTRINSIC_WO_CHAIN ||
21268           Opc == ISD::INTRINSIC_W_CHAIN ||
21269           Opc == ISD::INTRINSIC_VOID) &&
21270          "Should use MaskedValueIsZero if you don't know whether Op"
21271          " is a target node!");
21272
21273   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21274   switch (Opc) {
21275   default: break;
21276   case X86ISD::ADD:
21277   case X86ISD::SUB:
21278   case X86ISD::ADC:
21279   case X86ISD::SBB:
21280   case X86ISD::SMUL:
21281   case X86ISD::UMUL:
21282   case X86ISD::INC:
21283   case X86ISD::DEC:
21284   case X86ISD::OR:
21285   case X86ISD::XOR:
21286   case X86ISD::AND:
21287     // These nodes' second result is a boolean.
21288     if (Op.getResNo() == 0)
21289       break;
21290     // Fallthrough
21291   case X86ISD::SETCC:
21292     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21293     break;
21294   case ISD::INTRINSIC_WO_CHAIN: {
21295     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21296     unsigned NumLoBits = 0;
21297     switch (IntId) {
21298     default: break;
21299     case Intrinsic::x86_sse_movmsk_ps:
21300     case Intrinsic::x86_avx_movmsk_ps_256:
21301     case Intrinsic::x86_sse2_movmsk_pd:
21302     case Intrinsic::x86_avx_movmsk_pd_256:
21303     case Intrinsic::x86_mmx_pmovmskb:
21304     case Intrinsic::x86_sse2_pmovmskb_128:
21305     case Intrinsic::x86_avx2_pmovmskb: {
21306       // High bits of movmskp{s|d}, pmovmskb are known zero.
21307       switch (IntId) {
21308         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21309         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21310         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21311         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21312         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21313         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21314         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21315         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21316       }
21317       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21318       break;
21319     }
21320     }
21321     break;
21322   }
21323   }
21324 }
21325
21326 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21327   SDValue Op,
21328   const SelectionDAG &,
21329   unsigned Depth) const {
21330   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21331   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21332     return Op.getValueType().getScalarType().getSizeInBits();
21333
21334   // Fallback case.
21335   return 1;
21336 }
21337
21338 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21339 /// node is a GlobalAddress + offset.
21340 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21341                                        const GlobalValue* &GA,
21342                                        int64_t &Offset) const {
21343   if (N->getOpcode() == X86ISD::Wrapper) {
21344     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21345       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21346       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21347       return true;
21348     }
21349   }
21350   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21351 }
21352
21353 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21354 /// same as extracting the high 128-bit part of 256-bit vector and then
21355 /// inserting the result into the low part of a new 256-bit vector
21356 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21357   EVT VT = SVOp->getValueType(0);
21358   unsigned NumElems = VT.getVectorNumElements();
21359
21360   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21361   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21362     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21363         SVOp->getMaskElt(j) >= 0)
21364       return false;
21365
21366   return true;
21367 }
21368
21369 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21370 /// same as extracting the low 128-bit part of 256-bit vector and then
21371 /// inserting the result into the high part of a new 256-bit vector
21372 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21373   EVT VT = SVOp->getValueType(0);
21374   unsigned NumElems = VT.getVectorNumElements();
21375
21376   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21377   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21378     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21379         SVOp->getMaskElt(j) >= 0)
21380       return false;
21381
21382   return true;
21383 }
21384
21385 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21386 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21387                                         TargetLowering::DAGCombinerInfo &DCI,
21388                                         const X86Subtarget* Subtarget) {
21389   SDLoc dl(N);
21390   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21391   SDValue V1 = SVOp->getOperand(0);
21392   SDValue V2 = SVOp->getOperand(1);
21393   EVT VT = SVOp->getValueType(0);
21394   unsigned NumElems = VT.getVectorNumElements();
21395
21396   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21397       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21398     //
21399     //                   0,0,0,...
21400     //                      |
21401     //    V      UNDEF    BUILD_VECTOR    UNDEF
21402     //     \      /           \           /
21403     //  CONCAT_VECTOR         CONCAT_VECTOR
21404     //         \                  /
21405     //          \                /
21406     //          RESULT: V + zero extended
21407     //
21408     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21409         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21410         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21411       return SDValue();
21412
21413     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21414       return SDValue();
21415
21416     // To match the shuffle mask, the first half of the mask should
21417     // be exactly the first vector, and all the rest a splat with the
21418     // first element of the second one.
21419     for (unsigned i = 0; i != NumElems/2; ++i)
21420       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21421           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21422         return SDValue();
21423
21424     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21425     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21426       if (Ld->hasNUsesOfValue(1, 0)) {
21427         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21428         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21429         SDValue ResNode =
21430           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21431                                   Ld->getMemoryVT(),
21432                                   Ld->getPointerInfo(),
21433                                   Ld->getAlignment(),
21434                                   false/*isVolatile*/, true/*ReadMem*/,
21435                                   false/*WriteMem*/);
21436
21437         // Make sure the newly-created LOAD is in the same position as Ld in
21438         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21439         // and update uses of Ld's output chain to use the TokenFactor.
21440         if (Ld->hasAnyUseOfValue(1)) {
21441           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21442                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21443           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21444           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21445                                  SDValue(ResNode.getNode(), 1));
21446         }
21447
21448         return DAG.getBitcast(VT, ResNode);
21449       }
21450     }
21451
21452     // Emit a zeroed vector and insert the desired subvector on its
21453     // first half.
21454     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21455     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21456     return DCI.CombineTo(N, InsV);
21457   }
21458
21459   //===--------------------------------------------------------------------===//
21460   // Combine some shuffles into subvector extracts and inserts:
21461   //
21462
21463   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21464   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21465     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21466     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21467     return DCI.CombineTo(N, InsV);
21468   }
21469
21470   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21471   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21472     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21473     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21474     return DCI.CombineTo(N, InsV);
21475   }
21476
21477   return SDValue();
21478 }
21479
21480 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21481 /// possible.
21482 ///
21483 /// This is the leaf of the recursive combinine below. When we have found some
21484 /// chain of single-use x86 shuffle instructions and accumulated the combined
21485 /// shuffle mask represented by them, this will try to pattern match that mask
21486 /// into either a single instruction if there is a special purpose instruction
21487 /// for this operation, or into a PSHUFB instruction which is a fully general
21488 /// instruction but should only be used to replace chains over a certain depth.
21489 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21490                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21491                                    TargetLowering::DAGCombinerInfo &DCI,
21492                                    const X86Subtarget *Subtarget) {
21493   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21494
21495   // Find the operand that enters the chain. Note that multiple uses are OK
21496   // here, we're not going to remove the operand we find.
21497   SDValue Input = Op.getOperand(0);
21498   while (Input.getOpcode() == ISD::BITCAST)
21499     Input = Input.getOperand(0);
21500
21501   MVT VT = Input.getSimpleValueType();
21502   MVT RootVT = Root.getSimpleValueType();
21503   SDLoc DL(Root);
21504
21505   // Just remove no-op shuffle masks.
21506   if (Mask.size() == 1) {
21507     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21508                   /*AddTo*/ true);
21509     return true;
21510   }
21511
21512   // Use the float domain if the operand type is a floating point type.
21513   bool FloatDomain = VT.isFloatingPoint();
21514
21515   // For floating point shuffles, we don't have free copies in the shuffle
21516   // instructions or the ability to load as part of the instruction, so
21517   // canonicalize their shuffles to UNPCK or MOV variants.
21518   //
21519   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21520   // vectors because it can have a load folded into it that UNPCK cannot. This
21521   // doesn't preclude something switching to the shorter encoding post-RA.
21522   //
21523   // FIXME: Should teach these routines about AVX vector widths.
21524   if (FloatDomain && VT.getSizeInBits() == 128) {
21525     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21526       bool Lo = Mask.equals({0, 0});
21527       unsigned Shuffle;
21528       MVT ShuffleVT;
21529       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21530       // is no slower than UNPCKLPD but has the option to fold the input operand
21531       // into even an unaligned memory load.
21532       if (Lo && Subtarget->hasSSE3()) {
21533         Shuffle = X86ISD::MOVDDUP;
21534         ShuffleVT = MVT::v2f64;
21535       } else {
21536         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21537         // than the UNPCK variants.
21538         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21539         ShuffleVT = MVT::v4f32;
21540       }
21541       if (Depth == 1 && Root->getOpcode() == Shuffle)
21542         return false; // Nothing to do!
21543       Op = DAG.getBitcast(ShuffleVT, Input);
21544       DCI.AddToWorklist(Op.getNode());
21545       if (Shuffle == X86ISD::MOVDDUP)
21546         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21547       else
21548         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21549       DCI.AddToWorklist(Op.getNode());
21550       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21551                     /*AddTo*/ true);
21552       return true;
21553     }
21554     if (Subtarget->hasSSE3() &&
21555         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21556       bool Lo = Mask.equals({0, 0, 2, 2});
21557       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21558       MVT ShuffleVT = MVT::v4f32;
21559       if (Depth == 1 && Root->getOpcode() == Shuffle)
21560         return false; // Nothing to do!
21561       Op = DAG.getBitcast(ShuffleVT, Input);
21562       DCI.AddToWorklist(Op.getNode());
21563       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21564       DCI.AddToWorklist(Op.getNode());
21565       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21566                     /*AddTo*/ true);
21567       return true;
21568     }
21569     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21570       bool Lo = Mask.equals({0, 0, 1, 1});
21571       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21572       MVT ShuffleVT = MVT::v4f32;
21573       if (Depth == 1 && Root->getOpcode() == Shuffle)
21574         return false; // Nothing to do!
21575       Op = DAG.getBitcast(ShuffleVT, Input);
21576       DCI.AddToWorklist(Op.getNode());
21577       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21578       DCI.AddToWorklist(Op.getNode());
21579       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21580                     /*AddTo*/ true);
21581       return true;
21582     }
21583   }
21584
21585   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21586   // variants as none of these have single-instruction variants that are
21587   // superior to the UNPCK formulation.
21588   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21589       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21590        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21591        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21592        Mask.equals(
21593            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21594     bool Lo = Mask[0] == 0;
21595     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21596     if (Depth == 1 && Root->getOpcode() == Shuffle)
21597       return false; // Nothing to do!
21598     MVT ShuffleVT;
21599     switch (Mask.size()) {
21600     case 8:
21601       ShuffleVT = MVT::v8i16;
21602       break;
21603     case 16:
21604       ShuffleVT = MVT::v16i8;
21605       break;
21606     default:
21607       llvm_unreachable("Impossible mask size!");
21608     };
21609     Op = DAG.getBitcast(ShuffleVT, Input);
21610     DCI.AddToWorklist(Op.getNode());
21611     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21612     DCI.AddToWorklist(Op.getNode());
21613     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21614                   /*AddTo*/ true);
21615     return true;
21616   }
21617
21618   // Don't try to re-form single instruction chains under any circumstances now
21619   // that we've done encoding canonicalization for them.
21620   if (Depth < 2)
21621     return false;
21622
21623   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21624   // can replace them with a single PSHUFB instruction profitably. Intel's
21625   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21626   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21627   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21628     SmallVector<SDValue, 16> PSHUFBMask;
21629     int NumBytes = VT.getSizeInBits() / 8;
21630     int Ratio = NumBytes / Mask.size();
21631     for (int i = 0; i < NumBytes; ++i) {
21632       if (Mask[i / Ratio] == SM_SentinelUndef) {
21633         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21634         continue;
21635       }
21636       int M = Mask[i / Ratio] != SM_SentinelZero
21637                   ? Ratio * Mask[i / Ratio] + i % Ratio
21638                   : 255;
21639       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21640     }
21641     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21642     Op = DAG.getBitcast(ByteVT, Input);
21643     DCI.AddToWorklist(Op.getNode());
21644     SDValue PSHUFBMaskOp =
21645         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21646     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21647     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21648     DCI.AddToWorklist(Op.getNode());
21649     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21650                   /*AddTo*/ true);
21651     return true;
21652   }
21653
21654   // Failed to find any combines.
21655   return false;
21656 }
21657
21658 /// \brief Fully generic combining of x86 shuffle instructions.
21659 ///
21660 /// This should be the last combine run over the x86 shuffle instructions. Once
21661 /// they have been fully optimized, this will recursively consider all chains
21662 /// of single-use shuffle instructions, build a generic model of the cumulative
21663 /// shuffle operation, and check for simpler instructions which implement this
21664 /// operation. We use this primarily for two purposes:
21665 ///
21666 /// 1) Collapse generic shuffles to specialized single instructions when
21667 ///    equivalent. In most cases, this is just an encoding size win, but
21668 ///    sometimes we will collapse multiple generic shuffles into a single
21669 ///    special-purpose shuffle.
21670 /// 2) Look for sequences of shuffle instructions with 3 or more total
21671 ///    instructions, and replace them with the slightly more expensive SSSE3
21672 ///    PSHUFB instruction if available. We do this as the last combining step
21673 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21674 ///    a suitable short sequence of other instructions. The PHUFB will either
21675 ///    use a register or have to read from memory and so is slightly (but only
21676 ///    slightly) more expensive than the other shuffle instructions.
21677 ///
21678 /// Because this is inherently a quadratic operation (for each shuffle in
21679 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21680 /// This should never be an issue in practice as the shuffle lowering doesn't
21681 /// produce sequences of more than 8 instructions.
21682 ///
21683 /// FIXME: We will currently miss some cases where the redundant shuffling
21684 /// would simplify under the threshold for PSHUFB formation because of
21685 /// combine-ordering. To fix this, we should do the redundant instruction
21686 /// combining in this recursive walk.
21687 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21688                                           ArrayRef<int> RootMask,
21689                                           int Depth, bool HasPSHUFB,
21690                                           SelectionDAG &DAG,
21691                                           TargetLowering::DAGCombinerInfo &DCI,
21692                                           const X86Subtarget *Subtarget) {
21693   // Bound the depth of our recursive combine because this is ultimately
21694   // quadratic in nature.
21695   if (Depth > 8)
21696     return false;
21697
21698   // Directly rip through bitcasts to find the underlying operand.
21699   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21700     Op = Op.getOperand(0);
21701
21702   MVT VT = Op.getSimpleValueType();
21703   if (!VT.isVector())
21704     return false; // Bail if we hit a non-vector.
21705
21706   assert(Root.getSimpleValueType().isVector() &&
21707          "Shuffles operate on vector types!");
21708   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21709          "Can only combine shuffles of the same vector register size.");
21710
21711   if (!isTargetShuffle(Op.getOpcode()))
21712     return false;
21713   SmallVector<int, 16> OpMask;
21714   bool IsUnary;
21715   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21716   // We only can combine unary shuffles which we can decode the mask for.
21717   if (!HaveMask || !IsUnary)
21718     return false;
21719
21720   assert(VT.getVectorNumElements() == OpMask.size() &&
21721          "Different mask size from vector size!");
21722   assert(((RootMask.size() > OpMask.size() &&
21723            RootMask.size() % OpMask.size() == 0) ||
21724           (OpMask.size() > RootMask.size() &&
21725            OpMask.size() % RootMask.size() == 0) ||
21726           OpMask.size() == RootMask.size()) &&
21727          "The smaller number of elements must divide the larger.");
21728   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21729   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21730   assert(((RootRatio == 1 && OpRatio == 1) ||
21731           (RootRatio == 1) != (OpRatio == 1)) &&
21732          "Must not have a ratio for both incoming and op masks!");
21733
21734   SmallVector<int, 16> Mask;
21735   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21736
21737   // Merge this shuffle operation's mask into our accumulated mask. Note that
21738   // this shuffle's mask will be the first applied to the input, followed by the
21739   // root mask to get us all the way to the root value arrangement. The reason
21740   // for this order is that we are recursing up the operation chain.
21741   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21742     int RootIdx = i / RootRatio;
21743     if (RootMask[RootIdx] < 0) {
21744       // This is a zero or undef lane, we're done.
21745       Mask.push_back(RootMask[RootIdx]);
21746       continue;
21747     }
21748
21749     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21750     int OpIdx = RootMaskedIdx / OpRatio;
21751     if (OpMask[OpIdx] < 0) {
21752       // The incoming lanes are zero or undef, it doesn't matter which ones we
21753       // are using.
21754       Mask.push_back(OpMask[OpIdx]);
21755       continue;
21756     }
21757
21758     // Ok, we have non-zero lanes, map them through.
21759     Mask.push_back(OpMask[OpIdx] * OpRatio +
21760                    RootMaskedIdx % OpRatio);
21761   }
21762
21763   // See if we can recurse into the operand to combine more things.
21764   switch (Op.getOpcode()) {
21765     case X86ISD::PSHUFB:
21766       HasPSHUFB = true;
21767     case X86ISD::PSHUFD:
21768     case X86ISD::PSHUFHW:
21769     case X86ISD::PSHUFLW:
21770       if (Op.getOperand(0).hasOneUse() &&
21771           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21772                                         HasPSHUFB, DAG, DCI, Subtarget))
21773         return true;
21774       break;
21775
21776     case X86ISD::UNPCKL:
21777     case X86ISD::UNPCKH:
21778       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21779       // We can't check for single use, we have to check that this shuffle is the only user.
21780       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21781           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21782                                         HasPSHUFB, DAG, DCI, Subtarget))
21783           return true;
21784       break;
21785   }
21786
21787   // Minor canonicalization of the accumulated shuffle mask to make it easier
21788   // to match below. All this does is detect masks with squential pairs of
21789   // elements, and shrink them to the half-width mask. It does this in a loop
21790   // so it will reduce the size of the mask to the minimal width mask which
21791   // performs an equivalent shuffle.
21792   SmallVector<int, 16> WidenedMask;
21793   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21794     Mask = std::move(WidenedMask);
21795     WidenedMask.clear();
21796   }
21797
21798   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21799                                 Subtarget);
21800 }
21801
21802 /// \brief Get the PSHUF-style mask from PSHUF node.
21803 ///
21804 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21805 /// PSHUF-style masks that can be reused with such instructions.
21806 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21807   MVT VT = N.getSimpleValueType();
21808   SmallVector<int, 4> Mask;
21809   bool IsUnary;
21810   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21811   (void)HaveMask;
21812   assert(HaveMask);
21813
21814   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21815   // matter. Check that the upper masks are repeats and remove them.
21816   if (VT.getSizeInBits() > 128) {
21817     int LaneElts = 128 / VT.getScalarSizeInBits();
21818 #ifndef NDEBUG
21819     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21820       for (int j = 0; j < LaneElts; ++j)
21821         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21822                "Mask doesn't repeat in high 128-bit lanes!");
21823 #endif
21824     Mask.resize(LaneElts);
21825   }
21826
21827   switch (N.getOpcode()) {
21828   case X86ISD::PSHUFD:
21829     return Mask;
21830   case X86ISD::PSHUFLW:
21831     Mask.resize(4);
21832     return Mask;
21833   case X86ISD::PSHUFHW:
21834     Mask.erase(Mask.begin(), Mask.begin() + 4);
21835     for (int &M : Mask)
21836       M -= 4;
21837     return Mask;
21838   default:
21839     llvm_unreachable("No valid shuffle instruction found!");
21840   }
21841 }
21842
21843 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21844 ///
21845 /// We walk up the chain and look for a combinable shuffle, skipping over
21846 /// shuffles that we could hoist this shuffle's transformation past without
21847 /// altering anything.
21848 static SDValue
21849 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21850                              SelectionDAG &DAG,
21851                              TargetLowering::DAGCombinerInfo &DCI) {
21852   assert(N.getOpcode() == X86ISD::PSHUFD &&
21853          "Called with something other than an x86 128-bit half shuffle!");
21854   SDLoc DL(N);
21855
21856   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21857   // of the shuffles in the chain so that we can form a fresh chain to replace
21858   // this one.
21859   SmallVector<SDValue, 8> Chain;
21860   SDValue V = N.getOperand(0);
21861   for (; V.hasOneUse(); V = V.getOperand(0)) {
21862     switch (V.getOpcode()) {
21863     default:
21864       return SDValue(); // Nothing combined!
21865
21866     case ISD::BITCAST:
21867       // Skip bitcasts as we always know the type for the target specific
21868       // instructions.
21869       continue;
21870
21871     case X86ISD::PSHUFD:
21872       // Found another dword shuffle.
21873       break;
21874
21875     case X86ISD::PSHUFLW:
21876       // Check that the low words (being shuffled) are the identity in the
21877       // dword shuffle, and the high words are self-contained.
21878       if (Mask[0] != 0 || Mask[1] != 1 ||
21879           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21880         return SDValue();
21881
21882       Chain.push_back(V);
21883       continue;
21884
21885     case X86ISD::PSHUFHW:
21886       // Check that the high words (being shuffled) are the identity in the
21887       // dword shuffle, and the low words are self-contained.
21888       if (Mask[2] != 2 || Mask[3] != 3 ||
21889           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21890         return SDValue();
21891
21892       Chain.push_back(V);
21893       continue;
21894
21895     case X86ISD::UNPCKL:
21896     case X86ISD::UNPCKH:
21897       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21898       // shuffle into a preceding word shuffle.
21899       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21900           V.getSimpleValueType().getScalarType() != MVT::i16)
21901         return SDValue();
21902
21903       // Search for a half-shuffle which we can combine with.
21904       unsigned CombineOp =
21905           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21906       if (V.getOperand(0) != V.getOperand(1) ||
21907           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21908         return SDValue();
21909       Chain.push_back(V);
21910       V = V.getOperand(0);
21911       do {
21912         switch (V.getOpcode()) {
21913         default:
21914           return SDValue(); // Nothing to combine.
21915
21916         case X86ISD::PSHUFLW:
21917         case X86ISD::PSHUFHW:
21918           if (V.getOpcode() == CombineOp)
21919             break;
21920
21921           Chain.push_back(V);
21922
21923           // Fallthrough!
21924         case ISD::BITCAST:
21925           V = V.getOperand(0);
21926           continue;
21927         }
21928         break;
21929       } while (V.hasOneUse());
21930       break;
21931     }
21932     // Break out of the loop if we break out of the switch.
21933     break;
21934   }
21935
21936   if (!V.hasOneUse())
21937     // We fell out of the loop without finding a viable combining instruction.
21938     return SDValue();
21939
21940   // Merge this node's mask and our incoming mask.
21941   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21942   for (int &M : Mask)
21943     M = VMask[M];
21944   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21945                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21946
21947   // Rebuild the chain around this new shuffle.
21948   while (!Chain.empty()) {
21949     SDValue W = Chain.pop_back_val();
21950
21951     if (V.getValueType() != W.getOperand(0).getValueType())
21952       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21953
21954     switch (W.getOpcode()) {
21955     default:
21956       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21957
21958     case X86ISD::UNPCKL:
21959     case X86ISD::UNPCKH:
21960       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21961       break;
21962
21963     case X86ISD::PSHUFD:
21964     case X86ISD::PSHUFLW:
21965     case X86ISD::PSHUFHW:
21966       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21967       break;
21968     }
21969   }
21970   if (V.getValueType() != N.getValueType())
21971     V = DAG.getBitcast(N.getValueType(), V);
21972
21973   // Return the new chain to replace N.
21974   return V;
21975 }
21976
21977 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21978 ///
21979 /// We walk up the chain, skipping shuffles of the other half and looking
21980 /// through shuffles which switch halves trying to find a shuffle of the same
21981 /// pair of dwords.
21982 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21983                                         SelectionDAG &DAG,
21984                                         TargetLowering::DAGCombinerInfo &DCI) {
21985   assert(
21986       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21987       "Called with something other than an x86 128-bit half shuffle!");
21988   SDLoc DL(N);
21989   unsigned CombineOpcode = N.getOpcode();
21990
21991   // Walk up a single-use chain looking for a combinable shuffle.
21992   SDValue V = N.getOperand(0);
21993   for (; V.hasOneUse(); V = V.getOperand(0)) {
21994     switch (V.getOpcode()) {
21995     default:
21996       return false; // Nothing combined!
21997
21998     case ISD::BITCAST:
21999       // Skip bitcasts as we always know the type for the target specific
22000       // instructions.
22001       continue;
22002
22003     case X86ISD::PSHUFLW:
22004     case X86ISD::PSHUFHW:
22005       if (V.getOpcode() == CombineOpcode)
22006         break;
22007
22008       // Other-half shuffles are no-ops.
22009       continue;
22010     }
22011     // Break out of the loop if we break out of the switch.
22012     break;
22013   }
22014
22015   if (!V.hasOneUse())
22016     // We fell out of the loop without finding a viable combining instruction.
22017     return false;
22018
22019   // Combine away the bottom node as its shuffle will be accumulated into
22020   // a preceding shuffle.
22021   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22022
22023   // Record the old value.
22024   SDValue Old = V;
22025
22026   // Merge this node's mask and our incoming mask (adjusted to account for all
22027   // the pshufd instructions encountered).
22028   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22029   for (int &M : Mask)
22030     M = VMask[M];
22031   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22032                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22033
22034   // Check that the shuffles didn't cancel each other out. If not, we need to
22035   // combine to the new one.
22036   if (Old != V)
22037     // Replace the combinable shuffle with the combined one, updating all users
22038     // so that we re-evaluate the chain here.
22039     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22040
22041   return true;
22042 }
22043
22044 /// \brief Try to combine x86 target specific shuffles.
22045 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22046                                            TargetLowering::DAGCombinerInfo &DCI,
22047                                            const X86Subtarget *Subtarget) {
22048   SDLoc DL(N);
22049   MVT VT = N.getSimpleValueType();
22050   SmallVector<int, 4> Mask;
22051
22052   switch (N.getOpcode()) {
22053   case X86ISD::PSHUFD:
22054   case X86ISD::PSHUFLW:
22055   case X86ISD::PSHUFHW:
22056     Mask = getPSHUFShuffleMask(N);
22057     assert(Mask.size() == 4);
22058     break;
22059   default:
22060     return SDValue();
22061   }
22062
22063   // Nuke no-op shuffles that show up after combining.
22064   if (isNoopShuffleMask(Mask))
22065     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22066
22067   // Look for simplifications involving one or two shuffle instructions.
22068   SDValue V = N.getOperand(0);
22069   switch (N.getOpcode()) {
22070   default:
22071     break;
22072   case X86ISD::PSHUFLW:
22073   case X86ISD::PSHUFHW:
22074     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22075
22076     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22077       return SDValue(); // We combined away this shuffle, so we're done.
22078
22079     // See if this reduces to a PSHUFD which is no more expensive and can
22080     // combine with more operations. Note that it has to at least flip the
22081     // dwords as otherwise it would have been removed as a no-op.
22082     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22083       int DMask[] = {0, 1, 2, 3};
22084       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22085       DMask[DOffset + 0] = DOffset + 1;
22086       DMask[DOffset + 1] = DOffset + 0;
22087       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22088       V = DAG.getBitcast(DVT, V);
22089       DCI.AddToWorklist(V.getNode());
22090       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22091                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22092       DCI.AddToWorklist(V.getNode());
22093       return DAG.getBitcast(VT, V);
22094     }
22095
22096     // Look for shuffle patterns which can be implemented as a single unpack.
22097     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22098     // only works when we have a PSHUFD followed by two half-shuffles.
22099     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22100         (V.getOpcode() == X86ISD::PSHUFLW ||
22101          V.getOpcode() == X86ISD::PSHUFHW) &&
22102         V.getOpcode() != N.getOpcode() &&
22103         V.hasOneUse()) {
22104       SDValue D = V.getOperand(0);
22105       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22106         D = D.getOperand(0);
22107       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22108         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22109         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22110         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22111         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22112         int WordMask[8];
22113         for (int i = 0; i < 4; ++i) {
22114           WordMask[i + NOffset] = Mask[i] + NOffset;
22115           WordMask[i + VOffset] = VMask[i] + VOffset;
22116         }
22117         // Map the word mask through the DWord mask.
22118         int MappedMask[8];
22119         for (int i = 0; i < 8; ++i)
22120           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22121         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22122             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22123           // We can replace all three shuffles with an unpack.
22124           V = DAG.getBitcast(VT, D.getOperand(0));
22125           DCI.AddToWorklist(V.getNode());
22126           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22127                                                 : X86ISD::UNPCKH,
22128                              DL, VT, V, V);
22129         }
22130       }
22131     }
22132
22133     break;
22134
22135   case X86ISD::PSHUFD:
22136     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22137       return NewN;
22138
22139     break;
22140   }
22141
22142   return SDValue();
22143 }
22144
22145 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22146 ///
22147 /// We combine this directly on the abstract vector shuffle nodes so it is
22148 /// easier to generically match. We also insert dummy vector shuffle nodes for
22149 /// the operands which explicitly discard the lanes which are unused by this
22150 /// operation to try to flow through the rest of the combiner the fact that
22151 /// they're unused.
22152 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22153   SDLoc DL(N);
22154   EVT VT = N->getValueType(0);
22155
22156   // We only handle target-independent shuffles.
22157   // FIXME: It would be easy and harmless to use the target shuffle mask
22158   // extraction tool to support more.
22159   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22160     return SDValue();
22161
22162   auto *SVN = cast<ShuffleVectorSDNode>(N);
22163   ArrayRef<int> Mask = SVN->getMask();
22164   SDValue V1 = N->getOperand(0);
22165   SDValue V2 = N->getOperand(1);
22166
22167   // We require the first shuffle operand to be the SUB node, and the second to
22168   // be the ADD node.
22169   // FIXME: We should support the commuted patterns.
22170   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22171     return SDValue();
22172
22173   // If there are other uses of these operations we can't fold them.
22174   if (!V1->hasOneUse() || !V2->hasOneUse())
22175     return SDValue();
22176
22177   // Ensure that both operations have the same operands. Note that we can
22178   // commute the FADD operands.
22179   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22180   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22181       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22182     return SDValue();
22183
22184   // We're looking for blends between FADD and FSUB nodes. We insist on these
22185   // nodes being lined up in a specific expected pattern.
22186   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22187         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22188         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22189     return SDValue();
22190
22191   // Only specific types are legal at this point, assert so we notice if and
22192   // when these change.
22193   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22194           VT == MVT::v4f64) &&
22195          "Unknown vector type encountered!");
22196
22197   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22198 }
22199
22200 /// PerformShuffleCombine - Performs several different shuffle combines.
22201 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22202                                      TargetLowering::DAGCombinerInfo &DCI,
22203                                      const X86Subtarget *Subtarget) {
22204   SDLoc dl(N);
22205   SDValue N0 = N->getOperand(0);
22206   SDValue N1 = N->getOperand(1);
22207   EVT VT = N->getValueType(0);
22208
22209   // Don't create instructions with illegal types after legalize types has run.
22210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22211   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22212     return SDValue();
22213
22214   // If we have legalized the vector types, look for blends of FADD and FSUB
22215   // nodes that we can fuse into an ADDSUB node.
22216   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22217     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22218       return AddSub;
22219
22220   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22221   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22222       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22223     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22224
22225   // During Type Legalization, when promoting illegal vector types,
22226   // the backend might introduce new shuffle dag nodes and bitcasts.
22227   //
22228   // This code performs the following transformation:
22229   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22230   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22231   //
22232   // We do this only if both the bitcast and the BINOP dag nodes have
22233   // one use. Also, perform this transformation only if the new binary
22234   // operation is legal. This is to avoid introducing dag nodes that
22235   // potentially need to be further expanded (or custom lowered) into a
22236   // less optimal sequence of dag nodes.
22237   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22238       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22239       N0.getOpcode() == ISD::BITCAST) {
22240     SDValue BC0 = N0.getOperand(0);
22241     EVT SVT = BC0.getValueType();
22242     unsigned Opcode = BC0.getOpcode();
22243     unsigned NumElts = VT.getVectorNumElements();
22244
22245     if (BC0.hasOneUse() && SVT.isVector() &&
22246         SVT.getVectorNumElements() * 2 == NumElts &&
22247         TLI.isOperationLegal(Opcode, VT)) {
22248       bool CanFold = false;
22249       switch (Opcode) {
22250       default : break;
22251       case ISD::ADD :
22252       case ISD::FADD :
22253       case ISD::SUB :
22254       case ISD::FSUB :
22255       case ISD::MUL :
22256       case ISD::FMUL :
22257         CanFold = true;
22258       }
22259
22260       unsigned SVTNumElts = SVT.getVectorNumElements();
22261       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22262       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22263         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22264       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22265         CanFold = SVOp->getMaskElt(i) < 0;
22266
22267       if (CanFold) {
22268         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22269         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22270         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22271         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22272       }
22273     }
22274   }
22275
22276   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22277   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22278   // consecutive, non-overlapping, and in the right order.
22279   SmallVector<SDValue, 16> Elts;
22280   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22281     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22282
22283   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22284     return LD;
22285
22286   if (isTargetShuffle(N->getOpcode())) {
22287     SDValue Shuffle =
22288         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22289     if (Shuffle.getNode())
22290       return Shuffle;
22291
22292     // Try recursively combining arbitrary sequences of x86 shuffle
22293     // instructions into higher-order shuffles. We do this after combining
22294     // specific PSHUF instruction sequences into their minimal form so that we
22295     // can evaluate how many specialized shuffle instructions are involved in
22296     // a particular chain.
22297     SmallVector<int, 1> NonceMask; // Just a placeholder.
22298     NonceMask.push_back(0);
22299     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22300                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22301                                       DCI, Subtarget))
22302       return SDValue(); // This routine will use CombineTo to replace N.
22303   }
22304
22305   return SDValue();
22306 }
22307
22308 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22309 /// specific shuffle of a load can be folded into a single element load.
22310 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22311 /// shuffles have been custom lowered so we need to handle those here.
22312 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22313                                          TargetLowering::DAGCombinerInfo &DCI) {
22314   if (DCI.isBeforeLegalizeOps())
22315     return SDValue();
22316
22317   SDValue InVec = N->getOperand(0);
22318   SDValue EltNo = N->getOperand(1);
22319
22320   if (!isa<ConstantSDNode>(EltNo))
22321     return SDValue();
22322
22323   EVT OriginalVT = InVec.getValueType();
22324
22325   if (InVec.getOpcode() == ISD::BITCAST) {
22326     // Don't duplicate a load with other uses.
22327     if (!InVec.hasOneUse())
22328       return SDValue();
22329     EVT BCVT = InVec.getOperand(0).getValueType();
22330     if (!BCVT.isVector() ||
22331         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22332       return SDValue();
22333     InVec = InVec.getOperand(0);
22334   }
22335
22336   EVT CurrentVT = InVec.getValueType();
22337
22338   if (!isTargetShuffle(InVec.getOpcode()))
22339     return SDValue();
22340
22341   // Don't duplicate a load with other uses.
22342   if (!InVec.hasOneUse())
22343     return SDValue();
22344
22345   SmallVector<int, 16> ShuffleMask;
22346   bool UnaryShuffle;
22347   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22348                             ShuffleMask, UnaryShuffle))
22349     return SDValue();
22350
22351   // Select the input vector, guarding against out of range extract vector.
22352   unsigned NumElems = CurrentVT.getVectorNumElements();
22353   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22354   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22355   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22356                                          : InVec.getOperand(1);
22357
22358   // If inputs to shuffle are the same for both ops, then allow 2 uses
22359   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22360                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22361
22362   if (LdNode.getOpcode() == ISD::BITCAST) {
22363     // Don't duplicate a load with other uses.
22364     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22365       return SDValue();
22366
22367     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22368     LdNode = LdNode.getOperand(0);
22369   }
22370
22371   if (!ISD::isNormalLoad(LdNode.getNode()))
22372     return SDValue();
22373
22374   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22375
22376   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22377     return SDValue();
22378
22379   EVT EltVT = N->getValueType(0);
22380   // If there's a bitcast before the shuffle, check if the load type and
22381   // alignment is valid.
22382   unsigned Align = LN0->getAlignment();
22383   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22384   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22385       EltVT.getTypeForEVT(*DAG.getContext()));
22386
22387   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22388     return SDValue();
22389
22390   // All checks match so transform back to vector_shuffle so that DAG combiner
22391   // can finish the job
22392   SDLoc dl(N);
22393
22394   // Create shuffle node taking into account the case that its a unary shuffle
22395   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22396                                    : InVec.getOperand(1);
22397   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22398                                  InVec.getOperand(0), Shuffle,
22399                                  &ShuffleMask[0]);
22400   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22401   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22402                      EltNo);
22403 }
22404
22405 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22406 /// special and don't usually play with other vector types, it's better to
22407 /// handle them early to be sure we emit efficient code by avoiding
22408 /// store-load conversions.
22409 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22410   if (N->getValueType(0) != MVT::x86mmx ||
22411       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22412       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22413     return SDValue();
22414
22415   SDValue V = N->getOperand(0);
22416   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22417   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22418     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22419                        N->getValueType(0), V.getOperand(0));
22420
22421   return SDValue();
22422 }
22423
22424 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22425 /// generation and convert it from being a bunch of shuffles and extracts
22426 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22427 /// storing the value and loading scalars back, while for x64 we should
22428 /// use 64-bit extracts and shifts.
22429 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22430                                          TargetLowering::DAGCombinerInfo &DCI) {
22431   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22432     return NewOp;
22433
22434   SDValue InputVector = N->getOperand(0);
22435   SDLoc dl(InputVector);
22436   // Detect mmx to i32 conversion through a v2i32 elt extract.
22437   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22438       N->getValueType(0) == MVT::i32 &&
22439       InputVector.getValueType() == MVT::v2i32) {
22440
22441     // The bitcast source is a direct mmx result.
22442     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22443     if (MMXSrc.getValueType() == MVT::x86mmx)
22444       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22445                          N->getValueType(0),
22446                          InputVector.getNode()->getOperand(0));
22447
22448     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22449     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22450     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22451         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22452         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22453         MMXSrcOp.getValueType() == MVT::v1i64 &&
22454         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22455       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22456                          N->getValueType(0),
22457                          MMXSrcOp.getOperand(0));
22458   }
22459
22460   EVT VT = N->getValueType(0);
22461
22462   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22463       InputVector.getOpcode() == ISD::BITCAST &&
22464       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22465     uint64_t ExtractedElt =
22466           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22467     uint64_t InputValue =
22468           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22469     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22470     return DAG.getConstant(Res, dl, MVT::i1);
22471   }
22472   // Only operate on vectors of 4 elements, where the alternative shuffling
22473   // gets to be more expensive.
22474   if (InputVector.getValueType() != MVT::v4i32)
22475     return SDValue();
22476
22477   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22478   // single use which is a sign-extend or zero-extend, and all elements are
22479   // used.
22480   SmallVector<SDNode *, 4> Uses;
22481   unsigned ExtractedElements = 0;
22482   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22483        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22484     if (UI.getUse().getResNo() != InputVector.getResNo())
22485       return SDValue();
22486
22487     SDNode *Extract = *UI;
22488     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22489       return SDValue();
22490
22491     if (Extract->getValueType(0) != MVT::i32)
22492       return SDValue();
22493     if (!Extract->hasOneUse())
22494       return SDValue();
22495     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22496         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22497       return SDValue();
22498     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22499       return SDValue();
22500
22501     // Record which element was extracted.
22502     ExtractedElements |=
22503       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22504
22505     Uses.push_back(Extract);
22506   }
22507
22508   // If not all the elements were used, this may not be worthwhile.
22509   if (ExtractedElements != 15)
22510     return SDValue();
22511
22512   // Ok, we've now decided to do the transformation.
22513   // If 64-bit shifts are legal, use the extract-shift sequence,
22514   // otherwise bounce the vector off the cache.
22515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22516   SDValue Vals[4];
22517
22518   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22519     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22520     auto &DL = DAG.getDataLayout();
22521     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22522     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22523       DAG.getConstant(0, dl, VecIdxTy));
22524     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22525       DAG.getConstant(1, dl, VecIdxTy));
22526
22527     SDValue ShAmt = DAG.getConstant(
22528         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22529     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22530     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22531       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22532     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22533     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22534       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22535   } else {
22536     // Store the value to a temporary stack slot.
22537     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22538     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22539       MachinePointerInfo(), false, false, 0);
22540
22541     EVT ElementType = InputVector.getValueType().getVectorElementType();
22542     unsigned EltSize = ElementType.getSizeInBits() / 8;
22543
22544     // Replace each use (extract) with a load of the appropriate element.
22545     for (unsigned i = 0; i < 4; ++i) {
22546       uint64_t Offset = EltSize * i;
22547       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22548       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22549
22550       SDValue ScalarAddr =
22551           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22552
22553       // Load the scalar.
22554       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22555                             ScalarAddr, MachinePointerInfo(),
22556                             false, false, false, 0);
22557
22558     }
22559   }
22560
22561   // Replace the extracts
22562   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22563     UE = Uses.end(); UI != UE; ++UI) {
22564     SDNode *Extract = *UI;
22565
22566     SDValue Idx = Extract->getOperand(1);
22567     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22568     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22569   }
22570
22571   // The replacement was made in place; don't return anything.
22572   return SDValue();
22573 }
22574
22575 static SDValue
22576 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22577                                       const X86Subtarget *Subtarget) {
22578   SDLoc dl(N);
22579   SDValue Cond = N->getOperand(0);
22580   SDValue LHS = N->getOperand(1);
22581   SDValue RHS = N->getOperand(2);
22582
22583   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22584     SDValue CondSrc = Cond->getOperand(0);
22585     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22586       Cond = CondSrc->getOperand(0);
22587   }
22588
22589   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22590     return SDValue();
22591
22592   // A vselect where all conditions and data are constants can be optimized into
22593   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22594   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22595       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22596     return SDValue();
22597
22598   unsigned MaskValue = 0;
22599   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22600     return SDValue();
22601
22602   MVT VT = N->getSimpleValueType(0);
22603   unsigned NumElems = VT.getVectorNumElements();
22604   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22605   for (unsigned i = 0; i < NumElems; ++i) {
22606     // Be sure we emit undef where we can.
22607     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22608       ShuffleMask[i] = -1;
22609     else
22610       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22611   }
22612
22613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22614   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22615     return SDValue();
22616   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22617 }
22618
22619 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22620 /// nodes.
22621 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22622                                     TargetLowering::DAGCombinerInfo &DCI,
22623                                     const X86Subtarget *Subtarget) {
22624   SDLoc DL(N);
22625   SDValue Cond = N->getOperand(0);
22626   // Get the LHS/RHS of the select.
22627   SDValue LHS = N->getOperand(1);
22628   SDValue RHS = N->getOperand(2);
22629   EVT VT = LHS.getValueType();
22630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22631
22632   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22633   // instructions match the semantics of the common C idiom x<y?x:y but not
22634   // x<=y?x:y, because of how they handle negative zero (which can be
22635   // ignored in unsafe-math mode).
22636   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22637   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22638       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22639       (Subtarget->hasSSE2() ||
22640        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22641     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22642
22643     unsigned Opcode = 0;
22644     // Check for x CC y ? x : y.
22645     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22646         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22647       switch (CC) {
22648       default: break;
22649       case ISD::SETULT:
22650         // Converting this to a min would handle NaNs incorrectly, and swapping
22651         // the operands would cause it to handle comparisons between positive
22652         // and negative zero incorrectly.
22653         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22654           if (!DAG.getTarget().Options.UnsafeFPMath &&
22655               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22656             break;
22657           std::swap(LHS, RHS);
22658         }
22659         Opcode = X86ISD::FMIN;
22660         break;
22661       case ISD::SETOLE:
22662         // Converting this to a min would handle comparisons between positive
22663         // and negative zero incorrectly.
22664         if (!DAG.getTarget().Options.UnsafeFPMath &&
22665             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22666           break;
22667         Opcode = X86ISD::FMIN;
22668         break;
22669       case ISD::SETULE:
22670         // Converting this to a min would handle both negative zeros and NaNs
22671         // incorrectly, but we can swap the operands to fix both.
22672         std::swap(LHS, RHS);
22673       case ISD::SETOLT:
22674       case ISD::SETLT:
22675       case ISD::SETLE:
22676         Opcode = X86ISD::FMIN;
22677         break;
22678
22679       case ISD::SETOGE:
22680         // Converting this to a max would handle comparisons between positive
22681         // and negative zero incorrectly.
22682         if (!DAG.getTarget().Options.UnsafeFPMath &&
22683             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22684           break;
22685         Opcode = X86ISD::FMAX;
22686         break;
22687       case ISD::SETUGT:
22688         // Converting this to a max would handle NaNs incorrectly, and swapping
22689         // the operands would cause it to handle comparisons between positive
22690         // and negative zero incorrectly.
22691         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22692           if (!DAG.getTarget().Options.UnsafeFPMath &&
22693               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22694             break;
22695           std::swap(LHS, RHS);
22696         }
22697         Opcode = X86ISD::FMAX;
22698         break;
22699       case ISD::SETUGE:
22700         // Converting this to a max would handle both negative zeros and NaNs
22701         // incorrectly, but we can swap the operands to fix both.
22702         std::swap(LHS, RHS);
22703       case ISD::SETOGT:
22704       case ISD::SETGT:
22705       case ISD::SETGE:
22706         Opcode = X86ISD::FMAX;
22707         break;
22708       }
22709     // Check for x CC y ? y : x -- a min/max with reversed arms.
22710     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22711                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22712       switch (CC) {
22713       default: break;
22714       case ISD::SETOGE:
22715         // Converting this to a min would handle comparisons between positive
22716         // and negative zero incorrectly, and swapping the operands would
22717         // cause it to handle NaNs incorrectly.
22718         if (!DAG.getTarget().Options.UnsafeFPMath &&
22719             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22720           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22721             break;
22722           std::swap(LHS, RHS);
22723         }
22724         Opcode = X86ISD::FMIN;
22725         break;
22726       case ISD::SETUGT:
22727         // Converting this to a min would handle NaNs incorrectly.
22728         if (!DAG.getTarget().Options.UnsafeFPMath &&
22729             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22730           break;
22731         Opcode = X86ISD::FMIN;
22732         break;
22733       case ISD::SETUGE:
22734         // Converting this to a min would handle both negative zeros and NaNs
22735         // incorrectly, but we can swap the operands to fix both.
22736         std::swap(LHS, RHS);
22737       case ISD::SETOGT:
22738       case ISD::SETGT:
22739       case ISD::SETGE:
22740         Opcode = X86ISD::FMIN;
22741         break;
22742
22743       case ISD::SETULT:
22744         // Converting this to a max would handle NaNs incorrectly.
22745         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22746           break;
22747         Opcode = X86ISD::FMAX;
22748         break;
22749       case ISD::SETOLE:
22750         // Converting this to a max would handle comparisons between positive
22751         // and negative zero incorrectly, and swapping the operands would
22752         // cause it to handle NaNs incorrectly.
22753         if (!DAG.getTarget().Options.UnsafeFPMath &&
22754             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22755           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22756             break;
22757           std::swap(LHS, RHS);
22758         }
22759         Opcode = X86ISD::FMAX;
22760         break;
22761       case ISD::SETULE:
22762         // Converting this to a max would handle both negative zeros and NaNs
22763         // incorrectly, but we can swap the operands to fix both.
22764         std::swap(LHS, RHS);
22765       case ISD::SETOLT:
22766       case ISD::SETLT:
22767       case ISD::SETLE:
22768         Opcode = X86ISD::FMAX;
22769         break;
22770       }
22771     }
22772
22773     if (Opcode)
22774       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22775   }
22776
22777   EVT CondVT = Cond.getValueType();
22778   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22779       CondVT.getVectorElementType() == MVT::i1) {
22780     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22781     // lowering on KNL. In this case we convert it to
22782     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22783     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22784     // Since SKX these selects have a proper lowering.
22785     EVT OpVT = LHS.getValueType();
22786     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22787         (OpVT.getVectorElementType() == MVT::i8 ||
22788          OpVT.getVectorElementType() == MVT::i16) &&
22789         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22790       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22791       DCI.AddToWorklist(Cond.getNode());
22792       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22793     }
22794   }
22795   // If this is a select between two integer constants, try to do some
22796   // optimizations.
22797   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22798     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22799       // Don't do this for crazy integer types.
22800       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22801         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22802         // so that TrueC (the true value) is larger than FalseC.
22803         bool NeedsCondInvert = false;
22804
22805         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22806             // Efficiently invertible.
22807             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22808              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22809               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22810           NeedsCondInvert = true;
22811           std::swap(TrueC, FalseC);
22812         }
22813
22814         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22815         if (FalseC->getAPIntValue() == 0 &&
22816             TrueC->getAPIntValue().isPowerOf2()) {
22817           if (NeedsCondInvert) // Invert the condition if needed.
22818             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22819                                DAG.getConstant(1, DL, Cond.getValueType()));
22820
22821           // Zero extend the condition if needed.
22822           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22823
22824           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22825           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22826                              DAG.getConstant(ShAmt, DL, MVT::i8));
22827         }
22828
22829         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22830         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22831           if (NeedsCondInvert) // Invert the condition if needed.
22832             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22833                                DAG.getConstant(1, DL, Cond.getValueType()));
22834
22835           // Zero extend the condition if needed.
22836           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22837                              FalseC->getValueType(0), Cond);
22838           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22839                              SDValue(FalseC, 0));
22840         }
22841
22842         // Optimize cases that will turn into an LEA instruction.  This requires
22843         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22844         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22845           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22846           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22847
22848           bool isFastMultiplier = false;
22849           if (Diff < 10) {
22850             switch ((unsigned char)Diff) {
22851               default: break;
22852               case 1:  // result = add base, cond
22853               case 2:  // result = lea base(    , cond*2)
22854               case 3:  // result = lea base(cond, cond*2)
22855               case 4:  // result = lea base(    , cond*4)
22856               case 5:  // result = lea base(cond, cond*4)
22857               case 8:  // result = lea base(    , cond*8)
22858               case 9:  // result = lea base(cond, cond*8)
22859                 isFastMultiplier = true;
22860                 break;
22861             }
22862           }
22863
22864           if (isFastMultiplier) {
22865             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22866             if (NeedsCondInvert) // Invert the condition if needed.
22867               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22868                                  DAG.getConstant(1, DL, Cond.getValueType()));
22869
22870             // Zero extend the condition if needed.
22871             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22872                                Cond);
22873             // Scale the condition by the difference.
22874             if (Diff != 1)
22875               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22876                                  DAG.getConstant(Diff, DL,
22877                                                  Cond.getValueType()));
22878
22879             // Add the base if non-zero.
22880             if (FalseC->getAPIntValue() != 0)
22881               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22882                                  SDValue(FalseC, 0));
22883             return Cond;
22884           }
22885         }
22886       }
22887   }
22888
22889   // Canonicalize max and min:
22890   // (x > y) ? x : y -> (x >= y) ? x : y
22891   // (x < y) ? x : y -> (x <= y) ? x : y
22892   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22893   // the need for an extra compare
22894   // against zero. e.g.
22895   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22896   // subl   %esi, %edi
22897   // testl  %edi, %edi
22898   // movl   $0, %eax
22899   // cmovgl %edi, %eax
22900   // =>
22901   // xorl   %eax, %eax
22902   // subl   %esi, $edi
22903   // cmovsl %eax, %edi
22904   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22905       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22906       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22907     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22908     switch (CC) {
22909     default: break;
22910     case ISD::SETLT:
22911     case ISD::SETGT: {
22912       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22913       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22914                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22915       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22916     }
22917     }
22918   }
22919
22920   // Early exit check
22921   if (!TLI.isTypeLegal(VT))
22922     return SDValue();
22923
22924   // Match VSELECTs into subs with unsigned saturation.
22925   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22926       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22927       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22928        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22929     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22930
22931     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22932     // left side invert the predicate to simplify logic below.
22933     SDValue Other;
22934     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22935       Other = RHS;
22936       CC = ISD::getSetCCInverse(CC, true);
22937     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22938       Other = LHS;
22939     }
22940
22941     if (Other.getNode() && Other->getNumOperands() == 2 &&
22942         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22943       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22944       SDValue CondRHS = Cond->getOperand(1);
22945
22946       // Look for a general sub with unsigned saturation first.
22947       // x >= y ? x-y : 0 --> subus x, y
22948       // x >  y ? x-y : 0 --> subus x, y
22949       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22950           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22951         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22952
22953       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22954         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22955           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22956             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22957               // If the RHS is a constant we have to reverse the const
22958               // canonicalization.
22959               // x > C-1 ? x+-C : 0 --> subus x, C
22960               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22961                   CondRHSConst->getAPIntValue() ==
22962                       (-OpRHSConst->getAPIntValue() - 1))
22963                 return DAG.getNode(
22964                     X86ISD::SUBUS, DL, VT, OpLHS,
22965                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22966
22967           // Another special case: If C was a sign bit, the sub has been
22968           // canonicalized into a xor.
22969           // FIXME: Would it be better to use computeKnownBits to determine
22970           //        whether it's safe to decanonicalize the xor?
22971           // x s< 0 ? x^C : 0 --> subus x, C
22972           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22973               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22974               OpRHSConst->getAPIntValue().isSignBit())
22975             // Note that we have to rebuild the RHS constant here to ensure we
22976             // don't rely on particular values of undef lanes.
22977             return DAG.getNode(
22978                 X86ISD::SUBUS, DL, VT, OpLHS,
22979                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22980         }
22981     }
22982   }
22983
22984   // Simplify vector selection if condition value type matches vselect
22985   // operand type
22986   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22987     assert(Cond.getValueType().isVector() &&
22988            "vector select expects a vector selector!");
22989
22990     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22991     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22992
22993     // Try invert the condition if true value is not all 1s and false value
22994     // is not all 0s.
22995     if (!TValIsAllOnes && !FValIsAllZeros &&
22996         // Check if the selector will be produced by CMPP*/PCMP*
22997         Cond.getOpcode() == ISD::SETCC &&
22998         // Check if SETCC has already been promoted
22999         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23000             CondVT) {
23001       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23002       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23003
23004       if (TValIsAllZeros || FValIsAllOnes) {
23005         SDValue CC = Cond.getOperand(2);
23006         ISD::CondCode NewCC =
23007           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23008                                Cond.getOperand(0).getValueType().isInteger());
23009         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23010         std::swap(LHS, RHS);
23011         TValIsAllOnes = FValIsAllOnes;
23012         FValIsAllZeros = TValIsAllZeros;
23013       }
23014     }
23015
23016     if (TValIsAllOnes || FValIsAllZeros) {
23017       SDValue Ret;
23018
23019       if (TValIsAllOnes && FValIsAllZeros)
23020         Ret = Cond;
23021       else if (TValIsAllOnes)
23022         Ret =
23023             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23024       else if (FValIsAllZeros)
23025         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23026                           DAG.getBitcast(CondVT, LHS));
23027
23028       return DAG.getBitcast(VT, Ret);
23029     }
23030   }
23031
23032   // We should generate an X86ISD::BLENDI from a vselect if its argument
23033   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23034   // constants. This specific pattern gets generated when we split a
23035   // selector for a 512 bit vector in a machine without AVX512 (but with
23036   // 256-bit vectors), during legalization:
23037   //
23038   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23039   //
23040   // Iff we find this pattern and the build_vectors are built from
23041   // constants, we translate the vselect into a shuffle_vector that we
23042   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23043   if ((N->getOpcode() == ISD::VSELECT ||
23044        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23045       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23046     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23047     if (Shuffle.getNode())
23048       return Shuffle;
23049   }
23050
23051   // If this is a *dynamic* select (non-constant condition) and we can match
23052   // this node with one of the variable blend instructions, restructure the
23053   // condition so that the blends can use the high bit of each element and use
23054   // SimplifyDemandedBits to simplify the condition operand.
23055   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23056       !DCI.isBeforeLegalize() &&
23057       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23058     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23059
23060     // Don't optimize vector selects that map to mask-registers.
23061     if (BitWidth == 1)
23062       return SDValue();
23063
23064     // We can only handle the cases where VSELECT is directly legal on the
23065     // subtarget. We custom lower VSELECT nodes with constant conditions and
23066     // this makes it hard to see whether a dynamic VSELECT will correctly
23067     // lower, so we both check the operation's status and explicitly handle the
23068     // cases where a *dynamic* blend will fail even though a constant-condition
23069     // blend could be custom lowered.
23070     // FIXME: We should find a better way to handle this class of problems.
23071     // Potentially, we should combine constant-condition vselect nodes
23072     // pre-legalization into shuffles and not mark as many types as custom
23073     // lowered.
23074     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23075       return SDValue();
23076     // FIXME: We don't support i16-element blends currently. We could and
23077     // should support them by making *all* the bits in the condition be set
23078     // rather than just the high bit and using an i8-element blend.
23079     if (VT.getScalarType() == MVT::i16)
23080       return SDValue();
23081     // Dynamic blending was only available from SSE4.1 onward.
23082     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23083       return SDValue();
23084     // Byte blends are only available in AVX2
23085     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23086         !Subtarget->hasAVX2())
23087       return SDValue();
23088
23089     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23090     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23091
23092     APInt KnownZero, KnownOne;
23093     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23094                                           DCI.isBeforeLegalizeOps());
23095     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23096         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23097                                  TLO)) {
23098       // If we changed the computation somewhere in the DAG, this change
23099       // will affect all users of Cond.
23100       // Make sure it is fine and update all the nodes so that we do not
23101       // use the generic VSELECT anymore. Otherwise, we may perform
23102       // wrong optimizations as we messed up with the actual expectation
23103       // for the vector boolean values.
23104       if (Cond != TLO.Old) {
23105         // Check all uses of that condition operand to check whether it will be
23106         // consumed by non-BLEND instructions, which may depend on all bits are
23107         // set properly.
23108         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23109              I != E; ++I)
23110           if (I->getOpcode() != ISD::VSELECT)
23111             // TODO: Add other opcodes eventually lowered into BLEND.
23112             return SDValue();
23113
23114         // Update all the users of the condition, before committing the change,
23115         // so that the VSELECT optimizations that expect the correct vector
23116         // boolean value will not be triggered.
23117         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23118              I != E; ++I)
23119           DAG.ReplaceAllUsesOfValueWith(
23120               SDValue(*I, 0),
23121               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23122                           Cond, I->getOperand(1), I->getOperand(2)));
23123         DCI.CommitTargetLoweringOpt(TLO);
23124         return SDValue();
23125       }
23126       // At this point, only Cond is changed. Change the condition
23127       // just for N to keep the opportunity to optimize all other
23128       // users their own way.
23129       DAG.ReplaceAllUsesOfValueWith(
23130           SDValue(N, 0),
23131           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23132                       TLO.New, N->getOperand(1), N->getOperand(2)));
23133       return SDValue();
23134     }
23135   }
23136
23137   return SDValue();
23138 }
23139
23140 // Check whether a boolean test is testing a boolean value generated by
23141 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23142 // code.
23143 //
23144 // Simplify the following patterns:
23145 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23146 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23147 // to (Op EFLAGS Cond)
23148 //
23149 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23150 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23151 // to (Op EFLAGS !Cond)
23152 //
23153 // where Op could be BRCOND or CMOV.
23154 //
23155 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23156   // Quit if not CMP and SUB with its value result used.
23157   if (Cmp.getOpcode() != X86ISD::CMP &&
23158       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23159       return SDValue();
23160
23161   // Quit if not used as a boolean value.
23162   if (CC != X86::COND_E && CC != X86::COND_NE)
23163     return SDValue();
23164
23165   // Check CMP operands. One of them should be 0 or 1 and the other should be
23166   // an SetCC or extended from it.
23167   SDValue Op1 = Cmp.getOperand(0);
23168   SDValue Op2 = Cmp.getOperand(1);
23169
23170   SDValue SetCC;
23171   const ConstantSDNode* C = nullptr;
23172   bool needOppositeCond = (CC == X86::COND_E);
23173   bool checkAgainstTrue = false; // Is it a comparison against 1?
23174
23175   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23176     SetCC = Op2;
23177   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23178     SetCC = Op1;
23179   else // Quit if all operands are not constants.
23180     return SDValue();
23181
23182   if (C->getZExtValue() == 1) {
23183     needOppositeCond = !needOppositeCond;
23184     checkAgainstTrue = true;
23185   } else if (C->getZExtValue() != 0)
23186     // Quit if the constant is neither 0 or 1.
23187     return SDValue();
23188
23189   bool truncatedToBoolWithAnd = false;
23190   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23191   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23192          SetCC.getOpcode() == ISD::TRUNCATE ||
23193          SetCC.getOpcode() == ISD::AND) {
23194     if (SetCC.getOpcode() == ISD::AND) {
23195       int OpIdx = -1;
23196       ConstantSDNode *CS;
23197       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23198           CS->getZExtValue() == 1)
23199         OpIdx = 1;
23200       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23201           CS->getZExtValue() == 1)
23202         OpIdx = 0;
23203       if (OpIdx == -1)
23204         break;
23205       SetCC = SetCC.getOperand(OpIdx);
23206       truncatedToBoolWithAnd = true;
23207     } else
23208       SetCC = SetCC.getOperand(0);
23209   }
23210
23211   switch (SetCC.getOpcode()) {
23212   case X86ISD::SETCC_CARRY:
23213     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23214     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23215     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23216     // truncated to i1 using 'and'.
23217     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23218       break;
23219     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23220            "Invalid use of SETCC_CARRY!");
23221     // FALL THROUGH
23222   case X86ISD::SETCC:
23223     // Set the condition code or opposite one if necessary.
23224     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23225     if (needOppositeCond)
23226       CC = X86::GetOppositeBranchCondition(CC);
23227     return SetCC.getOperand(1);
23228   case X86ISD::CMOV: {
23229     // Check whether false/true value has canonical one, i.e. 0 or 1.
23230     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23231     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23232     // Quit if true value is not a constant.
23233     if (!TVal)
23234       return SDValue();
23235     // Quit if false value is not a constant.
23236     if (!FVal) {
23237       SDValue Op = SetCC.getOperand(0);
23238       // Skip 'zext' or 'trunc' node.
23239       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23240           Op.getOpcode() == ISD::TRUNCATE)
23241         Op = Op.getOperand(0);
23242       // A special case for rdrand/rdseed, where 0 is set if false cond is
23243       // found.
23244       if ((Op.getOpcode() != X86ISD::RDRAND &&
23245            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23246         return SDValue();
23247     }
23248     // Quit if false value is not the constant 0 or 1.
23249     bool FValIsFalse = true;
23250     if (FVal && FVal->getZExtValue() != 0) {
23251       if (FVal->getZExtValue() != 1)
23252         return SDValue();
23253       // If FVal is 1, opposite cond is needed.
23254       needOppositeCond = !needOppositeCond;
23255       FValIsFalse = false;
23256     }
23257     // Quit if TVal is not the constant opposite of FVal.
23258     if (FValIsFalse && TVal->getZExtValue() != 1)
23259       return SDValue();
23260     if (!FValIsFalse && TVal->getZExtValue() != 0)
23261       return SDValue();
23262     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23263     if (needOppositeCond)
23264       CC = X86::GetOppositeBranchCondition(CC);
23265     return SetCC.getOperand(3);
23266   }
23267   }
23268
23269   return SDValue();
23270 }
23271
23272 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23273 /// Match:
23274 ///   (X86or (X86setcc) (X86setcc))
23275 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23276 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23277                                            X86::CondCode &CC1, SDValue &Flags,
23278                                            bool &isAnd) {
23279   if (Cond->getOpcode() == X86ISD::CMP) {
23280     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23281     if (!CondOp1C || !CondOp1C->isNullValue())
23282       return false;
23283
23284     Cond = Cond->getOperand(0);
23285   }
23286
23287   isAnd = false;
23288
23289   SDValue SetCC0, SetCC1;
23290   switch (Cond->getOpcode()) {
23291   default: return false;
23292   case ISD::AND:
23293   case X86ISD::AND:
23294     isAnd = true;
23295     // fallthru
23296   case ISD::OR:
23297   case X86ISD::OR:
23298     SetCC0 = Cond->getOperand(0);
23299     SetCC1 = Cond->getOperand(1);
23300     break;
23301   };
23302
23303   // Make sure we have SETCC nodes, using the same flags value.
23304   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23305       SetCC1.getOpcode() != X86ISD::SETCC ||
23306       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23307     return false;
23308
23309   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23310   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23311   Flags = SetCC0->getOperand(1);
23312   return true;
23313 }
23314
23315 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23316 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23317                                   TargetLowering::DAGCombinerInfo &DCI,
23318                                   const X86Subtarget *Subtarget) {
23319   SDLoc DL(N);
23320
23321   // If the flag operand isn't dead, don't touch this CMOV.
23322   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23323     return SDValue();
23324
23325   SDValue FalseOp = N->getOperand(0);
23326   SDValue TrueOp = N->getOperand(1);
23327   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23328   SDValue Cond = N->getOperand(3);
23329
23330   if (CC == X86::COND_E || CC == X86::COND_NE) {
23331     switch (Cond.getOpcode()) {
23332     default: break;
23333     case X86ISD::BSR:
23334     case X86ISD::BSF:
23335       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23336       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23337         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23338     }
23339   }
23340
23341   SDValue Flags;
23342
23343   Flags = checkBoolTestSetCCCombine(Cond, CC);
23344   if (Flags.getNode() &&
23345       // Extra check as FCMOV only supports a subset of X86 cond.
23346       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23347     SDValue Ops[] = { FalseOp, TrueOp,
23348                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23349     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23350   }
23351
23352   // If this is a select between two integer constants, try to do some
23353   // optimizations.  Note that the operands are ordered the opposite of SELECT
23354   // operands.
23355   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23356     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23357       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23358       // larger than FalseC (the false value).
23359       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23360         CC = X86::GetOppositeBranchCondition(CC);
23361         std::swap(TrueC, FalseC);
23362         std::swap(TrueOp, FalseOp);
23363       }
23364
23365       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23366       // This is efficient for any integer data type (including i8/i16) and
23367       // shift amount.
23368       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23369         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23370                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23371
23372         // Zero extend the condition if needed.
23373         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23374
23375         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23376         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23377                            DAG.getConstant(ShAmt, DL, MVT::i8));
23378         if (N->getNumValues() == 2)  // Dead flag value?
23379           return DCI.CombineTo(N, Cond, SDValue());
23380         return Cond;
23381       }
23382
23383       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23384       // for any integer data type, including i8/i16.
23385       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23386         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23387                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23388
23389         // Zero extend the condition if needed.
23390         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23391                            FalseC->getValueType(0), Cond);
23392         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23393                            SDValue(FalseC, 0));
23394
23395         if (N->getNumValues() == 2)  // Dead flag value?
23396           return DCI.CombineTo(N, Cond, SDValue());
23397         return Cond;
23398       }
23399
23400       // Optimize cases that will turn into an LEA instruction.  This requires
23401       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23402       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23403         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23404         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23405
23406         bool isFastMultiplier = false;
23407         if (Diff < 10) {
23408           switch ((unsigned char)Diff) {
23409           default: break;
23410           case 1:  // result = add base, cond
23411           case 2:  // result = lea base(    , cond*2)
23412           case 3:  // result = lea base(cond, cond*2)
23413           case 4:  // result = lea base(    , cond*4)
23414           case 5:  // result = lea base(cond, cond*4)
23415           case 8:  // result = lea base(    , cond*8)
23416           case 9:  // result = lea base(cond, cond*8)
23417             isFastMultiplier = true;
23418             break;
23419           }
23420         }
23421
23422         if (isFastMultiplier) {
23423           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23424           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23425                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23426           // Zero extend the condition if needed.
23427           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23428                              Cond);
23429           // Scale the condition by the difference.
23430           if (Diff != 1)
23431             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23432                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23433
23434           // Add the base if non-zero.
23435           if (FalseC->getAPIntValue() != 0)
23436             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23437                                SDValue(FalseC, 0));
23438           if (N->getNumValues() == 2)  // Dead flag value?
23439             return DCI.CombineTo(N, Cond, SDValue());
23440           return Cond;
23441         }
23442       }
23443     }
23444   }
23445
23446   // Handle these cases:
23447   //   (select (x != c), e, c) -> select (x != c), e, x),
23448   //   (select (x == c), c, e) -> select (x == c), x, e)
23449   // where the c is an integer constant, and the "select" is the combination
23450   // of CMOV and CMP.
23451   //
23452   // The rationale for this change is that the conditional-move from a constant
23453   // needs two instructions, however, conditional-move from a register needs
23454   // only one instruction.
23455   //
23456   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23457   //  some instruction-combining opportunities. This opt needs to be
23458   //  postponed as late as possible.
23459   //
23460   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23461     // the DCI.xxxx conditions are provided to postpone the optimization as
23462     // late as possible.
23463
23464     ConstantSDNode *CmpAgainst = nullptr;
23465     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23466         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23467         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23468
23469       if (CC == X86::COND_NE &&
23470           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23471         CC = X86::GetOppositeBranchCondition(CC);
23472         std::swap(TrueOp, FalseOp);
23473       }
23474
23475       if (CC == X86::COND_E &&
23476           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23477         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23478                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23479         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23480       }
23481     }
23482   }
23483
23484   // Fold and/or of setcc's to double CMOV:
23485   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23486   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23487   //
23488   // This combine lets us generate:
23489   //   cmovcc1 (jcc1 if we don't have CMOV)
23490   //   cmovcc2 (same)
23491   // instead of:
23492   //   setcc1
23493   //   setcc2
23494   //   and/or
23495   //   cmovne (jne if we don't have CMOV)
23496   // When we can't use the CMOV instruction, it might increase branch
23497   // mispredicts.
23498   // When we can use CMOV, or when there is no mispredict, this improves
23499   // throughput and reduces register pressure.
23500   //
23501   if (CC == X86::COND_NE) {
23502     SDValue Flags;
23503     X86::CondCode CC0, CC1;
23504     bool isAndSetCC;
23505     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23506       if (isAndSetCC) {
23507         std::swap(FalseOp, TrueOp);
23508         CC0 = X86::GetOppositeBranchCondition(CC0);
23509         CC1 = X86::GetOppositeBranchCondition(CC1);
23510       }
23511
23512       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23513         Flags};
23514       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23515       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23516       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23517       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23518       return CMOV;
23519     }
23520   }
23521
23522   return SDValue();
23523 }
23524
23525 /// PerformMulCombine - Optimize a single multiply with constant into two
23526 /// in order to implement it with two cheaper instructions, e.g.
23527 /// LEA + SHL, LEA + LEA.
23528 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23529                                  TargetLowering::DAGCombinerInfo &DCI) {
23530   // An imul is usually smaller than the alternative sequence.
23531   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23532     return SDValue();
23533
23534   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23535     return SDValue();
23536
23537   EVT VT = N->getValueType(0);
23538   if (VT != MVT::i64 && VT != MVT::i32)
23539     return SDValue();
23540
23541   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23542   if (!C)
23543     return SDValue();
23544   uint64_t MulAmt = C->getZExtValue();
23545   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23546     return SDValue();
23547
23548   uint64_t MulAmt1 = 0;
23549   uint64_t MulAmt2 = 0;
23550   if ((MulAmt % 9) == 0) {
23551     MulAmt1 = 9;
23552     MulAmt2 = MulAmt / 9;
23553   } else if ((MulAmt % 5) == 0) {
23554     MulAmt1 = 5;
23555     MulAmt2 = MulAmt / 5;
23556   } else if ((MulAmt % 3) == 0) {
23557     MulAmt1 = 3;
23558     MulAmt2 = MulAmt / 3;
23559   }
23560   if (MulAmt2 &&
23561       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23562     SDLoc DL(N);
23563
23564     if (isPowerOf2_64(MulAmt2) &&
23565         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23566       // If second multiplifer is pow2, issue it first. We want the multiply by
23567       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23568       // is an add.
23569       std::swap(MulAmt1, MulAmt2);
23570
23571     SDValue NewMul;
23572     if (isPowerOf2_64(MulAmt1))
23573       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23574                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23575     else
23576       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23577                            DAG.getConstant(MulAmt1, DL, VT));
23578
23579     if (isPowerOf2_64(MulAmt2))
23580       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23581                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23582     else
23583       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23584                            DAG.getConstant(MulAmt2, DL, VT));
23585
23586     // Do not add new nodes to DAG combiner worklist.
23587     DCI.CombineTo(N, NewMul, false);
23588   }
23589   return SDValue();
23590 }
23591
23592 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23593   SDValue N0 = N->getOperand(0);
23594   SDValue N1 = N->getOperand(1);
23595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23596   EVT VT = N0.getValueType();
23597
23598   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23599   // since the result of setcc_c is all zero's or all ones.
23600   if (VT.isInteger() && !VT.isVector() &&
23601       N1C && N0.getOpcode() == ISD::AND &&
23602       N0.getOperand(1).getOpcode() == ISD::Constant) {
23603     SDValue N00 = N0.getOperand(0);
23604     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23605     APInt ShAmt = N1C->getAPIntValue();
23606     Mask = Mask.shl(ShAmt);
23607     bool MaskOK = false;
23608     // We can handle cases concerning bit-widening nodes containing setcc_c if
23609     // we carefully interrogate the mask to make sure we are semantics
23610     // preserving.
23611     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23612     // of the underlying setcc_c operation if the setcc_c was zero extended.
23613     // Consider the following example:
23614     //   zext(setcc_c)                 -> i32 0x0000FFFF
23615     //   c1                            -> i32 0x0000FFFF
23616     //   c2                            -> i32 0x00000001
23617     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23618     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23619     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23620       MaskOK = true;
23621     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23622                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23623       MaskOK = true;
23624     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23625                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23626                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23627       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23628     }
23629     if (MaskOK && Mask != 0) {
23630       SDLoc DL(N);
23631       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23632     }
23633   }
23634
23635   // Hardware support for vector shifts is sparse which makes us scalarize the
23636   // vector operations in many cases. Also, on sandybridge ADD is faster than
23637   // shl.
23638   // (shl V, 1) -> add V,V
23639   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23640     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23641       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23642       // We shift all of the values by one. In many cases we do not have
23643       // hardware support for this operation. This is better expressed as an ADD
23644       // of two values.
23645       if (N1SplatC->getAPIntValue() == 1)
23646         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23647     }
23648
23649   return SDValue();
23650 }
23651
23652 /// \brief Returns a vector of 0s if the node in input is a vector logical
23653 /// shift by a constant amount which is known to be bigger than or equal
23654 /// to the vector element size in bits.
23655 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23656                                       const X86Subtarget *Subtarget) {
23657   EVT VT = N->getValueType(0);
23658
23659   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23660       (!Subtarget->hasInt256() ||
23661        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23662     return SDValue();
23663
23664   SDValue Amt = N->getOperand(1);
23665   SDLoc DL(N);
23666   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23667     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23668       APInt ShiftAmt = AmtSplat->getAPIntValue();
23669       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23670
23671       // SSE2/AVX2 logical shifts always return a vector of 0s
23672       // if the shift amount is bigger than or equal to
23673       // the element size. The constant shift amount will be
23674       // encoded as a 8-bit immediate.
23675       if (ShiftAmt.trunc(8).uge(MaxAmount))
23676         return getZeroVector(VT, Subtarget, DAG, DL);
23677     }
23678
23679   return SDValue();
23680 }
23681
23682 /// PerformShiftCombine - Combine shifts.
23683 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23684                                    TargetLowering::DAGCombinerInfo &DCI,
23685                                    const X86Subtarget *Subtarget) {
23686   if (N->getOpcode() == ISD::SHL)
23687     if (SDValue V = PerformSHLCombine(N, DAG))
23688       return V;
23689
23690   // Try to fold this logical shift into a zero vector.
23691   if (N->getOpcode() != ISD::SRA)
23692     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23693       return V;
23694
23695   return SDValue();
23696 }
23697
23698 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23699 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23700 // and friends.  Likewise for OR -> CMPNEQSS.
23701 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23702                             TargetLowering::DAGCombinerInfo &DCI,
23703                             const X86Subtarget *Subtarget) {
23704   unsigned opcode;
23705
23706   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23707   // we're requiring SSE2 for both.
23708   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23709     SDValue N0 = N->getOperand(0);
23710     SDValue N1 = N->getOperand(1);
23711     SDValue CMP0 = N0->getOperand(1);
23712     SDValue CMP1 = N1->getOperand(1);
23713     SDLoc DL(N);
23714
23715     // The SETCCs should both refer to the same CMP.
23716     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23717       return SDValue();
23718
23719     SDValue CMP00 = CMP0->getOperand(0);
23720     SDValue CMP01 = CMP0->getOperand(1);
23721     EVT     VT    = CMP00.getValueType();
23722
23723     if (VT == MVT::f32 || VT == MVT::f64) {
23724       bool ExpectingFlags = false;
23725       // Check for any users that want flags:
23726       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23727            !ExpectingFlags && UI != UE; ++UI)
23728         switch (UI->getOpcode()) {
23729         default:
23730         case ISD::BR_CC:
23731         case ISD::BRCOND:
23732         case ISD::SELECT:
23733           ExpectingFlags = true;
23734           break;
23735         case ISD::CopyToReg:
23736         case ISD::SIGN_EXTEND:
23737         case ISD::ZERO_EXTEND:
23738         case ISD::ANY_EXTEND:
23739           break;
23740         }
23741
23742       if (!ExpectingFlags) {
23743         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23744         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23745
23746         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23747           X86::CondCode tmp = cc0;
23748           cc0 = cc1;
23749           cc1 = tmp;
23750         }
23751
23752         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23753             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23754           // FIXME: need symbolic constants for these magic numbers.
23755           // See X86ATTInstPrinter.cpp:printSSECC().
23756           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23757           if (Subtarget->hasAVX512()) {
23758             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23759                                          CMP01,
23760                                          DAG.getConstant(x86cc, DL, MVT::i8));
23761             if (N->getValueType(0) != MVT::i1)
23762               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23763                                  FSetCC);
23764             return FSetCC;
23765           }
23766           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23767                                               CMP00.getValueType(), CMP00, CMP01,
23768                                               DAG.getConstant(x86cc, DL,
23769                                                               MVT::i8));
23770
23771           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23772           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23773
23774           if (is64BitFP && !Subtarget->is64Bit()) {
23775             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23776             // 64-bit integer, since that's not a legal type. Since
23777             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23778             // bits, but can do this little dance to extract the lowest 32 bits
23779             // and work with those going forward.
23780             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23781                                            OnesOrZeroesF);
23782             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23783             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23784                                         Vector32, DAG.getIntPtrConstant(0, DL));
23785             IntVT = MVT::i32;
23786           }
23787
23788           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23789           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23790                                       DAG.getConstant(1, DL, IntVT));
23791           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23792                                               ANDed);
23793           return OneBitOfTruth;
23794         }
23795       }
23796     }
23797   }
23798   return SDValue();
23799 }
23800
23801 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23802 /// so it can be folded inside ANDNP.
23803 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23804   EVT VT = N->getValueType(0);
23805
23806   // Match direct AllOnes for 128 and 256-bit vectors
23807   if (ISD::isBuildVectorAllOnes(N))
23808     return true;
23809
23810   // Look through a bit convert.
23811   if (N->getOpcode() == ISD::BITCAST)
23812     N = N->getOperand(0).getNode();
23813
23814   // Sometimes the operand may come from a insert_subvector building a 256-bit
23815   // allones vector
23816   if (VT.is256BitVector() &&
23817       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23818     SDValue V1 = N->getOperand(0);
23819     SDValue V2 = N->getOperand(1);
23820
23821     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23822         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23823         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23824         ISD::isBuildVectorAllOnes(V2.getNode()))
23825       return true;
23826   }
23827
23828   return false;
23829 }
23830
23831 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23832 // register. In most cases we actually compare or select YMM-sized registers
23833 // and mixing the two types creates horrible code. This method optimizes
23834 // some of the transition sequences.
23835 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23836                                  TargetLowering::DAGCombinerInfo &DCI,
23837                                  const X86Subtarget *Subtarget) {
23838   EVT VT = N->getValueType(0);
23839   if (!VT.is256BitVector())
23840     return SDValue();
23841
23842   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23843           N->getOpcode() == ISD::ZERO_EXTEND ||
23844           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23845
23846   SDValue Narrow = N->getOperand(0);
23847   EVT NarrowVT = Narrow->getValueType(0);
23848   if (!NarrowVT.is128BitVector())
23849     return SDValue();
23850
23851   if (Narrow->getOpcode() != ISD::XOR &&
23852       Narrow->getOpcode() != ISD::AND &&
23853       Narrow->getOpcode() != ISD::OR)
23854     return SDValue();
23855
23856   SDValue N0  = Narrow->getOperand(0);
23857   SDValue N1  = Narrow->getOperand(1);
23858   SDLoc DL(Narrow);
23859
23860   // The Left side has to be a trunc.
23861   if (N0.getOpcode() != ISD::TRUNCATE)
23862     return SDValue();
23863
23864   // The type of the truncated inputs.
23865   EVT WideVT = N0->getOperand(0)->getValueType(0);
23866   if (WideVT != VT)
23867     return SDValue();
23868
23869   // The right side has to be a 'trunc' or a constant vector.
23870   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23871   ConstantSDNode *RHSConstSplat = nullptr;
23872   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23873     RHSConstSplat = RHSBV->getConstantSplatNode();
23874   if (!RHSTrunc && !RHSConstSplat)
23875     return SDValue();
23876
23877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23878
23879   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23880     return SDValue();
23881
23882   // Set N0 and N1 to hold the inputs to the new wide operation.
23883   N0 = N0->getOperand(0);
23884   if (RHSConstSplat) {
23885     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23886                      SDValue(RHSConstSplat, 0));
23887     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23888     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23889   } else if (RHSTrunc) {
23890     N1 = N1->getOperand(0);
23891   }
23892
23893   // Generate the wide operation.
23894   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23895   unsigned Opcode = N->getOpcode();
23896   switch (Opcode) {
23897   case ISD::ANY_EXTEND:
23898     return Op;
23899   case ISD::ZERO_EXTEND: {
23900     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23901     APInt Mask = APInt::getAllOnesValue(InBits);
23902     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23903     return DAG.getNode(ISD::AND, DL, VT,
23904                        Op, DAG.getConstant(Mask, DL, VT));
23905   }
23906   case ISD::SIGN_EXTEND:
23907     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23908                        Op, DAG.getValueType(NarrowVT));
23909   default:
23910     llvm_unreachable("Unexpected opcode");
23911   }
23912 }
23913
23914 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23915                                  TargetLowering::DAGCombinerInfo &DCI,
23916                                  const X86Subtarget *Subtarget) {
23917   SDValue N0 = N->getOperand(0);
23918   SDValue N1 = N->getOperand(1);
23919   SDLoc DL(N);
23920
23921   // A vector zext_in_reg may be represented as a shuffle,
23922   // feeding into a bitcast (this represents anyext) feeding into
23923   // an and with a mask.
23924   // We'd like to try to combine that into a shuffle with zero
23925   // plus a bitcast, removing the and.
23926   if (N0.getOpcode() != ISD::BITCAST ||
23927       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23928     return SDValue();
23929
23930   // The other side of the AND should be a splat of 2^C, where C
23931   // is the number of bits in the source type.
23932   if (N1.getOpcode() == ISD::BITCAST)
23933     N1 = N1.getOperand(0);
23934   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23935     return SDValue();
23936   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23937
23938   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23939   EVT SrcType = Shuffle->getValueType(0);
23940
23941   // We expect a single-source shuffle
23942   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23943     return SDValue();
23944
23945   unsigned SrcSize = SrcType.getScalarSizeInBits();
23946
23947   APInt SplatValue, SplatUndef;
23948   unsigned SplatBitSize;
23949   bool HasAnyUndefs;
23950   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23951                                 SplatBitSize, HasAnyUndefs))
23952     return SDValue();
23953
23954   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23955   // Make sure the splat matches the mask we expect
23956   if (SplatBitSize > ResSize ||
23957       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23958     return SDValue();
23959
23960   // Make sure the input and output size make sense
23961   if (SrcSize >= ResSize || ResSize % SrcSize)
23962     return SDValue();
23963
23964   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23965   // The number of u's between each two values depends on the ratio between
23966   // the source and dest type.
23967   unsigned ZextRatio = ResSize / SrcSize;
23968   bool IsZext = true;
23969   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23970     if (i % ZextRatio) {
23971       if (Shuffle->getMaskElt(i) > 0) {
23972         // Expected undef
23973         IsZext = false;
23974         break;
23975       }
23976     } else {
23977       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23978         // Expected element number
23979         IsZext = false;
23980         break;
23981       }
23982     }
23983   }
23984
23985   if (!IsZext)
23986     return SDValue();
23987
23988   // Ok, perform the transformation - replace the shuffle with
23989   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23990   // (instead of undef) where the k elements come from the zero vector.
23991   SmallVector<int, 8> Mask;
23992   unsigned NumElems = SrcType.getVectorNumElements();
23993   for (unsigned i = 0; i < NumElems; ++i)
23994     if (i % ZextRatio)
23995       Mask.push_back(NumElems);
23996     else
23997       Mask.push_back(i / ZextRatio);
23998
23999   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24000     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24001   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24002 }
24003
24004 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24005                                  TargetLowering::DAGCombinerInfo &DCI,
24006                                  const X86Subtarget *Subtarget) {
24007   if (DCI.isBeforeLegalizeOps())
24008     return SDValue();
24009
24010   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24011     return Zext;
24012
24013   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24014     return R;
24015
24016   EVT VT = N->getValueType(0);
24017   SDValue N0 = N->getOperand(0);
24018   SDValue N1 = N->getOperand(1);
24019   SDLoc DL(N);
24020
24021   // Create BEXTR instructions
24022   // BEXTR is ((X >> imm) & (2**size-1))
24023   if (VT == MVT::i32 || VT == MVT::i64) {
24024     // Check for BEXTR.
24025     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24026         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24027       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24028       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24029       if (MaskNode && ShiftNode) {
24030         uint64_t Mask = MaskNode->getZExtValue();
24031         uint64_t Shift = ShiftNode->getZExtValue();
24032         if (isMask_64(Mask)) {
24033           uint64_t MaskSize = countPopulation(Mask);
24034           if (Shift + MaskSize <= VT.getSizeInBits())
24035             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24036                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24037                                                VT));
24038         }
24039       }
24040     } // BEXTR
24041
24042     return SDValue();
24043   }
24044
24045   // Want to form ANDNP nodes:
24046   // 1) In the hopes of then easily combining them with OR and AND nodes
24047   //    to form PBLEND/PSIGN.
24048   // 2) To match ANDN packed intrinsics
24049   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24050     return SDValue();
24051
24052   // Check LHS for vnot
24053   if (N0.getOpcode() == ISD::XOR &&
24054       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24055       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24056     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24057
24058   // Check RHS for vnot
24059   if (N1.getOpcode() == ISD::XOR &&
24060       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24061       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24062     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24063
24064   return SDValue();
24065 }
24066
24067 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24068                                 TargetLowering::DAGCombinerInfo &DCI,
24069                                 const X86Subtarget *Subtarget) {
24070   if (DCI.isBeforeLegalizeOps())
24071     return SDValue();
24072
24073   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24074     return R;
24075
24076   SDValue N0 = N->getOperand(0);
24077   SDValue N1 = N->getOperand(1);
24078   EVT VT = N->getValueType(0);
24079
24080   // look for psign/blend
24081   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24082     if (!Subtarget->hasSSSE3() ||
24083         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24084       return SDValue();
24085
24086     // Canonicalize pandn to RHS
24087     if (N0.getOpcode() == X86ISD::ANDNP)
24088       std::swap(N0, N1);
24089     // or (and (m, y), (pandn m, x))
24090     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24091       SDValue Mask = N1.getOperand(0);
24092       SDValue X    = N1.getOperand(1);
24093       SDValue Y;
24094       if (N0.getOperand(0) == Mask)
24095         Y = N0.getOperand(1);
24096       if (N0.getOperand(1) == Mask)
24097         Y = N0.getOperand(0);
24098
24099       // Check to see if the mask appeared in both the AND and ANDNP and
24100       if (!Y.getNode())
24101         return SDValue();
24102
24103       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24104       // Look through mask bitcast.
24105       if (Mask.getOpcode() == ISD::BITCAST)
24106         Mask = Mask.getOperand(0);
24107       if (X.getOpcode() == ISD::BITCAST)
24108         X = X.getOperand(0);
24109       if (Y.getOpcode() == ISD::BITCAST)
24110         Y = Y.getOperand(0);
24111
24112       EVT MaskVT = Mask.getValueType();
24113
24114       // Validate that the Mask operand is a vector sra node.
24115       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24116       // there is no psrai.b
24117       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24118       unsigned SraAmt = ~0;
24119       if (Mask.getOpcode() == ISD::SRA) {
24120         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24121           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24122             SraAmt = AmtConst->getZExtValue();
24123       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24124         SDValue SraC = Mask.getOperand(1);
24125         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24126       }
24127       if ((SraAmt + 1) != EltBits)
24128         return SDValue();
24129
24130       SDLoc DL(N);
24131
24132       // Now we know we at least have a plendvb with the mask val.  See if
24133       // we can form a psignb/w/d.
24134       // psign = x.type == y.type == mask.type && y = sub(0, x);
24135       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24136           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24137           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24138         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24139                "Unsupported VT for PSIGN");
24140         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24141         return DAG.getBitcast(VT, Mask);
24142       }
24143       // PBLENDVB only available on SSE 4.1
24144       if (!Subtarget->hasSSE41())
24145         return SDValue();
24146
24147       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24148
24149       X = DAG.getBitcast(BlendVT, X);
24150       Y = DAG.getBitcast(BlendVT, Y);
24151       Mask = DAG.getBitcast(BlendVT, Mask);
24152       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24153       return DAG.getBitcast(VT, Mask);
24154     }
24155   }
24156
24157   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24158     return SDValue();
24159
24160   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24161   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24162
24163   // SHLD/SHRD instructions have lower register pressure, but on some
24164   // platforms they have higher latency than the equivalent
24165   // series of shifts/or that would otherwise be generated.
24166   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24167   // have higher latencies and we are not optimizing for size.
24168   if (!OptForSize && Subtarget->isSHLDSlow())
24169     return SDValue();
24170
24171   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24172     std::swap(N0, N1);
24173   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24174     return SDValue();
24175   if (!N0.hasOneUse() || !N1.hasOneUse())
24176     return SDValue();
24177
24178   SDValue ShAmt0 = N0.getOperand(1);
24179   if (ShAmt0.getValueType() != MVT::i8)
24180     return SDValue();
24181   SDValue ShAmt1 = N1.getOperand(1);
24182   if (ShAmt1.getValueType() != MVT::i8)
24183     return SDValue();
24184   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24185     ShAmt0 = ShAmt0.getOperand(0);
24186   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24187     ShAmt1 = ShAmt1.getOperand(0);
24188
24189   SDLoc DL(N);
24190   unsigned Opc = X86ISD::SHLD;
24191   SDValue Op0 = N0.getOperand(0);
24192   SDValue Op1 = N1.getOperand(0);
24193   if (ShAmt0.getOpcode() == ISD::SUB) {
24194     Opc = X86ISD::SHRD;
24195     std::swap(Op0, Op1);
24196     std::swap(ShAmt0, ShAmt1);
24197   }
24198
24199   unsigned Bits = VT.getSizeInBits();
24200   if (ShAmt1.getOpcode() == ISD::SUB) {
24201     SDValue Sum = ShAmt1.getOperand(0);
24202     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24203       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24204       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24205         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24206       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24207         return DAG.getNode(Opc, DL, VT,
24208                            Op0, Op1,
24209                            DAG.getNode(ISD::TRUNCATE, DL,
24210                                        MVT::i8, ShAmt0));
24211     }
24212   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24213     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24214     if (ShAmt0C &&
24215         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24216       return DAG.getNode(Opc, DL, VT,
24217                          N0.getOperand(0), N1.getOperand(0),
24218                          DAG.getNode(ISD::TRUNCATE, DL,
24219                                        MVT::i8, ShAmt0));
24220   }
24221
24222   return SDValue();
24223 }
24224
24225 // Generate NEG and CMOV for integer abs.
24226 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24227   EVT VT = N->getValueType(0);
24228
24229   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24230   // 8-bit integer abs to NEG and CMOV.
24231   if (VT.isInteger() && VT.getSizeInBits() == 8)
24232     return SDValue();
24233
24234   SDValue N0 = N->getOperand(0);
24235   SDValue N1 = N->getOperand(1);
24236   SDLoc DL(N);
24237
24238   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24239   // and change it to SUB and CMOV.
24240   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24241       N0.getOpcode() == ISD::ADD &&
24242       N0.getOperand(1) == N1 &&
24243       N1.getOpcode() == ISD::SRA &&
24244       N1.getOperand(0) == N0.getOperand(0))
24245     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24246       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24247         // Generate SUB & CMOV.
24248         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24249                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24250
24251         SDValue Ops[] = { N0.getOperand(0), Neg,
24252                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24253                           SDValue(Neg.getNode(), 1) };
24254         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24255       }
24256   return SDValue();
24257 }
24258
24259 // Try to turn tests against the signbit in the form of:
24260 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24261 // into:
24262 //   SETGT(X, -1)
24263 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24264   // This is only worth doing if the output type is i8.
24265   if (N->getValueType(0) != MVT::i8)
24266     return SDValue();
24267
24268   SDValue N0 = N->getOperand(0);
24269   SDValue N1 = N->getOperand(1);
24270
24271   // We should be performing an xor against a truncated shift.
24272   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24273     return SDValue();
24274
24275   // Make sure we are performing an xor against one.
24276   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24277     return SDValue();
24278
24279   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24280   SDValue Shift = N0.getOperand(0);
24281   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24282     return SDValue();
24283
24284   // Make sure we are truncating from one of i16, i32 or i64.
24285   EVT ShiftTy = Shift.getValueType();
24286   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24287     return SDValue();
24288
24289   // Make sure the shift amount extracts the sign bit.
24290   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24291       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24292     return SDValue();
24293
24294   // Create a greater-than comparison against -1.
24295   // N.B. Using SETGE against 0 works but we want a canonical looking
24296   // comparison, using SETGT matches up with what TranslateX86CC.
24297   SDLoc DL(N);
24298   SDValue ShiftOp = Shift.getOperand(0);
24299   EVT ShiftOpTy = ShiftOp.getValueType();
24300   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24301                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24302   return Cond;
24303 }
24304
24305 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24306                                  TargetLowering::DAGCombinerInfo &DCI,
24307                                  const X86Subtarget *Subtarget) {
24308   if (DCI.isBeforeLegalizeOps())
24309     return SDValue();
24310
24311   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24312     return RV;
24313
24314   if (Subtarget->hasCMov())
24315     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24316       return RV;
24317
24318   return SDValue();
24319 }
24320
24321 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24322 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24323                                   TargetLowering::DAGCombinerInfo &DCI,
24324                                   const X86Subtarget *Subtarget) {
24325   LoadSDNode *Ld = cast<LoadSDNode>(N);
24326   EVT RegVT = Ld->getValueType(0);
24327   EVT MemVT = Ld->getMemoryVT();
24328   SDLoc dl(Ld);
24329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24330
24331   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24332   // into two 16-byte operations.
24333   ISD::LoadExtType Ext = Ld->getExtensionType();
24334   bool Fast;
24335   unsigned AddressSpace = Ld->getAddressSpace();
24336   unsigned Alignment = Ld->getAlignment();
24337   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24338       Ext == ISD::NON_EXTLOAD &&
24339       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24340                              AddressSpace, Alignment, &Fast) && !Fast) {
24341     unsigned NumElems = RegVT.getVectorNumElements();
24342     if (NumElems < 2)
24343       return SDValue();
24344
24345     SDValue Ptr = Ld->getBasePtr();
24346     SDValue Increment =
24347         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24348
24349     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24350                                   NumElems/2);
24351     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24352                                 Ld->getPointerInfo(), Ld->isVolatile(),
24353                                 Ld->isNonTemporal(), Ld->isInvariant(),
24354                                 Alignment);
24355     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24356     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24357                                 Ld->getPointerInfo(), Ld->isVolatile(),
24358                                 Ld->isNonTemporal(), Ld->isInvariant(),
24359                                 std::min(16U, Alignment));
24360     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24361                              Load1.getValue(1),
24362                              Load2.getValue(1));
24363
24364     SDValue NewVec = DAG.getUNDEF(RegVT);
24365     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24366     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24367     return DCI.CombineTo(N, NewVec, TF, true);
24368   }
24369
24370   return SDValue();
24371 }
24372
24373 /// PerformMLOADCombine - Resolve extending loads
24374 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24375                                    TargetLowering::DAGCombinerInfo &DCI,
24376                                    const X86Subtarget *Subtarget) {
24377   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24378   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24379     return SDValue();
24380
24381   EVT VT = Mld->getValueType(0);
24382   unsigned NumElems = VT.getVectorNumElements();
24383   EVT LdVT = Mld->getMemoryVT();
24384   SDLoc dl(Mld);
24385
24386   assert(LdVT != VT && "Cannot extend to the same type");
24387   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24388   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24389   // From, To sizes and ElemCount must be pow of two
24390   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24391     "Unexpected size for extending masked load");
24392
24393   unsigned SizeRatio  = ToSz / FromSz;
24394   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24395
24396   // Create a type on which we perform the shuffle
24397   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24398           LdVT.getScalarType(), NumElems*SizeRatio);
24399   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24400
24401   // Convert Src0 value
24402   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24403   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24404     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24405     for (unsigned i = 0; i != NumElems; ++i)
24406       ShuffleVec[i] = i * SizeRatio;
24407
24408     // Can't shuffle using an illegal type.
24409     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24410             && "WideVecVT should be legal");
24411     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24412                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24413   }
24414   // Prepare the new mask
24415   SDValue NewMask;
24416   SDValue Mask = Mld->getMask();
24417   if (Mask.getValueType() == VT) {
24418     // Mask and original value have the same type
24419     NewMask = DAG.getBitcast(WideVecVT, Mask);
24420     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24421     for (unsigned i = 0; i != NumElems; ++i)
24422       ShuffleVec[i] = i * SizeRatio;
24423     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24424       ShuffleVec[i] = NumElems*SizeRatio;
24425     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24426                                    DAG.getConstant(0, dl, WideVecVT),
24427                                    &ShuffleVec[0]);
24428   }
24429   else {
24430     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24431     unsigned WidenNumElts = NumElems*SizeRatio;
24432     unsigned MaskNumElts = VT.getVectorNumElements();
24433     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24434                                      WidenNumElts);
24435
24436     unsigned NumConcat = WidenNumElts / MaskNumElts;
24437     SmallVector<SDValue, 16> Ops(NumConcat);
24438     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24439     Ops[0] = Mask;
24440     for (unsigned i = 1; i != NumConcat; ++i)
24441       Ops[i] = ZeroVal;
24442
24443     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24444   }
24445
24446   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24447                                      Mld->getBasePtr(), NewMask, WideSrc0,
24448                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24449                                      ISD::NON_EXTLOAD);
24450   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24451   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24452
24453 }
24454 /// PerformMSTORECombine - Resolve truncating stores
24455 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24456                                     const X86Subtarget *Subtarget) {
24457   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24458   if (!Mst->isTruncatingStore())
24459     return SDValue();
24460
24461   EVT VT = Mst->getValue().getValueType();
24462   unsigned NumElems = VT.getVectorNumElements();
24463   EVT StVT = Mst->getMemoryVT();
24464   SDLoc dl(Mst);
24465
24466   assert(StVT != VT && "Cannot truncate to the same type");
24467   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24468   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24469
24470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24471
24472   // The truncating store is legal in some cases. For example
24473   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24474   // are designated for truncate store.
24475   // In this case we don't need any further transformations.
24476   if (TLI.isTruncStoreLegal(VT, StVT))
24477     return SDValue();
24478
24479   // From, To sizes and ElemCount must be pow of two
24480   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24481     "Unexpected size for truncating masked store");
24482   // We are going to use the original vector elt for storing.
24483   // Accumulated smaller vector elements must be a multiple of the store size.
24484   assert (((NumElems * FromSz) % ToSz) == 0 &&
24485           "Unexpected ratio for truncating masked store");
24486
24487   unsigned SizeRatio  = FromSz / ToSz;
24488   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24489
24490   // Create a type on which we perform the shuffle
24491   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24492           StVT.getScalarType(), NumElems*SizeRatio);
24493
24494   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24495
24496   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24497   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24498   for (unsigned i = 0; i != NumElems; ++i)
24499     ShuffleVec[i] = i * SizeRatio;
24500
24501   // Can't shuffle using an illegal type.
24502   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24503           && "WideVecVT should be legal");
24504
24505   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24506                                         DAG.getUNDEF(WideVecVT),
24507                                         &ShuffleVec[0]);
24508
24509   SDValue NewMask;
24510   SDValue Mask = Mst->getMask();
24511   if (Mask.getValueType() == VT) {
24512     // Mask and original value have the same type
24513     NewMask = DAG.getBitcast(WideVecVT, Mask);
24514     for (unsigned i = 0; i != NumElems; ++i)
24515       ShuffleVec[i] = i * SizeRatio;
24516     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24517       ShuffleVec[i] = NumElems*SizeRatio;
24518     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24519                                    DAG.getConstant(0, dl, WideVecVT),
24520                                    &ShuffleVec[0]);
24521   }
24522   else {
24523     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24524     unsigned WidenNumElts = NumElems*SizeRatio;
24525     unsigned MaskNumElts = VT.getVectorNumElements();
24526     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24527                                      WidenNumElts);
24528
24529     unsigned NumConcat = WidenNumElts / MaskNumElts;
24530     SmallVector<SDValue, 16> Ops(NumConcat);
24531     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24532     Ops[0] = Mask;
24533     for (unsigned i = 1; i != NumConcat; ++i)
24534       Ops[i] = ZeroVal;
24535
24536     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24537   }
24538
24539   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24540                             NewMask, StVT, Mst->getMemOperand(), false);
24541 }
24542 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24543 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24544                                    const X86Subtarget *Subtarget) {
24545   StoreSDNode *St = cast<StoreSDNode>(N);
24546   EVT VT = St->getValue().getValueType();
24547   EVT StVT = St->getMemoryVT();
24548   SDLoc dl(St);
24549   SDValue StoredVal = St->getOperand(1);
24550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24551
24552   // If we are saving a concatenation of two XMM registers and 32-byte stores
24553   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24554   bool Fast;
24555   unsigned AddressSpace = St->getAddressSpace();
24556   unsigned Alignment = St->getAlignment();
24557   if (VT.is256BitVector() && StVT == VT &&
24558       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24559                              AddressSpace, Alignment, &Fast) && !Fast) {
24560     unsigned NumElems = VT.getVectorNumElements();
24561     if (NumElems < 2)
24562       return SDValue();
24563
24564     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24565     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24566
24567     SDValue Stride =
24568         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24569     SDValue Ptr0 = St->getBasePtr();
24570     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24571
24572     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24573                                 St->getPointerInfo(), St->isVolatile(),
24574                                 St->isNonTemporal(), Alignment);
24575     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24576                                 St->getPointerInfo(), St->isVolatile(),
24577                                 St->isNonTemporal(),
24578                                 std::min(16U, Alignment));
24579     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24580   }
24581
24582   // Optimize trunc store (of multiple scalars) to shuffle and store.
24583   // First, pack all of the elements in one place. Next, store to memory
24584   // in fewer chunks.
24585   if (St->isTruncatingStore() && VT.isVector()) {
24586     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24587     unsigned NumElems = VT.getVectorNumElements();
24588     assert(StVT != VT && "Cannot truncate to the same type");
24589     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24590     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24591
24592     // The truncating store is legal in some cases. For example
24593     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24594     // are designated for truncate store.
24595     // In this case we don't need any further transformations.
24596     if (TLI.isTruncStoreLegal(VT, StVT))
24597       return SDValue();
24598
24599     // From, To sizes and ElemCount must be pow of two
24600     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24601     // We are going to use the original vector elt for storing.
24602     // Accumulated smaller vector elements must be a multiple of the store size.
24603     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24604
24605     unsigned SizeRatio  = FromSz / ToSz;
24606
24607     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24608
24609     // Create a type on which we perform the shuffle
24610     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24611             StVT.getScalarType(), NumElems*SizeRatio);
24612
24613     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24614
24615     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24616     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24617     for (unsigned i = 0; i != NumElems; ++i)
24618       ShuffleVec[i] = i * SizeRatio;
24619
24620     // Can't shuffle using an illegal type.
24621     if (!TLI.isTypeLegal(WideVecVT))
24622       return SDValue();
24623
24624     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24625                                          DAG.getUNDEF(WideVecVT),
24626                                          &ShuffleVec[0]);
24627     // At this point all of the data is stored at the bottom of the
24628     // register. We now need to save it to mem.
24629
24630     // Find the largest store unit
24631     MVT StoreType = MVT::i8;
24632     for (MVT Tp : MVT::integer_valuetypes()) {
24633       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24634         StoreType = Tp;
24635     }
24636
24637     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24638     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24639         (64 <= NumElems * ToSz))
24640       StoreType = MVT::f64;
24641
24642     // Bitcast the original vector into a vector of store-size units
24643     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24644             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24645     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24646     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24647     SmallVector<SDValue, 8> Chains;
24648     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24649                                         TLI.getPointerTy(DAG.getDataLayout()));
24650     SDValue Ptr = St->getBasePtr();
24651
24652     // Perform one or more big stores into memory.
24653     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24654       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24655                                    StoreType, ShuffWide,
24656                                    DAG.getIntPtrConstant(i, dl));
24657       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24658                                 St->getPointerInfo(), St->isVolatile(),
24659                                 St->isNonTemporal(), St->getAlignment());
24660       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24661       Chains.push_back(Ch);
24662     }
24663
24664     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24665   }
24666
24667   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24668   // the FP state in cases where an emms may be missing.
24669   // A preferable solution to the general problem is to figure out the right
24670   // places to insert EMMS.  This qualifies as a quick hack.
24671
24672   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24673   if (VT.getSizeInBits() != 64)
24674     return SDValue();
24675
24676   const Function *F = DAG.getMachineFunction().getFunction();
24677   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24678   bool F64IsLegal =
24679       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24680   if ((VT.isVector() ||
24681        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24682       isa<LoadSDNode>(St->getValue()) &&
24683       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24684       St->getChain().hasOneUse() && !St->isVolatile()) {
24685     SDNode* LdVal = St->getValue().getNode();
24686     LoadSDNode *Ld = nullptr;
24687     int TokenFactorIndex = -1;
24688     SmallVector<SDValue, 8> Ops;
24689     SDNode* ChainVal = St->getChain().getNode();
24690     // Must be a store of a load.  We currently handle two cases:  the load
24691     // is a direct child, and it's under an intervening TokenFactor.  It is
24692     // possible to dig deeper under nested TokenFactors.
24693     if (ChainVal == LdVal)
24694       Ld = cast<LoadSDNode>(St->getChain());
24695     else if (St->getValue().hasOneUse() &&
24696              ChainVal->getOpcode() == ISD::TokenFactor) {
24697       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24698         if (ChainVal->getOperand(i).getNode() == LdVal) {
24699           TokenFactorIndex = i;
24700           Ld = cast<LoadSDNode>(St->getValue());
24701         } else
24702           Ops.push_back(ChainVal->getOperand(i));
24703       }
24704     }
24705
24706     if (!Ld || !ISD::isNormalLoad(Ld))
24707       return SDValue();
24708
24709     // If this is not the MMX case, i.e. we are just turning i64 load/store
24710     // into f64 load/store, avoid the transformation if there are multiple
24711     // uses of the loaded value.
24712     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24713       return SDValue();
24714
24715     SDLoc LdDL(Ld);
24716     SDLoc StDL(N);
24717     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24718     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24719     // pair instead.
24720     if (Subtarget->is64Bit() || F64IsLegal) {
24721       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24722       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24723                                   Ld->getPointerInfo(), Ld->isVolatile(),
24724                                   Ld->isNonTemporal(), Ld->isInvariant(),
24725                                   Ld->getAlignment());
24726       SDValue NewChain = NewLd.getValue(1);
24727       if (TokenFactorIndex != -1) {
24728         Ops.push_back(NewChain);
24729         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24730       }
24731       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24732                           St->getPointerInfo(),
24733                           St->isVolatile(), St->isNonTemporal(),
24734                           St->getAlignment());
24735     }
24736
24737     // Otherwise, lower to two pairs of 32-bit loads / stores.
24738     SDValue LoAddr = Ld->getBasePtr();
24739     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24740                                  DAG.getConstant(4, LdDL, MVT::i32));
24741
24742     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24743                                Ld->getPointerInfo(),
24744                                Ld->isVolatile(), Ld->isNonTemporal(),
24745                                Ld->isInvariant(), Ld->getAlignment());
24746     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24747                                Ld->getPointerInfo().getWithOffset(4),
24748                                Ld->isVolatile(), Ld->isNonTemporal(),
24749                                Ld->isInvariant(),
24750                                MinAlign(Ld->getAlignment(), 4));
24751
24752     SDValue NewChain = LoLd.getValue(1);
24753     if (TokenFactorIndex != -1) {
24754       Ops.push_back(LoLd);
24755       Ops.push_back(HiLd);
24756       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24757     }
24758
24759     LoAddr = St->getBasePtr();
24760     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24761                          DAG.getConstant(4, StDL, MVT::i32));
24762
24763     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24764                                 St->getPointerInfo(),
24765                                 St->isVolatile(), St->isNonTemporal(),
24766                                 St->getAlignment());
24767     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24768                                 St->getPointerInfo().getWithOffset(4),
24769                                 St->isVolatile(),
24770                                 St->isNonTemporal(),
24771                                 MinAlign(St->getAlignment(), 4));
24772     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24773   }
24774
24775   // This is similar to the above case, but here we handle a scalar 64-bit
24776   // integer store that is extracted from a vector on a 32-bit target.
24777   // If we have SSE2, then we can treat it like a floating-point double
24778   // to get past legalization. The execution dependencies fixup pass will
24779   // choose the optimal machine instruction for the store if this really is
24780   // an integer or v2f32 rather than an f64.
24781   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24782       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24783     SDValue OldExtract = St->getOperand(1);
24784     SDValue ExtOp0 = OldExtract.getOperand(0);
24785     unsigned VecSize = ExtOp0.getValueSizeInBits();
24786     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24787     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24788     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24789                                      BitCast, OldExtract.getOperand(1));
24790     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24791                         St->getPointerInfo(), St->isVolatile(),
24792                         St->isNonTemporal(), St->getAlignment());
24793   }
24794
24795   return SDValue();
24796 }
24797
24798 /// Return 'true' if this vector operation is "horizontal"
24799 /// and return the operands for the horizontal operation in LHS and RHS.  A
24800 /// horizontal operation performs the binary operation on successive elements
24801 /// of its first operand, then on successive elements of its second operand,
24802 /// returning the resulting values in a vector.  For example, if
24803 ///   A = < float a0, float a1, float a2, float a3 >
24804 /// and
24805 ///   B = < float b0, float b1, float b2, float b3 >
24806 /// then the result of doing a horizontal operation on A and B is
24807 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24808 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24809 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24810 /// set to A, RHS to B, and the routine returns 'true'.
24811 /// Note that the binary operation should have the property that if one of the
24812 /// operands is UNDEF then the result is UNDEF.
24813 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24814   // Look for the following pattern: if
24815   //   A = < float a0, float a1, float a2, float a3 >
24816   //   B = < float b0, float b1, float b2, float b3 >
24817   // and
24818   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24819   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24820   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24821   // which is A horizontal-op B.
24822
24823   // At least one of the operands should be a vector shuffle.
24824   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24825       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24826     return false;
24827
24828   MVT VT = LHS.getSimpleValueType();
24829
24830   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24831          "Unsupported vector type for horizontal add/sub");
24832
24833   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24834   // operate independently on 128-bit lanes.
24835   unsigned NumElts = VT.getVectorNumElements();
24836   unsigned NumLanes = VT.getSizeInBits()/128;
24837   unsigned NumLaneElts = NumElts / NumLanes;
24838   assert((NumLaneElts % 2 == 0) &&
24839          "Vector type should have an even number of elements in each lane");
24840   unsigned HalfLaneElts = NumLaneElts/2;
24841
24842   // View LHS in the form
24843   //   LHS = VECTOR_SHUFFLE A, B, LMask
24844   // If LHS is not a shuffle then pretend it is the shuffle
24845   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24846   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24847   // type VT.
24848   SDValue A, B;
24849   SmallVector<int, 16> LMask(NumElts);
24850   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24851     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24852       A = LHS.getOperand(0);
24853     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24854       B = LHS.getOperand(1);
24855     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24856     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24857   } else {
24858     if (LHS.getOpcode() != ISD::UNDEF)
24859       A = LHS;
24860     for (unsigned i = 0; i != NumElts; ++i)
24861       LMask[i] = i;
24862   }
24863
24864   // Likewise, view RHS in the form
24865   //   RHS = VECTOR_SHUFFLE C, D, RMask
24866   SDValue C, D;
24867   SmallVector<int, 16> RMask(NumElts);
24868   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24869     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24870       C = RHS.getOperand(0);
24871     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24872       D = RHS.getOperand(1);
24873     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24874     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24875   } else {
24876     if (RHS.getOpcode() != ISD::UNDEF)
24877       C = RHS;
24878     for (unsigned i = 0; i != NumElts; ++i)
24879       RMask[i] = i;
24880   }
24881
24882   // Check that the shuffles are both shuffling the same vectors.
24883   if (!(A == C && B == D) && !(A == D && B == C))
24884     return false;
24885
24886   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24887   if (!A.getNode() && !B.getNode())
24888     return false;
24889
24890   // If A and B occur in reverse order in RHS, then "swap" them (which means
24891   // rewriting the mask).
24892   if (A != C)
24893     ShuffleVectorSDNode::commuteMask(RMask);
24894
24895   // At this point LHS and RHS are equivalent to
24896   //   LHS = VECTOR_SHUFFLE A, B, LMask
24897   //   RHS = VECTOR_SHUFFLE A, B, RMask
24898   // Check that the masks correspond to performing a horizontal operation.
24899   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24900     for (unsigned i = 0; i != NumLaneElts; ++i) {
24901       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24902
24903       // Ignore any UNDEF components.
24904       if (LIdx < 0 || RIdx < 0 ||
24905           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24906           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24907         continue;
24908
24909       // Check that successive elements are being operated on.  If not, this is
24910       // not a horizontal operation.
24911       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24912       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24913       if (!(LIdx == Index && RIdx == Index + 1) &&
24914           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24915         return false;
24916     }
24917   }
24918
24919   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24920   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24921   return true;
24922 }
24923
24924 /// Do target-specific dag combines on floating point adds.
24925 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24926                                   const X86Subtarget *Subtarget) {
24927   EVT VT = N->getValueType(0);
24928   SDValue LHS = N->getOperand(0);
24929   SDValue RHS = N->getOperand(1);
24930
24931   // Try to synthesize horizontal adds from adds of shuffles.
24932   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24933        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24934       isHorizontalBinOp(LHS, RHS, true))
24935     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24936   return SDValue();
24937 }
24938
24939 /// Do target-specific dag combines on floating point subs.
24940 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24941                                   const X86Subtarget *Subtarget) {
24942   EVT VT = N->getValueType(0);
24943   SDValue LHS = N->getOperand(0);
24944   SDValue RHS = N->getOperand(1);
24945
24946   // Try to synthesize horizontal subs from subs of shuffles.
24947   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24948        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24949       isHorizontalBinOp(LHS, RHS, false))
24950     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24951   return SDValue();
24952 }
24953
24954 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24955 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24956   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24957
24958   // F[X]OR(0.0, x) -> x
24959   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24960     if (C->getValueAPF().isPosZero())
24961       return N->getOperand(1);
24962
24963   // F[X]OR(x, 0.0) -> x
24964   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24965     if (C->getValueAPF().isPosZero())
24966       return N->getOperand(0);
24967   return SDValue();
24968 }
24969
24970 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24971 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24972   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24973
24974   // Only perform optimizations if UnsafeMath is used.
24975   if (!DAG.getTarget().Options.UnsafeFPMath)
24976     return SDValue();
24977
24978   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24979   // into FMINC and FMAXC, which are Commutative operations.
24980   unsigned NewOp = 0;
24981   switch (N->getOpcode()) {
24982     default: llvm_unreachable("unknown opcode");
24983     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24984     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24985   }
24986
24987   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24988                      N->getOperand(0), N->getOperand(1));
24989 }
24990
24991 /// Do target-specific dag combines on X86ISD::FAND nodes.
24992 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24993   // FAND(0.0, x) -> 0.0
24994   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24995     if (C->getValueAPF().isPosZero())
24996       return N->getOperand(0);
24997
24998   // FAND(x, 0.0) -> 0.0
24999   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25000     if (C->getValueAPF().isPosZero())
25001       return N->getOperand(1);
25002
25003   return SDValue();
25004 }
25005
25006 /// Do target-specific dag combines on X86ISD::FANDN nodes
25007 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25008   // FANDN(0.0, x) -> x
25009   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25010     if (C->getValueAPF().isPosZero())
25011       return N->getOperand(1);
25012
25013   // FANDN(x, 0.0) -> 0.0
25014   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25015     if (C->getValueAPF().isPosZero())
25016       return N->getOperand(1);
25017
25018   return SDValue();
25019 }
25020
25021 static SDValue PerformBTCombine(SDNode *N,
25022                                 SelectionDAG &DAG,
25023                                 TargetLowering::DAGCombinerInfo &DCI) {
25024   // BT ignores high bits in the bit index operand.
25025   SDValue Op1 = N->getOperand(1);
25026   if (Op1.hasOneUse()) {
25027     unsigned BitWidth = Op1.getValueSizeInBits();
25028     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25029     APInt KnownZero, KnownOne;
25030     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25031                                           !DCI.isBeforeLegalizeOps());
25032     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25033     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25034         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25035       DCI.CommitTargetLoweringOpt(TLO);
25036   }
25037   return SDValue();
25038 }
25039
25040 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25041   SDValue Op = N->getOperand(0);
25042   if (Op.getOpcode() == ISD::BITCAST)
25043     Op = Op.getOperand(0);
25044   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25045   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25046       VT.getVectorElementType().getSizeInBits() ==
25047       OpVT.getVectorElementType().getSizeInBits()) {
25048     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25049   }
25050   return SDValue();
25051 }
25052
25053 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25054                                                const X86Subtarget *Subtarget) {
25055   EVT VT = N->getValueType(0);
25056   if (!VT.isVector())
25057     return SDValue();
25058
25059   SDValue N0 = N->getOperand(0);
25060   SDValue N1 = N->getOperand(1);
25061   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25062   SDLoc dl(N);
25063
25064   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25065   // both SSE and AVX2 since there is no sign-extended shift right
25066   // operation on a vector with 64-bit elements.
25067   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25068   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25069   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25070       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25071     SDValue N00 = N0.getOperand(0);
25072
25073     // EXTLOAD has a better solution on AVX2,
25074     // it may be replaced with X86ISD::VSEXT node.
25075     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25076       if (!ISD::isNormalLoad(N00.getNode()))
25077         return SDValue();
25078
25079     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25080         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25081                                   N00, N1);
25082       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25083     }
25084   }
25085   return SDValue();
25086 }
25087
25088 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25089                                   TargetLowering::DAGCombinerInfo &DCI,
25090                                   const X86Subtarget *Subtarget) {
25091   SDValue N0 = N->getOperand(0);
25092   EVT VT = N->getValueType(0);
25093   EVT SVT = VT.getScalarType();
25094   EVT InVT = N0.getValueType();
25095   EVT InSVT = InVT.getScalarType();
25096   SDLoc DL(N);
25097
25098   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25099   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25100   // This exposes the sext to the sdivrem lowering, so that it directly extends
25101   // from AH (which we otherwise need to do contortions to access).
25102   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25103       InVT == MVT::i8 && VT == MVT::i32) {
25104     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25105     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25106                             N0.getOperand(0), N0.getOperand(1));
25107     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25108     return R.getValue(1);
25109   }
25110
25111   if (!DCI.isBeforeLegalizeOps()) {
25112     if (InVT == MVT::i1) {
25113       SDValue Zero = DAG.getConstant(0, DL, VT);
25114       SDValue AllOnes =
25115         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25116       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25117     }
25118     return SDValue();
25119   }
25120
25121   if (VT.isVector() && Subtarget->hasSSE2()) {
25122     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25123       EVT InVT = N.getValueType();
25124       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25125                                    Size / InVT.getScalarSizeInBits());
25126       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25127                                     DAG.getUNDEF(InVT));
25128       Opnds[0] = N;
25129       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25130     };
25131
25132     // If target-size is less than 128-bits, extend to a type that would extend
25133     // to 128 bits, extend that and extract the original target vector.
25134     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25135         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25136         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25137       unsigned Scale = 128 / VT.getSizeInBits();
25138       EVT ExVT =
25139           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25140       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25141       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25142       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25143                          DAG.getIntPtrConstant(0, DL));
25144     }
25145
25146     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25147     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25148     if (VT.getSizeInBits() == 128 &&
25149         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25150         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25151       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25152       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25153     }
25154
25155     // On pre-AVX2 targets, split into 128-bit nodes of
25156     // ISD::SIGN_EXTEND_VECTOR_INREG.
25157     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25158         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25159         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25160       unsigned NumVecs = VT.getSizeInBits() / 128;
25161       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25162       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25163       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25164
25165       SmallVector<SDValue, 8> Opnds;
25166       for (unsigned i = 0, Offset = 0; i != NumVecs;
25167            ++i, Offset += NumSubElts) {
25168         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25169                                      DAG.getIntPtrConstant(Offset, DL));
25170         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25171         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25172         Opnds.push_back(SrcVec);
25173       }
25174       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25175     }
25176   }
25177
25178   if (!Subtarget->hasFp256())
25179     return SDValue();
25180
25181   if (VT.isVector() && VT.getSizeInBits() == 256)
25182     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25183       return R;
25184
25185   return SDValue();
25186 }
25187
25188 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25189                                  const X86Subtarget* Subtarget) {
25190   SDLoc dl(N);
25191   EVT VT = N->getValueType(0);
25192
25193   // Let legalize expand this if it isn't a legal type yet.
25194   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25195     return SDValue();
25196
25197   EVT ScalarVT = VT.getScalarType();
25198   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25199       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25200        !Subtarget->hasAVX512()))
25201     return SDValue();
25202
25203   SDValue A = N->getOperand(0);
25204   SDValue B = N->getOperand(1);
25205   SDValue C = N->getOperand(2);
25206
25207   bool NegA = (A.getOpcode() == ISD::FNEG);
25208   bool NegB = (B.getOpcode() == ISD::FNEG);
25209   bool NegC = (C.getOpcode() == ISD::FNEG);
25210
25211   // Negative multiplication when NegA xor NegB
25212   bool NegMul = (NegA != NegB);
25213   if (NegA)
25214     A = A.getOperand(0);
25215   if (NegB)
25216     B = B.getOperand(0);
25217   if (NegC)
25218     C = C.getOperand(0);
25219
25220   unsigned Opcode;
25221   if (!NegMul)
25222     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25223   else
25224     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25225
25226   return DAG.getNode(Opcode, dl, VT, A, B, C);
25227 }
25228
25229 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25230                                   TargetLowering::DAGCombinerInfo &DCI,
25231                                   const X86Subtarget *Subtarget) {
25232   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25233   //           (and (i32 x86isd::setcc_carry), 1)
25234   // This eliminates the zext. This transformation is necessary because
25235   // ISD::SETCC is always legalized to i8.
25236   SDLoc dl(N);
25237   SDValue N0 = N->getOperand(0);
25238   EVT VT = N->getValueType(0);
25239
25240   if (N0.getOpcode() == ISD::AND &&
25241       N0.hasOneUse() &&
25242       N0.getOperand(0).hasOneUse()) {
25243     SDValue N00 = N0.getOperand(0);
25244     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25245       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25246       if (!C || C->getZExtValue() != 1)
25247         return SDValue();
25248       return DAG.getNode(ISD::AND, dl, VT,
25249                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25250                                      N00.getOperand(0), N00.getOperand(1)),
25251                          DAG.getConstant(1, dl, VT));
25252     }
25253   }
25254
25255   if (N0.getOpcode() == ISD::TRUNCATE &&
25256       N0.hasOneUse() &&
25257       N0.getOperand(0).hasOneUse()) {
25258     SDValue N00 = N0.getOperand(0);
25259     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25260       return DAG.getNode(ISD::AND, dl, VT,
25261                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25262                                      N00.getOperand(0), N00.getOperand(1)),
25263                          DAG.getConstant(1, dl, VT));
25264     }
25265   }
25266
25267   if (VT.is256BitVector())
25268     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25269       return R;
25270
25271   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25272   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25273   // This exposes the zext to the udivrem lowering, so that it directly extends
25274   // from AH (which we otherwise need to do contortions to access).
25275   if (N0.getOpcode() == ISD::UDIVREM &&
25276       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25277       (VT == MVT::i32 || VT == MVT::i64)) {
25278     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25279     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25280                             N0.getOperand(0), N0.getOperand(1));
25281     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25282     return R.getValue(1);
25283   }
25284
25285   return SDValue();
25286 }
25287
25288 // Optimize x == -y --> x+y == 0
25289 //          x != -y --> x+y != 0
25290 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25291                                       const X86Subtarget* Subtarget) {
25292   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25293   SDValue LHS = N->getOperand(0);
25294   SDValue RHS = N->getOperand(1);
25295   EVT VT = N->getValueType(0);
25296   SDLoc DL(N);
25297
25298   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25299     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25300       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25301         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25302                                    LHS.getOperand(1));
25303         return DAG.getSetCC(DL, N->getValueType(0), addV,
25304                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25305       }
25306   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25307     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25308       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25309         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25310                                    RHS.getOperand(1));
25311         return DAG.getSetCC(DL, N->getValueType(0), addV,
25312                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25313       }
25314
25315   if (VT.getScalarType() == MVT::i1 &&
25316       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25317     bool IsSEXT0 =
25318         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25319         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25320     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25321
25322     if (!IsSEXT0 || !IsVZero1) {
25323       // Swap the operands and update the condition code.
25324       std::swap(LHS, RHS);
25325       CC = ISD::getSetCCSwappedOperands(CC);
25326
25327       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25328                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25329       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25330     }
25331
25332     if (IsSEXT0 && IsVZero1) {
25333       assert(VT == LHS.getOperand(0).getValueType() &&
25334              "Uexpected operand type");
25335       if (CC == ISD::SETGT)
25336         return DAG.getConstant(0, DL, VT);
25337       if (CC == ISD::SETLE)
25338         return DAG.getConstant(1, DL, VT);
25339       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25340         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25341
25342       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25343              "Unexpected condition code!");
25344       return LHS.getOperand(0);
25345     }
25346   }
25347
25348   return SDValue();
25349 }
25350
25351 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25352                                          SelectionDAG &DAG) {
25353   SDLoc dl(Load);
25354   MVT VT = Load->getSimpleValueType(0);
25355   MVT EVT = VT.getVectorElementType();
25356   SDValue Addr = Load->getOperand(1);
25357   SDValue NewAddr = DAG.getNode(
25358       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25359       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25360                       Addr.getSimpleValueType()));
25361
25362   SDValue NewLoad =
25363       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25364                   DAG.getMachineFunction().getMachineMemOperand(
25365                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25366   return NewLoad;
25367 }
25368
25369 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25370                                       const X86Subtarget *Subtarget) {
25371   SDLoc dl(N);
25372   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25373   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25374          "X86insertps is only defined for v4x32");
25375
25376   SDValue Ld = N->getOperand(1);
25377   if (MayFoldLoad(Ld)) {
25378     // Extract the countS bits from the immediate so we can get the proper
25379     // address when narrowing the vector load to a specific element.
25380     // When the second source op is a memory address, insertps doesn't use
25381     // countS and just gets an f32 from that address.
25382     unsigned DestIndex =
25383         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25384
25385     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25386
25387     // Create this as a scalar to vector to match the instruction pattern.
25388     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25389     // countS bits are ignored when loading from memory on insertps, which
25390     // means we don't need to explicitly set them to 0.
25391     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25392                        LoadScalarToVector, N->getOperand(2));
25393   }
25394   return SDValue();
25395 }
25396
25397 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25398   SDValue V0 = N->getOperand(0);
25399   SDValue V1 = N->getOperand(1);
25400   SDLoc DL(N);
25401   EVT VT = N->getValueType(0);
25402
25403   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25404   // operands and changing the mask to 1. This saves us a bunch of
25405   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25406   // x86InstrInfo knows how to commute this back after instruction selection
25407   // if it would help register allocation.
25408
25409   // TODO: If optimizing for size or a processor that doesn't suffer from
25410   // partial register update stalls, this should be transformed into a MOVSD
25411   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25412
25413   if (VT == MVT::v2f64)
25414     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25415       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25416         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25417         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25418       }
25419
25420   return SDValue();
25421 }
25422
25423 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25424 // as "sbb reg,reg", since it can be extended without zext and produces
25425 // an all-ones bit which is more useful than 0/1 in some cases.
25426 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25427                                MVT VT) {
25428   if (VT == MVT::i8)
25429     return DAG.getNode(ISD::AND, DL, VT,
25430                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25431                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25432                                    EFLAGS),
25433                        DAG.getConstant(1, DL, VT));
25434   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25435   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25436                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25437                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25438                                  EFLAGS));
25439 }
25440
25441 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25442 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25443                                    TargetLowering::DAGCombinerInfo &DCI,
25444                                    const X86Subtarget *Subtarget) {
25445   SDLoc DL(N);
25446   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25447   SDValue EFLAGS = N->getOperand(1);
25448
25449   if (CC == X86::COND_A) {
25450     // Try to convert COND_A into COND_B in an attempt to facilitate
25451     // materializing "setb reg".
25452     //
25453     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25454     // cannot take an immediate as its first operand.
25455     //
25456     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25457         EFLAGS.getValueType().isInteger() &&
25458         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25459       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25460                                    EFLAGS.getNode()->getVTList(),
25461                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25462       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25463       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25464     }
25465   }
25466
25467   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25468   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25469   // cases.
25470   if (CC == X86::COND_B)
25471     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25472
25473   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25474     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25475     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25476   }
25477
25478   return SDValue();
25479 }
25480
25481 // Optimize branch condition evaluation.
25482 //
25483 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25484                                     TargetLowering::DAGCombinerInfo &DCI,
25485                                     const X86Subtarget *Subtarget) {
25486   SDLoc DL(N);
25487   SDValue Chain = N->getOperand(0);
25488   SDValue Dest = N->getOperand(1);
25489   SDValue EFLAGS = N->getOperand(3);
25490   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25491
25492   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25493     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25494     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25495                        Flags);
25496   }
25497
25498   return SDValue();
25499 }
25500
25501 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25502                                                          SelectionDAG &DAG) {
25503   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25504   // optimize away operation when it's from a constant.
25505   //
25506   // The general transformation is:
25507   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25508   //       AND(VECTOR_CMP(x,y), constant2)
25509   //    constant2 = UNARYOP(constant)
25510
25511   // Early exit if this isn't a vector operation, the operand of the
25512   // unary operation isn't a bitwise AND, or if the sizes of the operations
25513   // aren't the same.
25514   EVT VT = N->getValueType(0);
25515   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25516       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25517       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25518     return SDValue();
25519
25520   // Now check that the other operand of the AND is a constant. We could
25521   // make the transformation for non-constant splats as well, but it's unclear
25522   // that would be a benefit as it would not eliminate any operations, just
25523   // perform one more step in scalar code before moving to the vector unit.
25524   if (BuildVectorSDNode *BV =
25525           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25526     // Bail out if the vector isn't a constant.
25527     if (!BV->isConstant())
25528       return SDValue();
25529
25530     // Everything checks out. Build up the new and improved node.
25531     SDLoc DL(N);
25532     EVT IntVT = BV->getValueType(0);
25533     // Create a new constant of the appropriate type for the transformed
25534     // DAG.
25535     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25536     // The AND node needs bitcasts to/from an integer vector type around it.
25537     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25538     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25539                                  N->getOperand(0)->getOperand(0), MaskConst);
25540     SDValue Res = DAG.getBitcast(VT, NewAnd);
25541     return Res;
25542   }
25543
25544   return SDValue();
25545 }
25546
25547 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25548                                         const X86Subtarget *Subtarget) {
25549   SDValue Op0 = N->getOperand(0);
25550   EVT VT = N->getValueType(0);
25551   EVT InVT = Op0.getValueType();
25552   EVT InSVT = InVT.getScalarType();
25553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25554
25555   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25556   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25557   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25558     SDLoc dl(N);
25559     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25560                                  InVT.getVectorNumElements());
25561     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25562
25563     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25564       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25565
25566     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25567   }
25568
25569   return SDValue();
25570 }
25571
25572 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25573                                         const X86Subtarget *Subtarget) {
25574   // First try to optimize away the conversion entirely when it's
25575   // conditionally from a constant. Vectors only.
25576   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25577     return Res;
25578
25579   // Now move on to more general possibilities.
25580   SDValue Op0 = N->getOperand(0);
25581   EVT VT = N->getValueType(0);
25582   EVT InVT = Op0.getValueType();
25583   EVT InSVT = InVT.getScalarType();
25584
25585   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25586   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25587   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25588     SDLoc dl(N);
25589     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25590                                  InVT.getVectorNumElements());
25591     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25592     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25593   }
25594
25595   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25596   // a 32-bit target where SSE doesn't support i64->FP operations.
25597   if (Op0.getOpcode() == ISD::LOAD) {
25598     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25599     EVT LdVT = Ld->getValueType(0);
25600
25601     // This transformation is not supported if the result type is f16
25602     if (VT == MVT::f16)
25603       return SDValue();
25604
25605     if (!Ld->isVolatile() && !VT.isVector() &&
25606         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25607         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25608       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25609           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25610       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25611       return FILDChain;
25612     }
25613   }
25614   return SDValue();
25615 }
25616
25617 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25618 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25619                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25620   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25621   // the result is either zero or one (depending on the input carry bit).
25622   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25623   if (X86::isZeroNode(N->getOperand(0)) &&
25624       X86::isZeroNode(N->getOperand(1)) &&
25625       // We don't have a good way to replace an EFLAGS use, so only do this when
25626       // dead right now.
25627       SDValue(N, 1).use_empty()) {
25628     SDLoc DL(N);
25629     EVT VT = N->getValueType(0);
25630     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25631     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25632                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25633                                            DAG.getConstant(X86::COND_B, DL,
25634                                                            MVT::i8),
25635                                            N->getOperand(2)),
25636                                DAG.getConstant(1, DL, VT));
25637     return DCI.CombineTo(N, Res1, CarryOut);
25638   }
25639
25640   return SDValue();
25641 }
25642
25643 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25644 //      (add Y, (setne X, 0)) -> sbb -1, Y
25645 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25646 //      (sub (setne X, 0), Y) -> adc -1, Y
25647 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25648   SDLoc DL(N);
25649
25650   // Look through ZExts.
25651   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25652   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25653     return SDValue();
25654
25655   SDValue SetCC = Ext.getOperand(0);
25656   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25657     return SDValue();
25658
25659   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25660   if (CC != X86::COND_E && CC != X86::COND_NE)
25661     return SDValue();
25662
25663   SDValue Cmp = SetCC.getOperand(1);
25664   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25665       !X86::isZeroNode(Cmp.getOperand(1)) ||
25666       !Cmp.getOperand(0).getValueType().isInteger())
25667     return SDValue();
25668
25669   SDValue CmpOp0 = Cmp.getOperand(0);
25670   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25671                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25672
25673   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25674   if (CC == X86::COND_NE)
25675     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25676                        DL, OtherVal.getValueType(), OtherVal,
25677                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25678                        NewCmp);
25679   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25680                      DL, OtherVal.getValueType(), OtherVal,
25681                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25682 }
25683
25684 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25685 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25686                                  const X86Subtarget *Subtarget) {
25687   EVT VT = N->getValueType(0);
25688   SDValue Op0 = N->getOperand(0);
25689   SDValue Op1 = N->getOperand(1);
25690
25691   // Try to synthesize horizontal adds from adds of shuffles.
25692   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25693        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25694       isHorizontalBinOp(Op0, Op1, true))
25695     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25696
25697   return OptimizeConditionalInDecrement(N, DAG);
25698 }
25699
25700 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25701                                  const X86Subtarget *Subtarget) {
25702   SDValue Op0 = N->getOperand(0);
25703   SDValue Op1 = N->getOperand(1);
25704
25705   // X86 can't encode an immediate LHS of a sub. See if we can push the
25706   // negation into a preceding instruction.
25707   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25708     // If the RHS of the sub is a XOR with one use and a constant, invert the
25709     // immediate. Then add one to the LHS of the sub so we can turn
25710     // X-Y -> X+~Y+1, saving one register.
25711     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25712         isa<ConstantSDNode>(Op1.getOperand(1))) {
25713       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25714       EVT VT = Op0.getValueType();
25715       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25716                                    Op1.getOperand(0),
25717                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25718       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25719                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25720     }
25721   }
25722
25723   // Try to synthesize horizontal adds from adds of shuffles.
25724   EVT VT = N->getValueType(0);
25725   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25726        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25727       isHorizontalBinOp(Op0, Op1, true))
25728     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25729
25730   return OptimizeConditionalInDecrement(N, DAG);
25731 }
25732
25733 /// performVZEXTCombine - Performs build vector combines
25734 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25735                                    TargetLowering::DAGCombinerInfo &DCI,
25736                                    const X86Subtarget *Subtarget) {
25737   SDLoc DL(N);
25738   MVT VT = N->getSimpleValueType(0);
25739   SDValue Op = N->getOperand(0);
25740   MVT OpVT = Op.getSimpleValueType();
25741   MVT OpEltVT = OpVT.getVectorElementType();
25742   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25743
25744   // (vzext (bitcast (vzext (x)) -> (vzext x)
25745   SDValue V = Op;
25746   while (V.getOpcode() == ISD::BITCAST)
25747     V = V.getOperand(0);
25748
25749   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25750     MVT InnerVT = V.getSimpleValueType();
25751     MVT InnerEltVT = InnerVT.getVectorElementType();
25752
25753     // If the element sizes match exactly, we can just do one larger vzext. This
25754     // is always an exact type match as vzext operates on integer types.
25755     if (OpEltVT == InnerEltVT) {
25756       assert(OpVT == InnerVT && "Types must match for vzext!");
25757       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25758     }
25759
25760     // The only other way we can combine them is if only a single element of the
25761     // inner vzext is used in the input to the outer vzext.
25762     if (InnerEltVT.getSizeInBits() < InputBits)
25763       return SDValue();
25764
25765     // In this case, the inner vzext is completely dead because we're going to
25766     // only look at bits inside of the low element. Just do the outer vzext on
25767     // a bitcast of the input to the inner.
25768     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25769   }
25770
25771   // Check if we can bypass extracting and re-inserting an element of an input
25772   // vector. Essentially:
25773   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25774   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25775       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25776       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25777     SDValue ExtractedV = V.getOperand(0);
25778     SDValue OrigV = ExtractedV.getOperand(0);
25779     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25780       if (ExtractIdx->getZExtValue() == 0) {
25781         MVT OrigVT = OrigV.getSimpleValueType();
25782         // Extract a subvector if necessary...
25783         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25784           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25785           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25786                                     OrigVT.getVectorNumElements() / Ratio);
25787           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25788                               DAG.getIntPtrConstant(0, DL));
25789         }
25790         Op = DAG.getBitcast(OpVT, OrigV);
25791         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25792       }
25793   }
25794
25795   return SDValue();
25796 }
25797
25798 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25799                                              DAGCombinerInfo &DCI) const {
25800   SelectionDAG &DAG = DCI.DAG;
25801   switch (N->getOpcode()) {
25802   default: break;
25803   case ISD::EXTRACT_VECTOR_ELT:
25804     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25805   case ISD::VSELECT:
25806   case ISD::SELECT:
25807   case X86ISD::SHRUNKBLEND:
25808     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25809   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25810   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25811   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25812   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25813   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25814   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25815   case ISD::SHL:
25816   case ISD::SRA:
25817   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25818   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25819   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25820   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25821   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25822   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25823   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25824   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25825   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25826   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25827   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25828   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25829   case X86ISD::FXOR:
25830   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25831   case X86ISD::FMIN:
25832   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25833   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25834   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25835   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25836   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25837   case ISD::ANY_EXTEND:
25838   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25839   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25840   case ISD::SIGN_EXTEND_INREG:
25841     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25842   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25843   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25844   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25845   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25846   case X86ISD::SHUFP:       // Handle all target specific shuffles
25847   case X86ISD::PALIGNR:
25848   case X86ISD::UNPCKH:
25849   case X86ISD::UNPCKL:
25850   case X86ISD::MOVHLPS:
25851   case X86ISD::MOVLHPS:
25852   case X86ISD::PSHUFB:
25853   case X86ISD::PSHUFD:
25854   case X86ISD::PSHUFHW:
25855   case X86ISD::PSHUFLW:
25856   case X86ISD::MOVSS:
25857   case X86ISD::MOVSD:
25858   case X86ISD::VPERMILPI:
25859   case X86ISD::VPERM2X128:
25860   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25861   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25862   case X86ISD::INSERTPS: {
25863     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25864       return PerformINSERTPSCombine(N, DAG, Subtarget);
25865     break;
25866   }
25867   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25868   }
25869
25870   return SDValue();
25871 }
25872
25873 /// isTypeDesirableForOp - Return true if the target has native support for
25874 /// the specified value type and it is 'desirable' to use the type for the
25875 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25876 /// instruction encodings are longer and some i16 instructions are slow.
25877 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25878   if (!isTypeLegal(VT))
25879     return false;
25880   if (VT != MVT::i16)
25881     return true;
25882
25883   switch (Opc) {
25884   default:
25885     return true;
25886   case ISD::LOAD:
25887   case ISD::SIGN_EXTEND:
25888   case ISD::ZERO_EXTEND:
25889   case ISD::ANY_EXTEND:
25890   case ISD::SHL:
25891   case ISD::SRL:
25892   case ISD::SUB:
25893   case ISD::ADD:
25894   case ISD::MUL:
25895   case ISD::AND:
25896   case ISD::OR:
25897   case ISD::XOR:
25898     return false;
25899   }
25900 }
25901
25902 /// IsDesirableToPromoteOp - This method query the target whether it is
25903 /// beneficial for dag combiner to promote the specified node. If true, it
25904 /// should return the desired promotion type by reference.
25905 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25906   EVT VT = Op.getValueType();
25907   if (VT != MVT::i16)
25908     return false;
25909
25910   bool Promote = false;
25911   bool Commute = false;
25912   switch (Op.getOpcode()) {
25913   default: break;
25914   case ISD::LOAD: {
25915     LoadSDNode *LD = cast<LoadSDNode>(Op);
25916     // If the non-extending load has a single use and it's not live out, then it
25917     // might be folded.
25918     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25919                                                      Op.hasOneUse()*/) {
25920       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25921              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25922         // The only case where we'd want to promote LOAD (rather then it being
25923         // promoted as an operand is when it's only use is liveout.
25924         if (UI->getOpcode() != ISD::CopyToReg)
25925           return false;
25926       }
25927     }
25928     Promote = true;
25929     break;
25930   }
25931   case ISD::SIGN_EXTEND:
25932   case ISD::ZERO_EXTEND:
25933   case ISD::ANY_EXTEND:
25934     Promote = true;
25935     break;
25936   case ISD::SHL:
25937   case ISD::SRL: {
25938     SDValue N0 = Op.getOperand(0);
25939     // Look out for (store (shl (load), x)).
25940     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25941       return false;
25942     Promote = true;
25943     break;
25944   }
25945   case ISD::ADD:
25946   case ISD::MUL:
25947   case ISD::AND:
25948   case ISD::OR:
25949   case ISD::XOR:
25950     Commute = true;
25951     // fallthrough
25952   case ISD::SUB: {
25953     SDValue N0 = Op.getOperand(0);
25954     SDValue N1 = Op.getOperand(1);
25955     if (!Commute && MayFoldLoad(N1))
25956       return false;
25957     // Avoid disabling potential load folding opportunities.
25958     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25959       return false;
25960     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25961       return false;
25962     Promote = true;
25963   }
25964   }
25965
25966   PVT = MVT::i32;
25967   return Promote;
25968 }
25969
25970 //===----------------------------------------------------------------------===//
25971 //                           X86 Inline Assembly Support
25972 //===----------------------------------------------------------------------===//
25973
25974 // Helper to match a string separated by whitespace.
25975 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25976   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25977
25978   for (StringRef Piece : Pieces) {
25979     if (!S.startswith(Piece)) // Check if the piece matches.
25980       return false;
25981
25982     S = S.substr(Piece.size());
25983     StringRef::size_type Pos = S.find_first_not_of(" \t");
25984     if (Pos == 0) // We matched a prefix.
25985       return false;
25986
25987     S = S.substr(Pos);
25988   }
25989
25990   return S.empty();
25991 }
25992
25993 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25994
25995   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25996     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25997         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25998         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25999
26000       if (AsmPieces.size() == 3)
26001         return true;
26002       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26003         return true;
26004     }
26005   }
26006   return false;
26007 }
26008
26009 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26010   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26011
26012   std::string AsmStr = IA->getAsmString();
26013
26014   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26015   if (!Ty || Ty->getBitWidth() % 16 != 0)
26016     return false;
26017
26018   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26019   SmallVector<StringRef, 4> AsmPieces;
26020   SplitString(AsmStr, AsmPieces, ";\n");
26021
26022   switch (AsmPieces.size()) {
26023   default: return false;
26024   case 1:
26025     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26026     // we will turn this bswap into something that will be lowered to logical
26027     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26028     // lower so don't worry about this.
26029     // bswap $0
26030     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26031         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26032         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26033         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26034         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26035         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26036       // No need to check constraints, nothing other than the equivalent of
26037       // "=r,0" would be valid here.
26038       return IntrinsicLowering::LowerToByteSwap(CI);
26039     }
26040
26041     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26042     if (CI->getType()->isIntegerTy(16) &&
26043         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26044         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26045          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26046       AsmPieces.clear();
26047       StringRef ConstraintsStr = IA->getConstraintString();
26048       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26049       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26050       if (clobbersFlagRegisters(AsmPieces))
26051         return IntrinsicLowering::LowerToByteSwap(CI);
26052     }
26053     break;
26054   case 3:
26055     if (CI->getType()->isIntegerTy(32) &&
26056         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26057         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26058         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26059         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26060       AsmPieces.clear();
26061       StringRef ConstraintsStr = IA->getConstraintString();
26062       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26063       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26064       if (clobbersFlagRegisters(AsmPieces))
26065         return IntrinsicLowering::LowerToByteSwap(CI);
26066     }
26067
26068     if (CI->getType()->isIntegerTy(64)) {
26069       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26070       if (Constraints.size() >= 2 &&
26071           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26072           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26073         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26074         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26075             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26076             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26077           return IntrinsicLowering::LowerToByteSwap(CI);
26078       }
26079     }
26080     break;
26081   }
26082   return false;
26083 }
26084
26085 /// getConstraintType - Given a constraint letter, return the type of
26086 /// constraint it is for this target.
26087 X86TargetLowering::ConstraintType
26088 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26089   if (Constraint.size() == 1) {
26090     switch (Constraint[0]) {
26091     case 'R':
26092     case 'q':
26093     case 'Q':
26094     case 'f':
26095     case 't':
26096     case 'u':
26097     case 'y':
26098     case 'x':
26099     case 'Y':
26100     case 'l':
26101       return C_RegisterClass;
26102     case 'a':
26103     case 'b':
26104     case 'c':
26105     case 'd':
26106     case 'S':
26107     case 'D':
26108     case 'A':
26109       return C_Register;
26110     case 'I':
26111     case 'J':
26112     case 'K':
26113     case 'L':
26114     case 'M':
26115     case 'N':
26116     case 'G':
26117     case 'C':
26118     case 'e':
26119     case 'Z':
26120       return C_Other;
26121     default:
26122       break;
26123     }
26124   }
26125   return TargetLowering::getConstraintType(Constraint);
26126 }
26127
26128 /// Examine constraint type and operand type and determine a weight value.
26129 /// This object must already have been set up with the operand type
26130 /// and the current alternative constraint selected.
26131 TargetLowering::ConstraintWeight
26132   X86TargetLowering::getSingleConstraintMatchWeight(
26133     AsmOperandInfo &info, const char *constraint) const {
26134   ConstraintWeight weight = CW_Invalid;
26135   Value *CallOperandVal = info.CallOperandVal;
26136     // If we don't have a value, we can't do a match,
26137     // but allow it at the lowest weight.
26138   if (!CallOperandVal)
26139     return CW_Default;
26140   Type *type = CallOperandVal->getType();
26141   // Look at the constraint type.
26142   switch (*constraint) {
26143   default:
26144     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26145   case 'R':
26146   case 'q':
26147   case 'Q':
26148   case 'a':
26149   case 'b':
26150   case 'c':
26151   case 'd':
26152   case 'S':
26153   case 'D':
26154   case 'A':
26155     if (CallOperandVal->getType()->isIntegerTy())
26156       weight = CW_SpecificReg;
26157     break;
26158   case 'f':
26159   case 't':
26160   case 'u':
26161     if (type->isFloatingPointTy())
26162       weight = CW_SpecificReg;
26163     break;
26164   case 'y':
26165     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26166       weight = CW_SpecificReg;
26167     break;
26168   case 'x':
26169   case 'Y':
26170     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26171         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26172       weight = CW_Register;
26173     break;
26174   case 'I':
26175     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26176       if (C->getZExtValue() <= 31)
26177         weight = CW_Constant;
26178     }
26179     break;
26180   case 'J':
26181     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26182       if (C->getZExtValue() <= 63)
26183         weight = CW_Constant;
26184     }
26185     break;
26186   case 'K':
26187     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26188       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26189         weight = CW_Constant;
26190     }
26191     break;
26192   case 'L':
26193     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26194       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26195         weight = CW_Constant;
26196     }
26197     break;
26198   case 'M':
26199     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26200       if (C->getZExtValue() <= 3)
26201         weight = CW_Constant;
26202     }
26203     break;
26204   case 'N':
26205     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26206       if (C->getZExtValue() <= 0xff)
26207         weight = CW_Constant;
26208     }
26209     break;
26210   case 'G':
26211   case 'C':
26212     if (isa<ConstantFP>(CallOperandVal)) {
26213       weight = CW_Constant;
26214     }
26215     break;
26216   case 'e':
26217     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26218       if ((C->getSExtValue() >= -0x80000000LL) &&
26219           (C->getSExtValue() <= 0x7fffffffLL))
26220         weight = CW_Constant;
26221     }
26222     break;
26223   case 'Z':
26224     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26225       if (C->getZExtValue() <= 0xffffffff)
26226         weight = CW_Constant;
26227     }
26228     break;
26229   }
26230   return weight;
26231 }
26232
26233 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26234 /// with another that has more specific requirements based on the type of the
26235 /// corresponding operand.
26236 const char *X86TargetLowering::
26237 LowerXConstraint(EVT ConstraintVT) const {
26238   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26239   // 'f' like normal targets.
26240   if (ConstraintVT.isFloatingPoint()) {
26241     if (Subtarget->hasSSE2())
26242       return "Y";
26243     if (Subtarget->hasSSE1())
26244       return "x";
26245   }
26246
26247   return TargetLowering::LowerXConstraint(ConstraintVT);
26248 }
26249
26250 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26251 /// vector.  If it is invalid, don't add anything to Ops.
26252 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26253                                                      std::string &Constraint,
26254                                                      std::vector<SDValue>&Ops,
26255                                                      SelectionDAG &DAG) const {
26256   SDValue Result;
26257
26258   // Only support length 1 constraints for now.
26259   if (Constraint.length() > 1) return;
26260
26261   char ConstraintLetter = Constraint[0];
26262   switch (ConstraintLetter) {
26263   default: break;
26264   case 'I':
26265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26266       if (C->getZExtValue() <= 31) {
26267         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26268                                        Op.getValueType());
26269         break;
26270       }
26271     }
26272     return;
26273   case 'J':
26274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26275       if (C->getZExtValue() <= 63) {
26276         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26277                                        Op.getValueType());
26278         break;
26279       }
26280     }
26281     return;
26282   case 'K':
26283     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26284       if (isInt<8>(C->getSExtValue())) {
26285         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26286                                        Op.getValueType());
26287         break;
26288       }
26289     }
26290     return;
26291   case 'L':
26292     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26293       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26294           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26295         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26296                                        Op.getValueType());
26297         break;
26298       }
26299     }
26300     return;
26301   case 'M':
26302     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26303       if (C->getZExtValue() <= 3) {
26304         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26305                                        Op.getValueType());
26306         break;
26307       }
26308     }
26309     return;
26310   case 'N':
26311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26312       if (C->getZExtValue() <= 255) {
26313         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26314                                        Op.getValueType());
26315         break;
26316       }
26317     }
26318     return;
26319   case 'O':
26320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26321       if (C->getZExtValue() <= 127) {
26322         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26323                                        Op.getValueType());
26324         break;
26325       }
26326     }
26327     return;
26328   case 'e': {
26329     // 32-bit signed value
26330     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26331       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26332                                            C->getSExtValue())) {
26333         // Widen to 64 bits here to get it sign extended.
26334         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26335         break;
26336       }
26337     // FIXME gcc accepts some relocatable values here too, but only in certain
26338     // memory models; it's complicated.
26339     }
26340     return;
26341   }
26342   case 'Z': {
26343     // 32-bit unsigned value
26344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26345       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26346                                            C->getZExtValue())) {
26347         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26348                                        Op.getValueType());
26349         break;
26350       }
26351     }
26352     // FIXME gcc accepts some relocatable values here too, but only in certain
26353     // memory models; it's complicated.
26354     return;
26355   }
26356   case 'i': {
26357     // Literal immediates are always ok.
26358     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26359       // Widen to 64 bits here to get it sign extended.
26360       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26361       break;
26362     }
26363
26364     // In any sort of PIC mode addresses need to be computed at runtime by
26365     // adding in a register or some sort of table lookup.  These can't
26366     // be used as immediates.
26367     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26368       return;
26369
26370     // If we are in non-pic codegen mode, we allow the address of a global (with
26371     // an optional displacement) to be used with 'i'.
26372     GlobalAddressSDNode *GA = nullptr;
26373     int64_t Offset = 0;
26374
26375     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26376     while (1) {
26377       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26378         Offset += GA->getOffset();
26379         break;
26380       } else if (Op.getOpcode() == ISD::ADD) {
26381         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26382           Offset += C->getZExtValue();
26383           Op = Op.getOperand(0);
26384           continue;
26385         }
26386       } else if (Op.getOpcode() == ISD::SUB) {
26387         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26388           Offset += -C->getZExtValue();
26389           Op = Op.getOperand(0);
26390           continue;
26391         }
26392       }
26393
26394       // Otherwise, this isn't something we can handle, reject it.
26395       return;
26396     }
26397
26398     const GlobalValue *GV = GA->getGlobal();
26399     // If we require an extra load to get this address, as in PIC mode, we
26400     // can't accept it.
26401     if (isGlobalStubReference(
26402             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26403       return;
26404
26405     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26406                                         GA->getValueType(0), Offset);
26407     break;
26408   }
26409   }
26410
26411   if (Result.getNode()) {
26412     Ops.push_back(Result);
26413     return;
26414   }
26415   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26416 }
26417
26418 std::pair<unsigned, const TargetRegisterClass *>
26419 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26420                                                 StringRef Constraint,
26421                                                 MVT VT) const {
26422   // First, see if this is a constraint that directly corresponds to an LLVM
26423   // register class.
26424   if (Constraint.size() == 1) {
26425     // GCC Constraint Letters
26426     switch (Constraint[0]) {
26427     default: break;
26428       // TODO: Slight differences here in allocation order and leaving
26429       // RIP in the class. Do they matter any more here than they do
26430       // in the normal allocation?
26431     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26432       if (Subtarget->is64Bit()) {
26433         if (VT == MVT::i32 || VT == MVT::f32)
26434           return std::make_pair(0U, &X86::GR32RegClass);
26435         if (VT == MVT::i16)
26436           return std::make_pair(0U, &X86::GR16RegClass);
26437         if (VT == MVT::i8 || VT == MVT::i1)
26438           return std::make_pair(0U, &X86::GR8RegClass);
26439         if (VT == MVT::i64 || VT == MVT::f64)
26440           return std::make_pair(0U, &X86::GR64RegClass);
26441         break;
26442       }
26443       // 32-bit fallthrough
26444     case 'Q':   // Q_REGS
26445       if (VT == MVT::i32 || VT == MVT::f32)
26446         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26447       if (VT == MVT::i16)
26448         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26449       if (VT == MVT::i8 || VT == MVT::i1)
26450         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26451       if (VT == MVT::i64)
26452         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26453       break;
26454     case 'r':   // GENERAL_REGS
26455     case 'l':   // INDEX_REGS
26456       if (VT == MVT::i8 || VT == MVT::i1)
26457         return std::make_pair(0U, &X86::GR8RegClass);
26458       if (VT == MVT::i16)
26459         return std::make_pair(0U, &X86::GR16RegClass);
26460       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26461         return std::make_pair(0U, &X86::GR32RegClass);
26462       return std::make_pair(0U, &X86::GR64RegClass);
26463     case 'R':   // LEGACY_REGS
26464       if (VT == MVT::i8 || VT == MVT::i1)
26465         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26466       if (VT == MVT::i16)
26467         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26468       if (VT == MVT::i32 || !Subtarget->is64Bit())
26469         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26470       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26471     case 'f':  // FP Stack registers.
26472       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26473       // value to the correct fpstack register class.
26474       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26475         return std::make_pair(0U, &X86::RFP32RegClass);
26476       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26477         return std::make_pair(0U, &X86::RFP64RegClass);
26478       return std::make_pair(0U, &X86::RFP80RegClass);
26479     case 'y':   // MMX_REGS if MMX allowed.
26480       if (!Subtarget->hasMMX()) break;
26481       return std::make_pair(0U, &X86::VR64RegClass);
26482     case 'Y':   // SSE_REGS if SSE2 allowed
26483       if (!Subtarget->hasSSE2()) break;
26484       // FALL THROUGH.
26485     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26486       if (!Subtarget->hasSSE1()) break;
26487
26488       switch (VT.SimpleTy) {
26489       default: break;
26490       // Scalar SSE types.
26491       case MVT::f32:
26492       case MVT::i32:
26493         return std::make_pair(0U, &X86::FR32RegClass);
26494       case MVT::f64:
26495       case MVT::i64:
26496         return std::make_pair(0U, &X86::FR64RegClass);
26497       // Vector types.
26498       case MVT::v16i8:
26499       case MVT::v8i16:
26500       case MVT::v4i32:
26501       case MVT::v2i64:
26502       case MVT::v4f32:
26503       case MVT::v2f64:
26504         return std::make_pair(0U, &X86::VR128RegClass);
26505       // AVX types.
26506       case MVT::v32i8:
26507       case MVT::v16i16:
26508       case MVT::v8i32:
26509       case MVT::v4i64:
26510       case MVT::v8f32:
26511       case MVT::v4f64:
26512         return std::make_pair(0U, &X86::VR256RegClass);
26513       case MVT::v8f64:
26514       case MVT::v16f32:
26515       case MVT::v16i32:
26516       case MVT::v8i64:
26517         return std::make_pair(0U, &X86::VR512RegClass);
26518       }
26519       break;
26520     }
26521   }
26522
26523   // Use the default implementation in TargetLowering to convert the register
26524   // constraint into a member of a register class.
26525   std::pair<unsigned, const TargetRegisterClass*> Res;
26526   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26527
26528   // Not found as a standard register?
26529   if (!Res.second) {
26530     // Map st(0) -> st(7) -> ST0
26531     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26532         tolower(Constraint[1]) == 's' &&
26533         tolower(Constraint[2]) == 't' &&
26534         Constraint[3] == '(' &&
26535         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26536         Constraint[5] == ')' &&
26537         Constraint[6] == '}') {
26538
26539       Res.first = X86::FP0+Constraint[4]-'0';
26540       Res.second = &X86::RFP80RegClass;
26541       return Res;
26542     }
26543
26544     // GCC allows "st(0)" to be called just plain "st".
26545     if (StringRef("{st}").equals_lower(Constraint)) {
26546       Res.first = X86::FP0;
26547       Res.second = &X86::RFP80RegClass;
26548       return Res;
26549     }
26550
26551     // flags -> EFLAGS
26552     if (StringRef("{flags}").equals_lower(Constraint)) {
26553       Res.first = X86::EFLAGS;
26554       Res.second = &X86::CCRRegClass;
26555       return Res;
26556     }
26557
26558     // 'A' means EAX + EDX.
26559     if (Constraint == "A") {
26560       Res.first = X86::EAX;
26561       Res.second = &X86::GR32_ADRegClass;
26562       return Res;
26563     }
26564     return Res;
26565   }
26566
26567   // Otherwise, check to see if this is a register class of the wrong value
26568   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26569   // turn into {ax},{dx}.
26570   // MVT::Other is used to specify clobber names.
26571   if (Res.second->hasType(VT) || VT == MVT::Other)
26572     return Res;   // Correct type already, nothing to do.
26573
26574   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26575   // return "eax". This should even work for things like getting 64bit integer
26576   // registers when given an f64 type.
26577   const TargetRegisterClass *Class = Res.second;
26578   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26579       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26580     unsigned Size = VT.getSizeInBits();
26581     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26582                                   : Size == 16 ? MVT::i16
26583                                   : Size == 32 ? MVT::i32
26584                                   : Size == 64 ? MVT::i64
26585                                   : MVT::Other;
26586     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26587     if (DestReg > 0) {
26588       Res.first = DestReg;
26589       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26590                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26591                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26592                  : &X86::GR64RegClass;
26593       assert(Res.second->contains(Res.first) && "Register in register class");
26594     } else {
26595       // No register found/type mismatch.
26596       Res.first = 0;
26597       Res.second = nullptr;
26598     }
26599   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26600              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26601              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26602              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26603              Class == &X86::VR512RegClass) {
26604     // Handle references to XMM physical registers that got mapped into the
26605     // wrong class.  This can happen with constraints like {xmm0} where the
26606     // target independent register mapper will just pick the first match it can
26607     // find, ignoring the required type.
26608
26609     if (VT == MVT::f32 || VT == MVT::i32)
26610       Res.second = &X86::FR32RegClass;
26611     else if (VT == MVT::f64 || VT == MVT::i64)
26612       Res.second = &X86::FR64RegClass;
26613     else if (X86::VR128RegClass.hasType(VT))
26614       Res.second = &X86::VR128RegClass;
26615     else if (X86::VR256RegClass.hasType(VT))
26616       Res.second = &X86::VR256RegClass;
26617     else if (X86::VR512RegClass.hasType(VT))
26618       Res.second = &X86::VR512RegClass;
26619     else {
26620       // Type mismatch and not a clobber: Return an error;
26621       Res.first = 0;
26622       Res.second = nullptr;
26623     }
26624   }
26625
26626   return Res;
26627 }
26628
26629 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26630                                             const AddrMode &AM, Type *Ty,
26631                                             unsigned AS) const {
26632   // Scaling factors are not free at all.
26633   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26634   // will take 2 allocations in the out of order engine instead of 1
26635   // for plain addressing mode, i.e. inst (reg1).
26636   // E.g.,
26637   // vaddps (%rsi,%drx), %ymm0, %ymm1
26638   // Requires two allocations (one for the load, one for the computation)
26639   // whereas:
26640   // vaddps (%rsi), %ymm0, %ymm1
26641   // Requires just 1 allocation, i.e., freeing allocations for other operations
26642   // and having less micro operations to execute.
26643   //
26644   // For some X86 architectures, this is even worse because for instance for
26645   // stores, the complex addressing mode forces the instruction to use the
26646   // "load" ports instead of the dedicated "store" port.
26647   // E.g., on Haswell:
26648   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26649   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26650   if (isLegalAddressingMode(DL, AM, Ty, AS))
26651     // Scale represents reg2 * scale, thus account for 1
26652     // as soon as we use a second register.
26653     return AM.Scale != 0;
26654   return -1;
26655 }
26656
26657 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26658   // Integer division on x86 is expensive. However, when aggressively optimizing
26659   // for code size, we prefer to use a div instruction, as it is usually smaller
26660   // than the alternative sequence.
26661   // The exception to this is vector division. Since x86 doesn't have vector
26662   // integer division, leaving the division as-is is a loss even in terms of
26663   // size, because it will have to be scalarized, while the alternative code
26664   // sequence can be performed in vector form.
26665   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26666                                    Attribute::MinSize);
26667   return OptSize && !VT.isVector();
26668 }