Use range-based for loops and use initializer list to remove a small static array...
[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
79   // X86 is weird. It always uses i8 for shift amounts and setcc results.
80   setBooleanContents(ZeroOrOneBooleanContent);
81   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
82   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
83
84   // For 64-bit, since we have so many registers, use the ILP scheduler.
85   // For 32-bit, use the register pressure specific scheduling.
86   // For Atom, always use ILP scheduling.
87   if (Subtarget->isAtom())
88     setSchedulingPreference(Sched::ILP);
89   else if (Subtarget->is64Bit())
90     setSchedulingPreference(Sched::ILP);
91   else
92     setSchedulingPreference(Sched::RegPressure);
93   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
94   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
95
96   // Bypass expensive divides on Atom when compiling with O2.
97   if (TM.getOptLevel() >= CodeGenOpt::Default) {
98     if (Subtarget->hasSlowDivide32())
99       addBypassSlowDiv(32, 8);
100     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
101       addBypassSlowDiv(64, 16);
102   }
103
104   if (Subtarget->isTargetKnownWindowsMSVC()) {
105     // Setup Windows compiler runtime calls.
106     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
107     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
108     setLibcallName(RTLIB::SREM_I64, "_allrem");
109     setLibcallName(RTLIB::UREM_I64, "_aullrem");
110     setLibcallName(RTLIB::MUL_I64, "_allmul");
111     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
112     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
116   }
117
118   if (Subtarget->isTargetDarwin()) {
119     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
120     setUseUnderscoreSetJmp(false);
121     setUseUnderscoreLongJmp(false);
122   } else if (Subtarget->isTargetWindowsGNU()) {
123     // MS runtime is weird: it exports _setjmp, but longjmp!
124     setUseUnderscoreSetJmp(true);
125     setUseUnderscoreLongJmp(false);
126   } else {
127     setUseUnderscoreSetJmp(true);
128     setUseUnderscoreLongJmp(true);
129   }
130
131   // Set up the register classes.
132   addRegisterClass(MVT::i8, &X86::GR8RegClass);
133   addRegisterClass(MVT::i16, &X86::GR16RegClass);
134   addRegisterClass(MVT::i32, &X86::GR32RegClass);
135   if (Subtarget->is64Bit())
136     addRegisterClass(MVT::i64, &X86::GR64RegClass);
137
138   for (MVT VT : MVT::integer_valuetypes())
139     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
140
141   // We don't accept any truncstore of integer registers.
142   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
143   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
145   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
146   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
147   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
148
149   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
150
151   // SETOEQ and SETUNE require checking two conditions.
152   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
153   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
155   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
158
159   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
160   // operation.
161   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
164
165   if (Subtarget->is64Bit()) {
166     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
167       // f32/f64 are legal, f80 is custom.
168       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
169     else
170       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
171     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
172   } else if (!Subtarget->useSoftFloat()) {
173     // We have an algorithm for SSE2->double, and we turn this into a
174     // 64-bit FILD followed by conditional FADD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
176     // We have an algorithm for SSE2, and we turn this into a 64-bit
177     // FILD or VCVTUSI2SS/SD for other targets.
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
179   }
180
181   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
182   // this operation.
183   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
185
186   if (!Subtarget->useSoftFloat()) {
187     // SSE has no i16 to fp conversion, only i32
188     if (X86ScalarSSEf32) {
189       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
190       // f32 and f64 cases are Legal, f80 case is not
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     } else {
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
195     }
196   } else {
197     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
199   }
200
201   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
202   // are Legal, f80 is custom lowered.
203   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
204   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
205
206   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
207   // this operation.
208   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
209   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
210
211   if (X86ScalarSSEf32) {
212     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
213     // f32 and f64 cases are Legal, f80 case is not
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   } else {
216     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
217     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
218   }
219
220   // Handle FP_TO_UINT by promoting the destination to a larger signed
221   // conversion.
222   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
224   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
225
226   if (Subtarget->is64Bit()) {
227     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
228       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
231     } else {
232       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
233       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
234     }
235   } else if (!Subtarget->useSoftFloat()) {
236     // Since AVX is a superset of SSE3, only check for SSE here.
237     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
238       // Expand FP_TO_UINT into a select.
239       // FIXME: We would like to use a Custom expander here eventually to do
240       // the optimal thing for SSE vs. the default expansion in the legalizer.
241       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
242     else
243       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
244       // With SSE3 we can use fisttpll to convert to a signed i64; without
245       // SSE, we're stuck with a fistpll.
246       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
247
248     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
249   }
250
251   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
252   if (!X86ScalarSSEf64) {
253     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
254     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
255     if (Subtarget->is64Bit()) {
256       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
257       // Without SSE, i64->f64 goes through memory.
258       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
259     }
260   }
261
262   // Scalar integer divide and remainder are lowered to use operations that
263   // produce two results, to match the available instructions. This exposes
264   // the two-result form to trivial CSE, which is able to combine x/y and x%y
265   // into a single instruction.
266   //
267   // Scalar integer multiply-high is also lowered to use two-result
268   // operations, to match the available instructions. However, plain multiply
269   // (low) operations are left as Legal, as there are single-result
270   // instructions for this in x86. Using the two-result multiply instructions
271   // when both high and low results are needed must be arranged by dagcombine.
272   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
273     setOperationAction(ISD::MULHS, VT, Expand);
274     setOperationAction(ISD::MULHU, VT, Expand);
275     setOperationAction(ISD::SDIV, VT, Expand);
276     setOperationAction(ISD::UDIV, VT, Expand);
277     setOperationAction(ISD::SREM, VT, Expand);
278     setOperationAction(ISD::UREM, VT, Expand);
279
280     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
281     setOperationAction(ISD::ADDC, VT, Custom);
282     setOperationAction(ISD::ADDE, VT, Custom);
283     setOperationAction(ISD::SUBC, VT, Custom);
284     setOperationAction(ISD::SUBE, VT, Custom);
285   }
286
287   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
288   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
289   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
291   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
303   if (Subtarget->is64Bit())
304     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
306   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
308   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
309
310   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
311     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
312     // is. We should promote the value to 64-bits to solve this.
313     // This is what the CRT headers do - `fmodf` is an inline header
314     // function casting to f64 and calling `fmod`.
315     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
316   } else {
317     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
318   }
319
320   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
322   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
323
324   // Promote the i8 variants and force them on up to i32 which has a shorter
325   // encoding.
326   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
327   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
328   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
330   if (Subtarget->hasBMI()) {
331     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
332     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
333     if (Subtarget->is64Bit())
334       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
335   } else {
336     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
337     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
338     if (Subtarget->is64Bit())
339       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
340   }
341
342   if (Subtarget->hasLZCNT()) {
343     // When promoting the i8 variants, force them to i32 for a shorter
344     // encoding.
345     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
346     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
351     if (Subtarget->is64Bit())
352       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
353   } else {
354     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
355     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
356     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
360     if (Subtarget->is64Bit()) {
361       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
362       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
363     }
364   }
365
366   // Special handling for half-precision floating point conversions.
367   // If we don't have F16C support, then lower half float conversions
368   // into library calls.
369   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
370     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
371     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
372   }
373
374   // There's never any support for operations beyond MVT::f32.
375   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
376   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
377   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
378   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
379
380   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
381   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
382   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
384   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
386
387   if (Subtarget->hasPOPCNT()) {
388     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
389   } else {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
391     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
392     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
393     if (Subtarget->is64Bit())
394       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
395   }
396
397   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
398
399   if (!Subtarget->hasMOVBE())
400     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
401
402   // These should be promoted to a larger select which is supported.
403   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
404   // X86 wants to expand cmov itself.
405   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
406   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
417   if (Subtarget->is64Bit()) {
418     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
419     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
420   }
421   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
422   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
423   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
424   // support continuation, user-level threading, and etc.. As a result, no
425   // other SjLj exception interfaces are implemented and please don't build
426   // your own exception handling based on them.
427   // LLVM/Clang supports zero-cost DWARF exception handling.
428   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
429   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
430
431   // Darwin ABI issue.
432   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
433   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
436   if (Subtarget->is64Bit())
437     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
438   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
439   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
440   if (Subtarget->is64Bit()) {
441     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
442     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
443     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
444     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
445     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
446   }
447   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
448   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
455   }
456
457   if (Subtarget->hasSSE1())
458     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
459
460   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
461
462   // Expand certain atomics
463   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
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     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
852     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
853     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
854     // ISD::CTTZ v2i64 - scalarization is faster.
855     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
856     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
857     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
858     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
859
860     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
861     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
862       MVT VT = (MVT::SimpleValueType)i;
863       // Do not attempt to custom lower non-power-of-2 vectors
864       if (!isPowerOf2_32(VT.getVectorNumElements()))
865         continue;
866       // Do not attempt to custom lower non-128-bit vectors
867       if (!VT.is128BitVector())
868         continue;
869       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
870       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
871       setOperationAction(ISD::VSELECT,            VT, Custom);
872       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
873     }
874
875     // We support custom legalizing of sext and anyext loads for specific
876     // memory vector types which we can load as a scalar (or sequence of
877     // scalars) and extend in-register to a legal 128-bit vector type. For sext
878     // loads these must work with a single scalar load.
879     for (MVT VT : MVT::integer_vector_valuetypes()) {
880       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
881       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
882       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
883       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
884       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
885       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
886       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
887       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
888       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
889     }
890
891     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
892     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
893     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
894     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
895     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
896     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900     if (Subtarget->is64Bit()) {
901       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903     }
904
905     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907       MVT VT = (MVT::SimpleValueType)i;
908
909       // Do not attempt to promote non-128-bit vectors
910       if (!VT.is128BitVector())
911         continue;
912
913       setOperationAction(ISD::AND,    VT, Promote);
914       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915       setOperationAction(ISD::OR,     VT, Promote);
916       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917       setOperationAction(ISD::XOR,    VT, Promote);
918       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919       setOperationAction(ISD::LOAD,   VT, Promote);
920       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921       setOperationAction(ISD::SELECT, VT, Promote);
922       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923     }
924
925     // Custom lower v2i64 and v2f64 selects.
926     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
927     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
928     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
929     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
930
931     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
932     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
933
934     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
935
936     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
937     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
938     // As there is no 64-bit GPR available, we need build a special custom
939     // sequence to convert from v2i32 to v2f32.
940     if (!Subtarget->is64Bit())
941       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
942
943     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
944     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
945
946     for (MVT VT : MVT::fp_vector_valuetypes())
947       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
948
949     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
950     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
951     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
952   }
953
954   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
955     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
956       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
957       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
958       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
959       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
960       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
961     }
962
963     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
964     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
965     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
966     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
967     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
968     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
969     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
970     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
971
972     // FIXME: Do we need to handle scalar-to-vector here?
973     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
974
975     // We directly match byte blends in the backend as they match the VSELECT
976     // condition form.
977     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
978
979     // SSE41 brings specific instructions for doing vector sign extend even in
980     // cases where we don't have SRA.
981     for (MVT VT : MVT::integer_vector_valuetypes()) {
982       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
983       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
984       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
985     }
986
987     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
988     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
989     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
990     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
994
995     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
996     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
997     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1001
1002     // i8 and i16 vectors are custom because the source register and source
1003     // source memory operand types are not the same width.  f32 vectors are
1004     // custom since the immediate controlling the insert encodes additional
1005     // information.
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1010
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1014     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015
1016     // FIXME: these should be Legal, but that's only for the case where
1017     // the index is constant.  For now custom expand to deal with that.
1018     if (Subtarget->is64Bit()) {
1019       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1020       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1021     }
1022   }
1023
1024   if (Subtarget->hasSSE2()) {
1025     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1026     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1027     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1028
1029     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1037
1038     // In the customized shift lowering, the legal cases in AVX2 will be
1039     // recognized.
1040     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1041     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1042
1043     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1044     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1045
1046     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1047     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1048   }
1049
1050   if (Subtarget->hasXOP()) {
1051     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1052     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1053     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1054     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1055     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1059   }
1060
1061   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1062     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1063     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1064     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1065     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1066     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1067     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1068
1069     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1070     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1071     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1072
1073     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1074     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1075     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1076     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1077     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1078     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1083     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1084     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1085
1086     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1087     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1088     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1089     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1091     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1094     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1096     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1097     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1098
1099     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1100     // even though v8i16 is a legal type.
1101     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1102     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1103     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1104
1105     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1107     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1108
1109     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1110     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1111
1112     for (MVT VT : MVT::fp_vector_valuetypes())
1113       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1114
1115     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1116     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1117
1118     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1119     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1120
1121     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1122     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1123
1124     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1128
1129     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1130     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1131     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1132
1133     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1134     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1135     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1136     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1137     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1138     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1139     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1140     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1141     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1142     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1143     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1144     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1145
1146     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1147     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1148     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1149     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1150
1151     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1152     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1153     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1154     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1155     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1156     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1157     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1158     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1159
1160     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1161       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1162       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1163       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1164       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1165       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1166       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1167     }
1168
1169     if (Subtarget->hasInt256()) {
1170       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1171       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1172       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1173       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1174
1175       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1178       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1179
1180       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1182       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1183       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1184
1185       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1186       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1187       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1188       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1189
1190       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1191       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1192       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1193       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1194       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1195       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1196       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1197       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1198       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1199       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1200       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1201       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1202
1203       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1204       // when we have a 256bit-wide blend with immediate.
1205       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1206
1207       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1208       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1209       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1210       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1211       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1214
1215       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1216       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1217       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1218       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1221     } else {
1222       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1223       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1224       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1225       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1226
1227       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1229       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1230       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1231
1232       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1238       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1239       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1240       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1241       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1242       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1243       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1244       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1245       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1246       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1247       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1248       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1249     }
1250
1251     // In the customized shift lowering, the legal cases in AVX2 will be
1252     // recognized.
1253     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1254     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1255
1256     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1257     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1258
1259     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1261
1262     // Custom lower several nodes for 256-bit types.
1263     for (MVT VT : MVT::vector_valuetypes()) {
1264       if (VT.getScalarSizeInBits() >= 32) {
1265         setOperationAction(ISD::MLOAD,  VT, Legal);
1266         setOperationAction(ISD::MSTORE, VT, Legal);
1267       }
1268       // Extract subvector is special because the value type
1269       // (result) is 128-bit but the source is 256-bit wide.
1270       if (VT.is128BitVector()) {
1271         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1272       }
1273       // Do not attempt to custom lower other non-256-bit vectors
1274       if (!VT.is256BitVector())
1275         continue;
1276
1277       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1278       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1279       setOperationAction(ISD::VSELECT,            VT, Custom);
1280       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1281       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1283       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1284       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1285     }
1286
1287     if (Subtarget->hasInt256())
1288       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1289
1290     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1291     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1292       MVT VT = (MVT::SimpleValueType)i;
1293
1294       // Do not attempt to promote non-256-bit vectors
1295       if (!VT.is256BitVector())
1296         continue;
1297
1298       setOperationAction(ISD::AND,    VT, Promote);
1299       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1300       setOperationAction(ISD::OR,     VT, Promote);
1301       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1302       setOperationAction(ISD::XOR,    VT, Promote);
1303       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1304       setOperationAction(ISD::LOAD,   VT, Promote);
1305       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1306       setOperationAction(ISD::SELECT, VT, Promote);
1307       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308     }
1309   }
1310
1311   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1312     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1315     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1316
1317     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1318     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1319     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1320
1321     for (MVT VT : MVT::fp_vector_valuetypes())
1322       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1323
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1328     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1330     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1331     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1332     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1333     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1334     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1335     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1336
1337     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1338     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1339     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1340     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1341     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1342     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1343     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1344     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1345     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1346     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1350     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1351
1352     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1356     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1357     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1358
1359     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1364     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1366     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1367
1368     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1372     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1382     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1383     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1384
1385     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1388     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1390     if (Subtarget->hasVLX()){
1391       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1394       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396
1397       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1400       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402     }
1403     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1404     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1405     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1406     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1407     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1408     if (Subtarget->hasDQI()) {
1409       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1410       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1411
1412       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1413       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1414       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1415       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1416       if (Subtarget->hasVLX()) {
1417         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1418         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1419         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1420         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1421         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1422         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1423         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1424         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1425       }
1426     }
1427     if (Subtarget->hasVLX()) {
1428       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1429       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1430       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1431       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1432       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1433       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1434       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1435       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1436     }
1437     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1438     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1439     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1440     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1441     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1442     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1443     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1444     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1445     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1446     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1447     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1448     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1449     if (Subtarget->hasDQI()) {
1450       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1451       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1452     }
1453     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1454     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1455     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1456     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1457     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1458     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1459     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1460     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1461     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1462     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1463
1464     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1465     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1466     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1467     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1469
1470     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1471     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1472
1473     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1474
1475     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1476     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1477     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1478     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1479     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1480     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1481     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1482     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1483     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1484     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1485     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1486
1487     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1488     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1489     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1490     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1491     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1492     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1493     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1494     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1495
1496     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1497     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1498
1499     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1500     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1501
1502     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1503
1504     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1505     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1506
1507     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1508     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1509
1510     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1511     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1512
1513     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1514     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1515     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1516     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1517     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1518     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1519
1520     if (Subtarget->hasCDI()) {
1521       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1522       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1523       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1524       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1525
1526       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1527       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1528       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1529       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1531       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1532       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1533       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1534
1535       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1536       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1537
1538       if (Subtarget->hasVLX()) {
1539         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1540         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1541         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1542         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1543         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1544         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1545         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1546         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1547
1548         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1549         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1550         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1551         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1552       } else {
1553         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1554         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1555         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1556         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1557         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1558         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1559         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1560         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1561       }
1562     } // Subtarget->hasCDI()
1563
1564     if (Subtarget->hasDQI()) {
1565       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1566       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1567       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1568     }
1569     // Custom lower several nodes.
1570     for (MVT VT : MVT::vector_valuetypes()) {
1571       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1572       if (EltSize == 1) {
1573         setOperationAction(ISD::AND, VT, Legal);
1574         setOperationAction(ISD::OR,  VT, Legal);
1575         setOperationAction(ISD::XOR,  VT, Legal);
1576       }
1577       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1578         setOperationAction(ISD::MGATHER,  VT, Custom);
1579         setOperationAction(ISD::MSCATTER, VT, Custom);
1580       }
1581       // Extract subvector is special because the value type
1582       // (result) is 256/128-bit but the source is 512-bit wide.
1583       if (VT.is128BitVector() || VT.is256BitVector()) {
1584         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1585       }
1586       if (VT.getVectorElementType() == MVT::i1)
1587         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1588
1589       // Do not attempt to custom lower other non-512-bit vectors
1590       if (!VT.is512BitVector())
1591         continue;
1592
1593       if (EltSize >= 32) {
1594         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1595         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1596         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1597         setOperationAction(ISD::VSELECT,             VT, Legal);
1598         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1599         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1600         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1601         setOperationAction(ISD::MLOAD,               VT, Legal);
1602         setOperationAction(ISD::MSTORE,              VT, Legal);
1603       }
1604     }
1605     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1606       MVT VT = (MVT::SimpleValueType)i;
1607
1608       // Do not attempt to promote non-512-bit vectors.
1609       if (!VT.is512BitVector())
1610         continue;
1611
1612       setOperationAction(ISD::SELECT, VT, Promote);
1613       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1614     }
1615   }// has  AVX-512
1616
1617   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1618     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1619     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1620
1621     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1622     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1623
1624     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1625     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1626     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1627     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1628     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1629     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1630     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1631     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1632     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1633     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1634     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1635     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1636     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1637     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1639     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1640     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1641     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1643     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1644     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1645     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1646     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1647     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1648     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1649     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1650     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1651     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1652     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1653     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1654     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1655     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1656     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1657     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1659     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1660     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1661     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1662     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1663     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1664     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1665     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1666
1667     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1668     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1669     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1670     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1671     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1672     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1673     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1674     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1675
1676     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1677     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1678     if (Subtarget->hasVLX())
1679       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1680
1681     if (Subtarget->hasCDI()) {
1682       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1683       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1684       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1685       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1686     }
1687
1688     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1689       const MVT VT = (MVT::SimpleValueType)i;
1690
1691       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1692
1693       // Do not attempt to promote non-512-bit vectors.
1694       if (!VT.is512BitVector())
1695         continue;
1696
1697       if (EltSize < 32) {
1698         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1699         setOperationAction(ISD::VSELECT,             VT, Legal);
1700       }
1701     }
1702   }
1703
1704   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1705     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1706     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1707
1708     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1709     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1710     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1711     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1712     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1713     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1714     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1715     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1716     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1717     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1718     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1719     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1720
1721     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1722     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1723     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1724     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1725     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1726     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1727     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1728     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1729
1730     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1731     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1732     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1733     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1734     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1735     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1736     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1737     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1738   }
1739
1740   // We want to custom lower some of our intrinsics.
1741   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1742   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1743   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1744   if (!Subtarget->is64Bit())
1745     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1746
1747   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1748   // handle type legalization for these operations here.
1749   //
1750   // FIXME: We really should do custom legalization for addition and
1751   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1752   // than generic legalization for 64-bit multiplication-with-overflow, though.
1753   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1754     if (VT == MVT::i64 && !Subtarget->is64Bit())
1755       continue;
1756     // Add/Sub/Mul with overflow operations are custom lowered.
1757     setOperationAction(ISD::SADDO, VT, Custom);
1758     setOperationAction(ISD::UADDO, VT, Custom);
1759     setOperationAction(ISD::SSUBO, VT, Custom);
1760     setOperationAction(ISD::USUBO, VT, Custom);
1761     setOperationAction(ISD::SMULO, VT, Custom);
1762     setOperationAction(ISD::UMULO, VT, Custom);
1763   }
1764
1765   if (!Subtarget->is64Bit()) {
1766     // These libcalls are not available in 32-bit.
1767     setLibcallName(RTLIB::SHL_I128, nullptr);
1768     setLibcallName(RTLIB::SRL_I128, nullptr);
1769     setLibcallName(RTLIB::SRA_I128, nullptr);
1770   }
1771
1772   // Combine sin / cos into one node or libcall if possible.
1773   if (Subtarget->hasSinCos()) {
1774     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1775     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1776     if (Subtarget->isTargetDarwin()) {
1777       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1778       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1779       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1780       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1781     }
1782   }
1783
1784   if (Subtarget->isTargetWin64()) {
1785     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1786     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1787     setOperationAction(ISD::SREM, MVT::i128, Custom);
1788     setOperationAction(ISD::UREM, MVT::i128, Custom);
1789     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1790     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1791   }
1792
1793   // We have target-specific dag combine patterns for the following nodes:
1794   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1795   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1796   setTargetDAGCombine(ISD::BITCAST);
1797   setTargetDAGCombine(ISD::VSELECT);
1798   setTargetDAGCombine(ISD::SELECT);
1799   setTargetDAGCombine(ISD::SHL);
1800   setTargetDAGCombine(ISD::SRA);
1801   setTargetDAGCombine(ISD::SRL);
1802   setTargetDAGCombine(ISD::OR);
1803   setTargetDAGCombine(ISD::AND);
1804   setTargetDAGCombine(ISD::ADD);
1805   setTargetDAGCombine(ISD::FADD);
1806   setTargetDAGCombine(ISD::FSUB);
1807   setTargetDAGCombine(ISD::FMA);
1808   setTargetDAGCombine(ISD::SUB);
1809   setTargetDAGCombine(ISD::LOAD);
1810   setTargetDAGCombine(ISD::MLOAD);
1811   setTargetDAGCombine(ISD::STORE);
1812   setTargetDAGCombine(ISD::MSTORE);
1813   setTargetDAGCombine(ISD::ZERO_EXTEND);
1814   setTargetDAGCombine(ISD::ANY_EXTEND);
1815   setTargetDAGCombine(ISD::SIGN_EXTEND);
1816   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1817   setTargetDAGCombine(ISD::SINT_TO_FP);
1818   setTargetDAGCombine(ISD::UINT_TO_FP);
1819   setTargetDAGCombine(ISD::SETCC);
1820   setTargetDAGCombine(ISD::BUILD_VECTOR);
1821   setTargetDAGCombine(ISD::MUL);
1822   setTargetDAGCombine(ISD::XOR);
1823
1824   computeRegisterProperties(Subtarget->getRegisterInfo());
1825
1826   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1827   MaxStoresPerMemsetOptSize = 8;
1828   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1829   MaxStoresPerMemcpyOptSize = 4;
1830   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1831   MaxStoresPerMemmoveOptSize = 4;
1832   setPrefLoopAlignment(4); // 2^4 bytes.
1833
1834   // A predictable cmov does not hurt on an in-order CPU.
1835   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1836   PredictableSelectIsExpensive = !Subtarget->isAtom();
1837   EnableExtLdPromotion = true;
1838   setPrefFunctionAlignment(4); // 2^4 bytes.
1839
1840   verifyIntrinsicTables();
1841 }
1842
1843 // This has so far only been implemented for 64-bit MachO.
1844 bool X86TargetLowering::useLoadStackGuardNode() const {
1845   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1846 }
1847
1848 TargetLoweringBase::LegalizeTypeAction
1849 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1850   if (ExperimentalVectorWideningLegalization &&
1851       VT.getVectorNumElements() != 1 &&
1852       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1853     return TypeWidenVector;
1854
1855   return TargetLoweringBase::getPreferredVectorAction(VT);
1856 }
1857
1858 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1859                                           EVT VT) const {
1860   if (!VT.isVector())
1861     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1862
1863   const unsigned NumElts = VT.getVectorNumElements();
1864   const EVT EltVT = VT.getVectorElementType();
1865   if (VT.is512BitVector()) {
1866     if (Subtarget->hasAVX512())
1867       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1868           EltVT == MVT::f32 || EltVT == MVT::f64)
1869         switch(NumElts) {
1870         case  8: return MVT::v8i1;
1871         case 16: return MVT::v16i1;
1872       }
1873     if (Subtarget->hasBWI())
1874       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1875         switch(NumElts) {
1876         case 32: return MVT::v32i1;
1877         case 64: return MVT::v64i1;
1878       }
1879   }
1880
1881   if (VT.is256BitVector() || VT.is128BitVector()) {
1882     if (Subtarget->hasVLX())
1883       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1884           EltVT == MVT::f32 || EltVT == MVT::f64)
1885         switch(NumElts) {
1886         case 2: return MVT::v2i1;
1887         case 4: return MVT::v4i1;
1888         case 8: return MVT::v8i1;
1889       }
1890     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1891       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1892         switch(NumElts) {
1893         case  8: return MVT::v8i1;
1894         case 16: return MVT::v16i1;
1895         case 32: return MVT::v32i1;
1896       }
1897   }
1898
1899   return VT.changeVectorElementTypeToInteger();
1900 }
1901
1902 /// Helper for getByValTypeAlignment to determine
1903 /// the desired ByVal argument alignment.
1904 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1905   if (MaxAlign == 16)
1906     return;
1907   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1908     if (VTy->getBitWidth() == 128)
1909       MaxAlign = 16;
1910   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1911     unsigned EltAlign = 0;
1912     getMaxByValAlign(ATy->getElementType(), EltAlign);
1913     if (EltAlign > MaxAlign)
1914       MaxAlign = EltAlign;
1915   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1916     for (auto *EltTy : STy->elements()) {
1917       unsigned EltAlign = 0;
1918       getMaxByValAlign(EltTy, EltAlign);
1919       if (EltAlign > MaxAlign)
1920         MaxAlign = EltAlign;
1921       if (MaxAlign == 16)
1922         break;
1923     }
1924   }
1925 }
1926
1927 /// Return the desired alignment for ByVal aggregate
1928 /// function arguments in the caller parameter area. For X86, aggregates
1929 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1930 /// are at 4-byte boundaries.
1931 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1932                                                   const DataLayout &DL) const {
1933   if (Subtarget->is64Bit()) {
1934     // Max of 8 and alignment of type.
1935     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1936     if (TyAlign > 8)
1937       return TyAlign;
1938     return 8;
1939   }
1940
1941   unsigned Align = 4;
1942   if (Subtarget->hasSSE1())
1943     getMaxByValAlign(Ty, Align);
1944   return Align;
1945 }
1946
1947 /// Returns the target specific optimal type for load
1948 /// and store operations as a result of memset, memcpy, and memmove
1949 /// lowering. If DstAlign is zero that means it's safe to destination
1950 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1951 /// means there isn't a need to check it against alignment requirement,
1952 /// probably because the source does not need to be loaded. If 'IsMemset' is
1953 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1954 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1955 /// source is constant so it does not need to be loaded.
1956 /// It returns EVT::Other if the type should be determined using generic
1957 /// target-independent logic.
1958 EVT
1959 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1960                                        unsigned DstAlign, unsigned SrcAlign,
1961                                        bool IsMemset, bool ZeroMemset,
1962                                        bool MemcpyStrSrc,
1963                                        MachineFunction &MF) const {
1964   const Function *F = MF.getFunction();
1965   if ((!IsMemset || ZeroMemset) &&
1966       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1967     if (Size >= 16 &&
1968         (!Subtarget->isUnalignedMem16Slow() ||
1969          ((DstAlign == 0 || DstAlign >= 16) &&
1970           (SrcAlign == 0 || SrcAlign >= 16)))) {
1971       if (Size >= 32) {
1972         // FIXME: Check if unaligned 32-byte accesses are slow.
1973         if (Subtarget->hasInt256())
1974           return MVT::v8i32;
1975         if (Subtarget->hasFp256())
1976           return MVT::v8f32;
1977       }
1978       if (Subtarget->hasSSE2())
1979         return MVT::v4i32;
1980       if (Subtarget->hasSSE1())
1981         return MVT::v4f32;
1982     } else if (!MemcpyStrSrc && Size >= 8 &&
1983                !Subtarget->is64Bit() &&
1984                Subtarget->hasSSE2()) {
1985       // Do not use f64 to lower memcpy if source is string constant. It's
1986       // better to use i32 to avoid the loads.
1987       return MVT::f64;
1988     }
1989   }
1990   // This is a compromise. If we reach here, unaligned accesses may be slow on
1991   // this target. However, creating smaller, aligned accesses could be even
1992   // slower and would certainly be a lot more code.
1993   if (Subtarget->is64Bit() && Size >= 8)
1994     return MVT::i64;
1995   return MVT::i32;
1996 }
1997
1998 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1999   if (VT == MVT::f32)
2000     return X86ScalarSSEf32;
2001   else if (VT == MVT::f64)
2002     return X86ScalarSSEf64;
2003   return true;
2004 }
2005
2006 bool
2007 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2008                                                   unsigned,
2009                                                   unsigned,
2010                                                   bool *Fast) const {
2011   if (Fast) {
2012     switch (VT.getSizeInBits()) {
2013     default:
2014       // 8-byte and under are always assumed to be fast.
2015       *Fast = true;
2016       break;
2017     case 128:
2018       *Fast = !Subtarget->isUnalignedMem16Slow();
2019       break;
2020     case 256:
2021       *Fast = !Subtarget->isUnalignedMem32Slow();
2022       break;
2023     // TODO: What about AVX-512 (512-bit) accesses?
2024     }
2025   }
2026   // Misaligned accesses of any size are always allowed.
2027   return true;
2028 }
2029
2030 /// Return the entry encoding for a jump table in the
2031 /// current function.  The returned value is a member of the
2032 /// MachineJumpTableInfo::JTEntryKind enum.
2033 unsigned X86TargetLowering::getJumpTableEncoding() const {
2034   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2035   // symbol.
2036   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2037       Subtarget->isPICStyleGOT())
2038     return MachineJumpTableInfo::EK_Custom32;
2039
2040   // Otherwise, use the normal jump table encoding heuristics.
2041   return TargetLowering::getJumpTableEncoding();
2042 }
2043
2044 bool X86TargetLowering::useSoftFloat() const {
2045   return Subtarget->useSoftFloat();
2046 }
2047
2048 const MCExpr *
2049 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2050                                              const MachineBasicBlock *MBB,
2051                                              unsigned uid,MCContext &Ctx) const{
2052   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2053          Subtarget->isPICStyleGOT());
2054   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2055   // entries.
2056   return MCSymbolRefExpr::create(MBB->getSymbol(),
2057                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2058 }
2059
2060 /// Returns relocation base for the given PIC jumptable.
2061 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2062                                                     SelectionDAG &DAG) const {
2063   if (!Subtarget->is64Bit())
2064     // This doesn't have SDLoc associated with it, but is not really the
2065     // same as a Register.
2066     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2067                        getPointerTy(DAG.getDataLayout()));
2068   return Table;
2069 }
2070
2071 /// This returns the relocation base for the given PIC jumptable,
2072 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2073 const MCExpr *X86TargetLowering::
2074 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2075                              MCContext &Ctx) const {
2076   // X86-64 uses RIP relative addressing based on the jump table label.
2077   if (Subtarget->isPICStyleRIPRel())
2078     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2079
2080   // Otherwise, the reference is relative to the PIC base.
2081   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2082 }
2083
2084 std::pair<const TargetRegisterClass *, uint8_t>
2085 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2086                                            MVT VT) const {
2087   const TargetRegisterClass *RRC = nullptr;
2088   uint8_t Cost = 1;
2089   switch (VT.SimpleTy) {
2090   default:
2091     return TargetLowering::findRepresentativeClass(TRI, VT);
2092   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2093     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2094     break;
2095   case MVT::x86mmx:
2096     RRC = &X86::VR64RegClass;
2097     break;
2098   case MVT::f32: case MVT::f64:
2099   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2100   case MVT::v4f32: case MVT::v2f64:
2101   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2102   case MVT::v4f64:
2103     RRC = &X86::VR128RegClass;
2104     break;
2105   }
2106   return std::make_pair(RRC, Cost);
2107 }
2108
2109 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2110                                                unsigned &Offset) const {
2111   if (!Subtarget->isTargetLinux())
2112     return false;
2113
2114   if (Subtarget->is64Bit()) {
2115     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2116     Offset = 0x28;
2117     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2118       AddressSpace = 256;
2119     else
2120       AddressSpace = 257;
2121   } else {
2122     // %gs:0x14 on i386
2123     Offset = 0x14;
2124     AddressSpace = 256;
2125   }
2126   return true;
2127 }
2128
2129 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2130   if (!Subtarget->isTargetAndroid())
2131     return TargetLowering::getSafeStackPointerLocation(IRB);
2132
2133   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2134   // definition of TLS_SLOT_SAFESTACK in
2135   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2136   unsigned AddressSpace, Offset;
2137   if (Subtarget->is64Bit()) {
2138     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2139     Offset = 0x48;
2140     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2141       AddressSpace = 256;
2142     else
2143       AddressSpace = 257;
2144   } else {
2145     // %gs:0x24 on i386
2146     Offset = 0x24;
2147     AddressSpace = 256;
2148   }
2149
2150   return ConstantExpr::getIntToPtr(
2151       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2152       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2153 }
2154
2155 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2156                                             unsigned DestAS) const {
2157   assert(SrcAS != DestAS && "Expected different address spaces!");
2158
2159   return SrcAS < 256 && DestAS < 256;
2160 }
2161
2162 //===----------------------------------------------------------------------===//
2163 //               Return Value Calling Convention Implementation
2164 //===----------------------------------------------------------------------===//
2165
2166 #include "X86GenCallingConv.inc"
2167
2168 bool X86TargetLowering::CanLowerReturn(
2169     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2170     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2171   SmallVector<CCValAssign, 16> RVLocs;
2172   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2173   return CCInfo.CheckReturn(Outs, RetCC_X86);
2174 }
2175
2176 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2177   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2178   return ScratchRegs;
2179 }
2180
2181 SDValue
2182 X86TargetLowering::LowerReturn(SDValue Chain,
2183                                CallingConv::ID CallConv, bool isVarArg,
2184                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2185                                const SmallVectorImpl<SDValue> &OutVals,
2186                                SDLoc dl, SelectionDAG &DAG) const {
2187   MachineFunction &MF = DAG.getMachineFunction();
2188   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2189
2190   SmallVector<CCValAssign, 16> RVLocs;
2191   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2192   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2193
2194   SDValue Flag;
2195   SmallVector<SDValue, 6> RetOps;
2196   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2197   // Operand #1 = Bytes To Pop
2198   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2199                    MVT::i16));
2200
2201   // Copy the result values into the output registers.
2202   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2203     CCValAssign &VA = RVLocs[i];
2204     assert(VA.isRegLoc() && "Can only return in registers!");
2205     SDValue ValToCopy = OutVals[i];
2206     EVT ValVT = ValToCopy.getValueType();
2207
2208     // Promote values to the appropriate types.
2209     if (VA.getLocInfo() == CCValAssign::SExt)
2210       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2211     else if (VA.getLocInfo() == CCValAssign::ZExt)
2212       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2213     else if (VA.getLocInfo() == CCValAssign::AExt) {
2214       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2215         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2216       else
2217         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2218     }
2219     else if (VA.getLocInfo() == CCValAssign::BCvt)
2220       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2221
2222     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2223            "Unexpected FP-extend for return value.");
2224
2225     // If this is x86-64, and we disabled SSE, we can't return FP values,
2226     // or SSE or MMX vectors.
2227     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2228          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2229           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2230       report_fatal_error("SSE register return with SSE disabled");
2231     }
2232     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2233     // llvm-gcc has never done it right and no one has noticed, so this
2234     // should be OK for now.
2235     if (ValVT == MVT::f64 &&
2236         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2237       report_fatal_error("SSE2 register return with SSE2 disabled");
2238
2239     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2240     // the RET instruction and handled by the FP Stackifier.
2241     if (VA.getLocReg() == X86::FP0 ||
2242         VA.getLocReg() == X86::FP1) {
2243       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2244       // change the value to the FP stack register class.
2245       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2246         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2247       RetOps.push_back(ValToCopy);
2248       // Don't emit a copytoreg.
2249       continue;
2250     }
2251
2252     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2253     // which is returned in RAX / RDX.
2254     if (Subtarget->is64Bit()) {
2255       if (ValVT == MVT::x86mmx) {
2256         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2257           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2258           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2259                                   ValToCopy);
2260           // If we don't have SSE2 available, convert to v4f32 so the generated
2261           // register is legal.
2262           if (!Subtarget->hasSSE2())
2263             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2264         }
2265       }
2266     }
2267
2268     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2269     Flag = Chain.getValue(1);
2270     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2271   }
2272
2273   // All x86 ABIs require that for returning structs by value we copy
2274   // the sret argument into %rax/%eax (depending on ABI) for the return.
2275   // We saved the argument into a virtual register in the entry block,
2276   // so now we copy the value out and into %rax/%eax.
2277   //
2278   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2279   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2280   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2281   // either case FuncInfo->setSRetReturnReg() will have been called.
2282   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2283     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2284                                      getPointerTy(MF.getDataLayout()));
2285
2286     unsigned RetValReg
2287         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2288           X86::RAX : X86::EAX;
2289     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2290     Flag = Chain.getValue(1);
2291
2292     // RAX/EAX now acts like a return value.
2293     RetOps.push_back(
2294         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2295   }
2296
2297   RetOps[0] = Chain;  // Update chain.
2298
2299   // Add the flag if we have it.
2300   if (Flag.getNode())
2301     RetOps.push_back(Flag);
2302
2303   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2304 }
2305
2306 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2307   if (N->getNumValues() != 1)
2308     return false;
2309   if (!N->hasNUsesOfValue(1, 0))
2310     return false;
2311
2312   SDValue TCChain = Chain;
2313   SDNode *Copy = *N->use_begin();
2314   if (Copy->getOpcode() == ISD::CopyToReg) {
2315     // If the copy has a glue operand, we conservatively assume it isn't safe to
2316     // perform a tail call.
2317     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2318       return false;
2319     TCChain = Copy->getOperand(0);
2320   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2321     return false;
2322
2323   bool HasRet = false;
2324   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2325        UI != UE; ++UI) {
2326     if (UI->getOpcode() != X86ISD::RET_FLAG)
2327       return false;
2328     // If we are returning more than one value, we can definitely
2329     // not make a tail call see PR19530
2330     if (UI->getNumOperands() > 4)
2331       return false;
2332     if (UI->getNumOperands() == 4 &&
2333         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2334       return false;
2335     HasRet = true;
2336   }
2337
2338   if (!HasRet)
2339     return false;
2340
2341   Chain = TCChain;
2342   return true;
2343 }
2344
2345 EVT
2346 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2347                                             ISD::NodeType ExtendKind) const {
2348   MVT ReturnMVT;
2349   // TODO: Is this also valid on 32-bit?
2350   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2351     ReturnMVT = MVT::i8;
2352   else
2353     ReturnMVT = MVT::i32;
2354
2355   EVT MinVT = getRegisterType(Context, ReturnMVT);
2356   return VT.bitsLT(MinVT) ? MinVT : VT;
2357 }
2358
2359 /// Lower the result values of a call into the
2360 /// appropriate copies out of appropriate physical registers.
2361 ///
2362 SDValue
2363 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2364                                    CallingConv::ID CallConv, bool isVarArg,
2365                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2366                                    SDLoc dl, SelectionDAG &DAG,
2367                                    SmallVectorImpl<SDValue> &InVals) const {
2368
2369   // Assign locations to each value returned by this call.
2370   SmallVector<CCValAssign, 16> RVLocs;
2371   bool Is64Bit = Subtarget->is64Bit();
2372   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2373                  *DAG.getContext());
2374   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2375
2376   // Copy all of the result registers out of their specified physreg.
2377   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2378     CCValAssign &VA = RVLocs[i];
2379     EVT CopyVT = VA.getLocVT();
2380
2381     // If this is x86-64, and we disabled SSE, we can't return FP values
2382     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2383         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2384       report_fatal_error("SSE register return with SSE disabled");
2385     }
2386
2387     // If we prefer to use the value in xmm registers, copy it out as f80 and
2388     // use a truncate to move it from fp stack reg to xmm reg.
2389     bool RoundAfterCopy = false;
2390     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2391         isScalarFPTypeInSSEReg(VA.getValVT())) {
2392       CopyVT = MVT::f80;
2393       RoundAfterCopy = (CopyVT != VA.getLocVT());
2394     }
2395
2396     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2397                                CopyVT, InFlag).getValue(1);
2398     SDValue Val = Chain.getValue(0);
2399
2400     if (RoundAfterCopy)
2401       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2402                         // This truncation won't change the value.
2403                         DAG.getIntPtrConstant(1, dl));
2404
2405     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2406       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2407
2408     InFlag = Chain.getValue(2);
2409     InVals.push_back(Val);
2410   }
2411
2412   return Chain;
2413 }
2414
2415 //===----------------------------------------------------------------------===//
2416 //                C & StdCall & Fast Calling Convention implementation
2417 //===----------------------------------------------------------------------===//
2418 //  StdCall calling convention seems to be standard for many Windows' API
2419 //  routines and around. It differs from C calling convention just a little:
2420 //  callee should clean up the stack, not caller. Symbols should be also
2421 //  decorated in some fancy way :) It doesn't support any vector arguments.
2422 //  For info on fast calling convention see Fast Calling Convention (tail call)
2423 //  implementation LowerX86_32FastCCCallTo.
2424
2425 /// CallIsStructReturn - Determines whether a call uses struct return
2426 /// semantics.
2427 enum StructReturnType {
2428   NotStructReturn,
2429   RegStructReturn,
2430   StackStructReturn
2431 };
2432 static StructReturnType
2433 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2434   if (Outs.empty())
2435     return NotStructReturn;
2436
2437   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2438   if (!Flags.isSRet())
2439     return NotStructReturn;
2440   if (Flags.isInReg())
2441     return RegStructReturn;
2442   return StackStructReturn;
2443 }
2444
2445 /// Determines whether a function uses struct return semantics.
2446 static StructReturnType
2447 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2448   if (Ins.empty())
2449     return NotStructReturn;
2450
2451   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2452   if (!Flags.isSRet())
2453     return NotStructReturn;
2454   if (Flags.isInReg())
2455     return RegStructReturn;
2456   return StackStructReturn;
2457 }
2458
2459 /// Make a copy of an aggregate at address specified by "Src" to address
2460 /// "Dst" with size and alignment information specified by the specific
2461 /// parameter attribute. The copy will be passed as a byval function parameter.
2462 static SDValue
2463 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2464                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2465                           SDLoc dl) {
2466   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2467
2468   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2469                        /*isVolatile*/false, /*AlwaysInline=*/true,
2470                        /*isTailCall*/false,
2471                        MachinePointerInfo(), MachinePointerInfo());
2472 }
2473
2474 /// Return true if the calling convention is one that we can guarantee TCO for.
2475 static bool canGuaranteeTCO(CallingConv::ID CC) {
2476   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2477           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2478 }
2479
2480 /// Return true if we might ever do TCO for calls with this calling convention.
2481 static bool mayTailCallThisCC(CallingConv::ID CC) {
2482   switch (CC) {
2483   // C calling conventions:
2484   case CallingConv::C:
2485   case CallingConv::X86_64_Win64:
2486   case CallingConv::X86_64_SysV:
2487   // Callee pop conventions:
2488   case CallingConv::X86_ThisCall:
2489   case CallingConv::X86_StdCall:
2490   case CallingConv::X86_VectorCall:
2491   case CallingConv::X86_FastCall:
2492     return true;
2493   default:
2494     return canGuaranteeTCO(CC);
2495   }
2496 }
2497
2498 /// Return true if the function is being made into a tailcall target by
2499 /// changing its ABI.
2500 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2501   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2502 }
2503
2504 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2505   auto Attr =
2506       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2507   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2508     return false;
2509
2510   CallSite CS(CI);
2511   CallingConv::ID CalleeCC = CS.getCallingConv();
2512   if (!mayTailCallThisCC(CalleeCC))
2513     return false;
2514
2515   return true;
2516 }
2517
2518 SDValue
2519 X86TargetLowering::LowerMemArgument(SDValue Chain,
2520                                     CallingConv::ID CallConv,
2521                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2522                                     SDLoc dl, SelectionDAG &DAG,
2523                                     const CCValAssign &VA,
2524                                     MachineFrameInfo *MFI,
2525                                     unsigned i) const {
2526   // Create the nodes corresponding to a load from this parameter slot.
2527   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2528   bool AlwaysUseMutable = shouldGuaranteeTCO(
2529       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2530   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2531   EVT ValVT;
2532
2533   // If value is passed by pointer we have address passed instead of the value
2534   // itself.
2535   bool ExtendedInMem = VA.isExtInLoc() &&
2536     VA.getValVT().getScalarType() == MVT::i1;
2537
2538   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2539     ValVT = VA.getLocVT();
2540   else
2541     ValVT = VA.getValVT();
2542
2543   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2544   // changed with more analysis.
2545   // In case of tail call optimization mark all arguments mutable. Since they
2546   // could be overwritten by lowering of arguments in case of a tail call.
2547   if (Flags.isByVal()) {
2548     unsigned Bytes = Flags.getByValSize();
2549     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2550     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2551     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2552   } else {
2553     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2554                                     VA.getLocMemOffset(), isImmutable);
2555     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2556     SDValue Val = DAG.getLoad(
2557         ValVT, dl, Chain, FIN,
2558         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2559         false, false, 0);
2560     return ExtendedInMem ?
2561       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2562   }
2563 }
2564
2565 // FIXME: Get this from tablegen.
2566 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2567                                                 const X86Subtarget *Subtarget) {
2568   assert(Subtarget->is64Bit());
2569
2570   if (Subtarget->isCallingConvWin64(CallConv)) {
2571     static const MCPhysReg GPR64ArgRegsWin64[] = {
2572       X86::RCX, X86::RDX, X86::R8,  X86::R9
2573     };
2574     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2575   }
2576
2577   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2578     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2579   };
2580   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2581 }
2582
2583 // FIXME: Get this from tablegen.
2584 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2585                                                 CallingConv::ID CallConv,
2586                                                 const X86Subtarget *Subtarget) {
2587   assert(Subtarget->is64Bit());
2588   if (Subtarget->isCallingConvWin64(CallConv)) {
2589     // The XMM registers which might contain var arg parameters are shadowed
2590     // in their paired GPR.  So we only need to save the GPR to their home
2591     // slots.
2592     // TODO: __vectorcall will change this.
2593     return None;
2594   }
2595
2596   const Function *Fn = MF.getFunction();
2597   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2598   bool isSoftFloat = Subtarget->useSoftFloat();
2599   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2600          "SSE register cannot be used when SSE is disabled!");
2601   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2602     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2603     // registers.
2604     return None;
2605
2606   static const MCPhysReg XMMArgRegs64Bit[] = {
2607     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2608     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2609   };
2610   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2611 }
2612
2613 SDValue X86TargetLowering::LowerFormalArguments(
2614     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2615     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2616     SmallVectorImpl<SDValue> &InVals) const {
2617   MachineFunction &MF = DAG.getMachineFunction();
2618   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2619   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2620
2621   const Function* Fn = MF.getFunction();
2622   if (Fn->hasExternalLinkage() &&
2623       Subtarget->isTargetCygMing() &&
2624       Fn->getName() == "main")
2625     FuncInfo->setForceFramePointer(true);
2626
2627   MachineFrameInfo *MFI = MF.getFrameInfo();
2628   bool Is64Bit = Subtarget->is64Bit();
2629   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2630
2631   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2632          "Var args not supported with calling convention fastcc, ghc or hipe");
2633
2634   // Assign locations to all of the incoming arguments.
2635   SmallVector<CCValAssign, 16> ArgLocs;
2636   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2637
2638   // Allocate shadow area for Win64
2639   if (IsWin64)
2640     CCInfo.AllocateStack(32, 8);
2641
2642   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2643
2644   unsigned LastVal = ~0U;
2645   SDValue ArgValue;
2646   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2647     CCValAssign &VA = ArgLocs[i];
2648     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2649     // places.
2650     assert(VA.getValNo() != LastVal &&
2651            "Don't support value assigned to multiple locs yet");
2652     (void)LastVal;
2653     LastVal = VA.getValNo();
2654
2655     if (VA.isRegLoc()) {
2656       EVT RegVT = VA.getLocVT();
2657       const TargetRegisterClass *RC;
2658       if (RegVT == MVT::i32)
2659         RC = &X86::GR32RegClass;
2660       else if (Is64Bit && RegVT == MVT::i64)
2661         RC = &X86::GR64RegClass;
2662       else if (RegVT == MVT::f32)
2663         RC = &X86::FR32RegClass;
2664       else if (RegVT == MVT::f64)
2665         RC = &X86::FR64RegClass;
2666       else if (RegVT.is512BitVector())
2667         RC = &X86::VR512RegClass;
2668       else if (RegVT.is256BitVector())
2669         RC = &X86::VR256RegClass;
2670       else if (RegVT.is128BitVector())
2671         RC = &X86::VR128RegClass;
2672       else if (RegVT == MVT::x86mmx)
2673         RC = &X86::VR64RegClass;
2674       else if (RegVT == MVT::i1)
2675         RC = &X86::VK1RegClass;
2676       else if (RegVT == MVT::v8i1)
2677         RC = &X86::VK8RegClass;
2678       else if (RegVT == MVT::v16i1)
2679         RC = &X86::VK16RegClass;
2680       else if (RegVT == MVT::v32i1)
2681         RC = &X86::VK32RegClass;
2682       else if (RegVT == MVT::v64i1)
2683         RC = &X86::VK64RegClass;
2684       else
2685         llvm_unreachable("Unknown argument type!");
2686
2687       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2688       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2689
2690       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2691       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2692       // right size.
2693       if (VA.getLocInfo() == CCValAssign::SExt)
2694         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2695                                DAG.getValueType(VA.getValVT()));
2696       else if (VA.getLocInfo() == CCValAssign::ZExt)
2697         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2698                                DAG.getValueType(VA.getValVT()));
2699       else if (VA.getLocInfo() == CCValAssign::BCvt)
2700         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2701
2702       if (VA.isExtInLoc()) {
2703         // Handle MMX values passed in XMM regs.
2704         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2705           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2706         else
2707           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2708       }
2709     } else {
2710       assert(VA.isMemLoc());
2711       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2712     }
2713
2714     // If value is passed via pointer - do a load.
2715     if (VA.getLocInfo() == CCValAssign::Indirect)
2716       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2717                              MachinePointerInfo(), false, false, false, 0);
2718
2719     InVals.push_back(ArgValue);
2720   }
2721
2722   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2723     // All x86 ABIs require that for returning structs by value we copy the
2724     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2725     // the argument into a virtual register so that we can access it from the
2726     // return points.
2727     if (Ins[i].Flags.isSRet()) {
2728       unsigned Reg = FuncInfo->getSRetReturnReg();
2729       if (!Reg) {
2730         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2731         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2732         FuncInfo->setSRetReturnReg(Reg);
2733       }
2734       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2735       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2736       break;
2737     }
2738   }
2739
2740   unsigned StackSize = CCInfo.getNextStackOffset();
2741   // Align stack specially for tail calls.
2742   if (shouldGuaranteeTCO(CallConv,
2743                          MF.getTarget().Options.GuaranteedTailCallOpt))
2744     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2745
2746   // If the function takes variable number of arguments, make a frame index for
2747   // the start of the first vararg value... for expansion of llvm.va_start. We
2748   // can skip this if there are no va_start calls.
2749   if (MFI->hasVAStart() &&
2750       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2751                    CallConv != CallingConv::X86_ThisCall))) {
2752     FuncInfo->setVarArgsFrameIndex(
2753         MFI->CreateFixedObject(1, StackSize, true));
2754   }
2755
2756   MachineModuleInfo &MMI = MF.getMMI();
2757
2758   // Figure out if XMM registers are in use.
2759   assert(!(Subtarget->useSoftFloat() &&
2760            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2761          "SSE register cannot be used when SSE is disabled!");
2762
2763   // 64-bit calling conventions support varargs and register parameters, so we
2764   // have to do extra work to spill them in the prologue.
2765   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2766     // Find the first unallocated argument registers.
2767     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2768     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2769     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2770     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2771     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2772            "SSE register cannot be used when SSE is disabled!");
2773
2774     // Gather all the live in physical registers.
2775     SmallVector<SDValue, 6> LiveGPRs;
2776     SmallVector<SDValue, 8> LiveXMMRegs;
2777     SDValue ALVal;
2778     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2779       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2780       LiveGPRs.push_back(
2781           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2782     }
2783     if (!ArgXMMs.empty()) {
2784       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2785       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2786       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2787         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2788         LiveXMMRegs.push_back(
2789             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2790       }
2791     }
2792
2793     if (IsWin64) {
2794       // Get to the caller-allocated home save location.  Add 8 to account
2795       // for the return address.
2796       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2797       FuncInfo->setRegSaveFrameIndex(
2798           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2799       // Fixup to set vararg frame on shadow area (4 x i64).
2800       if (NumIntRegs < 4)
2801         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2802     } else {
2803       // For X86-64, if there are vararg parameters that are passed via
2804       // registers, then we must store them to their spots on the stack so
2805       // they may be loaded by deferencing the result of va_next.
2806       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2807       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2808       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2809           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2810     }
2811
2812     // Store the integer parameter registers.
2813     SmallVector<SDValue, 8> MemOps;
2814     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2815                                       getPointerTy(DAG.getDataLayout()));
2816     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2817     for (SDValue Val : LiveGPRs) {
2818       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2819                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2820       SDValue Store =
2821           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2822                        MachinePointerInfo::getFixedStack(
2823                            DAG.getMachineFunction(),
2824                            FuncInfo->getRegSaveFrameIndex(), Offset),
2825                        false, false, 0);
2826       MemOps.push_back(Store);
2827       Offset += 8;
2828     }
2829
2830     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2831       // Now store the XMM (fp + vector) parameter registers.
2832       SmallVector<SDValue, 12> SaveXMMOps;
2833       SaveXMMOps.push_back(Chain);
2834       SaveXMMOps.push_back(ALVal);
2835       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2836                              FuncInfo->getRegSaveFrameIndex(), dl));
2837       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2838                              FuncInfo->getVarArgsFPOffset(), dl));
2839       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2840                         LiveXMMRegs.end());
2841       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2842                                    MVT::Other, SaveXMMOps));
2843     }
2844
2845     if (!MemOps.empty())
2846       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2847   }
2848
2849   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2850     // Find the largest legal vector type.
2851     MVT VecVT = MVT::Other;
2852     // FIXME: Only some x86_32 calling conventions support AVX512.
2853     if (Subtarget->hasAVX512() &&
2854         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2855                      CallConv == CallingConv::Intel_OCL_BI)))
2856       VecVT = MVT::v16f32;
2857     else if (Subtarget->hasAVX())
2858       VecVT = MVT::v8f32;
2859     else if (Subtarget->hasSSE2())
2860       VecVT = MVT::v4f32;
2861
2862     // We forward some GPRs and some vector types.
2863     SmallVector<MVT, 2> RegParmTypes;
2864     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2865     RegParmTypes.push_back(IntVT);
2866     if (VecVT != MVT::Other)
2867       RegParmTypes.push_back(VecVT);
2868
2869     // Compute the set of forwarded registers. The rest are scratch.
2870     SmallVectorImpl<ForwardedRegister> &Forwards =
2871         FuncInfo->getForwardedMustTailRegParms();
2872     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2873
2874     // Conservatively forward AL on x86_64, since it might be used for varargs.
2875     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2876       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2877       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2878     }
2879
2880     // Copy all forwards from physical to virtual registers.
2881     for (ForwardedRegister &F : Forwards) {
2882       // FIXME: Can we use a less constrained schedule?
2883       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2884       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2885       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2886     }
2887   }
2888
2889   // Some CCs need callee pop.
2890   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2891                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2892     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2893   } else {
2894     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2895     // If this is an sret function, the return should pop the hidden pointer.
2896     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2897         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2898         argsAreStructReturn(Ins) == StackStructReturn)
2899       FuncInfo->setBytesToPopOnReturn(4);
2900   }
2901
2902   if (!Is64Bit) {
2903     // RegSaveFrameIndex is X86-64 only.
2904     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2905     if (CallConv == CallingConv::X86_FastCall ||
2906         CallConv == CallingConv::X86_ThisCall)
2907       // fastcc functions can't have varargs.
2908       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2909   }
2910
2911   FuncInfo->setArgumentStackSize(StackSize);
2912
2913   if (MMI.hasWinEHFuncInfo(Fn)) {
2914     if (Is64Bit) {
2915       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2916       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2917       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2918       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2919       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2920                            MachinePointerInfo::getFixedStack(
2921                                DAG.getMachineFunction(), UnwindHelpFI),
2922                            /*isVolatile=*/true,
2923                            /*isNonTemporal=*/false, /*Alignment=*/0);
2924     } else {
2925       // Functions using Win32 EH are considered to have opaque SP adjustments
2926       // to force local variables to be addressed from the frame or base
2927       // pointers.
2928       MFI->setHasOpaqueSPAdjustment(true);
2929     }
2930   }
2931
2932   return Chain;
2933 }
2934
2935 SDValue
2936 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2937                                     SDValue StackPtr, SDValue Arg,
2938                                     SDLoc dl, SelectionDAG &DAG,
2939                                     const CCValAssign &VA,
2940                                     ISD::ArgFlagsTy Flags) const {
2941   unsigned LocMemOffset = VA.getLocMemOffset();
2942   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2943   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2944                        StackPtr, PtrOff);
2945   if (Flags.isByVal())
2946     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2947
2948   return DAG.getStore(
2949       Chain, dl, Arg, PtrOff,
2950       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2951       false, false, 0);
2952 }
2953
2954 /// Emit a load of return address if tail call
2955 /// optimization is performed and it is required.
2956 SDValue
2957 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2958                                            SDValue &OutRetAddr, SDValue Chain,
2959                                            bool IsTailCall, bool Is64Bit,
2960                                            int FPDiff, SDLoc dl) const {
2961   // Adjust the Return address stack slot.
2962   EVT VT = getPointerTy(DAG.getDataLayout());
2963   OutRetAddr = getReturnAddressFrameIndex(DAG);
2964
2965   // Load the "old" Return address.
2966   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2967                            false, false, false, 0);
2968   return SDValue(OutRetAddr.getNode(), 1);
2969 }
2970
2971 /// Emit a store of the return address if tail call
2972 /// optimization is performed and it is required (FPDiff!=0).
2973 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2974                                         SDValue Chain, SDValue RetAddrFrIdx,
2975                                         EVT PtrVT, unsigned SlotSize,
2976                                         int FPDiff, SDLoc dl) {
2977   // Store the return address to the appropriate stack slot.
2978   if (!FPDiff) return Chain;
2979   // Calculate the new stack slot for the return address.
2980   int NewReturnAddrFI =
2981     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2982                                          false);
2983   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2984   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2985                        MachinePointerInfo::getFixedStack(
2986                            DAG.getMachineFunction(), NewReturnAddrFI),
2987                        false, false, 0);
2988   return Chain;
2989 }
2990
2991 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2992 /// operation of specified width.
2993 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2994                        SDValue V2) {
2995   unsigned NumElems = VT.getVectorNumElements();
2996   SmallVector<int, 8> Mask;
2997   Mask.push_back(NumElems);
2998   for (unsigned i = 1; i != NumElems; ++i)
2999     Mask.push_back(i);
3000   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3001 }
3002
3003 SDValue
3004 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3005                              SmallVectorImpl<SDValue> &InVals) const {
3006   SelectionDAG &DAG                     = CLI.DAG;
3007   SDLoc &dl                             = CLI.DL;
3008   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3009   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3010   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3011   SDValue Chain                         = CLI.Chain;
3012   SDValue Callee                        = CLI.Callee;
3013   CallingConv::ID CallConv              = CLI.CallConv;
3014   bool &isTailCall                      = CLI.IsTailCall;
3015   bool isVarArg                         = CLI.IsVarArg;
3016
3017   MachineFunction &MF = DAG.getMachineFunction();
3018   bool Is64Bit        = Subtarget->is64Bit();
3019   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3020   StructReturnType SR = callIsStructReturn(Outs);
3021   bool IsSibcall      = false;
3022   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3023   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3024
3025   if (Attr.getValueAsString() == "true")
3026     isTailCall = false;
3027
3028   if (Subtarget->isPICStyleGOT() &&
3029       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3030     // If we are using a GOT, disable tail calls to external symbols with
3031     // default visibility. Tail calling such a symbol requires using a GOT
3032     // relocation, which forces early binding of the symbol. This breaks code
3033     // that require lazy function symbol resolution. Using musttail or
3034     // GuaranteedTailCallOpt will override this.
3035     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3036     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3037                G->getGlobal()->hasDefaultVisibility()))
3038       isTailCall = false;
3039   }
3040
3041   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3042   if (IsMustTail) {
3043     // Force this to be a tail call.  The verifier rules are enough to ensure
3044     // that we can lower this successfully without moving the return address
3045     // around.
3046     isTailCall = true;
3047   } else if (isTailCall) {
3048     // Check if it's really possible to do a tail call.
3049     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3050                     isVarArg, SR != NotStructReturn,
3051                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3052                     Outs, OutVals, Ins, DAG);
3053
3054     // Sibcalls are automatically detected tailcalls which do not require
3055     // ABI changes.
3056     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3057       IsSibcall = true;
3058
3059     if (isTailCall)
3060       ++NumTailCalls;
3061   }
3062
3063   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3064          "Var args not supported with calling convention fastcc, ghc or hipe");
3065
3066   // Analyze operands of the call, assigning locations to each operand.
3067   SmallVector<CCValAssign, 16> ArgLocs;
3068   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3069
3070   // Allocate shadow area for Win64
3071   if (IsWin64)
3072     CCInfo.AllocateStack(32, 8);
3073
3074   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3075
3076   // Get a count of how many bytes are to be pushed on the stack.
3077   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3078   if (IsSibcall)
3079     // This is a sibcall. The memory operands are available in caller's
3080     // own caller's stack.
3081     NumBytes = 0;
3082   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3083            canGuaranteeTCO(CallConv))
3084     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3085
3086   int FPDiff = 0;
3087   if (isTailCall && !IsSibcall && !IsMustTail) {
3088     // Lower arguments at fp - stackoffset + fpdiff.
3089     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3090
3091     FPDiff = NumBytesCallerPushed - NumBytes;
3092
3093     // Set the delta of movement of the returnaddr stackslot.
3094     // But only set if delta is greater than previous delta.
3095     if (FPDiff < X86Info->getTCReturnAddrDelta())
3096       X86Info->setTCReturnAddrDelta(FPDiff);
3097   }
3098
3099   unsigned NumBytesToPush = NumBytes;
3100   unsigned NumBytesToPop = NumBytes;
3101
3102   // If we have an inalloca argument, all stack space has already been allocated
3103   // for us and be right at the top of the stack.  We don't support multiple
3104   // arguments passed in memory when using inalloca.
3105   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3106     NumBytesToPush = 0;
3107     if (!ArgLocs.back().isMemLoc())
3108       report_fatal_error("cannot use inalloca attribute on a register "
3109                          "parameter");
3110     if (ArgLocs.back().getLocMemOffset() != 0)
3111       report_fatal_error("any parameter with the inalloca attribute must be "
3112                          "the only memory argument");
3113   }
3114
3115   if (!IsSibcall)
3116     Chain = DAG.getCALLSEQ_START(
3117         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3118
3119   SDValue RetAddrFrIdx;
3120   // Load return address for tail calls.
3121   if (isTailCall && FPDiff)
3122     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3123                                     Is64Bit, FPDiff, dl);
3124
3125   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3126   SmallVector<SDValue, 8> MemOpChains;
3127   SDValue StackPtr;
3128
3129   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3130   // of tail call optimization arguments are handle later.
3131   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3132   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3133     // Skip inalloca arguments, they have already been written.
3134     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3135     if (Flags.isInAlloca())
3136       continue;
3137
3138     CCValAssign &VA = ArgLocs[i];
3139     EVT RegVT = VA.getLocVT();
3140     SDValue Arg = OutVals[i];
3141     bool isByVal = Flags.isByVal();
3142
3143     // Promote the value if needed.
3144     switch (VA.getLocInfo()) {
3145     default: llvm_unreachable("Unknown loc info!");
3146     case CCValAssign::Full: break;
3147     case CCValAssign::SExt:
3148       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3149       break;
3150     case CCValAssign::ZExt:
3151       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3152       break;
3153     case CCValAssign::AExt:
3154       if (Arg.getValueType().isVector() &&
3155           Arg.getValueType().getScalarType() == MVT::i1)
3156         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3157       else if (RegVT.is128BitVector()) {
3158         // Special case: passing MMX values in XMM registers.
3159         Arg = DAG.getBitcast(MVT::i64, Arg);
3160         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3161         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3162       } else
3163         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3164       break;
3165     case CCValAssign::BCvt:
3166       Arg = DAG.getBitcast(RegVT, Arg);
3167       break;
3168     case CCValAssign::Indirect: {
3169       // Store the argument.
3170       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3171       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3172       Chain = DAG.getStore(
3173           Chain, dl, Arg, SpillSlot,
3174           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3175           false, false, 0);
3176       Arg = SpillSlot;
3177       break;
3178     }
3179     }
3180
3181     if (VA.isRegLoc()) {
3182       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3183       if (isVarArg && IsWin64) {
3184         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3185         // shadow reg if callee is a varargs function.
3186         unsigned ShadowReg = 0;
3187         switch (VA.getLocReg()) {
3188         case X86::XMM0: ShadowReg = X86::RCX; break;
3189         case X86::XMM1: ShadowReg = X86::RDX; break;
3190         case X86::XMM2: ShadowReg = X86::R8; break;
3191         case X86::XMM3: ShadowReg = X86::R9; break;
3192         }
3193         if (ShadowReg)
3194           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3195       }
3196     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3197       assert(VA.isMemLoc());
3198       if (!StackPtr.getNode())
3199         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3200                                       getPointerTy(DAG.getDataLayout()));
3201       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3202                                              dl, DAG, VA, Flags));
3203     }
3204   }
3205
3206   if (!MemOpChains.empty())
3207     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3208
3209   if (Subtarget->isPICStyleGOT()) {
3210     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3211     // GOT pointer.
3212     if (!isTailCall) {
3213       RegsToPass.push_back(std::make_pair(
3214           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3215                                           getPointerTy(DAG.getDataLayout()))));
3216     } else {
3217       // If we are tail calling and generating PIC/GOT style code load the
3218       // address of the callee into ECX. The value in ecx is used as target of
3219       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3220       // for tail calls on PIC/GOT architectures. Normally we would just put the
3221       // address of GOT into ebx and then call target@PLT. But for tail calls
3222       // ebx would be restored (since ebx is callee saved) before jumping to the
3223       // target@PLT.
3224
3225       // Note: The actual moving to ECX is done further down.
3226       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3227       if (G && !G->getGlobal()->hasLocalLinkage() &&
3228           G->getGlobal()->hasDefaultVisibility())
3229         Callee = LowerGlobalAddress(Callee, DAG);
3230       else if (isa<ExternalSymbolSDNode>(Callee))
3231         Callee = LowerExternalSymbol(Callee, DAG);
3232     }
3233   }
3234
3235   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3236     // From AMD64 ABI document:
3237     // For calls that may call functions that use varargs or stdargs
3238     // (prototype-less calls or calls to functions containing ellipsis (...) in
3239     // the declaration) %al is used as hidden argument to specify the number
3240     // of SSE registers used. The contents of %al do not need to match exactly
3241     // the number of registers, but must be an ubound on the number of SSE
3242     // registers used and is in the range 0 - 8 inclusive.
3243
3244     // Count the number of XMM registers allocated.
3245     static const MCPhysReg XMMArgRegs[] = {
3246       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3247       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3248     };
3249     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3250     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3251            && "SSE registers cannot be used when SSE is disabled");
3252
3253     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3254                                         DAG.getConstant(NumXMMRegs, dl,
3255                                                         MVT::i8)));
3256   }
3257
3258   if (isVarArg && IsMustTail) {
3259     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3260     for (const auto &F : Forwards) {
3261       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3262       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3263     }
3264   }
3265
3266   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3267   // don't need this because the eligibility check rejects calls that require
3268   // shuffling arguments passed in memory.
3269   if (!IsSibcall && isTailCall) {
3270     // Force all the incoming stack arguments to be loaded from the stack
3271     // before any new outgoing arguments are stored to the stack, because the
3272     // outgoing stack slots may alias the incoming argument stack slots, and
3273     // the alias isn't otherwise explicit. This is slightly more conservative
3274     // than necessary, because it means that each store effectively depends
3275     // on every argument instead of just those arguments it would clobber.
3276     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3277
3278     SmallVector<SDValue, 8> MemOpChains2;
3279     SDValue FIN;
3280     int FI = 0;
3281     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3282       CCValAssign &VA = ArgLocs[i];
3283       if (VA.isRegLoc())
3284         continue;
3285       assert(VA.isMemLoc());
3286       SDValue Arg = OutVals[i];
3287       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3288       // Skip inalloca arguments.  They don't require any work.
3289       if (Flags.isInAlloca())
3290         continue;
3291       // Create frame index.
3292       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3293       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3294       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3295       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3296
3297       if (Flags.isByVal()) {
3298         // Copy relative to framepointer.
3299         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3300         if (!StackPtr.getNode())
3301           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3302                                         getPointerTy(DAG.getDataLayout()));
3303         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3304                              StackPtr, Source);
3305
3306         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3307                                                          ArgChain,
3308                                                          Flags, DAG, dl));
3309       } else {
3310         // Store relative to framepointer.
3311         MemOpChains2.push_back(DAG.getStore(
3312             ArgChain, dl, Arg, FIN,
3313             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3314             false, false, 0));
3315       }
3316     }
3317
3318     if (!MemOpChains2.empty())
3319       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3320
3321     // Store the return address to the appropriate stack slot.
3322     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3323                                      getPointerTy(DAG.getDataLayout()),
3324                                      RegInfo->getSlotSize(), FPDiff, dl);
3325   }
3326
3327   // Build a sequence of copy-to-reg nodes chained together with token chain
3328   // and flag operands which copy the outgoing args into registers.
3329   SDValue InFlag;
3330   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3331     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3332                              RegsToPass[i].second, InFlag);
3333     InFlag = Chain.getValue(1);
3334   }
3335
3336   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3337     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3338     // In the 64-bit large code model, we have to make all calls
3339     // through a register, since the call instruction's 32-bit
3340     // pc-relative offset may not be large enough to hold the whole
3341     // address.
3342   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3343     // If the callee is a GlobalAddress node (quite common, every direct call
3344     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3345     // it.
3346     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3347
3348     // We should use extra load for direct calls to dllimported functions in
3349     // non-JIT mode.
3350     const GlobalValue *GV = G->getGlobal();
3351     if (!GV->hasDLLImportStorageClass()) {
3352       unsigned char OpFlags = 0;
3353       bool ExtraLoad = false;
3354       unsigned WrapperKind = ISD::DELETED_NODE;
3355
3356       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3357       // external symbols most go through the PLT in PIC mode.  If the symbol
3358       // has hidden or protected visibility, or if it is static or local, then
3359       // we don't need to use the PLT - we can directly call it.
3360       if (Subtarget->isTargetELF() &&
3361           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3362           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3363         OpFlags = X86II::MO_PLT;
3364       } else if (Subtarget->isPICStyleStubAny() &&
3365                  !GV->isStrongDefinitionForLinker() &&
3366                  (!Subtarget->getTargetTriple().isMacOSX() ||
3367                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3368         // PC-relative references to external symbols should go through $stub,
3369         // unless we're building with the leopard linker or later, which
3370         // automatically synthesizes these stubs.
3371         OpFlags = X86II::MO_DARWIN_STUB;
3372       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3373                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3374         // If the function is marked as non-lazy, generate an indirect call
3375         // which loads from the GOT directly. This avoids runtime overhead
3376         // at the cost of eager binding (and one extra byte of encoding).
3377         OpFlags = X86II::MO_GOTPCREL;
3378         WrapperKind = X86ISD::WrapperRIP;
3379         ExtraLoad = true;
3380       }
3381
3382       Callee = DAG.getTargetGlobalAddress(
3383           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3384
3385       // Add a wrapper if needed.
3386       if (WrapperKind != ISD::DELETED_NODE)
3387         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3388                              getPointerTy(DAG.getDataLayout()), Callee);
3389       // Add extra indirection if needed.
3390       if (ExtraLoad)
3391         Callee = DAG.getLoad(
3392             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3393             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3394             false, 0);
3395     }
3396   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3397     unsigned char OpFlags = 0;
3398
3399     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3400     // external symbols should go through the PLT.
3401     if (Subtarget->isTargetELF() &&
3402         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3403       OpFlags = X86II::MO_PLT;
3404     } else if (Subtarget->isPICStyleStubAny() &&
3405                (!Subtarget->getTargetTriple().isMacOSX() ||
3406                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3407       // PC-relative references to external symbols should go through $stub,
3408       // unless we're building with the leopard linker or later, which
3409       // automatically synthesizes these stubs.
3410       OpFlags = X86II::MO_DARWIN_STUB;
3411     }
3412
3413     Callee = DAG.getTargetExternalSymbol(
3414         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3415   } else if (Subtarget->isTarget64BitILP32() &&
3416              Callee->getValueType(0) == MVT::i32) {
3417     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3418     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3419   }
3420
3421   // Returns a chain & a flag for retval copy to use.
3422   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3423   SmallVector<SDValue, 8> Ops;
3424
3425   if (!IsSibcall && isTailCall) {
3426     Chain = DAG.getCALLSEQ_END(Chain,
3427                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3428                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3429     InFlag = Chain.getValue(1);
3430   }
3431
3432   Ops.push_back(Chain);
3433   Ops.push_back(Callee);
3434
3435   if (isTailCall)
3436     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3437
3438   // Add argument registers to the end of the list so that they are known live
3439   // into the call.
3440   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3441     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3442                                   RegsToPass[i].second.getValueType()));
3443
3444   // Add a register mask operand representing the call-preserved registers.
3445   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3446   assert(Mask && "Missing call preserved mask for calling convention");
3447
3448   // If this is an invoke in a 32-bit function using a funclet-based
3449   // personality, assume the function clobbers all registers. If an exception
3450   // is thrown, the runtime will not restore CSRs.
3451   // FIXME: Model this more precisely so that we can register allocate across
3452   // the normal edge and spill and fill across the exceptional edge.
3453   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3454     const Function *CallerFn = MF.getFunction();
3455     EHPersonality Pers =
3456         CallerFn->hasPersonalityFn()
3457             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3458             : EHPersonality::Unknown;
3459     if (isFuncletEHPersonality(Pers))
3460       Mask = RegInfo->getNoPreservedMask();
3461   }
3462
3463   Ops.push_back(DAG.getRegisterMask(Mask));
3464
3465   if (InFlag.getNode())
3466     Ops.push_back(InFlag);
3467
3468   if (isTailCall) {
3469     // We used to do:
3470     //// If this is the first return lowered for this function, add the regs
3471     //// to the liveout set for the function.
3472     // This isn't right, although it's probably harmless on x86; liveouts
3473     // should be computed from returns not tail calls.  Consider a void
3474     // function making a tail call to a function returning int.
3475     MF.getFrameInfo()->setHasTailCall();
3476     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3477   }
3478
3479   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3480   InFlag = Chain.getValue(1);
3481
3482   // Create the CALLSEQ_END node.
3483   unsigned NumBytesForCalleeToPop;
3484   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3485                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3486     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3487   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3488            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3489            SR == StackStructReturn)
3490     // If this is a call to a struct-return function, the callee
3491     // pops the hidden struct pointer, so we have to push it back.
3492     // This is common for Darwin/X86, Linux & Mingw32 targets.
3493     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3494     NumBytesForCalleeToPop = 4;
3495   else
3496     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3497
3498   // Returns a flag for retval copy to use.
3499   if (!IsSibcall) {
3500     Chain = DAG.getCALLSEQ_END(Chain,
3501                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3502                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3503                                                      true),
3504                                InFlag, dl);
3505     InFlag = Chain.getValue(1);
3506   }
3507
3508   // Handle result values, copying them out of physregs into vregs that we
3509   // return.
3510   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3511                          Ins, dl, DAG, InVals);
3512 }
3513
3514 //===----------------------------------------------------------------------===//
3515 //                Fast Calling Convention (tail call) implementation
3516 //===----------------------------------------------------------------------===//
3517
3518 //  Like std call, callee cleans arguments, convention except that ECX is
3519 //  reserved for storing the tail called function address. Only 2 registers are
3520 //  free for argument passing (inreg). Tail call optimization is performed
3521 //  provided:
3522 //                * tailcallopt is enabled
3523 //                * caller/callee are fastcc
3524 //  On X86_64 architecture with GOT-style position independent code only local
3525 //  (within module) calls are supported at the moment.
3526 //  To keep the stack aligned according to platform abi the function
3527 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3528 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3529 //  If a tail called function callee has more arguments than the caller the
3530 //  caller needs to make sure that there is room to move the RETADDR to. This is
3531 //  achieved by reserving an area the size of the argument delta right after the
3532 //  original RETADDR, but before the saved framepointer or the spilled registers
3533 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3534 //  stack layout:
3535 //    arg1
3536 //    arg2
3537 //    RETADDR
3538 //    [ new RETADDR
3539 //      move area ]
3540 //    (possible EBP)
3541 //    ESI
3542 //    EDI
3543 //    local1 ..
3544
3545 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3546 /// requirement.
3547 unsigned
3548 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3549                                                SelectionDAG& DAG) const {
3550   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3551   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3552   unsigned StackAlignment = TFI.getStackAlignment();
3553   uint64_t AlignMask = StackAlignment - 1;
3554   int64_t Offset = StackSize;
3555   unsigned SlotSize = RegInfo->getSlotSize();
3556   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3557     // Number smaller than 12 so just add the difference.
3558     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3559   } else {
3560     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3561     Offset = ((~AlignMask) & Offset) + StackAlignment +
3562       (StackAlignment-SlotSize);
3563   }
3564   return Offset;
3565 }
3566
3567 /// Return true if the given stack call argument is already available in the
3568 /// same position (relatively) of the caller's incoming argument stack.
3569 static
3570 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3571                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3572                          const X86InstrInfo *TII) {
3573   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3574   int FI = INT_MAX;
3575   if (Arg.getOpcode() == ISD::CopyFromReg) {
3576     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3577     if (!TargetRegisterInfo::isVirtualRegister(VR))
3578       return false;
3579     MachineInstr *Def = MRI->getVRegDef(VR);
3580     if (!Def)
3581       return false;
3582     if (!Flags.isByVal()) {
3583       if (!TII->isLoadFromStackSlot(Def, FI))
3584         return false;
3585     } else {
3586       unsigned Opcode = Def->getOpcode();
3587       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3588            Opcode == X86::LEA64_32r) &&
3589           Def->getOperand(1).isFI()) {
3590         FI = Def->getOperand(1).getIndex();
3591         Bytes = Flags.getByValSize();
3592       } else
3593         return false;
3594     }
3595   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3596     if (Flags.isByVal())
3597       // ByVal argument is passed in as a pointer but it's now being
3598       // dereferenced. e.g.
3599       // define @foo(%struct.X* %A) {
3600       //   tail call @bar(%struct.X* byval %A)
3601       // }
3602       return false;
3603     SDValue Ptr = Ld->getBasePtr();
3604     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3605     if (!FINode)
3606       return false;
3607     FI = FINode->getIndex();
3608   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3609     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3610     FI = FINode->getIndex();
3611     Bytes = Flags.getByValSize();
3612   } else
3613     return false;
3614
3615   assert(FI != INT_MAX);
3616   if (!MFI->isFixedObjectIndex(FI))
3617     return false;
3618   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3619 }
3620
3621 /// Check whether the call is eligible for tail call optimization. Targets
3622 /// that want to do tail call optimization should implement this function.
3623 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3624     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3625     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3626     const SmallVectorImpl<ISD::OutputArg> &Outs,
3627     const SmallVectorImpl<SDValue> &OutVals,
3628     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3629   if (!mayTailCallThisCC(CalleeCC))
3630     return false;
3631
3632   // If -tailcallopt is specified, make fastcc functions tail-callable.
3633   MachineFunction &MF = DAG.getMachineFunction();
3634   const Function *CallerF = MF.getFunction();
3635
3636   // If the function return type is x86_fp80 and the callee return type is not,
3637   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3638   // perform a tailcall optimization here.
3639   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3640     return false;
3641
3642   CallingConv::ID CallerCC = CallerF->getCallingConv();
3643   bool CCMatch = CallerCC == CalleeCC;
3644   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3645   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3646
3647   // Win64 functions have extra shadow space for argument homing. Don't do the
3648   // sibcall if the caller and callee have mismatched expectations for this
3649   // space.
3650   if (IsCalleeWin64 != IsCallerWin64)
3651     return false;
3652
3653   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3654     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3655       return true;
3656     return false;
3657   }
3658
3659   // Look for obvious safe cases to perform tail call optimization that do not
3660   // require ABI changes. This is what gcc calls sibcall.
3661
3662   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3663   // emit a special epilogue.
3664   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3665   if (RegInfo->needsStackRealignment(MF))
3666     return false;
3667
3668   // Also avoid sibcall optimization if either caller or callee uses struct
3669   // return semantics.
3670   if (isCalleeStructRet || isCallerStructRet)
3671     return false;
3672
3673   // Do not sibcall optimize vararg calls unless all arguments are passed via
3674   // registers.
3675   if (isVarArg && !Outs.empty()) {
3676     // Optimizing for varargs on Win64 is unlikely to be safe without
3677     // additional testing.
3678     if (IsCalleeWin64 || IsCallerWin64)
3679       return false;
3680
3681     SmallVector<CCValAssign, 16> ArgLocs;
3682     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3683                    *DAG.getContext());
3684
3685     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3686     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3687       if (!ArgLocs[i].isRegLoc())
3688         return false;
3689   }
3690
3691   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3692   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3693   // this into a sibcall.
3694   bool Unused = false;
3695   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3696     if (!Ins[i].Used) {
3697       Unused = true;
3698       break;
3699     }
3700   }
3701   if (Unused) {
3702     SmallVector<CCValAssign, 16> RVLocs;
3703     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3704                    *DAG.getContext());
3705     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3706     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3707       CCValAssign &VA = RVLocs[i];
3708       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3709         return false;
3710     }
3711   }
3712
3713   // If the calling conventions do not match, then we'd better make sure the
3714   // results are returned in the same way as what the caller expects.
3715   if (!CCMatch) {
3716     SmallVector<CCValAssign, 16> RVLocs1;
3717     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3718                     *DAG.getContext());
3719     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3720
3721     SmallVector<CCValAssign, 16> RVLocs2;
3722     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3723                     *DAG.getContext());
3724     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3725
3726     if (RVLocs1.size() != RVLocs2.size())
3727       return false;
3728     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3729       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3730         return false;
3731       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3732         return false;
3733       if (RVLocs1[i].isRegLoc()) {
3734         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3735           return false;
3736       } else {
3737         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3738           return false;
3739       }
3740     }
3741   }
3742
3743   unsigned StackArgsSize = 0;
3744
3745   // If the callee takes no arguments then go on to check the results of the
3746   // call.
3747   if (!Outs.empty()) {
3748     // Check if stack adjustment is needed. For now, do not do this if any
3749     // argument is passed on the stack.
3750     SmallVector<CCValAssign, 16> ArgLocs;
3751     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3752                    *DAG.getContext());
3753
3754     // Allocate shadow area for Win64
3755     if (IsCalleeWin64)
3756       CCInfo.AllocateStack(32, 8);
3757
3758     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3759     StackArgsSize = CCInfo.getNextStackOffset();
3760
3761     if (CCInfo.getNextStackOffset()) {
3762       // Check if the arguments are already laid out in the right way as
3763       // the caller's fixed stack objects.
3764       MachineFrameInfo *MFI = MF.getFrameInfo();
3765       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3766       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3767       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3768         CCValAssign &VA = ArgLocs[i];
3769         SDValue Arg = OutVals[i];
3770         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3771         if (VA.getLocInfo() == CCValAssign::Indirect)
3772           return false;
3773         if (!VA.isRegLoc()) {
3774           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3775                                    MFI, MRI, TII))
3776             return false;
3777         }
3778       }
3779     }
3780
3781     // If the tailcall address may be in a register, then make sure it's
3782     // possible to register allocate for it. In 32-bit, the call address can
3783     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3784     // callee-saved registers are restored. These happen to be the same
3785     // registers used to pass 'inreg' arguments so watch out for those.
3786     if (!Subtarget->is64Bit() &&
3787         ((!isa<GlobalAddressSDNode>(Callee) &&
3788           !isa<ExternalSymbolSDNode>(Callee)) ||
3789          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3790       unsigned NumInRegs = 0;
3791       // In PIC we need an extra register to formulate the address computation
3792       // for the callee.
3793       unsigned MaxInRegs =
3794         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3795
3796       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3797         CCValAssign &VA = ArgLocs[i];
3798         if (!VA.isRegLoc())
3799           continue;
3800         unsigned Reg = VA.getLocReg();
3801         switch (Reg) {
3802         default: break;
3803         case X86::EAX: case X86::EDX: case X86::ECX:
3804           if (++NumInRegs == MaxInRegs)
3805             return false;
3806           break;
3807         }
3808       }
3809     }
3810   }
3811
3812   bool CalleeWillPop =
3813       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3814                        MF.getTarget().Options.GuaranteedTailCallOpt);
3815
3816   if (unsigned BytesToPop =
3817           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3818     // If we have bytes to pop, the callee must pop them.
3819     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3820     if (!CalleePopMatches)
3821       return false;
3822   } else if (CalleeWillPop && StackArgsSize > 0) {
3823     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3824     return false;
3825   }
3826
3827   return true;
3828 }
3829
3830 FastISel *
3831 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3832                                   const TargetLibraryInfo *libInfo) const {
3833   return X86::createFastISel(funcInfo, libInfo);
3834 }
3835
3836 //===----------------------------------------------------------------------===//
3837 //                           Other Lowering Hooks
3838 //===----------------------------------------------------------------------===//
3839
3840 static bool MayFoldLoad(SDValue Op) {
3841   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3842 }
3843
3844 static bool MayFoldIntoStore(SDValue Op) {
3845   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3846 }
3847
3848 static bool isTargetShuffle(unsigned Opcode) {
3849   switch(Opcode) {
3850   default: return false;
3851   case X86ISD::BLENDI:
3852   case X86ISD::PSHUFB:
3853   case X86ISD::PSHUFD:
3854   case X86ISD::PSHUFHW:
3855   case X86ISD::PSHUFLW:
3856   case X86ISD::SHUFP:
3857   case X86ISD::PALIGNR:
3858   case X86ISD::MOVLHPS:
3859   case X86ISD::MOVLHPD:
3860   case X86ISD::MOVHLPS:
3861   case X86ISD::MOVLPS:
3862   case X86ISD::MOVLPD:
3863   case X86ISD::MOVSHDUP:
3864   case X86ISD::MOVSLDUP:
3865   case X86ISD::MOVDDUP:
3866   case X86ISD::MOVSS:
3867   case X86ISD::MOVSD:
3868   case X86ISD::UNPCKL:
3869   case X86ISD::UNPCKH:
3870   case X86ISD::VPERMILPI:
3871   case X86ISD::VPERM2X128:
3872   case X86ISD::VPERMI:
3873   case X86ISD::VPERMV:
3874   case X86ISD::VPERMV3:
3875     return true;
3876   }
3877 }
3878
3879 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3880                                     SDValue V1, unsigned TargetMask,
3881                                     SelectionDAG &DAG) {
3882   switch(Opc) {
3883   default: llvm_unreachable("Unknown x86 shuffle node");
3884   case X86ISD::PSHUFD:
3885   case X86ISD::PSHUFHW:
3886   case X86ISD::PSHUFLW:
3887   case X86ISD::VPERMILPI:
3888   case X86ISD::VPERMI:
3889     return DAG.getNode(Opc, dl, VT, V1,
3890                        DAG.getConstant(TargetMask, dl, MVT::i8));
3891   }
3892 }
3893
3894 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3895                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3896   switch(Opc) {
3897   default: llvm_unreachable("Unknown x86 shuffle node");
3898   case X86ISD::MOVLHPS:
3899   case X86ISD::MOVLHPD:
3900   case X86ISD::MOVHLPS:
3901   case X86ISD::MOVLPS:
3902   case X86ISD::MOVLPD:
3903   case X86ISD::MOVSS:
3904   case X86ISD::MOVSD:
3905   case X86ISD::UNPCKL:
3906   case X86ISD::UNPCKH:
3907     return DAG.getNode(Opc, dl, VT, V1, V2);
3908   }
3909 }
3910
3911 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3912   MachineFunction &MF = DAG.getMachineFunction();
3913   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3914   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3915   int ReturnAddrIndex = FuncInfo->getRAIndex();
3916
3917   if (ReturnAddrIndex == 0) {
3918     // Set up a frame object for the return address.
3919     unsigned SlotSize = RegInfo->getSlotSize();
3920     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3921                                                            -(int64_t)SlotSize,
3922                                                            false);
3923     FuncInfo->setRAIndex(ReturnAddrIndex);
3924   }
3925
3926   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3927 }
3928
3929 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3930                                        bool hasSymbolicDisplacement) {
3931   // Offset should fit into 32 bit immediate field.
3932   if (!isInt<32>(Offset))
3933     return false;
3934
3935   // If we don't have a symbolic displacement - we don't have any extra
3936   // restrictions.
3937   if (!hasSymbolicDisplacement)
3938     return true;
3939
3940   // FIXME: Some tweaks might be needed for medium code model.
3941   if (M != CodeModel::Small && M != CodeModel::Kernel)
3942     return false;
3943
3944   // For small code model we assume that latest object is 16MB before end of 31
3945   // bits boundary. We may also accept pretty large negative constants knowing
3946   // that all objects are in the positive half of address space.
3947   if (M == CodeModel::Small && Offset < 16*1024*1024)
3948     return true;
3949
3950   // For kernel code model we know that all object resist in the negative half
3951   // of 32bits address space. We may not accept negative offsets, since they may
3952   // be just off and we may accept pretty large positive ones.
3953   if (M == CodeModel::Kernel && Offset >= 0)
3954     return true;
3955
3956   return false;
3957 }
3958
3959 /// Determines whether the callee is required to pop its own arguments.
3960 /// Callee pop is necessary to support tail calls.
3961 bool X86::isCalleePop(CallingConv::ID CallingConv,
3962                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3963   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3964   // can guarantee TCO.
3965   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3966     return true;
3967
3968   switch (CallingConv) {
3969   default:
3970     return false;
3971   case CallingConv::X86_StdCall:
3972   case CallingConv::X86_FastCall:
3973   case CallingConv::X86_ThisCall:
3974   case CallingConv::X86_VectorCall:
3975     return !is64Bit;
3976   }
3977 }
3978
3979 /// \brief Return true if the condition is an unsigned comparison operation.
3980 static bool isX86CCUnsigned(unsigned X86CC) {
3981   switch (X86CC) {
3982   default: llvm_unreachable("Invalid integer condition!");
3983   case X86::COND_E:     return true;
3984   case X86::COND_G:     return false;
3985   case X86::COND_GE:    return false;
3986   case X86::COND_L:     return false;
3987   case X86::COND_LE:    return false;
3988   case X86::COND_NE:    return true;
3989   case X86::COND_B:     return true;
3990   case X86::COND_A:     return true;
3991   case X86::COND_BE:    return true;
3992   case X86::COND_AE:    return true;
3993   }
3994   llvm_unreachable("covered switch fell through?!");
3995 }
3996
3997 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3998 /// condition code, returning the condition code and the LHS/RHS of the
3999 /// comparison to make.
4000 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4001                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4002   if (!isFP) {
4003     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4004       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4005         // X > -1   -> X == 0, jump !sign.
4006         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4007         return X86::COND_NS;
4008       }
4009       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4010         // X < 0   -> X == 0, jump on sign.
4011         return X86::COND_S;
4012       }
4013       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4014         // X < 1   -> X <= 0
4015         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4016         return X86::COND_LE;
4017       }
4018     }
4019
4020     switch (SetCCOpcode) {
4021     default: llvm_unreachable("Invalid integer condition!");
4022     case ISD::SETEQ:  return X86::COND_E;
4023     case ISD::SETGT:  return X86::COND_G;
4024     case ISD::SETGE:  return X86::COND_GE;
4025     case ISD::SETLT:  return X86::COND_L;
4026     case ISD::SETLE:  return X86::COND_LE;
4027     case ISD::SETNE:  return X86::COND_NE;
4028     case ISD::SETULT: return X86::COND_B;
4029     case ISD::SETUGT: return X86::COND_A;
4030     case ISD::SETULE: return X86::COND_BE;
4031     case ISD::SETUGE: return X86::COND_AE;
4032     }
4033   }
4034
4035   // First determine if it is required or is profitable to flip the operands.
4036
4037   // If LHS is a foldable load, but RHS is not, flip the condition.
4038   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4039       !ISD::isNON_EXTLoad(RHS.getNode())) {
4040     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4041     std::swap(LHS, RHS);
4042   }
4043
4044   switch (SetCCOpcode) {
4045   default: break;
4046   case ISD::SETOLT:
4047   case ISD::SETOLE:
4048   case ISD::SETUGT:
4049   case ISD::SETUGE:
4050     std::swap(LHS, RHS);
4051     break;
4052   }
4053
4054   // On a floating point condition, the flags are set as follows:
4055   // ZF  PF  CF   op
4056   //  0 | 0 | 0 | X > Y
4057   //  0 | 0 | 1 | X < Y
4058   //  1 | 0 | 0 | X == Y
4059   //  1 | 1 | 1 | unordered
4060   switch (SetCCOpcode) {
4061   default: llvm_unreachable("Condcode should be pre-legalized away");
4062   case ISD::SETUEQ:
4063   case ISD::SETEQ:   return X86::COND_E;
4064   case ISD::SETOLT:              // flipped
4065   case ISD::SETOGT:
4066   case ISD::SETGT:   return X86::COND_A;
4067   case ISD::SETOLE:              // flipped
4068   case ISD::SETOGE:
4069   case ISD::SETGE:   return X86::COND_AE;
4070   case ISD::SETUGT:              // flipped
4071   case ISD::SETULT:
4072   case ISD::SETLT:   return X86::COND_B;
4073   case ISD::SETUGE:              // flipped
4074   case ISD::SETULE:
4075   case ISD::SETLE:   return X86::COND_BE;
4076   case ISD::SETONE:
4077   case ISD::SETNE:   return X86::COND_NE;
4078   case ISD::SETUO:   return X86::COND_P;
4079   case ISD::SETO:    return X86::COND_NP;
4080   case ISD::SETOEQ:
4081   case ISD::SETUNE:  return X86::COND_INVALID;
4082   }
4083 }
4084
4085 /// Is there a floating point cmov for the specific X86 condition code?
4086 /// Current x86 isa includes the following FP cmov instructions:
4087 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4088 static bool hasFPCMov(unsigned X86CC) {
4089   switch (X86CC) {
4090   default:
4091     return false;
4092   case X86::COND_B:
4093   case X86::COND_BE:
4094   case X86::COND_E:
4095   case X86::COND_P:
4096   case X86::COND_A:
4097   case X86::COND_AE:
4098   case X86::COND_NE:
4099   case X86::COND_NP:
4100     return true;
4101   }
4102 }
4103
4104 /// Returns true if the target can instruction select the
4105 /// specified FP immediate natively. If false, the legalizer will
4106 /// materialize the FP immediate as a load from a constant pool.
4107 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4108   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4109     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4110       return true;
4111   }
4112   return false;
4113 }
4114
4115 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4116                                               ISD::LoadExtType ExtTy,
4117                                               EVT NewVT) const {
4118   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4119   // relocation target a movq or addq instruction: don't let the load shrink.
4120   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4121   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4122     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4123       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4124   return true;
4125 }
4126
4127 /// \brief Returns true if it is beneficial to convert a load of a constant
4128 /// to just the constant itself.
4129 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4130                                                           Type *Ty) const {
4131   assert(Ty->isIntegerTy());
4132
4133   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4134   if (BitSize == 0 || BitSize > 64)
4135     return false;
4136   return true;
4137 }
4138
4139 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4140                                                 unsigned Index) const {
4141   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4142     return false;
4143
4144   return (Index == 0 || Index == ResVT.getVectorNumElements());
4145 }
4146
4147 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4148   // Speculate cttz only if we can directly use TZCNT.
4149   return Subtarget->hasBMI();
4150 }
4151
4152 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4153   // Speculate ctlz only if we can directly use LZCNT.
4154   return Subtarget->hasLZCNT();
4155 }
4156
4157 /// Return true if every element in Mask, beginning
4158 /// from position Pos and ending in Pos+Size is undef.
4159 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4160   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4161     if (0 <= Mask[i])
4162       return false;
4163   return true;
4164 }
4165
4166 /// Return true if Val is undef or if its value falls within the
4167 /// specified range (L, H].
4168 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4169   return (Val < 0) || (Val >= Low && Val < Hi);
4170 }
4171
4172 /// Val is either less than zero (undef) or equal to the specified value.
4173 static bool isUndefOrEqual(int Val, int CmpVal) {
4174   return (Val < 0 || Val == CmpVal);
4175 }
4176
4177 /// Return true if every element in Mask, beginning
4178 /// from position Pos and ending in Pos+Size, falls within the specified
4179 /// sequential range (Low, Low+Size]. or is undef.
4180 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4181                                        unsigned Pos, unsigned Size, int Low) {
4182   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4183     if (!isUndefOrEqual(Mask[i], Low))
4184       return false;
4185   return true;
4186 }
4187
4188 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4189 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4190 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4191   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4192   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4193     return false;
4194
4195   // The index should be aligned on a vecWidth-bit boundary.
4196   uint64_t Index =
4197     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4198
4199   MVT VT = N->getSimpleValueType(0);
4200   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4201   bool Result = (Index * ElSize) % vecWidth == 0;
4202
4203   return Result;
4204 }
4205
4206 /// Return true if the specified INSERT_SUBVECTOR
4207 /// operand specifies a subvector insert that is suitable for input to
4208 /// insertion of 128 or 256-bit subvectors
4209 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4210   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4211   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4212     return false;
4213   // The index should be aligned on a vecWidth-bit boundary.
4214   uint64_t Index =
4215     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4216
4217   MVT VT = N->getSimpleValueType(0);
4218   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4219   bool Result = (Index * ElSize) % vecWidth == 0;
4220
4221   return Result;
4222 }
4223
4224 bool X86::isVINSERT128Index(SDNode *N) {
4225   return isVINSERTIndex(N, 128);
4226 }
4227
4228 bool X86::isVINSERT256Index(SDNode *N) {
4229   return isVINSERTIndex(N, 256);
4230 }
4231
4232 bool X86::isVEXTRACT128Index(SDNode *N) {
4233   return isVEXTRACTIndex(N, 128);
4234 }
4235
4236 bool X86::isVEXTRACT256Index(SDNode *N) {
4237   return isVEXTRACTIndex(N, 256);
4238 }
4239
4240 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4241   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4242   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4243     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4244
4245   uint64_t Index =
4246     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4247
4248   MVT VecVT = N->getOperand(0).getSimpleValueType();
4249   MVT ElVT = VecVT.getVectorElementType();
4250
4251   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4252   return Index / NumElemsPerChunk;
4253 }
4254
4255 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4256   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4257   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4258     llvm_unreachable("Illegal insert subvector for VINSERT");
4259
4260   uint64_t Index =
4261     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4262
4263   MVT VecVT = N->getSimpleValueType(0);
4264   MVT ElVT = VecVT.getVectorElementType();
4265
4266   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4267   return Index / NumElemsPerChunk;
4268 }
4269
4270 /// Return the appropriate immediate to extract the specified
4271 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4272 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4273   return getExtractVEXTRACTImmediate(N, 128);
4274 }
4275
4276 /// Return the appropriate immediate to extract the specified
4277 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4278 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4279   return getExtractVEXTRACTImmediate(N, 256);
4280 }
4281
4282 /// Return the appropriate immediate to insert at the specified
4283 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4284 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4285   return getInsertVINSERTImmediate(N, 128);
4286 }
4287
4288 /// Return the appropriate immediate to insert at the specified
4289 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4290 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4291   return getInsertVINSERTImmediate(N, 256);
4292 }
4293
4294 /// Returns true if V is a constant integer zero.
4295 static bool isZero(SDValue V) {
4296   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4297   return C && C->isNullValue();
4298 }
4299
4300 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4301 bool X86::isZeroNode(SDValue Elt) {
4302   if (isZero(Elt))
4303     return true;
4304   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4305     return CFP->getValueAPF().isPosZero();
4306   return false;
4307 }
4308
4309 // Build a vector of constants
4310 // Use an UNDEF node if MaskElt == -1.
4311 // Spilt 64-bit constants in the 32-bit mode.
4312 static SDValue getConstVector(ArrayRef<int> Values, EVT VT,
4313                               SelectionDAG &DAG,
4314                               SDLoc dl, bool IsMask = false) {
4315
4316   SmallVector<SDValue, 32>  Ops;
4317   bool Split = false;
4318
4319   EVT ConstVecVT = VT;
4320   unsigned NumElts = VT.getVectorNumElements();
4321   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4322   if (!In64BitMode && VT.getScalarType() == MVT::i64) {
4323     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4324     Split = true;
4325   }
4326
4327   EVT EltVT = ConstVecVT.getScalarType();
4328   for (unsigned i = 0; i < NumElts; ++i) {
4329     bool IsUndef = Values[i] < 0 && IsMask;
4330     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4331       DAG.getConstant(Values[i], dl, EltVT);
4332     Ops.push_back(OpNode);
4333     if (Split)
4334       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4335                     DAG.getConstant(0, dl, EltVT));
4336   }
4337   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4338   if (Split)
4339     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4340   return ConstsNode;
4341 }
4342
4343 /// Returns a vector of specified type with all zero elements.
4344 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4345                              SelectionDAG &DAG, SDLoc dl) {
4346   assert(VT.isVector() && "Expected a vector type");
4347
4348   // Always build SSE zero vectors as <4 x i32> bitcasted
4349   // to their dest type. This ensures they get CSE'd.
4350   SDValue Vec;
4351   if (VT.is128BitVector()) {  // SSE
4352     if (Subtarget->hasSSE2()) {  // SSE2
4353       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4354       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4355     } else { // SSE1
4356       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4357       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4358     }
4359   } else if (VT.is256BitVector()) { // AVX
4360     if (Subtarget->hasInt256()) { // AVX2
4361       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4362       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4363       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4364     } else {
4365       // 256-bit logic and arithmetic instructions in AVX are all
4366       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4367       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4368       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4369       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4370     }
4371   } else if (VT.is512BitVector()) { // AVX-512
4372       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4373       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4374                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4375       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4376   } else if (VT.getScalarType() == MVT::i1) {
4377
4378     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4379             && "Unexpected vector type");
4380     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4381             && "Unexpected vector type");
4382     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4383     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4384     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4385   } else
4386     llvm_unreachable("Unexpected vector type");
4387
4388   return DAG.getBitcast(VT, Vec);
4389 }
4390
4391 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4392                                 SelectionDAG &DAG, SDLoc dl,
4393                                 unsigned vectorWidth) {
4394   assert((vectorWidth == 128 || vectorWidth == 256) &&
4395          "Unsupported vector width");
4396   EVT VT = Vec.getValueType();
4397   EVT ElVT = VT.getVectorElementType();
4398   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4399   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4400                                   VT.getVectorNumElements()/Factor);
4401
4402   // Extract from UNDEF is UNDEF.
4403   if (Vec.getOpcode() == ISD::UNDEF)
4404     return DAG.getUNDEF(ResultVT);
4405
4406   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4407   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4408
4409   // This is the index of the first element of the vectorWidth-bit chunk
4410   // we want.
4411   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4412                                * ElemsPerChunk);
4413
4414   // If the input is a buildvector just emit a smaller one.
4415   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4416     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4417                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4418                                     ElemsPerChunk));
4419
4420   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4421   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4422 }
4423
4424 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4425 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4426 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4427 /// instructions or a simple subregister reference. Idx is an index in the
4428 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4429 /// lowering EXTRACT_VECTOR_ELT operations easier.
4430 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4431                                    SelectionDAG &DAG, SDLoc dl) {
4432   assert((Vec.getValueType().is256BitVector() ||
4433           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4434   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4435 }
4436
4437 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4438 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4439                                    SelectionDAG &DAG, SDLoc dl) {
4440   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4441   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4442 }
4443
4444 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4445                                unsigned IdxVal, SelectionDAG &DAG,
4446                                SDLoc dl, unsigned vectorWidth) {
4447   assert((vectorWidth == 128 || vectorWidth == 256) &&
4448          "Unsupported vector width");
4449   // Inserting UNDEF is Result
4450   if (Vec.getOpcode() == ISD::UNDEF)
4451     return Result;
4452   EVT VT = Vec.getValueType();
4453   EVT ElVT = VT.getVectorElementType();
4454   EVT ResultVT = Result.getValueType();
4455
4456   // Insert the relevant vectorWidth bits.
4457   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4458
4459   // This is the index of the first element of the vectorWidth-bit chunk
4460   // we want.
4461   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4462                                * ElemsPerChunk);
4463
4464   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4465   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4466 }
4467
4468 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4469 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4470 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4471 /// simple superregister reference.  Idx is an index in the 128 bits
4472 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4473 /// lowering INSERT_VECTOR_ELT operations easier.
4474 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4475                                   SelectionDAG &DAG, SDLoc dl) {
4476   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4477
4478   // For insertion into the zero index (low half) of a 256-bit vector, it is
4479   // more efficient to generate a blend with immediate instead of an insert*128.
4480   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4481   // extend the subvector to the size of the result vector. Make sure that
4482   // we are not recursing on that node by checking for undef here.
4483   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4484       Result.getOpcode() != ISD::UNDEF) {
4485     EVT ResultVT = Result.getValueType();
4486     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4487     SDValue Undef = DAG.getUNDEF(ResultVT);
4488     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4489                                  Vec, ZeroIndex);
4490
4491     // The blend instruction, and therefore its mask, depend on the data type.
4492     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4493     if (ScalarType.isFloatingPoint()) {
4494       // Choose either vblendps (float) or vblendpd (double).
4495       unsigned ScalarSize = ScalarType.getSizeInBits();
4496       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4497       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4498       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4499       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4500     }
4501
4502     const X86Subtarget &Subtarget =
4503     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4504
4505     // AVX2 is needed for 256-bit integer blend support.
4506     // Integers must be cast to 32-bit because there is only vpblendd;
4507     // vpblendw can't be used for this because it has a handicapped mask.
4508
4509     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4510     // is still more efficient than using the wrong domain vinsertf128 that
4511     // will be created by InsertSubVector().
4512     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4513
4514     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4515     Vec256 = DAG.getBitcast(CastVT, Vec256);
4516     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4517     return DAG.getBitcast(ResultVT, Vec256);
4518   }
4519
4520   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4521 }
4522
4523 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4524                                   SelectionDAG &DAG, SDLoc dl) {
4525   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4526   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4527 }
4528
4529 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4530 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4531 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4532 /// large BUILD_VECTORS.
4533 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4534                                    unsigned NumElems, SelectionDAG &DAG,
4535                                    SDLoc dl) {
4536   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4537   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4538 }
4539
4540 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4541                                    unsigned NumElems, SelectionDAG &DAG,
4542                                    SDLoc dl) {
4543   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4544   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4545 }
4546
4547 /// Returns a vector of specified type with all bits set.
4548 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4549 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4550 /// Then bitcast to their original type, ensuring they get CSE'd.
4551 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4552                              SelectionDAG &DAG, SDLoc dl) {
4553   assert(VT.isVector() && "Expected a vector type");
4554
4555   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4556   SDValue Vec;
4557   if (VT.is512BitVector()) {
4558     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4559                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4560     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4561   } else if (VT.is256BitVector()) {
4562     if (Subtarget->hasInt256()) { // AVX2
4563       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4564       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4565     } else { // AVX
4566       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4567       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4568     }
4569   } else if (VT.is128BitVector()) {
4570     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4571   } else
4572     llvm_unreachable("Unexpected vector type");
4573
4574   return DAG.getBitcast(VT, Vec);
4575 }
4576
4577 /// Returns a vector_shuffle node for an unpackl operation.
4578 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4579                           SDValue V2) {
4580   unsigned NumElems = VT.getVectorNumElements();
4581   SmallVector<int, 8> Mask;
4582   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4583     Mask.push_back(i);
4584     Mask.push_back(i + NumElems);
4585   }
4586   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4587 }
4588
4589 /// Returns a vector_shuffle node for an unpackh operation.
4590 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4591                           SDValue V2) {
4592   unsigned NumElems = VT.getVectorNumElements();
4593   SmallVector<int, 8> Mask;
4594   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4595     Mask.push_back(i + Half);
4596     Mask.push_back(i + NumElems + Half);
4597   }
4598   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4599 }
4600
4601 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4602 /// This produces a shuffle where the low element of V2 is swizzled into the
4603 /// zero/undef vector, landing at element Idx.
4604 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4605 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4606                                            bool IsZero,
4607                                            const X86Subtarget *Subtarget,
4608                                            SelectionDAG &DAG) {
4609   MVT VT = V2.getSimpleValueType();
4610   SDValue V1 = IsZero
4611     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4612   unsigned NumElems = VT.getVectorNumElements();
4613   SmallVector<int, 16> MaskVec;
4614   for (unsigned i = 0; i != NumElems; ++i)
4615     // If this is the insertion idx, put the low elt of V2 here.
4616     MaskVec.push_back(i == Idx ? NumElems : i);
4617   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4618 }
4619
4620 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4621 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4622 /// uses one source. Note that this will set IsUnary for shuffles which use a
4623 /// single input multiple times, and in those cases it will
4624 /// adjust the mask to only have indices within that single input.
4625 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4626 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4627                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4628   unsigned NumElems = VT.getVectorNumElements();
4629   SDValue ImmN;
4630
4631   IsUnary = false;
4632   bool IsFakeUnary = false;
4633   switch(N->getOpcode()) {
4634   case X86ISD::BLENDI:
4635     ImmN = N->getOperand(N->getNumOperands()-1);
4636     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4637     break;
4638   case X86ISD::SHUFP:
4639     ImmN = N->getOperand(N->getNumOperands()-1);
4640     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4641     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4642     break;
4643   case X86ISD::UNPCKH:
4644     DecodeUNPCKHMask(VT, Mask);
4645     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4646     break;
4647   case X86ISD::UNPCKL:
4648     DecodeUNPCKLMask(VT, Mask);
4649     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4650     break;
4651   case X86ISD::MOVHLPS:
4652     DecodeMOVHLPSMask(NumElems, Mask);
4653     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4654     break;
4655   case X86ISD::MOVLHPS:
4656     DecodeMOVLHPSMask(NumElems, Mask);
4657     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4658     break;
4659   case X86ISD::PALIGNR:
4660     ImmN = N->getOperand(N->getNumOperands()-1);
4661     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4662     break;
4663   case X86ISD::PSHUFD:
4664   case X86ISD::VPERMILPI:
4665     ImmN = N->getOperand(N->getNumOperands()-1);
4666     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4667     IsUnary = true;
4668     break;
4669   case X86ISD::PSHUFHW:
4670     ImmN = N->getOperand(N->getNumOperands()-1);
4671     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4672     IsUnary = true;
4673     break;
4674   case X86ISD::PSHUFLW:
4675     ImmN = N->getOperand(N->getNumOperands()-1);
4676     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4677     IsUnary = true;
4678     break;
4679   case X86ISD::PSHUFB: {
4680     IsUnary = true;
4681     SDValue MaskNode = N->getOperand(1);
4682     while (MaskNode->getOpcode() == ISD::BITCAST)
4683       MaskNode = MaskNode->getOperand(0);
4684
4685     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4686       // If we have a build-vector, then things are easy.
4687       EVT VT = MaskNode.getValueType();
4688       assert(VT.isVector() &&
4689              "Can't produce a non-vector with a build_vector!");
4690       if (!VT.isInteger())
4691         return false;
4692
4693       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4694
4695       SmallVector<uint64_t, 32> RawMask;
4696       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4697         SDValue Op = MaskNode->getOperand(i);
4698         if (Op->getOpcode() == ISD::UNDEF) {
4699           RawMask.push_back((uint64_t)SM_SentinelUndef);
4700           continue;
4701         }
4702         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4703         if (!CN)
4704           return false;
4705         APInt MaskElement = CN->getAPIntValue();
4706
4707         // We now have to decode the element which could be any integer size and
4708         // extract each byte of it.
4709         for (int j = 0; j < NumBytesPerElement; ++j) {
4710           // Note that this is x86 and so always little endian: the low byte is
4711           // the first byte of the mask.
4712           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4713           MaskElement = MaskElement.lshr(8);
4714         }
4715       }
4716       DecodePSHUFBMask(RawMask, Mask);
4717       break;
4718     }
4719
4720     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4721     if (!MaskLoad)
4722       return false;
4723
4724     SDValue Ptr = MaskLoad->getBasePtr();
4725     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4726         Ptr->getOpcode() == X86ISD::WrapperRIP)
4727       Ptr = Ptr->getOperand(0);
4728
4729     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4730     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4731       return false;
4732
4733     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4734       DecodePSHUFBMask(C, Mask);
4735       if (Mask.empty())
4736         return false;
4737       break;
4738     }
4739
4740     return false;
4741   }
4742   case X86ISD::VPERMI:
4743     ImmN = N->getOperand(N->getNumOperands()-1);
4744     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4745     IsUnary = true;
4746     break;
4747   case X86ISD::MOVSS:
4748   case X86ISD::MOVSD:
4749     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4750     break;
4751   case X86ISD::VPERM2X128:
4752     ImmN = N->getOperand(N->getNumOperands()-1);
4753     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4754     if (Mask.empty()) return false;
4755     // Mask only contains negative index if an element is zero.
4756     if (std::any_of(Mask.begin(), Mask.end(),
4757                     [](int M){ return M == SM_SentinelZero; }))
4758       return false;
4759     break;
4760   case X86ISD::MOVSLDUP:
4761     DecodeMOVSLDUPMask(VT, Mask);
4762     IsUnary = true;
4763     break;
4764   case X86ISD::MOVSHDUP:
4765     DecodeMOVSHDUPMask(VT, Mask);
4766     IsUnary = true;
4767     break;
4768   case X86ISD::MOVDDUP:
4769     DecodeMOVDDUPMask(VT, Mask);
4770     IsUnary = true;
4771     break;
4772   case X86ISD::MOVLHPD:
4773   case X86ISD::MOVLPD:
4774   case X86ISD::MOVLPS:
4775     // Not yet implemented
4776     return false;
4777   case X86ISD::VPERMV: {
4778     IsUnary = true;
4779     SDValue MaskNode = N->getOperand(0);
4780     while (MaskNode->getOpcode() == ISD::BITCAST)
4781       MaskNode = MaskNode->getOperand(0);
4782
4783     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4784     SmallVector<uint64_t, 32> RawMask;
4785     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4786       // If we have a build-vector, then things are easy.
4787       assert(MaskNode.getValueType().isInteger() &&
4788              MaskNode.getValueType().getVectorNumElements() ==
4789              VT.getVectorNumElements());
4790
4791       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4792         SDValue Op = MaskNode->getOperand(i);
4793         if (Op->getOpcode() == ISD::UNDEF)
4794           RawMask.push_back((uint64_t)SM_SentinelUndef);
4795         else if (isa<ConstantSDNode>(Op)) {
4796           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4797           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4798         } else
4799           return false;
4800       }
4801       DecodeVPERMVMask(RawMask, Mask);
4802       break;
4803     }
4804     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4805       unsigned NumEltsInMask = MaskNode->getNumOperands();
4806       MaskNode = MaskNode->getOperand(0);
4807       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4808       if (CN) {
4809         APInt MaskEltValue = CN->getAPIntValue();
4810         for (unsigned i = 0; i < NumEltsInMask; ++i)
4811           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4812         DecodeVPERMVMask(RawMask, Mask);
4813         break;
4814       }
4815       // It may be a scalar load
4816     }
4817
4818     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4819     if (!MaskLoad)
4820       return false;
4821
4822     SDValue Ptr = MaskLoad->getBasePtr();
4823     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4824         Ptr->getOpcode() == X86ISD::WrapperRIP)
4825       Ptr = Ptr->getOperand(0);
4826
4827     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4828     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4829       return false;
4830
4831     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4832     if (C) {
4833       DecodeVPERMVMask(C, VT, Mask);
4834       if (Mask.empty())
4835         return false;
4836       break;
4837     }
4838     return false;
4839   }
4840   case X86ISD::VPERMV3: {
4841     IsUnary = false;
4842     SDValue MaskNode = N->getOperand(1);
4843     while (MaskNode->getOpcode() == ISD::BITCAST)
4844       MaskNode = MaskNode->getOperand(1);
4845
4846     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4847       // If we have a build-vector, then things are easy.
4848       assert(MaskNode.getValueType().isInteger() &&
4849              MaskNode.getValueType().getVectorNumElements() ==
4850              VT.getVectorNumElements());
4851
4852       SmallVector<uint64_t, 32> RawMask;
4853       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4854
4855       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4856         SDValue Op = MaskNode->getOperand(i);
4857         if (Op->getOpcode() == ISD::UNDEF)
4858           RawMask.push_back((uint64_t)SM_SentinelUndef);
4859         else {
4860           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4861           if (!CN)
4862             return false;
4863           APInt MaskElement = CN->getAPIntValue();
4864           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4865         }
4866       }
4867       DecodeVPERMV3Mask(RawMask, Mask);
4868       break;
4869     }
4870
4871     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4872     if (!MaskLoad)
4873       return false;
4874
4875     SDValue Ptr = MaskLoad->getBasePtr();
4876     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4877         Ptr->getOpcode() == X86ISD::WrapperRIP)
4878       Ptr = Ptr->getOperand(0);
4879
4880     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4881     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4882       return false;
4883
4884     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4885     if (C) {
4886       DecodeVPERMV3Mask(C, VT, Mask);
4887       if (Mask.empty())
4888         return false;
4889       break;
4890     }
4891     return false;
4892   }
4893   default: llvm_unreachable("unknown target shuffle node");
4894   }
4895
4896   // If we have a fake unary shuffle, the shuffle mask is spread across two
4897   // inputs that are actually the same node. Re-map the mask to always point
4898   // into the first input.
4899   if (IsFakeUnary)
4900     for (int &M : Mask)
4901       if (M >= (int)Mask.size())
4902         M -= Mask.size();
4903
4904   return true;
4905 }
4906
4907 /// Returns the scalar element that will make up the ith
4908 /// element of the result of the vector shuffle.
4909 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4910                                    unsigned Depth) {
4911   if (Depth == 6)
4912     return SDValue();  // Limit search depth.
4913
4914   SDValue V = SDValue(N, 0);
4915   EVT VT = V.getValueType();
4916   unsigned Opcode = V.getOpcode();
4917
4918   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4919   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4920     int Elt = SV->getMaskElt(Index);
4921
4922     if (Elt < 0)
4923       return DAG.getUNDEF(VT.getVectorElementType());
4924
4925     unsigned NumElems = VT.getVectorNumElements();
4926     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4927                                          : SV->getOperand(1);
4928     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4929   }
4930
4931   // Recurse into target specific vector shuffles to find scalars.
4932   if (isTargetShuffle(Opcode)) {
4933     MVT ShufVT = V.getSimpleValueType();
4934     unsigned NumElems = ShufVT.getVectorNumElements();
4935     SmallVector<int, 16> ShuffleMask;
4936     bool IsUnary;
4937
4938     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4939       return SDValue();
4940
4941     int Elt = ShuffleMask[Index];
4942     if (Elt < 0)
4943       return DAG.getUNDEF(ShufVT.getVectorElementType());
4944
4945     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4946                                          : N->getOperand(1);
4947     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4948                                Depth+1);
4949   }
4950
4951   // Actual nodes that may contain scalar elements
4952   if (Opcode == ISD::BITCAST) {
4953     V = V.getOperand(0);
4954     EVT SrcVT = V.getValueType();
4955     unsigned NumElems = VT.getVectorNumElements();
4956
4957     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4958       return SDValue();
4959   }
4960
4961   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4962     return (Index == 0) ? V.getOperand(0)
4963                         : DAG.getUNDEF(VT.getVectorElementType());
4964
4965   if (V.getOpcode() == ISD::BUILD_VECTOR)
4966     return V.getOperand(Index);
4967
4968   return SDValue();
4969 }
4970
4971 /// Custom lower build_vector of v16i8.
4972 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4973                                        unsigned NumNonZero, unsigned NumZero,
4974                                        SelectionDAG &DAG,
4975                                        const X86Subtarget* Subtarget,
4976                                        const TargetLowering &TLI) {
4977   if (NumNonZero > 8)
4978     return SDValue();
4979
4980   SDLoc dl(Op);
4981   SDValue V;
4982   bool First = true;
4983
4984   // SSE4.1 - use PINSRB to insert each byte directly.
4985   if (Subtarget->hasSSE41()) {
4986     for (unsigned i = 0; i < 16; ++i) {
4987       bool isNonZero = (NonZeros & (1 << i)) != 0;
4988       if (isNonZero) {
4989         if (First) {
4990           if (NumZero)
4991             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4992           else
4993             V = DAG.getUNDEF(MVT::v16i8);
4994           First = false;
4995         }
4996         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4997                         MVT::v16i8, V, Op.getOperand(i),
4998                         DAG.getIntPtrConstant(i, dl));
4999       }
5000     }
5001
5002     return V;
5003   }
5004
5005   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5006   for (unsigned i = 0; i < 16; ++i) {
5007     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5008     if (ThisIsNonZero && First) {
5009       if (NumZero)
5010         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5011       else
5012         V = DAG.getUNDEF(MVT::v8i16);
5013       First = false;
5014     }
5015
5016     if ((i & 1) != 0) {
5017       SDValue ThisElt, LastElt;
5018       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5019       if (LastIsNonZero) {
5020         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5021                               MVT::i16, Op.getOperand(i-1));
5022       }
5023       if (ThisIsNonZero) {
5024         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5025         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5026                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5027         if (LastIsNonZero)
5028           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5029       } else
5030         ThisElt = LastElt;
5031
5032       if (ThisElt.getNode())
5033         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5034                         DAG.getIntPtrConstant(i/2, dl));
5035     }
5036   }
5037
5038   return DAG.getBitcast(MVT::v16i8, V);
5039 }
5040
5041 /// Custom lower build_vector of v8i16.
5042 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5043                                      unsigned NumNonZero, unsigned NumZero,
5044                                      SelectionDAG &DAG,
5045                                      const X86Subtarget* Subtarget,
5046                                      const TargetLowering &TLI) {
5047   if (NumNonZero > 4)
5048     return SDValue();
5049
5050   SDLoc dl(Op);
5051   SDValue V;
5052   bool First = true;
5053   for (unsigned i = 0; i < 8; ++i) {
5054     bool isNonZero = (NonZeros & (1 << i)) != 0;
5055     if (isNonZero) {
5056       if (First) {
5057         if (NumZero)
5058           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5059         else
5060           V = DAG.getUNDEF(MVT::v8i16);
5061         First = false;
5062       }
5063       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5064                       MVT::v8i16, V, Op.getOperand(i),
5065                       DAG.getIntPtrConstant(i, dl));
5066     }
5067   }
5068
5069   return V;
5070 }
5071
5072 /// Custom lower build_vector of v4i32 or v4f32.
5073 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5074                                      const X86Subtarget *Subtarget,
5075                                      const TargetLowering &TLI) {
5076   // Find all zeroable elements.
5077   std::bitset<4> Zeroable;
5078   for (int i=0; i < 4; ++i) {
5079     SDValue Elt = Op->getOperand(i);
5080     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5081   }
5082   assert(Zeroable.size() - Zeroable.count() > 1 &&
5083          "We expect at least two non-zero elements!");
5084
5085   // We only know how to deal with build_vector nodes where elements are either
5086   // zeroable or extract_vector_elt with constant index.
5087   SDValue FirstNonZero;
5088   unsigned FirstNonZeroIdx;
5089   for (unsigned i=0; i < 4; ++i) {
5090     if (Zeroable[i])
5091       continue;
5092     SDValue Elt = Op->getOperand(i);
5093     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5094         !isa<ConstantSDNode>(Elt.getOperand(1)))
5095       return SDValue();
5096     // Make sure that this node is extracting from a 128-bit vector.
5097     MVT VT = Elt.getOperand(0).getSimpleValueType();
5098     if (!VT.is128BitVector())
5099       return SDValue();
5100     if (!FirstNonZero.getNode()) {
5101       FirstNonZero = Elt;
5102       FirstNonZeroIdx = i;
5103     }
5104   }
5105
5106   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5107   SDValue V1 = FirstNonZero.getOperand(0);
5108   MVT VT = V1.getSimpleValueType();
5109
5110   // See if this build_vector can be lowered as a blend with zero.
5111   SDValue Elt;
5112   unsigned EltMaskIdx, EltIdx;
5113   int Mask[4];
5114   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5115     if (Zeroable[EltIdx]) {
5116       // The zero vector will be on the right hand side.
5117       Mask[EltIdx] = EltIdx+4;
5118       continue;
5119     }
5120
5121     Elt = Op->getOperand(EltIdx);
5122     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5123     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5124     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5125       break;
5126     Mask[EltIdx] = EltIdx;
5127   }
5128
5129   if (EltIdx == 4) {
5130     // Let the shuffle legalizer deal with blend operations.
5131     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5132     if (V1.getSimpleValueType() != VT)
5133       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5134     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5135   }
5136
5137   // See if we can lower this build_vector to a INSERTPS.
5138   if (!Subtarget->hasSSE41())
5139     return SDValue();
5140
5141   SDValue V2 = Elt.getOperand(0);
5142   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5143     V1 = SDValue();
5144
5145   bool CanFold = true;
5146   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5147     if (Zeroable[i])
5148       continue;
5149
5150     SDValue Current = Op->getOperand(i);
5151     SDValue SrcVector = Current->getOperand(0);
5152     if (!V1.getNode())
5153       V1 = SrcVector;
5154     CanFold = SrcVector == V1 &&
5155       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5156   }
5157
5158   if (!CanFold)
5159     return SDValue();
5160
5161   assert(V1.getNode() && "Expected at least two non-zero elements!");
5162   if (V1.getSimpleValueType() != MVT::v4f32)
5163     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5164   if (V2.getSimpleValueType() != MVT::v4f32)
5165     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5166
5167   // Ok, we can emit an INSERTPS instruction.
5168   unsigned ZMask = Zeroable.to_ulong();
5169
5170   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5171   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5172   SDLoc DL(Op);
5173   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5174                                DAG.getIntPtrConstant(InsertPSMask, DL));
5175   return DAG.getBitcast(VT, Result);
5176 }
5177
5178 /// Return a vector logical shift node.
5179 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5180                          unsigned NumBits, SelectionDAG &DAG,
5181                          const TargetLowering &TLI, SDLoc dl) {
5182   assert(VT.is128BitVector() && "Unknown type for VShift");
5183   MVT ShVT = MVT::v2i64;
5184   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5185   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5186   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5187   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5188   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5189   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5190 }
5191
5192 static SDValue
5193 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5194
5195   // Check if the scalar load can be widened into a vector load. And if
5196   // the address is "base + cst" see if the cst can be "absorbed" into
5197   // the shuffle mask.
5198   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5199     SDValue Ptr = LD->getBasePtr();
5200     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5201       return SDValue();
5202     EVT PVT = LD->getValueType(0);
5203     if (PVT != MVT::i32 && PVT != MVT::f32)
5204       return SDValue();
5205
5206     int FI = -1;
5207     int64_t Offset = 0;
5208     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5209       FI = FINode->getIndex();
5210       Offset = 0;
5211     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5212                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5213       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5214       Offset = Ptr.getConstantOperandVal(1);
5215       Ptr = Ptr.getOperand(0);
5216     } else {
5217       return SDValue();
5218     }
5219
5220     // FIXME: 256-bit vector instructions don't require a strict alignment,
5221     // improve this code to support it better.
5222     unsigned RequiredAlign = VT.getSizeInBits()/8;
5223     SDValue Chain = LD->getChain();
5224     // Make sure the stack object alignment is at least 16 or 32.
5225     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5226     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5227       if (MFI->isFixedObjectIndex(FI)) {
5228         // Can't change the alignment. FIXME: It's possible to compute
5229         // the exact stack offset and reference FI + adjust offset instead.
5230         // If someone *really* cares about this. That's the way to implement it.
5231         return SDValue();
5232       } else {
5233         MFI->setObjectAlignment(FI, RequiredAlign);
5234       }
5235     }
5236
5237     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5238     // Ptr + (Offset & ~15).
5239     if (Offset < 0)
5240       return SDValue();
5241     if ((Offset % RequiredAlign) & 3)
5242       return SDValue();
5243     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5244     if (StartOffset) {
5245       SDLoc DL(Ptr);
5246       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5247                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5248     }
5249
5250     int EltNo = (Offset - StartOffset) >> 2;
5251     unsigned NumElems = VT.getVectorNumElements();
5252
5253     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5254     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5255                              LD->getPointerInfo().getWithOffset(StartOffset),
5256                              false, false, false, 0);
5257
5258     SmallVector<int, 8> Mask(NumElems, EltNo);
5259
5260     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5261   }
5262
5263   return SDValue();
5264 }
5265
5266 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5267 /// elements can be replaced by a single large load which has the same value as
5268 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5269 ///
5270 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5271 ///
5272 /// FIXME: we'd also like to handle the case where the last elements are zero
5273 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5274 /// There's even a handy isZeroNode for that purpose.
5275 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5276                                         SDLoc &DL, SelectionDAG &DAG,
5277                                         bool isAfterLegalize) {
5278   unsigned NumElems = Elts.size();
5279
5280   LoadSDNode *LDBase = nullptr;
5281   unsigned LastLoadedElt = -1U;
5282
5283   // For each element in the initializer, see if we've found a load or an undef.
5284   // If we don't find an initial load element, or later load elements are
5285   // non-consecutive, bail out.
5286   for (unsigned i = 0; i < NumElems; ++i) {
5287     SDValue Elt = Elts[i];
5288     // Look through a bitcast.
5289     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5290       Elt = Elt.getOperand(0);
5291     if (!Elt.getNode() ||
5292         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5293       return SDValue();
5294     if (!LDBase) {
5295       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5296         return SDValue();
5297       LDBase = cast<LoadSDNode>(Elt.getNode());
5298       LastLoadedElt = i;
5299       continue;
5300     }
5301     if (Elt.getOpcode() == ISD::UNDEF)
5302       continue;
5303
5304     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5305     EVT LdVT = Elt.getValueType();
5306     // Each loaded element must be the correct fractional portion of the
5307     // requested vector load.
5308     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5309       return SDValue();
5310     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5311       return SDValue();
5312     LastLoadedElt = i;
5313   }
5314
5315   // If we have found an entire vector of loads and undefs, then return a large
5316   // load of the entire vector width starting at the base pointer.  If we found
5317   // consecutive loads for the low half, generate a vzext_load node.
5318   if (LastLoadedElt == NumElems - 1) {
5319     assert(LDBase && "Did not find base load for merging consecutive loads");
5320     EVT EltVT = LDBase->getValueType(0);
5321     // Ensure that the input vector size for the merged loads matches the
5322     // cumulative size of the input elements.
5323     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5324       return SDValue();
5325
5326     if (isAfterLegalize &&
5327         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5328       return SDValue();
5329
5330     SDValue NewLd = SDValue();
5331
5332     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5333                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5334                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5335                         LDBase->getAlignment());
5336
5337     if (LDBase->hasAnyUseOfValue(1)) {
5338       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5339                                      SDValue(LDBase, 1),
5340                                      SDValue(NewLd.getNode(), 1));
5341       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5342       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5343                              SDValue(NewLd.getNode(), 1));
5344     }
5345
5346     return NewLd;
5347   }
5348
5349   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5350   //of a v4i32 / v4f32. It's probably worth generalizing.
5351   EVT EltVT = VT.getVectorElementType();
5352   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5353       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5354     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5355     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5356     SDValue ResNode =
5357         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5358                                 LDBase->getPointerInfo(),
5359                                 LDBase->getAlignment(),
5360                                 false/*isVolatile*/, true/*ReadMem*/,
5361                                 false/*WriteMem*/);
5362
5363     // Make sure the newly-created LOAD is in the same position as LDBase in
5364     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5365     // update uses of LDBase's output chain to use the TokenFactor.
5366     if (LDBase->hasAnyUseOfValue(1)) {
5367       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5368                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5369       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5370       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5371                              SDValue(ResNode.getNode(), 1));
5372     }
5373
5374     return DAG.getBitcast(VT, ResNode);
5375   }
5376   return SDValue();
5377 }
5378
5379 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5380 /// to generate a splat value for the following cases:
5381 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5382 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5383 /// a scalar load, or a constant.
5384 /// The VBROADCAST node is returned when a pattern is found,
5385 /// or SDValue() otherwise.
5386 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5387                                     SelectionDAG &DAG) {
5388   // VBROADCAST requires AVX.
5389   // TODO: Splats could be generated for non-AVX CPUs using SSE
5390   // instructions, but there's less potential gain for only 128-bit vectors.
5391   if (!Subtarget->hasAVX())
5392     return SDValue();
5393
5394   MVT VT = Op.getSimpleValueType();
5395   SDLoc dl(Op);
5396
5397   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5398          "Unsupported vector type for broadcast.");
5399
5400   SDValue Ld;
5401   bool ConstSplatVal;
5402
5403   switch (Op.getOpcode()) {
5404     default:
5405       // Unknown pattern found.
5406       return SDValue();
5407
5408     case ISD::BUILD_VECTOR: {
5409       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5410       BitVector UndefElements;
5411       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5412
5413       // We need a splat of a single value to use broadcast, and it doesn't
5414       // make any sense if the value is only in one element of the vector.
5415       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5416         return SDValue();
5417
5418       Ld = Splat;
5419       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5420                        Ld.getOpcode() == ISD::ConstantFP);
5421
5422       // Make sure that all of the users of a non-constant load are from the
5423       // BUILD_VECTOR node.
5424       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5425         return SDValue();
5426       break;
5427     }
5428
5429     case ISD::VECTOR_SHUFFLE: {
5430       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5431
5432       // Shuffles must have a splat mask where the first element is
5433       // broadcasted.
5434       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5435         return SDValue();
5436
5437       SDValue Sc = Op.getOperand(0);
5438       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5439           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5440
5441         if (!Subtarget->hasInt256())
5442           return SDValue();
5443
5444         // Use the register form of the broadcast instruction available on AVX2.
5445         if (VT.getSizeInBits() >= 256)
5446           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5447         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5448       }
5449
5450       Ld = Sc.getOperand(0);
5451       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5452                        Ld.getOpcode() == ISD::ConstantFP);
5453
5454       // The scalar_to_vector node and the suspected
5455       // load node must have exactly one user.
5456       // Constants may have multiple users.
5457
5458       // AVX-512 has register version of the broadcast
5459       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5460         Ld.getValueType().getSizeInBits() >= 32;
5461       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5462           !hasRegVer))
5463         return SDValue();
5464       break;
5465     }
5466   }
5467
5468   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5469   bool IsGE256 = (VT.getSizeInBits() >= 256);
5470
5471   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5472   // instruction to save 8 or more bytes of constant pool data.
5473   // TODO: If multiple splats are generated to load the same constant,
5474   // it may be detrimental to overall size. There needs to be a way to detect
5475   // that condition to know if this is truly a size win.
5476   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5477
5478   // Handle broadcasting a single constant scalar from the constant pool
5479   // into a vector.
5480   // On Sandybridge (no AVX2), it is still better to load a constant vector
5481   // from the constant pool and not to broadcast it from a scalar.
5482   // But override that restriction when optimizing for size.
5483   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5484   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5485     EVT CVT = Ld.getValueType();
5486     assert(!CVT.isVector() && "Must not broadcast a vector type");
5487
5488     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5489     // For size optimization, also splat v2f64 and v2i64, and for size opt
5490     // with AVX2, also splat i8 and i16.
5491     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5492     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5493         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5494       const Constant *C = nullptr;
5495       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5496         C = CI->getConstantIntValue();
5497       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5498         C = CF->getConstantFPValue();
5499
5500       assert(C && "Invalid constant type");
5501
5502       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5503       SDValue CP =
5504           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5505       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5506       Ld = DAG.getLoad(
5507           CVT, dl, DAG.getEntryNode(), CP,
5508           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5509           false, false, Alignment);
5510
5511       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5512     }
5513   }
5514
5515   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5516
5517   // Handle AVX2 in-register broadcasts.
5518   if (!IsLoad && Subtarget->hasInt256() &&
5519       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5520     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5521
5522   // The scalar source must be a normal load.
5523   if (!IsLoad)
5524     return SDValue();
5525
5526   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5527       (Subtarget->hasVLX() && ScalarSize == 64))
5528     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5529
5530   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5531   // double since there is no vbroadcastsd xmm
5532   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5533     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5534       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5535   }
5536
5537   // Unsupported broadcast.
5538   return SDValue();
5539 }
5540
5541 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5542 /// underlying vector and index.
5543 ///
5544 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5545 /// index.
5546 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5547                                          SDValue ExtIdx) {
5548   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5549   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5550     return Idx;
5551
5552   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5553   // lowered this:
5554   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5555   // to:
5556   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5557   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5558   //                           undef)
5559   //                       Constant<0>)
5560   // In this case the vector is the extract_subvector expression and the index
5561   // is 2, as specified by the shuffle.
5562   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5563   SDValue ShuffleVec = SVOp->getOperand(0);
5564   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5565   assert(ShuffleVecVT.getVectorElementType() ==
5566          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5567
5568   int ShuffleIdx = SVOp->getMaskElt(Idx);
5569   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5570     ExtractedFromVec = ShuffleVec;
5571     return ShuffleIdx;
5572   }
5573   return Idx;
5574 }
5575
5576 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5577   MVT VT = Op.getSimpleValueType();
5578
5579   // Skip if insert_vec_elt is not supported.
5580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5581   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5582     return SDValue();
5583
5584   SDLoc DL(Op);
5585   unsigned NumElems = Op.getNumOperands();
5586
5587   SDValue VecIn1;
5588   SDValue VecIn2;
5589   SmallVector<unsigned, 4> InsertIndices;
5590   SmallVector<int, 8> Mask(NumElems, -1);
5591
5592   for (unsigned i = 0; i != NumElems; ++i) {
5593     unsigned Opc = Op.getOperand(i).getOpcode();
5594
5595     if (Opc == ISD::UNDEF)
5596       continue;
5597
5598     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5599       // Quit if more than 1 elements need inserting.
5600       if (InsertIndices.size() > 1)
5601         return SDValue();
5602
5603       InsertIndices.push_back(i);
5604       continue;
5605     }
5606
5607     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5608     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5609     // Quit if non-constant index.
5610     if (!isa<ConstantSDNode>(ExtIdx))
5611       return SDValue();
5612     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5613
5614     // Quit if extracted from vector of different type.
5615     if (ExtractedFromVec.getValueType() != VT)
5616       return SDValue();
5617
5618     if (!VecIn1.getNode())
5619       VecIn1 = ExtractedFromVec;
5620     else if (VecIn1 != ExtractedFromVec) {
5621       if (!VecIn2.getNode())
5622         VecIn2 = ExtractedFromVec;
5623       else if (VecIn2 != ExtractedFromVec)
5624         // Quit if more than 2 vectors to shuffle
5625         return SDValue();
5626     }
5627
5628     if (ExtractedFromVec == VecIn1)
5629       Mask[i] = Idx;
5630     else if (ExtractedFromVec == VecIn2)
5631       Mask[i] = Idx + NumElems;
5632   }
5633
5634   if (!VecIn1.getNode())
5635     return SDValue();
5636
5637   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5638   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5639   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5640     unsigned Idx = InsertIndices[i];
5641     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5642                      DAG.getIntPtrConstant(Idx, DL));
5643   }
5644
5645   return NV;
5646 }
5647
5648 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5649   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5650          Op.getScalarValueSizeInBits() == 1 &&
5651          "Can not convert non-constant vector");
5652   uint64_t Immediate = 0;
5653   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5654     SDValue In = Op.getOperand(idx);
5655     if (In.getOpcode() != ISD::UNDEF)
5656       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5657   }
5658   SDLoc dl(Op);
5659   MVT VT =
5660    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5661   return DAG.getConstant(Immediate, dl, VT);
5662 }
5663 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5664 SDValue
5665 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5666
5667   MVT VT = Op.getSimpleValueType();
5668   assert((VT.getVectorElementType() == MVT::i1) &&
5669          "Unexpected type in LowerBUILD_VECTORvXi1!");
5670
5671   SDLoc dl(Op);
5672   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5673     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5674     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5675     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5676   }
5677
5678   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5679     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5680     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5681     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5682   }
5683
5684   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5685     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5686     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5687       return DAG.getBitcast(VT, Imm);
5688     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5689     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5690                         DAG.getIntPtrConstant(0, dl));
5691   }
5692
5693   // Vector has one or more non-const elements
5694   uint64_t Immediate = 0;
5695   SmallVector<unsigned, 16> NonConstIdx;
5696   bool IsSplat = true;
5697   bool HasConstElts = false;
5698   int SplatIdx = -1;
5699   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5700     SDValue In = Op.getOperand(idx);
5701     if (In.getOpcode() == ISD::UNDEF)
5702       continue;
5703     if (!isa<ConstantSDNode>(In))
5704       NonConstIdx.push_back(idx);
5705     else {
5706       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5707       HasConstElts = true;
5708     }
5709     if (SplatIdx == -1)
5710       SplatIdx = idx;
5711     else if (In != Op.getOperand(SplatIdx))
5712       IsSplat = false;
5713   }
5714
5715   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5716   if (IsSplat)
5717     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5718                        DAG.getConstant(1, dl, VT),
5719                        DAG.getConstant(0, dl, VT));
5720
5721   // insert elements one by one
5722   SDValue DstVec;
5723   SDValue Imm;
5724   if (Immediate) {
5725     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5726     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5727   }
5728   else if (HasConstElts)
5729     Imm = DAG.getConstant(0, dl, VT);
5730   else
5731     Imm = DAG.getUNDEF(VT);
5732   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5733     DstVec = DAG.getBitcast(VT, Imm);
5734   else {
5735     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5736     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5737                          DAG.getIntPtrConstant(0, dl));
5738   }
5739
5740   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5741     unsigned InsertIdx = NonConstIdx[i];
5742     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5743                          Op.getOperand(InsertIdx),
5744                          DAG.getIntPtrConstant(InsertIdx, dl));
5745   }
5746   return DstVec;
5747 }
5748
5749 /// \brief Return true if \p N implements a horizontal binop and return the
5750 /// operands for the horizontal binop into V0 and V1.
5751 ///
5752 /// This is a helper function of LowerToHorizontalOp().
5753 /// This function checks that the build_vector \p N in input implements a
5754 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5755 /// operation to match.
5756 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5757 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5758 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5759 /// arithmetic sub.
5760 ///
5761 /// This function only analyzes elements of \p N whose indices are
5762 /// in range [BaseIdx, LastIdx).
5763 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5764                               SelectionDAG &DAG,
5765                               unsigned BaseIdx, unsigned LastIdx,
5766                               SDValue &V0, SDValue &V1) {
5767   EVT VT = N->getValueType(0);
5768
5769   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5770   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5771          "Invalid Vector in input!");
5772
5773   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5774   bool CanFold = true;
5775   unsigned ExpectedVExtractIdx = BaseIdx;
5776   unsigned NumElts = LastIdx - BaseIdx;
5777   V0 = DAG.getUNDEF(VT);
5778   V1 = DAG.getUNDEF(VT);
5779
5780   // Check if N implements a horizontal binop.
5781   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5782     SDValue Op = N->getOperand(i + BaseIdx);
5783
5784     // Skip UNDEFs.
5785     if (Op->getOpcode() == ISD::UNDEF) {
5786       // Update the expected vector extract index.
5787       if (i * 2 == NumElts)
5788         ExpectedVExtractIdx = BaseIdx;
5789       ExpectedVExtractIdx += 2;
5790       continue;
5791     }
5792
5793     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5794
5795     if (!CanFold)
5796       break;
5797
5798     SDValue Op0 = Op.getOperand(0);
5799     SDValue Op1 = Op.getOperand(1);
5800
5801     // Try to match the following pattern:
5802     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5803     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5804         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5805         Op0.getOperand(0) == Op1.getOperand(0) &&
5806         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5807         isa<ConstantSDNode>(Op1.getOperand(1)));
5808     if (!CanFold)
5809       break;
5810
5811     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5812     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5813
5814     if (i * 2 < NumElts) {
5815       if (V0.getOpcode() == ISD::UNDEF) {
5816         V0 = Op0.getOperand(0);
5817         if (V0.getValueType() != VT)
5818           return false;
5819       }
5820     } else {
5821       if (V1.getOpcode() == ISD::UNDEF) {
5822         V1 = Op0.getOperand(0);
5823         if (V1.getValueType() != VT)
5824           return false;
5825       }
5826       if (i * 2 == NumElts)
5827         ExpectedVExtractIdx = BaseIdx;
5828     }
5829
5830     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5831     if (I0 == ExpectedVExtractIdx)
5832       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5833     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5834       // Try to match the following dag sequence:
5835       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5836       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5837     } else
5838       CanFold = false;
5839
5840     ExpectedVExtractIdx += 2;
5841   }
5842
5843   return CanFold;
5844 }
5845
5846 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5847 /// a concat_vector.
5848 ///
5849 /// This is a helper function of LowerToHorizontalOp().
5850 /// This function expects two 256-bit vectors called V0 and V1.
5851 /// At first, each vector is split into two separate 128-bit vectors.
5852 /// Then, the resulting 128-bit vectors are used to implement two
5853 /// horizontal binary operations.
5854 ///
5855 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5856 ///
5857 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5858 /// the two new horizontal binop.
5859 /// When Mode is set, the first horizontal binop dag node would take as input
5860 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5861 /// horizontal binop dag node would take as input the lower 128-bit of V1
5862 /// and the upper 128-bit of V1.
5863 ///   Example:
5864 ///     HADD V0_LO, V0_HI
5865 ///     HADD V1_LO, V1_HI
5866 ///
5867 /// Otherwise, the first horizontal binop dag node takes as input the lower
5868 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5869 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5870 ///   Example:
5871 ///     HADD V0_LO, V1_LO
5872 ///     HADD V0_HI, V1_HI
5873 ///
5874 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5875 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5876 /// the upper 128-bits of the result.
5877 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5878                                      SDLoc DL, SelectionDAG &DAG,
5879                                      unsigned X86Opcode, bool Mode,
5880                                      bool isUndefLO, bool isUndefHI) {
5881   EVT VT = V0.getValueType();
5882   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5883          "Invalid nodes in input!");
5884
5885   unsigned NumElts = VT.getVectorNumElements();
5886   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5887   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5888   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5889   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5890   EVT NewVT = V0_LO.getValueType();
5891
5892   SDValue LO = DAG.getUNDEF(NewVT);
5893   SDValue HI = DAG.getUNDEF(NewVT);
5894
5895   if (Mode) {
5896     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5897     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5898       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5899     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5900       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5901   } else {
5902     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5903     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5904                        V1_LO->getOpcode() != ISD::UNDEF))
5905       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5906
5907     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5908                        V1_HI->getOpcode() != ISD::UNDEF))
5909       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5910   }
5911
5912   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5913 }
5914
5915 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5916 /// node.
5917 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5918                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5919   EVT VT = BV->getValueType(0);
5920   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5921       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5922     return SDValue();
5923
5924   SDLoc DL(BV);
5925   unsigned NumElts = VT.getVectorNumElements();
5926   SDValue InVec0 = DAG.getUNDEF(VT);
5927   SDValue InVec1 = DAG.getUNDEF(VT);
5928
5929   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5930           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5931
5932   // Odd-numbered elements in the input build vector are obtained from
5933   // adding two integer/float elements.
5934   // Even-numbered elements in the input build vector are obtained from
5935   // subtracting two integer/float elements.
5936   unsigned ExpectedOpcode = ISD::FSUB;
5937   unsigned NextExpectedOpcode = ISD::FADD;
5938   bool AddFound = false;
5939   bool SubFound = false;
5940
5941   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5942     SDValue Op = BV->getOperand(i);
5943
5944     // Skip 'undef' values.
5945     unsigned Opcode = Op.getOpcode();
5946     if (Opcode == ISD::UNDEF) {
5947       std::swap(ExpectedOpcode, NextExpectedOpcode);
5948       continue;
5949     }
5950
5951     // Early exit if we found an unexpected opcode.
5952     if (Opcode != ExpectedOpcode)
5953       return SDValue();
5954
5955     SDValue Op0 = Op.getOperand(0);
5956     SDValue Op1 = Op.getOperand(1);
5957
5958     // Try to match the following pattern:
5959     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5960     // Early exit if we cannot match that sequence.
5961     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5962         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5963         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5964         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5965         Op0.getOperand(1) != Op1.getOperand(1))
5966       return SDValue();
5967
5968     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5969     if (I0 != i)
5970       return SDValue();
5971
5972     // We found a valid add/sub node. Update the information accordingly.
5973     if (i & 1)
5974       AddFound = true;
5975     else
5976       SubFound = true;
5977
5978     // Update InVec0 and InVec1.
5979     if (InVec0.getOpcode() == ISD::UNDEF) {
5980       InVec0 = Op0.getOperand(0);
5981       if (InVec0.getValueType() != VT)
5982         return SDValue();
5983     }
5984     if (InVec1.getOpcode() == ISD::UNDEF) {
5985       InVec1 = Op1.getOperand(0);
5986       if (InVec1.getValueType() != VT)
5987         return SDValue();
5988     }
5989
5990     // Make sure that operands in input to each add/sub node always
5991     // come from a same pair of vectors.
5992     if (InVec0 != Op0.getOperand(0)) {
5993       if (ExpectedOpcode == ISD::FSUB)
5994         return SDValue();
5995
5996       // FADD is commutable. Try to commute the operands
5997       // and then test again.
5998       std::swap(Op0, Op1);
5999       if (InVec0 != Op0.getOperand(0))
6000         return SDValue();
6001     }
6002
6003     if (InVec1 != Op1.getOperand(0))
6004       return SDValue();
6005
6006     // Update the pair of expected opcodes.
6007     std::swap(ExpectedOpcode, NextExpectedOpcode);
6008   }
6009
6010   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6011   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6012       InVec1.getOpcode() != ISD::UNDEF)
6013     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6014
6015   return SDValue();
6016 }
6017
6018 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6019 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6020                                    const X86Subtarget *Subtarget,
6021                                    SelectionDAG &DAG) {
6022   EVT VT = BV->getValueType(0);
6023   unsigned NumElts = VT.getVectorNumElements();
6024   unsigned NumUndefsLO = 0;
6025   unsigned NumUndefsHI = 0;
6026   unsigned Half = NumElts/2;
6027
6028   // Count the number of UNDEF operands in the build_vector in input.
6029   for (unsigned i = 0, e = Half; i != e; ++i)
6030     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6031       NumUndefsLO++;
6032
6033   for (unsigned i = Half, e = NumElts; i != e; ++i)
6034     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6035       NumUndefsHI++;
6036
6037   // Early exit if this is either a build_vector of all UNDEFs or all the
6038   // operands but one are UNDEF.
6039   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6040     return SDValue();
6041
6042   SDLoc DL(BV);
6043   SDValue InVec0, InVec1;
6044   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6045     // Try to match an SSE3 float HADD/HSUB.
6046     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6047       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6048
6049     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6050       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6051   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6052     // Try to match an SSSE3 integer HADD/HSUB.
6053     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6054       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6055
6056     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6057       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6058   }
6059
6060   if (!Subtarget->hasAVX())
6061     return SDValue();
6062
6063   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6064     // Try to match an AVX horizontal add/sub of packed single/double
6065     // precision floating point values from 256-bit vectors.
6066     SDValue InVec2, InVec3;
6067     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6068         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6069         ((InVec0.getOpcode() == ISD::UNDEF ||
6070           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6071         ((InVec1.getOpcode() == ISD::UNDEF ||
6072           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6073       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6074
6075     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6076         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6077         ((InVec0.getOpcode() == ISD::UNDEF ||
6078           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6079         ((InVec1.getOpcode() == ISD::UNDEF ||
6080           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6081       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6082   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6083     // Try to match an AVX2 horizontal add/sub of signed integers.
6084     SDValue InVec2, InVec3;
6085     unsigned X86Opcode;
6086     bool CanFold = true;
6087
6088     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6089         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6090         ((InVec0.getOpcode() == ISD::UNDEF ||
6091           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6092         ((InVec1.getOpcode() == ISD::UNDEF ||
6093           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6094       X86Opcode = X86ISD::HADD;
6095     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6096         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6097         ((InVec0.getOpcode() == ISD::UNDEF ||
6098           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6099         ((InVec1.getOpcode() == ISD::UNDEF ||
6100           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6101       X86Opcode = X86ISD::HSUB;
6102     else
6103       CanFold = false;
6104
6105     if (CanFold) {
6106       // Fold this build_vector into a single horizontal add/sub.
6107       // Do this only if the target has AVX2.
6108       if (Subtarget->hasAVX2())
6109         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6110
6111       // Do not try to expand this build_vector into a pair of horizontal
6112       // add/sub if we can emit a pair of scalar add/sub.
6113       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6114         return SDValue();
6115
6116       // Convert this build_vector into a pair of horizontal binop followed by
6117       // a concat vector.
6118       bool isUndefLO = NumUndefsLO == Half;
6119       bool isUndefHI = NumUndefsHI == Half;
6120       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6121                                    isUndefLO, isUndefHI);
6122     }
6123   }
6124
6125   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6126        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6127     unsigned X86Opcode;
6128     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6129       X86Opcode = X86ISD::HADD;
6130     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6131       X86Opcode = X86ISD::HSUB;
6132     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6133       X86Opcode = X86ISD::FHADD;
6134     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6135       X86Opcode = X86ISD::FHSUB;
6136     else
6137       return SDValue();
6138
6139     // Don't try to expand this build_vector into a pair of horizontal add/sub
6140     // if we can simply emit a pair of scalar add/sub.
6141     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6142       return SDValue();
6143
6144     // Convert this build_vector into two horizontal add/sub followed by
6145     // a concat vector.
6146     bool isUndefLO = NumUndefsLO == Half;
6147     bool isUndefHI = NumUndefsHI == Half;
6148     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6149                                  isUndefLO, isUndefHI);
6150   }
6151
6152   return SDValue();
6153 }
6154
6155 SDValue
6156 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6157   SDLoc dl(Op);
6158
6159   MVT VT = Op.getSimpleValueType();
6160   MVT ExtVT = VT.getVectorElementType();
6161   unsigned NumElems = Op.getNumOperands();
6162
6163   // Generate vectors for predicate vectors.
6164   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6165     return LowerBUILD_VECTORvXi1(Op, DAG);
6166
6167   // Vectors containing all zeros can be matched by pxor and xorps later
6168   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6169     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6170     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6171     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6172       return Op;
6173
6174     return getZeroVector(VT, Subtarget, DAG, dl);
6175   }
6176
6177   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6178   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6179   // vpcmpeqd on 256-bit vectors.
6180   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6181     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6182       return Op;
6183
6184     if (!VT.is512BitVector())
6185       return getOnesVector(VT, Subtarget, DAG, dl);
6186   }
6187
6188   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6189   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6190     return AddSub;
6191   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6192     return HorizontalOp;
6193   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6194     return Broadcast;
6195
6196   unsigned EVTBits = ExtVT.getSizeInBits();
6197
6198   unsigned NumZero  = 0;
6199   unsigned NumNonZero = 0;
6200   unsigned NonZeros = 0;
6201   bool IsAllConstants = true;
6202   SmallSet<SDValue, 8> Values;
6203   for (unsigned i = 0; i < NumElems; ++i) {
6204     SDValue Elt = Op.getOperand(i);
6205     if (Elt.getOpcode() == ISD::UNDEF)
6206       continue;
6207     Values.insert(Elt);
6208     if (Elt.getOpcode() != ISD::Constant &&
6209         Elt.getOpcode() != ISD::ConstantFP)
6210       IsAllConstants = false;
6211     if (X86::isZeroNode(Elt))
6212       NumZero++;
6213     else {
6214       NonZeros |= (1 << i);
6215       NumNonZero++;
6216     }
6217   }
6218
6219   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6220   if (NumNonZero == 0)
6221     return DAG.getUNDEF(VT);
6222
6223   // Special case for single non-zero, non-undef, element.
6224   if (NumNonZero == 1) {
6225     unsigned Idx = countTrailingZeros(NonZeros);
6226     SDValue Item = Op.getOperand(Idx);
6227
6228     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6229     // the value are obviously zero, truncate the value to i32 and do the
6230     // insertion that way.  Only do this if the value is non-constant or if the
6231     // value is a constant being inserted into element 0.  It is cheaper to do
6232     // a constant pool load than it is to do a movd + shuffle.
6233     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6234         (!IsAllConstants || Idx == 0)) {
6235       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6236         // Handle SSE only.
6237         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6238         EVT VecVT = MVT::v4i32;
6239
6240         // Truncate the value (which may itself be a constant) to i32, and
6241         // convert it to a vector with movd (S2V+shuffle to zero extend).
6242         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6243         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6244         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6245                                       Item, Idx * 2, true, Subtarget, DAG));
6246       }
6247     }
6248
6249     // If we have a constant or non-constant insertion into the low element of
6250     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6251     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6252     // depending on what the source datatype is.
6253     if (Idx == 0) {
6254       if (NumZero == 0)
6255         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6256
6257       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6258           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6259         if (VT.is512BitVector()) {
6260           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6261           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6262                              Item, DAG.getIntPtrConstant(0, dl));
6263         }
6264         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6265                "Expected an SSE value type!");
6266         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6267         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6268         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6269       }
6270
6271       // We can't directly insert an i8 or i16 into a vector, so zero extend
6272       // it to i32 first.
6273       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6274         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6275         if (VT.is256BitVector()) {
6276           if (Subtarget->hasAVX()) {
6277             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6278             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6279           } else {
6280             // Without AVX, we need to extend to a 128-bit vector and then
6281             // insert into the 256-bit vector.
6282             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6283             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6284             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6285           }
6286         } else {
6287           assert(VT.is128BitVector() && "Expected an SSE value type!");
6288           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6289           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6290         }
6291         return DAG.getBitcast(VT, Item);
6292       }
6293     }
6294
6295     // Is it a vector logical left shift?
6296     if (NumElems == 2 && Idx == 1 &&
6297         X86::isZeroNode(Op.getOperand(0)) &&
6298         !X86::isZeroNode(Op.getOperand(1))) {
6299       unsigned NumBits = VT.getSizeInBits();
6300       return getVShift(true, VT,
6301                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6302                                    VT, Op.getOperand(1)),
6303                        NumBits/2, DAG, *this, dl);
6304     }
6305
6306     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6307       return SDValue();
6308
6309     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6310     // is a non-constant being inserted into an element other than the low one,
6311     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6312     // movd/movss) to move this into the low element, then shuffle it into
6313     // place.
6314     if (EVTBits == 32) {
6315       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6316       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6317     }
6318   }
6319
6320   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6321   if (Values.size() == 1) {
6322     if (EVTBits == 32) {
6323       // Instead of a shuffle like this:
6324       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6325       // Check if it's possible to issue this instead.
6326       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6327       unsigned Idx = countTrailingZeros(NonZeros);
6328       SDValue Item = Op.getOperand(Idx);
6329       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6330         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6331     }
6332     return SDValue();
6333   }
6334
6335   // A vector full of immediates; various special cases are already
6336   // handled, so this is best done with a single constant-pool load.
6337   if (IsAllConstants)
6338     return SDValue();
6339
6340   // For AVX-length vectors, see if we can use a vector load to get all of the
6341   // elements, otherwise build the individual 128-bit pieces and use
6342   // shuffles to put them in place.
6343   if (VT.is256BitVector() || VT.is512BitVector()) {
6344     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6345
6346     // Check for a build vector of consecutive loads.
6347     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6348       return LD;
6349
6350     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6351
6352     // Build both the lower and upper subvector.
6353     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6354                                 makeArrayRef(&V[0], NumElems/2));
6355     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6356                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6357
6358     // Recreate the wider vector with the lower and upper part.
6359     if (VT.is256BitVector())
6360       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6361     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6362   }
6363
6364   // Let legalizer expand 2-wide build_vectors.
6365   if (EVTBits == 64) {
6366     if (NumNonZero == 1) {
6367       // One half is zero or undef.
6368       unsigned Idx = countTrailingZeros(NonZeros);
6369       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6370                                  Op.getOperand(Idx));
6371       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6372     }
6373     return SDValue();
6374   }
6375
6376   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6377   if (EVTBits == 8 && NumElems == 16)
6378     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6379                                         Subtarget, *this))
6380       return V;
6381
6382   if (EVTBits == 16 && NumElems == 8)
6383     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6384                                       Subtarget, *this))
6385       return V;
6386
6387   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6388   if (EVTBits == 32 && NumElems == 4)
6389     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6390       return V;
6391
6392   // If element VT is == 32 bits, turn it into a number of shuffles.
6393   SmallVector<SDValue, 8> V(NumElems);
6394   if (NumElems == 4 && NumZero > 0) {
6395     for (unsigned i = 0; i < 4; ++i) {
6396       bool isZero = !(NonZeros & (1 << i));
6397       if (isZero)
6398         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6399       else
6400         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6401     }
6402
6403     for (unsigned i = 0; i < 2; ++i) {
6404       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6405         default: break;
6406         case 0:
6407           V[i] = V[i*2];  // Must be a zero vector.
6408           break;
6409         case 1:
6410           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6411           break;
6412         case 2:
6413           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6414           break;
6415         case 3:
6416           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6417           break;
6418       }
6419     }
6420
6421     bool Reverse1 = (NonZeros & 0x3) == 2;
6422     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6423     int MaskVec[] = {
6424       Reverse1 ? 1 : 0,
6425       Reverse1 ? 0 : 1,
6426       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6427       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6428     };
6429     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6430   }
6431
6432   if (Values.size() > 1 && VT.is128BitVector()) {
6433     // Check for a build vector of consecutive loads.
6434     for (unsigned i = 0; i < NumElems; ++i)
6435       V[i] = Op.getOperand(i);
6436
6437     // Check for elements which are consecutive loads.
6438     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6439       return LD;
6440
6441     // Check for a build vector from mostly shuffle plus few inserting.
6442     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6443       return Sh;
6444
6445     // For SSE 4.1, use insertps to put the high elements into the low element.
6446     if (Subtarget->hasSSE41()) {
6447       SDValue Result;
6448       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6449         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6450       else
6451         Result = DAG.getUNDEF(VT);
6452
6453       for (unsigned i = 1; i < NumElems; ++i) {
6454         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6455         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6456                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6457       }
6458       return Result;
6459     }
6460
6461     // Otherwise, expand into a number of unpckl*, start by extending each of
6462     // our (non-undef) elements to the full vector width with the element in the
6463     // bottom slot of the vector (which generates no code for SSE).
6464     for (unsigned i = 0; i < NumElems; ++i) {
6465       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6466         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6467       else
6468         V[i] = DAG.getUNDEF(VT);
6469     }
6470
6471     // Next, we iteratively mix elements, e.g. for v4f32:
6472     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6473     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6474     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6475     unsigned EltStride = NumElems >> 1;
6476     while (EltStride != 0) {
6477       for (unsigned i = 0; i < EltStride; ++i) {
6478         // If V[i+EltStride] is undef and this is the first round of mixing,
6479         // then it is safe to just drop this shuffle: V[i] is already in the
6480         // right place, the one element (since it's the first round) being
6481         // inserted as undef can be dropped.  This isn't safe for successive
6482         // rounds because they will permute elements within both vectors.
6483         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6484             EltStride == NumElems/2)
6485           continue;
6486
6487         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6488       }
6489       EltStride >>= 1;
6490     }
6491     return V[0];
6492   }
6493   return SDValue();
6494 }
6495
6496 // 256-bit AVX can use the vinsertf128 instruction
6497 // to create 256-bit vectors from two other 128-bit ones.
6498 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6499   SDLoc dl(Op);
6500   MVT ResVT = Op.getSimpleValueType();
6501
6502   assert((ResVT.is256BitVector() ||
6503           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6504
6505   SDValue V1 = Op.getOperand(0);
6506   SDValue V2 = Op.getOperand(1);
6507   unsigned NumElems = ResVT.getVectorNumElements();
6508   if (ResVT.is256BitVector())
6509     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6510
6511   if (Op.getNumOperands() == 4) {
6512     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6513                                 ResVT.getVectorNumElements()/2);
6514     SDValue V3 = Op.getOperand(2);
6515     SDValue V4 = Op.getOperand(3);
6516     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6517       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6518   }
6519   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6520 }
6521
6522 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6523                                        const X86Subtarget *Subtarget,
6524                                        SelectionDAG & DAG) {
6525   SDLoc dl(Op);
6526   MVT ResVT = Op.getSimpleValueType();
6527   unsigned NumOfOperands = Op.getNumOperands();
6528
6529   assert(isPowerOf2_32(NumOfOperands) &&
6530          "Unexpected number of operands in CONCAT_VECTORS");
6531
6532   if (NumOfOperands > 2) {
6533     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6534                                   ResVT.getVectorNumElements()/2);
6535     SmallVector<SDValue, 2> Ops;
6536     for (unsigned i = 0; i < NumOfOperands/2; i++)
6537       Ops.push_back(Op.getOperand(i));
6538     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6539     Ops.clear();
6540     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6541       Ops.push_back(Op.getOperand(i));
6542     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6543     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6544   }
6545
6546   SDValue V1 = Op.getOperand(0);
6547   SDValue V2 = Op.getOperand(1);
6548   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6549   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6550
6551   if (IsZeroV1 && IsZeroV2)
6552     return getZeroVector(ResVT, Subtarget, DAG, dl);
6553
6554   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6555   SDValue Undef = DAG.getUNDEF(ResVT);
6556   unsigned NumElems = ResVT.getVectorNumElements();
6557   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6558
6559   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6560   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6561   if (IsZeroV1)
6562     return V2;
6563
6564   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6565   // Zero the upper bits of V1
6566   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6567   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6568   if (IsZeroV2)
6569     return V1;
6570   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6571 }
6572
6573 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6574                                    const X86Subtarget *Subtarget,
6575                                    SelectionDAG &DAG) {
6576   MVT VT = Op.getSimpleValueType();
6577   if (VT.getVectorElementType() == MVT::i1)
6578     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6579
6580   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6581          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6582           Op.getNumOperands() == 4)));
6583
6584   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6585   // from two other 128-bit ones.
6586
6587   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6588   return LowerAVXCONCAT_VECTORS(Op, DAG);
6589 }
6590
6591 //===----------------------------------------------------------------------===//
6592 // Vector shuffle lowering
6593 //
6594 // This is an experimental code path for lowering vector shuffles on x86. It is
6595 // designed to handle arbitrary vector shuffles and blends, gracefully
6596 // degrading performance as necessary. It works hard to recognize idiomatic
6597 // shuffles and lower them to optimal instruction patterns without leaving
6598 // a framework that allows reasonably efficient handling of all vector shuffle
6599 // patterns.
6600 //===----------------------------------------------------------------------===//
6601
6602 /// \brief Tiny helper function to identify a no-op mask.
6603 ///
6604 /// This is a somewhat boring predicate function. It checks whether the mask
6605 /// array input, which is assumed to be a single-input shuffle mask of the kind
6606 /// used by the X86 shuffle instructions (not a fully general
6607 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6608 /// in-place shuffle are 'no-op's.
6609 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6610   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6611     if (Mask[i] != -1 && Mask[i] != i)
6612       return false;
6613   return true;
6614 }
6615
6616 /// \brief Helper function to classify a mask as a single-input mask.
6617 ///
6618 /// This isn't a generic single-input test because in the vector shuffle
6619 /// lowering we canonicalize single inputs to be the first input operand. This
6620 /// means we can more quickly test for a single input by only checking whether
6621 /// an input from the second operand exists. We also assume that the size of
6622 /// mask corresponds to the size of the input vectors which isn't true in the
6623 /// fully general case.
6624 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6625   for (int M : Mask)
6626     if (M >= (int)Mask.size())
6627       return false;
6628   return true;
6629 }
6630
6631 /// \brief Test whether there are elements crossing 128-bit lanes in this
6632 /// shuffle mask.
6633 ///
6634 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6635 /// and we routinely test for these.
6636 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6637   int LaneSize = 128 / VT.getScalarSizeInBits();
6638   int Size = Mask.size();
6639   for (int i = 0; i < Size; ++i)
6640     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6641       return true;
6642   return false;
6643 }
6644
6645 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6646 ///
6647 /// This checks a shuffle mask to see if it is performing the same
6648 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6649 /// that it is also not lane-crossing. It may however involve a blend from the
6650 /// same lane of a second vector.
6651 ///
6652 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6653 /// non-trivial to compute in the face of undef lanes. The representation is
6654 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6655 /// entries from both V1 and V2 inputs to the wider mask.
6656 static bool
6657 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6658                                 SmallVectorImpl<int> &RepeatedMask) {
6659   int LaneSize = 128 / VT.getScalarSizeInBits();
6660   RepeatedMask.resize(LaneSize, -1);
6661   int Size = Mask.size();
6662   for (int i = 0; i < Size; ++i) {
6663     if (Mask[i] < 0)
6664       continue;
6665     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6666       // This entry crosses lanes, so there is no way to model this shuffle.
6667       return false;
6668
6669     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6670     if (RepeatedMask[i % LaneSize] == -1)
6671       // This is the first non-undef entry in this slot of a 128-bit lane.
6672       RepeatedMask[i % LaneSize] =
6673           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6674     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6675       // Found a mismatch with the repeated mask.
6676       return false;
6677   }
6678   return true;
6679 }
6680
6681 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6682 /// arguments.
6683 ///
6684 /// This is a fast way to test a shuffle mask against a fixed pattern:
6685 ///
6686 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6687 ///
6688 /// It returns true if the mask is exactly as wide as the argument list, and
6689 /// each element of the mask is either -1 (signifying undef) or the value given
6690 /// in the argument.
6691 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6692                                 ArrayRef<int> ExpectedMask) {
6693   if (Mask.size() != ExpectedMask.size())
6694     return false;
6695
6696   int Size = Mask.size();
6697
6698   // If the values are build vectors, we can look through them to find
6699   // equivalent inputs that make the shuffles equivalent.
6700   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6701   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6702
6703   for (int i = 0; i < Size; ++i)
6704     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6705       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6706       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6707       if (!MaskBV || !ExpectedBV ||
6708           MaskBV->getOperand(Mask[i] % Size) !=
6709               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6710         return false;
6711     }
6712
6713   return true;
6714 }
6715
6716 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6717 ///
6718 /// This helper function produces an 8-bit shuffle immediate corresponding to
6719 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6720 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6721 /// example.
6722 ///
6723 /// NB: We rely heavily on "undef" masks preserving the input lane.
6724 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6725                                           SelectionDAG &DAG) {
6726   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6727   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6728   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6729   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6730   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6731
6732   unsigned Imm = 0;
6733   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6734   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6735   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6736   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6737   return DAG.getConstant(Imm, DL, MVT::i8);
6738 }
6739
6740 /// \brief Compute whether each element of a shuffle is zeroable.
6741 ///
6742 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6743 /// Either it is an undef element in the shuffle mask, the element of the input
6744 /// referenced is undef, or the element of the input referenced is known to be
6745 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6746 /// as many lanes with this technique as possible to simplify the remaining
6747 /// shuffle.
6748 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6749                                                      SDValue V1, SDValue V2) {
6750   SmallBitVector Zeroable(Mask.size(), false);
6751
6752   while (V1.getOpcode() == ISD::BITCAST)
6753     V1 = V1->getOperand(0);
6754   while (V2.getOpcode() == ISD::BITCAST)
6755     V2 = V2->getOperand(0);
6756
6757   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6758   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6759
6760   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6761     int M = Mask[i];
6762     // Handle the easy cases.
6763     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6764       Zeroable[i] = true;
6765       continue;
6766     }
6767
6768     // If this is an index into a build_vector node (which has the same number
6769     // of elements), dig out the input value and use it.
6770     SDValue V = M < Size ? V1 : V2;
6771     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6772       continue;
6773
6774     SDValue Input = V.getOperand(M % Size);
6775     // The UNDEF opcode check really should be dead code here, but not quite
6776     // worth asserting on (it isn't invalid, just unexpected).
6777     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6778       Zeroable[i] = true;
6779   }
6780
6781   return Zeroable;
6782 }
6783
6784 // X86 has dedicated unpack instructions that can handle specific blend
6785 // operations: UNPCKH and UNPCKL.
6786 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6787                                            SDValue V1, SDValue V2,
6788                                            SelectionDAG &DAG) {
6789   int NumElts = VT.getVectorNumElements();
6790   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6791   SmallVector<int, 8> Unpckl;
6792   SmallVector<int, 8> Unpckh;
6793
6794   for (int i = 0; i < NumElts; ++i) {
6795     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6796     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6797     int HiPos = LoPos + NumEltsInLane / 2;
6798     Unpckl.push_back(LoPos);
6799     Unpckh.push_back(HiPos);
6800   }
6801
6802   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6803     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6804   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6805     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6806
6807   // Commute and try again.
6808   ShuffleVectorSDNode::commuteMask(Unpckl);
6809   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6810     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6811
6812   ShuffleVectorSDNode::commuteMask(Unpckh);
6813   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6814     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6815
6816   return SDValue();
6817 }
6818
6819 /// \brief Try to emit a bitmask instruction for a shuffle.
6820 ///
6821 /// This handles cases where we can model a blend exactly as a bitmask due to
6822 /// one of the inputs being zeroable.
6823 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6824                                            SDValue V2, ArrayRef<int> Mask,
6825                                            SelectionDAG &DAG) {
6826   MVT EltVT = VT.getScalarType();
6827   int NumEltBits = EltVT.getSizeInBits();
6828   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6829   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6830   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6831                                     IntEltVT);
6832   if (EltVT.isFloatingPoint()) {
6833     Zero = DAG.getBitcast(EltVT, Zero);
6834     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6835   }
6836   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6837   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6838   SDValue V;
6839   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6840     if (Zeroable[i])
6841       continue;
6842     if (Mask[i] % Size != i)
6843       return SDValue(); // Not a blend.
6844     if (!V)
6845       V = Mask[i] < Size ? V1 : V2;
6846     else if (V != (Mask[i] < Size ? V1 : V2))
6847       return SDValue(); // Can only let one input through the mask.
6848
6849     VMaskOps[i] = AllOnes;
6850   }
6851   if (!V)
6852     return SDValue(); // No non-zeroable elements!
6853
6854   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6855   V = DAG.getNode(VT.isFloatingPoint()
6856                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6857                   DL, VT, V, VMask);
6858   return V;
6859 }
6860
6861 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6862 ///
6863 /// This is used as a fallback approach when first class blend instructions are
6864 /// unavailable. Currently it is only suitable for integer vectors, but could
6865 /// be generalized for floating point vectors if desirable.
6866 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6867                                             SDValue V2, ArrayRef<int> Mask,
6868                                             SelectionDAG &DAG) {
6869   assert(VT.isInteger() && "Only supports integer vector types!");
6870   MVT EltVT = VT.getScalarType();
6871   int NumEltBits = EltVT.getSizeInBits();
6872   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6873   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6874                                     EltVT);
6875   SmallVector<SDValue, 16> MaskOps;
6876   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6877     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6878       return SDValue(); // Shuffled input!
6879     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6880   }
6881
6882   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6883   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6884   // We have to cast V2 around.
6885   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6886   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6887                                       DAG.getBitcast(MaskVT, V1Mask),
6888                                       DAG.getBitcast(MaskVT, V2)));
6889   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6890 }
6891
6892 /// \brief Try to emit a blend instruction for a shuffle.
6893 ///
6894 /// This doesn't do any checks for the availability of instructions for blending
6895 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6896 /// be matched in the backend with the type given. What it does check for is
6897 /// that the shuffle mask is in fact a blend.
6898 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6899                                          SDValue V2, ArrayRef<int> Mask,
6900                                          const X86Subtarget *Subtarget,
6901                                          SelectionDAG &DAG) {
6902   unsigned BlendMask = 0;
6903   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6904     if (Mask[i] >= Size) {
6905       if (Mask[i] != i + Size)
6906         return SDValue(); // Shuffled V2 input!
6907       BlendMask |= 1u << i;
6908       continue;
6909     }
6910     if (Mask[i] >= 0 && Mask[i] != i)
6911       return SDValue(); // Shuffled V1 input!
6912   }
6913   switch (VT.SimpleTy) {
6914   case MVT::v2f64:
6915   case MVT::v4f32:
6916   case MVT::v4f64:
6917   case MVT::v8f32:
6918     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6919                        DAG.getConstant(BlendMask, DL, MVT::i8));
6920
6921   case MVT::v4i64:
6922   case MVT::v8i32:
6923     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6924     // FALLTHROUGH
6925   case MVT::v2i64:
6926   case MVT::v4i32:
6927     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6928     // that instruction.
6929     if (Subtarget->hasAVX2()) {
6930       // Scale the blend by the number of 32-bit dwords per element.
6931       int Scale =  VT.getScalarSizeInBits() / 32;
6932       BlendMask = 0;
6933       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6934         if (Mask[i] >= Size)
6935           for (int j = 0; j < Scale; ++j)
6936             BlendMask |= 1u << (i * Scale + j);
6937
6938       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6939       V1 = DAG.getBitcast(BlendVT, V1);
6940       V2 = DAG.getBitcast(BlendVT, V2);
6941       return DAG.getBitcast(
6942           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6943                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6944     }
6945     // FALLTHROUGH
6946   case MVT::v8i16: {
6947     // For integer shuffles we need to expand the mask and cast the inputs to
6948     // v8i16s prior to blending.
6949     int Scale = 8 / VT.getVectorNumElements();
6950     BlendMask = 0;
6951     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6952       if (Mask[i] >= Size)
6953         for (int j = 0; j < Scale; ++j)
6954           BlendMask |= 1u << (i * Scale + j);
6955
6956     V1 = DAG.getBitcast(MVT::v8i16, V1);
6957     V2 = DAG.getBitcast(MVT::v8i16, V2);
6958     return DAG.getBitcast(VT,
6959                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6960                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6961   }
6962
6963   case MVT::v16i16: {
6964     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6965     SmallVector<int, 8> RepeatedMask;
6966     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6967       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6968       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6969       BlendMask = 0;
6970       for (int i = 0; i < 8; ++i)
6971         if (RepeatedMask[i] >= 16)
6972           BlendMask |= 1u << i;
6973       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6974                          DAG.getConstant(BlendMask, DL, MVT::i8));
6975     }
6976   }
6977     // FALLTHROUGH
6978   case MVT::v16i8:
6979   case MVT::v32i8: {
6980     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6981            "256-bit byte-blends require AVX2 support!");
6982
6983     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6984     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6985       return Masked;
6986
6987     // Scale the blend by the number of bytes per element.
6988     int Scale = VT.getScalarSizeInBits() / 8;
6989
6990     // This form of blend is always done on bytes. Compute the byte vector
6991     // type.
6992     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6993
6994     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6995     // mix of LLVM's code generator and the x86 backend. We tell the code
6996     // generator that boolean values in the elements of an x86 vector register
6997     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6998     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6999     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7000     // of the element (the remaining are ignored) and 0 in that high bit would
7001     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7002     // the LLVM model for boolean values in vector elements gets the relevant
7003     // bit set, it is set backwards and over constrained relative to x86's
7004     // actual model.
7005     SmallVector<SDValue, 32> VSELECTMask;
7006     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7007       for (int j = 0; j < Scale; ++j)
7008         VSELECTMask.push_back(
7009             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7010                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7011                                           MVT::i8));
7012
7013     V1 = DAG.getBitcast(BlendVT, V1);
7014     V2 = DAG.getBitcast(BlendVT, V2);
7015     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7016                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7017                                                       BlendVT, VSELECTMask),
7018                                           V1, V2));
7019   }
7020
7021   default:
7022     llvm_unreachable("Not a supported integer vector type!");
7023   }
7024 }
7025
7026 /// \brief Try to lower as a blend of elements from two inputs followed by
7027 /// a single-input permutation.
7028 ///
7029 /// This matches the pattern where we can blend elements from two inputs and
7030 /// then reduce the shuffle to a single-input permutation.
7031 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7032                                                    SDValue V2,
7033                                                    ArrayRef<int> Mask,
7034                                                    SelectionDAG &DAG) {
7035   // We build up the blend mask while checking whether a blend is a viable way
7036   // to reduce the shuffle.
7037   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7038   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7039
7040   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7041     if (Mask[i] < 0)
7042       continue;
7043
7044     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7045
7046     if (BlendMask[Mask[i] % Size] == -1)
7047       BlendMask[Mask[i] % Size] = Mask[i];
7048     else if (BlendMask[Mask[i] % Size] != Mask[i])
7049       return SDValue(); // Can't blend in the needed input!
7050
7051     PermuteMask[i] = Mask[i] % Size;
7052   }
7053
7054   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7055   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7056 }
7057
7058 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7059 /// blends and permutes.
7060 ///
7061 /// This matches the extremely common pattern for handling combined
7062 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7063 /// operations. It will try to pick the best arrangement of shuffles and
7064 /// blends.
7065 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7066                                                           SDValue V1,
7067                                                           SDValue V2,
7068                                                           ArrayRef<int> Mask,
7069                                                           SelectionDAG &DAG) {
7070   // Shuffle the input elements into the desired positions in V1 and V2 and
7071   // blend them together.
7072   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7073   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7074   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7075   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7076     if (Mask[i] >= 0 && Mask[i] < Size) {
7077       V1Mask[i] = Mask[i];
7078       BlendMask[i] = i;
7079     } else if (Mask[i] >= Size) {
7080       V2Mask[i] = Mask[i] - Size;
7081       BlendMask[i] = i + Size;
7082     }
7083
7084   // Try to lower with the simpler initial blend strategy unless one of the
7085   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7086   // shuffle may be able to fold with a load or other benefit. However, when
7087   // we'll have to do 2x as many shuffles in order to achieve this, blending
7088   // first is a better strategy.
7089   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7090     if (SDValue BlendPerm =
7091             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7092       return BlendPerm;
7093
7094   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7095   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7096   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7097 }
7098
7099 /// \brief Try to lower a vector shuffle as a byte rotation.
7100 ///
7101 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7102 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7103 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7104 /// try to generically lower a vector shuffle through such an pattern. It
7105 /// does not check for the profitability of lowering either as PALIGNR or
7106 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7107 /// This matches shuffle vectors that look like:
7108 ///
7109 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7110 ///
7111 /// Essentially it concatenates V1 and V2, shifts right by some number of
7112 /// elements, and takes the low elements as the result. Note that while this is
7113 /// specified as a *right shift* because x86 is little-endian, it is a *left
7114 /// rotate* of the vector lanes.
7115 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7116                                               SDValue V2,
7117                                               ArrayRef<int> Mask,
7118                                               const X86Subtarget *Subtarget,
7119                                               SelectionDAG &DAG) {
7120   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7121
7122   int NumElts = Mask.size();
7123   int NumLanes = VT.getSizeInBits() / 128;
7124   int NumLaneElts = NumElts / NumLanes;
7125
7126   // We need to detect various ways of spelling a rotation:
7127   //   [11, 12, 13, 14, 15,  0,  1,  2]
7128   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7129   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7130   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7131   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7132   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7133   int Rotation = 0;
7134   SDValue Lo, Hi;
7135   for (int l = 0; l < NumElts; l += NumLaneElts) {
7136     for (int i = 0; i < NumLaneElts; ++i) {
7137       if (Mask[l + i] == -1)
7138         continue;
7139       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7140
7141       // Get the mod-Size index and lane correct it.
7142       int LaneIdx = (Mask[l + i] % NumElts) - l;
7143       // Make sure it was in this lane.
7144       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7145         return SDValue();
7146
7147       // Determine where a rotated vector would have started.
7148       int StartIdx = i - LaneIdx;
7149       if (StartIdx == 0)
7150         // The identity rotation isn't interesting, stop.
7151         return SDValue();
7152
7153       // If we found the tail of a vector the rotation must be the missing
7154       // front. If we found the head of a vector, it must be how much of the
7155       // head.
7156       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7157
7158       if (Rotation == 0)
7159         Rotation = CandidateRotation;
7160       else if (Rotation != CandidateRotation)
7161         // The rotations don't match, so we can't match this mask.
7162         return SDValue();
7163
7164       // Compute which value this mask is pointing at.
7165       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7166
7167       // Compute which of the two target values this index should be assigned
7168       // to. This reflects whether the high elements are remaining or the low
7169       // elements are remaining.
7170       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7171
7172       // Either set up this value if we've not encountered it before, or check
7173       // that it remains consistent.
7174       if (!TargetV)
7175         TargetV = MaskV;
7176       else if (TargetV != MaskV)
7177         // This may be a rotation, but it pulls from the inputs in some
7178         // unsupported interleaving.
7179         return SDValue();
7180     }
7181   }
7182
7183   // Check that we successfully analyzed the mask, and normalize the results.
7184   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7185   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7186   if (!Lo)
7187     Lo = Hi;
7188   else if (!Hi)
7189     Hi = Lo;
7190
7191   // The actual rotate instruction rotates bytes, so we need to scale the
7192   // rotation based on how many bytes are in the vector lane.
7193   int Scale = 16 / NumLaneElts;
7194
7195   // SSSE3 targets can use the palignr instruction.
7196   if (Subtarget->hasSSSE3()) {
7197     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7198     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7199     Lo = DAG.getBitcast(AlignVT, Lo);
7200     Hi = DAG.getBitcast(AlignVT, Hi);
7201
7202     return DAG.getBitcast(
7203         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7204                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7205   }
7206
7207   assert(VT.getSizeInBits() == 128 &&
7208          "Rotate-based lowering only supports 128-bit lowering!");
7209   assert(Mask.size() <= 16 &&
7210          "Can shuffle at most 16 bytes in a 128-bit vector!");
7211
7212   // Default SSE2 implementation
7213   int LoByteShift = 16 - Rotation * Scale;
7214   int HiByteShift = Rotation * Scale;
7215
7216   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7217   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7218   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7219
7220   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7221                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7222   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7223                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7224   return DAG.getBitcast(VT,
7225                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7226 }
7227
7228 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7229 ///
7230 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7231 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7232 /// matches elements from one of the input vectors shuffled to the left or
7233 /// right with zeroable elements 'shifted in'. It handles both the strictly
7234 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7235 /// quad word lane.
7236 ///
7237 /// PSHL : (little-endian) left bit shift.
7238 /// [ zz, 0, zz,  2 ]
7239 /// [ -1, 4, zz, -1 ]
7240 /// PSRL : (little-endian) right bit shift.
7241 /// [  1, zz,  3, zz]
7242 /// [ -1, -1,  7, zz]
7243 /// PSLLDQ : (little-endian) left byte shift
7244 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7245 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7246 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7247 /// PSRLDQ : (little-endian) right byte shift
7248 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7249 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7250 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7251 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7252                                          SDValue V2, ArrayRef<int> Mask,
7253                                          SelectionDAG &DAG) {
7254   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7255
7256   int Size = Mask.size();
7257   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7258
7259   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7260     for (int i = 0; i < Size; i += Scale)
7261       for (int j = 0; j < Shift; ++j)
7262         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7263           return false;
7264
7265     return true;
7266   };
7267
7268   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7269     for (int i = 0; i != Size; i += Scale) {
7270       unsigned Pos = Left ? i + Shift : i;
7271       unsigned Low = Left ? i : i + Shift;
7272       unsigned Len = Scale - Shift;
7273       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7274                                       Low + (V == V1 ? 0 : Size)))
7275         return SDValue();
7276     }
7277
7278     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7279     bool ByteShift = ShiftEltBits > 64;
7280     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7281                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7282     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7283
7284     // Normalize the scale for byte shifts to still produce an i64 element
7285     // type.
7286     Scale = ByteShift ? Scale / 2 : Scale;
7287
7288     // We need to round trip through the appropriate type for the shift.
7289     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7290     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7291     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7292            "Illegal integer vector type");
7293     V = DAG.getBitcast(ShiftVT, V);
7294
7295     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7296                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7297     return DAG.getBitcast(VT, V);
7298   };
7299
7300   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7301   // keep doubling the size of the integer elements up to that. We can
7302   // then shift the elements of the integer vector by whole multiples of
7303   // their width within the elements of the larger integer vector. Test each
7304   // multiple to see if we can find a match with the moved element indices
7305   // and that the shifted in elements are all zeroable.
7306   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7307     for (int Shift = 1; Shift != Scale; ++Shift)
7308       for (bool Left : {true, false})
7309         if (CheckZeros(Shift, Scale, Left))
7310           for (SDValue V : {V1, V2})
7311             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7312               return Match;
7313
7314   // no match
7315   return SDValue();
7316 }
7317
7318 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7319 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7320                                            SDValue V2, ArrayRef<int> Mask,
7321                                            SelectionDAG &DAG) {
7322   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7323   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7324
7325   int Size = Mask.size();
7326   int HalfSize = Size / 2;
7327   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7328
7329   // Upper half must be undefined.
7330   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7331     return SDValue();
7332
7333   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7334   // Remainder of lower half result is zero and upper half is all undef.
7335   auto LowerAsEXTRQ = [&]() {
7336     // Determine the extraction length from the part of the
7337     // lower half that isn't zeroable.
7338     int Len = HalfSize;
7339     for (; Len > 0; --Len)
7340       if (!Zeroable[Len - 1])
7341         break;
7342     assert(Len > 0 && "Zeroable shuffle mask");
7343
7344     // Attempt to match first Len sequential elements from the lower half.
7345     SDValue Src;
7346     int Idx = -1;
7347     for (int i = 0; i != Len; ++i) {
7348       int M = Mask[i];
7349       if (M < 0)
7350         continue;
7351       SDValue &V = (M < Size ? V1 : V2);
7352       M = M % Size;
7353
7354       // All mask elements must be in the lower half.
7355       if (M >= HalfSize)
7356         return SDValue();
7357
7358       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7359         Src = V;
7360         Idx = M - i;
7361         continue;
7362       }
7363       return SDValue();
7364     }
7365
7366     if (Idx < 0)
7367       return SDValue();
7368
7369     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7370     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7371     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7372     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7373                        DAG.getConstant(BitLen, DL, MVT::i8),
7374                        DAG.getConstant(BitIdx, DL, MVT::i8));
7375   };
7376
7377   if (SDValue ExtrQ = LowerAsEXTRQ())
7378     return ExtrQ;
7379
7380   // INSERTQ: Extract lowest Len elements from lower half of second source and
7381   // insert over first source, starting at Idx.
7382   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7383   auto LowerAsInsertQ = [&]() {
7384     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7385       SDValue Base;
7386
7387       // Attempt to match first source from mask before insertion point.
7388       if (isUndefInRange(Mask, 0, Idx)) {
7389         /* EMPTY */
7390       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7391         Base = V1;
7392       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7393         Base = V2;
7394       } else {
7395         continue;
7396       }
7397
7398       // Extend the extraction length looking to match both the insertion of
7399       // the second source and the remaining elements of the first.
7400       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7401         SDValue Insert;
7402         int Len = Hi - Idx;
7403
7404         // Match insertion.
7405         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7406           Insert = V1;
7407         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7408           Insert = V2;
7409         } else {
7410           continue;
7411         }
7412
7413         // Match the remaining elements of the lower half.
7414         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7415           /* EMPTY */
7416         } else if ((!Base || (Base == V1)) &&
7417                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7418           Base = V1;
7419         } else if ((!Base || (Base == V2)) &&
7420                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7421                                               Size + Hi)) {
7422           Base = V2;
7423         } else {
7424           continue;
7425         }
7426
7427         // We may not have a base (first source) - this can safely be undefined.
7428         if (!Base)
7429           Base = DAG.getUNDEF(VT);
7430
7431         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7432         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7433         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7434                            DAG.getConstant(BitLen, DL, MVT::i8),
7435                            DAG.getConstant(BitIdx, DL, MVT::i8));
7436       }
7437     }
7438
7439     return SDValue();
7440   };
7441
7442   if (SDValue InsertQ = LowerAsInsertQ())
7443     return InsertQ;
7444
7445   return SDValue();
7446 }
7447
7448 /// \brief Lower a vector shuffle as a zero or any extension.
7449 ///
7450 /// Given a specific number of elements, element bit width, and extension
7451 /// stride, produce either a zero or any extension based on the available
7452 /// features of the subtarget. The extended elements are consecutive and
7453 /// begin and can start from an offseted element index in the input; to
7454 /// avoid excess shuffling the offset must either being in the bottom lane
7455 /// or at the start of a higher lane. All extended elements must be from
7456 /// the same lane.
7457 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7458     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7459     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7460   assert(Scale > 1 && "Need a scale to extend.");
7461   int EltBits = VT.getScalarSizeInBits();
7462   int NumElements = VT.getVectorNumElements();
7463   int NumEltsPerLane = 128 / EltBits;
7464   int OffsetLane = Offset / NumEltsPerLane;
7465   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7466          "Only 8, 16, and 32 bit elements can be extended.");
7467   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7468   assert(0 <= Offset && "Extension offset must be positive.");
7469   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7470          "Extension offset must be in the first lane or start an upper lane.");
7471
7472   // Check that an index is in same lane as the base offset.
7473   auto SafeOffset = [&](int Idx) {
7474     return OffsetLane == (Idx / NumEltsPerLane);
7475   };
7476
7477   // Shift along an input so that the offset base moves to the first element.
7478   auto ShuffleOffset = [&](SDValue V) {
7479     if (!Offset)
7480       return V;
7481
7482     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7483     for (int i = 0; i * Scale < NumElements; ++i) {
7484       int SrcIdx = i + Offset;
7485       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7486     }
7487     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7488   };
7489
7490   // Found a valid zext mask! Try various lowering strategies based on the
7491   // input type and available ISA extensions.
7492   if (Subtarget->hasSSE41()) {
7493     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7494     // PUNPCK will catch this in a later shuffle match.
7495     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7496       return SDValue();
7497     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7498                                  NumElements / Scale);
7499     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7500     return DAG.getBitcast(VT, InputV);
7501   }
7502
7503   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7504
7505   // For any extends we can cheat for larger element sizes and use shuffle
7506   // instructions that can fold with a load and/or copy.
7507   if (AnyExt && EltBits == 32) {
7508     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7509                          -1};
7510     return DAG.getBitcast(
7511         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7512                         DAG.getBitcast(MVT::v4i32, InputV),
7513                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7514   }
7515   if (AnyExt && EltBits == 16 && Scale > 2) {
7516     int PSHUFDMask[4] = {Offset / 2, -1,
7517                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7518     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7519                          DAG.getBitcast(MVT::v4i32, InputV),
7520                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7521     int PSHUFWMask[4] = {1, -1, -1, -1};
7522     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7523     return DAG.getBitcast(
7524         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7525                         DAG.getBitcast(MVT::v8i16, InputV),
7526                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7527   }
7528
7529   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7530   // to 64-bits.
7531   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7532     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7533     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7534
7535     int LoIdx = Offset * EltBits;
7536     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7537                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7538                                          DAG.getConstant(EltBits, DL, MVT::i8),
7539                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7540
7541     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7542         !SafeOffset(Offset + 1))
7543       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7544
7545     int HiIdx = (Offset + 1) * EltBits;
7546     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7547                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7548                                          DAG.getConstant(EltBits, DL, MVT::i8),
7549                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7550     return DAG.getNode(ISD::BITCAST, DL, VT,
7551                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7552   }
7553
7554   // If this would require more than 2 unpack instructions to expand, use
7555   // pshufb when available. We can only use more than 2 unpack instructions
7556   // when zero extending i8 elements which also makes it easier to use pshufb.
7557   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7558     assert(NumElements == 16 && "Unexpected byte vector width!");
7559     SDValue PSHUFBMask[16];
7560     for (int i = 0; i < 16; ++i) {
7561       int Idx = Offset + (i / Scale);
7562       PSHUFBMask[i] = DAG.getConstant(
7563           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7564     }
7565     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7566     return DAG.getBitcast(VT,
7567                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7568                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7569                                                   MVT::v16i8, PSHUFBMask)));
7570   }
7571
7572   // If we are extending from an offset, ensure we start on a boundary that
7573   // we can unpack from.
7574   int AlignToUnpack = Offset % (NumElements / Scale);
7575   if (AlignToUnpack) {
7576     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7577     for (int i = AlignToUnpack; i < NumElements; ++i)
7578       ShMask[i - AlignToUnpack] = i;
7579     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7580     Offset -= AlignToUnpack;
7581   }
7582
7583   // Otherwise emit a sequence of unpacks.
7584   do {
7585     unsigned UnpackLoHi = X86ISD::UNPCKL;
7586     if (Offset >= (NumElements / 2)) {
7587       UnpackLoHi = X86ISD::UNPCKH;
7588       Offset -= (NumElements / 2);
7589     }
7590
7591     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7592     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7593                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7594     InputV = DAG.getBitcast(InputVT, InputV);
7595     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7596     Scale /= 2;
7597     EltBits *= 2;
7598     NumElements /= 2;
7599   } while (Scale > 1);
7600   return DAG.getBitcast(VT, InputV);
7601 }
7602
7603 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7604 ///
7605 /// This routine will try to do everything in its power to cleverly lower
7606 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7607 /// check for the profitability of this lowering,  it tries to aggressively
7608 /// match this pattern. It will use all of the micro-architectural details it
7609 /// can to emit an efficient lowering. It handles both blends with all-zero
7610 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7611 /// masking out later).
7612 ///
7613 /// The reason we have dedicated lowering for zext-style shuffles is that they
7614 /// are both incredibly common and often quite performance sensitive.
7615 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7616     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7617     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7618   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7619
7620   int Bits = VT.getSizeInBits();
7621   int NumLanes = Bits / 128;
7622   int NumElements = VT.getVectorNumElements();
7623   int NumEltsPerLane = NumElements / NumLanes;
7624   assert(VT.getScalarSizeInBits() <= 32 &&
7625          "Exceeds 32-bit integer zero extension limit");
7626   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7627
7628   // Define a helper function to check a particular ext-scale and lower to it if
7629   // valid.
7630   auto Lower = [&](int Scale) -> SDValue {
7631     SDValue InputV;
7632     bool AnyExt = true;
7633     int Offset = 0;
7634     int Matches = 0;
7635     for (int i = 0; i < NumElements; ++i) {
7636       int M = Mask[i];
7637       if (M == -1)
7638         continue; // Valid anywhere but doesn't tell us anything.
7639       if (i % Scale != 0) {
7640         // Each of the extended elements need to be zeroable.
7641         if (!Zeroable[i])
7642           return SDValue();
7643
7644         // We no longer are in the anyext case.
7645         AnyExt = false;
7646         continue;
7647       }
7648
7649       // Each of the base elements needs to be consecutive indices into the
7650       // same input vector.
7651       SDValue V = M < NumElements ? V1 : V2;
7652       M = M % NumElements;
7653       if (!InputV) {
7654         InputV = V;
7655         Offset = M - (i / Scale);
7656       } else if (InputV != V)
7657         return SDValue(); // Flip-flopping inputs.
7658
7659       // Offset must start in the lowest 128-bit lane or at the start of an
7660       // upper lane.
7661       // FIXME: Is it ever worth allowing a negative base offset?
7662       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7663             (Offset % NumEltsPerLane) == 0))
7664         return SDValue();
7665
7666       // If we are offsetting, all referenced entries must come from the same
7667       // lane.
7668       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7669         return SDValue();
7670
7671       if ((M % NumElements) != (Offset + (i / Scale)))
7672         return SDValue(); // Non-consecutive strided elements.
7673       Matches++;
7674     }
7675
7676     // If we fail to find an input, we have a zero-shuffle which should always
7677     // have already been handled.
7678     // FIXME: Maybe handle this here in case during blending we end up with one?
7679     if (!InputV)
7680       return SDValue();
7681
7682     // If we are offsetting, don't extend if we only match a single input, we
7683     // can always do better by using a basic PSHUF or PUNPCK.
7684     if (Offset != 0 && Matches < 2)
7685       return SDValue();
7686
7687     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7688         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7689   };
7690
7691   // The widest scale possible for extending is to a 64-bit integer.
7692   assert(Bits % 64 == 0 &&
7693          "The number of bits in a vector must be divisible by 64 on x86!");
7694   int NumExtElements = Bits / 64;
7695
7696   // Each iteration, try extending the elements half as much, but into twice as
7697   // many elements.
7698   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7699     assert(NumElements % NumExtElements == 0 &&
7700            "The input vector size must be divisible by the extended size.");
7701     if (SDValue V = Lower(NumElements / NumExtElements))
7702       return V;
7703   }
7704
7705   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7706   if (Bits != 128)
7707     return SDValue();
7708
7709   // Returns one of the source operands if the shuffle can be reduced to a
7710   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7711   auto CanZExtLowHalf = [&]() {
7712     for (int i = NumElements / 2; i != NumElements; ++i)
7713       if (!Zeroable[i])
7714         return SDValue();
7715     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7716       return V1;
7717     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7718       return V2;
7719     return SDValue();
7720   };
7721
7722   if (SDValue V = CanZExtLowHalf()) {
7723     V = DAG.getBitcast(MVT::v2i64, V);
7724     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7725     return DAG.getBitcast(VT, V);
7726   }
7727
7728   // No viable ext lowering found.
7729   return SDValue();
7730 }
7731
7732 /// \brief Try to get a scalar value for a specific element of a vector.
7733 ///
7734 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7735 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7736                                               SelectionDAG &DAG) {
7737   MVT VT = V.getSimpleValueType();
7738   MVT EltVT = VT.getVectorElementType();
7739   while (V.getOpcode() == ISD::BITCAST)
7740     V = V.getOperand(0);
7741   // If the bitcasts shift the element size, we can't extract an equivalent
7742   // element from it.
7743   MVT NewVT = V.getSimpleValueType();
7744   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7745     return SDValue();
7746
7747   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7748       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7749     // Ensure the scalar operand is the same size as the destination.
7750     // FIXME: Add support for scalar truncation where possible.
7751     SDValue S = V.getOperand(Idx);
7752     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7753       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7754   }
7755
7756   return SDValue();
7757 }
7758
7759 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7760 ///
7761 /// This is particularly important because the set of instructions varies
7762 /// significantly based on whether the operand is a load or not.
7763 static bool isShuffleFoldableLoad(SDValue V) {
7764   while (V.getOpcode() == ISD::BITCAST)
7765     V = V.getOperand(0);
7766
7767   return ISD::isNON_EXTLoad(V.getNode());
7768 }
7769
7770 /// \brief Try to lower insertion of a single element into a zero vector.
7771 ///
7772 /// This is a common pattern that we have especially efficient patterns to lower
7773 /// across all subtarget feature sets.
7774 static SDValue lowerVectorShuffleAsElementInsertion(
7775     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7776     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7777   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7778   MVT ExtVT = VT;
7779   MVT EltVT = VT.getVectorElementType();
7780
7781   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7782                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7783                 Mask.begin();
7784   bool IsV1Zeroable = true;
7785   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7786     if (i != V2Index && !Zeroable[i]) {
7787       IsV1Zeroable = false;
7788       break;
7789     }
7790
7791   // Check for a single input from a SCALAR_TO_VECTOR node.
7792   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7793   // all the smarts here sunk into that routine. However, the current
7794   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7795   // vector shuffle lowering is dead.
7796   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7797                                                DAG);
7798   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7799     // We need to zext the scalar if it is smaller than an i32.
7800     V2S = DAG.getBitcast(EltVT, V2S);
7801     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7802       // Using zext to expand a narrow element won't work for non-zero
7803       // insertions.
7804       if (!IsV1Zeroable)
7805         return SDValue();
7806
7807       // Zero-extend directly to i32.
7808       ExtVT = MVT::v4i32;
7809       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7810     }
7811     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7812   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7813              EltVT == MVT::i16) {
7814     // Either not inserting from the low element of the input or the input
7815     // element size is too small to use VZEXT_MOVL to clear the high bits.
7816     return SDValue();
7817   }
7818
7819   if (!IsV1Zeroable) {
7820     // If V1 can't be treated as a zero vector we have fewer options to lower
7821     // this. We can't support integer vectors or non-zero targets cheaply, and
7822     // the V1 elements can't be permuted in any way.
7823     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7824     if (!VT.isFloatingPoint() || V2Index != 0)
7825       return SDValue();
7826     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7827     V1Mask[V2Index] = -1;
7828     if (!isNoopShuffleMask(V1Mask))
7829       return SDValue();
7830     // This is essentially a special case blend operation, but if we have
7831     // general purpose blend operations, they are always faster. Bail and let
7832     // the rest of the lowering handle these as blends.
7833     if (Subtarget->hasSSE41())
7834       return SDValue();
7835
7836     // Otherwise, use MOVSD or MOVSS.
7837     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7838            "Only two types of floating point element types to handle!");
7839     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7840                        ExtVT, V1, V2);
7841   }
7842
7843   // This lowering only works for the low element with floating point vectors.
7844   if (VT.isFloatingPoint() && V2Index != 0)
7845     return SDValue();
7846
7847   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7848   if (ExtVT != VT)
7849     V2 = DAG.getBitcast(VT, V2);
7850
7851   if (V2Index != 0) {
7852     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7853     // the desired position. Otherwise it is more efficient to do a vector
7854     // shift left. We know that we can do a vector shift left because all
7855     // the inputs are zero.
7856     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7857       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7858       V2Shuffle[V2Index] = 0;
7859       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7860     } else {
7861       V2 = DAG.getBitcast(MVT::v2i64, V2);
7862       V2 = DAG.getNode(
7863           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7864           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7865                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7866                               DAG.getDataLayout(), VT)));
7867       V2 = DAG.getBitcast(VT, V2);
7868     }
7869   }
7870   return V2;
7871 }
7872
7873 /// \brief Try to lower broadcast of a single element.
7874 ///
7875 /// For convenience, this code also bundles all of the subtarget feature set
7876 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7877 /// a convenient way to factor it out.
7878 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7879                                              ArrayRef<int> Mask,
7880                                              const X86Subtarget *Subtarget,
7881                                              SelectionDAG &DAG) {
7882   if (!Subtarget->hasAVX())
7883     return SDValue();
7884   if (VT.isInteger() && !Subtarget->hasAVX2())
7885     return SDValue();
7886
7887   // Check that the mask is a broadcast.
7888   int BroadcastIdx = -1;
7889   for (int M : Mask)
7890     if (M >= 0 && BroadcastIdx == -1)
7891       BroadcastIdx = M;
7892     else if (M >= 0 && M != BroadcastIdx)
7893       return SDValue();
7894
7895   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7896                                             "a sorted mask where the broadcast "
7897                                             "comes from V1.");
7898
7899   // Go up the chain of (vector) values to find a scalar load that we can
7900   // combine with the broadcast.
7901   for (;;) {
7902     switch (V.getOpcode()) {
7903     case ISD::CONCAT_VECTORS: {
7904       int OperandSize = Mask.size() / V.getNumOperands();
7905       V = V.getOperand(BroadcastIdx / OperandSize);
7906       BroadcastIdx %= OperandSize;
7907       continue;
7908     }
7909
7910     case ISD::INSERT_SUBVECTOR: {
7911       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7912       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7913       if (!ConstantIdx)
7914         break;
7915
7916       int BeginIdx = (int)ConstantIdx->getZExtValue();
7917       int EndIdx =
7918           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7919       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7920         BroadcastIdx -= BeginIdx;
7921         V = VInner;
7922       } else {
7923         V = VOuter;
7924       }
7925       continue;
7926     }
7927     }
7928     break;
7929   }
7930
7931   // Check if this is a broadcast of a scalar. We special case lowering
7932   // for scalars so that we can more effectively fold with loads.
7933   // First, look through bitcast: if the original value has a larger element
7934   // type than the shuffle, the broadcast element is in essence truncated.
7935   // Make that explicit to ease folding.
7936   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7937     EVT EltVT = VT.getVectorElementType();
7938     SDValue V0 = V.getOperand(0);
7939     EVT V0VT = V0.getValueType();
7940
7941     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7942         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7943          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7944       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7945       BroadcastIdx = 0;
7946     }
7947   }
7948
7949   // Also check the simpler case, where we can directly reuse the scalar.
7950   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7951       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7952     V = V.getOperand(BroadcastIdx);
7953
7954     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7955     // Only AVX2 has register broadcasts.
7956     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7957       return SDValue();
7958   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7959     // We can't broadcast from a vector register without AVX2, and we can only
7960     // broadcast from the zero-element of a vector register.
7961     return SDValue();
7962   }
7963
7964   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7965 }
7966
7967 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7968 // INSERTPS when the V1 elements are already in the correct locations
7969 // because otherwise we can just always use two SHUFPS instructions which
7970 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7971 // perform INSERTPS if a single V1 element is out of place and all V2
7972 // elements are zeroable.
7973 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7974                                             ArrayRef<int> Mask,
7975                                             SelectionDAG &DAG) {
7976   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7977   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7978   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7979   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7980
7981   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7982
7983   unsigned ZMask = 0;
7984   int V1DstIndex = -1;
7985   int V2DstIndex = -1;
7986   bool V1UsedInPlace = false;
7987
7988   for (int i = 0; i < 4; ++i) {
7989     // Synthesize a zero mask from the zeroable elements (includes undefs).
7990     if (Zeroable[i]) {
7991       ZMask |= 1 << i;
7992       continue;
7993     }
7994
7995     // Flag if we use any V1 inputs in place.
7996     if (i == Mask[i]) {
7997       V1UsedInPlace = true;
7998       continue;
7999     }
8000
8001     // We can only insert a single non-zeroable element.
8002     if (V1DstIndex != -1 || V2DstIndex != -1)
8003       return SDValue();
8004
8005     if (Mask[i] < 4) {
8006       // V1 input out of place for insertion.
8007       V1DstIndex = i;
8008     } else {
8009       // V2 input for insertion.
8010       V2DstIndex = i;
8011     }
8012   }
8013
8014   // Don't bother if we have no (non-zeroable) element for insertion.
8015   if (V1DstIndex == -1 && V2DstIndex == -1)
8016     return SDValue();
8017
8018   // Determine element insertion src/dst indices. The src index is from the
8019   // start of the inserted vector, not the start of the concatenated vector.
8020   unsigned V2SrcIndex = 0;
8021   if (V1DstIndex != -1) {
8022     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8023     // and don't use the original V2 at all.
8024     V2SrcIndex = Mask[V1DstIndex];
8025     V2DstIndex = V1DstIndex;
8026     V2 = V1;
8027   } else {
8028     V2SrcIndex = Mask[V2DstIndex] - 4;
8029   }
8030
8031   // If no V1 inputs are used in place, then the result is created only from
8032   // the zero mask and the V2 insertion - so remove V1 dependency.
8033   if (!V1UsedInPlace)
8034     V1 = DAG.getUNDEF(MVT::v4f32);
8035
8036   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8037   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8038
8039   // Insert the V2 element into the desired position.
8040   SDLoc DL(Op);
8041   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8042                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8043 }
8044
8045 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8046 /// UNPCK instruction.
8047 ///
8048 /// This specifically targets cases where we end up with alternating between
8049 /// the two inputs, and so can permute them into something that feeds a single
8050 /// UNPCK instruction. Note that this routine only targets integer vectors
8051 /// because for floating point vectors we have a generalized SHUFPS lowering
8052 /// strategy that handles everything that doesn't *exactly* match an unpack,
8053 /// making this clever lowering unnecessary.
8054 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8055                                                     SDValue V1, SDValue V2,
8056                                                     ArrayRef<int> Mask,
8057                                                     SelectionDAG &DAG) {
8058   assert(!VT.isFloatingPoint() &&
8059          "This routine only supports integer vectors.");
8060   assert(!isSingleInputShuffleMask(Mask) &&
8061          "This routine should only be used when blending two inputs.");
8062   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8063
8064   int Size = Mask.size();
8065
8066   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8067     return M >= 0 && M % Size < Size / 2;
8068   });
8069   int NumHiInputs = std::count_if(
8070       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8071
8072   bool UnpackLo = NumLoInputs >= NumHiInputs;
8073
8074   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8075     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8076     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8077
8078     for (int i = 0; i < Size; ++i) {
8079       if (Mask[i] < 0)
8080         continue;
8081
8082       // Each element of the unpack contains Scale elements from this mask.
8083       int UnpackIdx = i / Scale;
8084
8085       // We only handle the case where V1 feeds the first slots of the unpack.
8086       // We rely on canonicalization to ensure this is the case.
8087       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8088         return SDValue();
8089
8090       // Setup the mask for this input. The indexing is tricky as we have to
8091       // handle the unpack stride.
8092       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8093       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8094           Mask[i] % Size;
8095     }
8096
8097     // If we will have to shuffle both inputs to use the unpack, check whether
8098     // we can just unpack first and shuffle the result. If so, skip this unpack.
8099     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8100         !isNoopShuffleMask(V2Mask))
8101       return SDValue();
8102
8103     // Shuffle the inputs into place.
8104     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8105     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8106
8107     // Cast the inputs to the type we will use to unpack them.
8108     V1 = DAG.getBitcast(UnpackVT, V1);
8109     V2 = DAG.getBitcast(UnpackVT, V2);
8110
8111     // Unpack the inputs and cast the result back to the desired type.
8112     return DAG.getBitcast(
8113         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8114                         UnpackVT, V1, V2));
8115   };
8116
8117   // We try each unpack from the largest to the smallest to try and find one
8118   // that fits this mask.
8119   int OrigNumElements = VT.getVectorNumElements();
8120   int OrigScalarSize = VT.getScalarSizeInBits();
8121   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8122     int Scale = ScalarSize / OrigScalarSize;
8123     int NumElements = OrigNumElements / Scale;
8124     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8125     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8126       return Unpack;
8127   }
8128
8129   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8130   // initial unpack.
8131   if (NumLoInputs == 0 || NumHiInputs == 0) {
8132     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8133            "We have to have *some* inputs!");
8134     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8135
8136     // FIXME: We could consider the total complexity of the permute of each
8137     // possible unpacking. Or at the least we should consider how many
8138     // half-crossings are created.
8139     // FIXME: We could consider commuting the unpacks.
8140
8141     SmallVector<int, 32> PermMask;
8142     PermMask.assign(Size, -1);
8143     for (int i = 0; i < Size; ++i) {
8144       if (Mask[i] < 0)
8145         continue;
8146
8147       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8148
8149       PermMask[i] =
8150           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8151     }
8152     return DAG.getVectorShuffle(
8153         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8154                             DL, VT, V1, V2),
8155         DAG.getUNDEF(VT), PermMask);
8156   }
8157
8158   return SDValue();
8159 }
8160
8161 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8162 ///
8163 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8164 /// support for floating point shuffles but not integer shuffles. These
8165 /// instructions will incur a domain crossing penalty on some chips though so
8166 /// it is better to avoid lowering through this for integer vectors where
8167 /// possible.
8168 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8169                                        const X86Subtarget *Subtarget,
8170                                        SelectionDAG &DAG) {
8171   SDLoc DL(Op);
8172   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8173   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8174   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8176   ArrayRef<int> Mask = SVOp->getMask();
8177   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8178
8179   if (isSingleInputShuffleMask(Mask)) {
8180     // Use low duplicate instructions for masks that match their pattern.
8181     if (Subtarget->hasSSE3())
8182       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8183         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8184
8185     // Straight shuffle of a single input vector. Simulate this by using the
8186     // single input as both of the "inputs" to this instruction..
8187     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8188
8189     if (Subtarget->hasAVX()) {
8190       // If we have AVX, we can use VPERMILPS which will allow folding a load
8191       // into the shuffle.
8192       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8193                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8194     }
8195
8196     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8197                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8198   }
8199   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8200   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8201
8202   // If we have a single input, insert that into V1 if we can do so cheaply.
8203   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8204     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8205             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8206       return Insertion;
8207     // Try inverting the insertion since for v2 masks it is easy to do and we
8208     // can't reliably sort the mask one way or the other.
8209     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8210                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8211     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8212             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8213       return Insertion;
8214   }
8215
8216   // Try to use one of the special instruction patterns to handle two common
8217   // blend patterns if a zero-blend above didn't work.
8218   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8219       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8220     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8221       // We can either use a special instruction to load over the low double or
8222       // to move just the low double.
8223       return DAG.getNode(
8224           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8225           DL, MVT::v2f64, V2,
8226           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8227
8228   if (Subtarget->hasSSE41())
8229     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8230                                                   Subtarget, DAG))
8231       return Blend;
8232
8233   // Use dedicated unpack instructions for masks that match their pattern.
8234   if (SDValue V =
8235           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8236     return V;
8237
8238   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8239   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8240                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8241 }
8242
8243 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8244 ///
8245 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8246 /// the integer unit to minimize domain crossing penalties. However, for blends
8247 /// it falls back to the floating point shuffle operation with appropriate bit
8248 /// casting.
8249 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8250                                        const X86Subtarget *Subtarget,
8251                                        SelectionDAG &DAG) {
8252   SDLoc DL(Op);
8253   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8254   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8255   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8257   ArrayRef<int> Mask = SVOp->getMask();
8258   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8259
8260   if (isSingleInputShuffleMask(Mask)) {
8261     // Check for being able to broadcast a single element.
8262     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8263                                                           Mask, Subtarget, DAG))
8264       return Broadcast;
8265
8266     // Straight shuffle of a single input vector. For everything from SSE2
8267     // onward this has a single fast instruction with no scary immediates.
8268     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8269     V1 = DAG.getBitcast(MVT::v4i32, V1);
8270     int WidenedMask[4] = {
8271         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8272         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8273     return DAG.getBitcast(
8274         MVT::v2i64,
8275         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8276                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8277   }
8278   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8279   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8280   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8281   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8282
8283   // If we have a blend of two PACKUS operations an the blend aligns with the
8284   // low and half halves, we can just merge the PACKUS operations. This is
8285   // particularly important as it lets us merge shuffles that this routine itself
8286   // creates.
8287   auto GetPackNode = [](SDValue V) {
8288     while (V.getOpcode() == ISD::BITCAST)
8289       V = V.getOperand(0);
8290
8291     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8292   };
8293   if (SDValue V1Pack = GetPackNode(V1))
8294     if (SDValue V2Pack = GetPackNode(V2))
8295       return DAG.getBitcast(MVT::v2i64,
8296                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8297                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8298                                                      : V1Pack.getOperand(1),
8299                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8300                                                      : V2Pack.getOperand(1)));
8301
8302   // Try to use shift instructions.
8303   if (SDValue Shift =
8304           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8305     return Shift;
8306
8307   // When loading a scalar and then shuffling it into a vector we can often do
8308   // the insertion cheaply.
8309   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8310           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8311     return Insertion;
8312   // Try inverting the insertion since for v2 masks it is easy to do and we
8313   // can't reliably sort the mask one way or the other.
8314   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8315   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8316           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8317     return Insertion;
8318
8319   // We have different paths for blend lowering, but they all must use the
8320   // *exact* same predicate.
8321   bool IsBlendSupported = Subtarget->hasSSE41();
8322   if (IsBlendSupported)
8323     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8324                                                   Subtarget, DAG))
8325       return Blend;
8326
8327   // Use dedicated unpack instructions for masks that match their pattern.
8328   if (SDValue V =
8329           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8330     return V;
8331
8332   // Try to use byte rotation instructions.
8333   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8334   if (Subtarget->hasSSSE3())
8335     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8336             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8337       return Rotate;
8338
8339   // If we have direct support for blends, we should lower by decomposing into
8340   // a permute. That will be faster than the domain cross.
8341   if (IsBlendSupported)
8342     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8343                                                       Mask, DAG);
8344
8345   // We implement this with SHUFPD which is pretty lame because it will likely
8346   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8347   // However, all the alternatives are still more cycles and newer chips don't
8348   // have this problem. It would be really nice if x86 had better shuffles here.
8349   V1 = DAG.getBitcast(MVT::v2f64, V1);
8350   V2 = DAG.getBitcast(MVT::v2f64, V2);
8351   return DAG.getBitcast(MVT::v2i64,
8352                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8353 }
8354
8355 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8356 ///
8357 /// This is used to disable more specialized lowerings when the shufps lowering
8358 /// will happen to be efficient.
8359 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8360   // This routine only handles 128-bit shufps.
8361   assert(Mask.size() == 4 && "Unsupported mask size!");
8362
8363   // To lower with a single SHUFPS we need to have the low half and high half
8364   // each requiring a single input.
8365   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8366     return false;
8367   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8368     return false;
8369
8370   return true;
8371 }
8372
8373 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8374 ///
8375 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8376 /// It makes no assumptions about whether this is the *best* lowering, it simply
8377 /// uses it.
8378 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8379                                             ArrayRef<int> Mask, SDValue V1,
8380                                             SDValue V2, SelectionDAG &DAG) {
8381   SDValue LowV = V1, HighV = V2;
8382   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8383
8384   int NumV2Elements =
8385       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8386
8387   if (NumV2Elements == 1) {
8388     int V2Index =
8389         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8390         Mask.begin();
8391
8392     // Compute the index adjacent to V2Index and in the same half by toggling
8393     // the low bit.
8394     int V2AdjIndex = V2Index ^ 1;
8395
8396     if (Mask[V2AdjIndex] == -1) {
8397       // Handles all the cases where we have a single V2 element and an undef.
8398       // This will only ever happen in the high lanes because we commute the
8399       // vector otherwise.
8400       if (V2Index < 2)
8401         std::swap(LowV, HighV);
8402       NewMask[V2Index] -= 4;
8403     } else {
8404       // Handle the case where the V2 element ends up adjacent to a V1 element.
8405       // To make this work, blend them together as the first step.
8406       int V1Index = V2AdjIndex;
8407       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8408       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8409                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8410
8411       // Now proceed to reconstruct the final blend as we have the necessary
8412       // high or low half formed.
8413       if (V2Index < 2) {
8414         LowV = V2;
8415         HighV = V1;
8416       } else {
8417         HighV = V2;
8418       }
8419       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8420       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8421     }
8422   } else if (NumV2Elements == 2) {
8423     if (Mask[0] < 4 && Mask[1] < 4) {
8424       // Handle the easy case where we have V1 in the low lanes and V2 in the
8425       // high lanes.
8426       NewMask[2] -= 4;
8427       NewMask[3] -= 4;
8428     } else if (Mask[2] < 4 && Mask[3] < 4) {
8429       // We also handle the reversed case because this utility may get called
8430       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8431       // arrange things in the right direction.
8432       NewMask[0] -= 4;
8433       NewMask[1] -= 4;
8434       HighV = V1;
8435       LowV = V2;
8436     } else {
8437       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8438       // trying to place elements directly, just blend them and set up the final
8439       // shuffle to place them.
8440
8441       // The first two blend mask elements are for V1, the second two are for
8442       // V2.
8443       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8444                           Mask[2] < 4 ? Mask[2] : Mask[3],
8445                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8446                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8447       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8448                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8449
8450       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8451       // a blend.
8452       LowV = HighV = V1;
8453       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8454       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8455       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8456       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8457     }
8458   }
8459   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8460                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8461 }
8462
8463 /// \brief Lower 4-lane 32-bit floating point shuffles.
8464 ///
8465 /// Uses instructions exclusively from the floating point unit to minimize
8466 /// domain crossing penalties, as these are sufficient to implement all v4f32
8467 /// shuffles.
8468 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8469                                        const X86Subtarget *Subtarget,
8470                                        SelectionDAG &DAG) {
8471   SDLoc DL(Op);
8472   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8473   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8474   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8475   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8476   ArrayRef<int> Mask = SVOp->getMask();
8477   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8478
8479   int NumV2Elements =
8480       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8481
8482   if (NumV2Elements == 0) {
8483     // Check for being able to broadcast a single element.
8484     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8485                                                           Mask, Subtarget, DAG))
8486       return Broadcast;
8487
8488     // Use even/odd duplicate instructions for masks that match their pattern.
8489     if (Subtarget->hasSSE3()) {
8490       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8491         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8492       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8493         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8494     }
8495
8496     if (Subtarget->hasAVX()) {
8497       // If we have AVX, we can use VPERMILPS which will allow folding a load
8498       // into the shuffle.
8499       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8500                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8501     }
8502
8503     // Otherwise, use a straight shuffle of a single input vector. We pass the
8504     // input vector to both operands to simulate this with a SHUFPS.
8505     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8506                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8507   }
8508
8509   // There are special ways we can lower some single-element blends. However, we
8510   // have custom ways we can lower more complex single-element blends below that
8511   // we defer to if both this and BLENDPS fail to match, so restrict this to
8512   // when the V2 input is targeting element 0 of the mask -- that is the fast
8513   // case here.
8514   if (NumV2Elements == 1 && Mask[0] >= 4)
8515     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8516                                                          Mask, Subtarget, DAG))
8517       return V;
8518
8519   if (Subtarget->hasSSE41()) {
8520     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8521                                                   Subtarget, DAG))
8522       return Blend;
8523
8524     // Use INSERTPS if we can complete the shuffle efficiently.
8525     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8526       return V;
8527
8528     if (!isSingleSHUFPSMask(Mask))
8529       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8530               DL, MVT::v4f32, V1, V2, Mask, DAG))
8531         return BlendPerm;
8532   }
8533
8534   // Use dedicated unpack instructions for masks that match their pattern.
8535   if (SDValue V =
8536           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8537     return V;
8538
8539   // Otherwise fall back to a SHUFPS lowering strategy.
8540   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8541 }
8542
8543 /// \brief Lower 4-lane i32 vector shuffles.
8544 ///
8545 /// We try to handle these with integer-domain shuffles where we can, but for
8546 /// blends we use the floating point domain blend instructions.
8547 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8548                                        const X86Subtarget *Subtarget,
8549                                        SelectionDAG &DAG) {
8550   SDLoc DL(Op);
8551   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8552   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8553   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8554   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8555   ArrayRef<int> Mask = SVOp->getMask();
8556   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8557
8558   // Whenever we can lower this as a zext, that instruction is strictly faster
8559   // than any alternative. It also allows us to fold memory operands into the
8560   // shuffle in many cases.
8561   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8562                                                          Mask, Subtarget, DAG))
8563     return ZExt;
8564
8565   int NumV2Elements =
8566       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8567
8568   if (NumV2Elements == 0) {
8569     // Check for being able to broadcast a single element.
8570     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8571                                                           Mask, Subtarget, DAG))
8572       return Broadcast;
8573
8574     // Straight shuffle of a single input vector. For everything from SSE2
8575     // onward this has a single fast instruction with no scary immediates.
8576     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8577     // but we aren't actually going to use the UNPCK instruction because doing
8578     // so prevents folding a load into this instruction or making a copy.
8579     const int UnpackLoMask[] = {0, 0, 1, 1};
8580     const int UnpackHiMask[] = {2, 2, 3, 3};
8581     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8582       Mask = UnpackLoMask;
8583     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8584       Mask = UnpackHiMask;
8585
8586     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8587                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8588   }
8589
8590   // Try to use shift instructions.
8591   if (SDValue Shift =
8592           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8593     return Shift;
8594
8595   // There are special ways we can lower some single-element blends.
8596   if (NumV2Elements == 1)
8597     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8598                                                          Mask, Subtarget, DAG))
8599       return V;
8600
8601   // We have different paths for blend lowering, but they all must use the
8602   // *exact* same predicate.
8603   bool IsBlendSupported = Subtarget->hasSSE41();
8604   if (IsBlendSupported)
8605     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8606                                                   Subtarget, DAG))
8607       return Blend;
8608
8609   if (SDValue Masked =
8610           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8611     return Masked;
8612
8613   // Use dedicated unpack instructions for masks that match their pattern.
8614   if (SDValue V =
8615           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8616     return V;
8617
8618   // Try to use byte rotation instructions.
8619   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8620   if (Subtarget->hasSSSE3())
8621     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8622             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8623       return Rotate;
8624
8625   // If we have direct support for blends, we should lower by decomposing into
8626   // a permute. That will be faster than the domain cross.
8627   if (IsBlendSupported)
8628     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8629                                                       Mask, DAG);
8630
8631   // Try to lower by permuting the inputs into an unpack instruction.
8632   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8633                                                             V2, Mask, DAG))
8634     return Unpack;
8635
8636   // We implement this with SHUFPS because it can blend from two vectors.
8637   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8638   // up the inputs, bypassing domain shift penalties that we would encur if we
8639   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8640   // relevant.
8641   return DAG.getBitcast(
8642       MVT::v4i32,
8643       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8644                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8645 }
8646
8647 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8648 /// shuffle lowering, and the most complex part.
8649 ///
8650 /// The lowering strategy is to try to form pairs of input lanes which are
8651 /// targeted at the same half of the final vector, and then use a dword shuffle
8652 /// to place them onto the right half, and finally unpack the paired lanes into
8653 /// their final position.
8654 ///
8655 /// The exact breakdown of how to form these dword pairs and align them on the
8656 /// correct sides is really tricky. See the comments within the function for
8657 /// more of the details.
8658 ///
8659 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8660 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8661 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8662 /// vector, form the analogous 128-bit 8-element Mask.
8663 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8664     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8665     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8666   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8667   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8668
8669   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8670   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8671   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8672
8673   SmallVector<int, 4> LoInputs;
8674   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8675                [](int M) { return M >= 0; });
8676   std::sort(LoInputs.begin(), LoInputs.end());
8677   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8678   SmallVector<int, 4> HiInputs;
8679   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8680                [](int M) { return M >= 0; });
8681   std::sort(HiInputs.begin(), HiInputs.end());
8682   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8683   int NumLToL =
8684       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8685   int NumHToL = LoInputs.size() - NumLToL;
8686   int NumLToH =
8687       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8688   int NumHToH = HiInputs.size() - NumLToH;
8689   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8690   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8691   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8692   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8693
8694   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8695   // such inputs we can swap two of the dwords across the half mark and end up
8696   // with <=2 inputs to each half in each half. Once there, we can fall through
8697   // to the generic code below. For example:
8698   //
8699   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8700   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8701   //
8702   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8703   // and an existing 2-into-2 on the other half. In this case we may have to
8704   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8705   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8706   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8707   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8708   // half than the one we target for fixing) will be fixed when we re-enter this
8709   // path. We will also combine away any sequence of PSHUFD instructions that
8710   // result into a single instruction. Here is an example of the tricky case:
8711   //
8712   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8713   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8714   //
8715   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8716   //
8717   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8718   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8719   //
8720   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8721   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8722   //
8723   // The result is fine to be handled by the generic logic.
8724   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8725                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8726                           int AOffset, int BOffset) {
8727     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8728            "Must call this with A having 3 or 1 inputs from the A half.");
8729     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8730            "Must call this with B having 1 or 3 inputs from the B half.");
8731     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8732            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8733
8734     bool ThreeAInputs = AToAInputs.size() == 3;
8735
8736     // Compute the index of dword with only one word among the three inputs in
8737     // a half by taking the sum of the half with three inputs and subtracting
8738     // the sum of the actual three inputs. The difference is the remaining
8739     // slot.
8740     int ADWord, BDWord;
8741     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8742     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8743     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8744     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8745     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8746     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8747     int TripleNonInputIdx =
8748         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8749     TripleDWord = TripleNonInputIdx / 2;
8750
8751     // We use xor with one to compute the adjacent DWord to whichever one the
8752     // OneInput is in.
8753     OneInputDWord = (OneInput / 2) ^ 1;
8754
8755     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8756     // and BToA inputs. If there is also such a problem with the BToB and AToB
8757     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8758     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8759     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8760     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8761       // Compute how many inputs will be flipped by swapping these DWords. We
8762       // need
8763       // to balance this to ensure we don't form a 3-1 shuffle in the other
8764       // half.
8765       int NumFlippedAToBInputs =
8766           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8767           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8768       int NumFlippedBToBInputs =
8769           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8770           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8771       if ((NumFlippedAToBInputs == 1 &&
8772            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8773           (NumFlippedBToBInputs == 1 &&
8774            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8775         // We choose whether to fix the A half or B half based on whether that
8776         // half has zero flipped inputs. At zero, we may not be able to fix it
8777         // with that half. We also bias towards fixing the B half because that
8778         // will more commonly be the high half, and we have to bias one way.
8779         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8780                                                        ArrayRef<int> Inputs) {
8781           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8782           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8783                                          PinnedIdx ^ 1) != Inputs.end();
8784           // Determine whether the free index is in the flipped dword or the
8785           // unflipped dword based on where the pinned index is. We use this bit
8786           // in an xor to conditionally select the adjacent dword.
8787           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8788           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8789                                              FixFreeIdx) != Inputs.end();
8790           if (IsFixIdxInput == IsFixFreeIdxInput)
8791             FixFreeIdx += 1;
8792           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8793                                         FixFreeIdx) != Inputs.end();
8794           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8795                  "We need to be changing the number of flipped inputs!");
8796           int PSHUFHalfMask[] = {0, 1, 2, 3};
8797           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8798           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8799                           MVT::v8i16, V,
8800                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8801
8802           for (int &M : Mask)
8803             if (M != -1 && M == FixIdx)
8804               M = FixFreeIdx;
8805             else if (M != -1 && M == FixFreeIdx)
8806               M = FixIdx;
8807         };
8808         if (NumFlippedBToBInputs != 0) {
8809           int BPinnedIdx =
8810               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8811           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8812         } else {
8813           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8814           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8815           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8816         }
8817       }
8818     }
8819
8820     int PSHUFDMask[] = {0, 1, 2, 3};
8821     PSHUFDMask[ADWord] = BDWord;
8822     PSHUFDMask[BDWord] = ADWord;
8823     V = DAG.getBitcast(
8824         VT,
8825         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8826                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8827
8828     // Adjust the mask to match the new locations of A and B.
8829     for (int &M : Mask)
8830       if (M != -1 && M/2 == ADWord)
8831         M = 2 * BDWord + M % 2;
8832       else if (M != -1 && M/2 == BDWord)
8833         M = 2 * ADWord + M % 2;
8834
8835     // Recurse back into this routine to re-compute state now that this isn't
8836     // a 3 and 1 problem.
8837     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8838                                                      DAG);
8839   };
8840   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8841     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8842   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8843     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8844
8845   // At this point there are at most two inputs to the low and high halves from
8846   // each half. That means the inputs can always be grouped into dwords and
8847   // those dwords can then be moved to the correct half with a dword shuffle.
8848   // We use at most one low and one high word shuffle to collect these paired
8849   // inputs into dwords, and finally a dword shuffle to place them.
8850   int PSHUFLMask[4] = {-1, -1, -1, -1};
8851   int PSHUFHMask[4] = {-1, -1, -1, -1};
8852   int PSHUFDMask[4] = {-1, -1, -1, -1};
8853
8854   // First fix the masks for all the inputs that are staying in their
8855   // original halves. This will then dictate the targets of the cross-half
8856   // shuffles.
8857   auto fixInPlaceInputs =
8858       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8859                     MutableArrayRef<int> SourceHalfMask,
8860                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8861     if (InPlaceInputs.empty())
8862       return;
8863     if (InPlaceInputs.size() == 1) {
8864       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8865           InPlaceInputs[0] - HalfOffset;
8866       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8867       return;
8868     }
8869     if (IncomingInputs.empty()) {
8870       // Just fix all of the in place inputs.
8871       for (int Input : InPlaceInputs) {
8872         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8873         PSHUFDMask[Input / 2] = Input / 2;
8874       }
8875       return;
8876     }
8877
8878     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8879     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8880         InPlaceInputs[0] - HalfOffset;
8881     // Put the second input next to the first so that they are packed into
8882     // a dword. We find the adjacent index by toggling the low bit.
8883     int AdjIndex = InPlaceInputs[0] ^ 1;
8884     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8885     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8886     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8887   };
8888   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8889   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8890
8891   // Now gather the cross-half inputs and place them into a free dword of
8892   // their target half.
8893   // FIXME: This operation could almost certainly be simplified dramatically to
8894   // look more like the 3-1 fixing operation.
8895   auto moveInputsToRightHalf = [&PSHUFDMask](
8896       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8897       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8898       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8899       int DestOffset) {
8900     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8901       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8902     };
8903     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8904                                                int Word) {
8905       int LowWord = Word & ~1;
8906       int HighWord = Word | 1;
8907       return isWordClobbered(SourceHalfMask, LowWord) ||
8908              isWordClobbered(SourceHalfMask, HighWord);
8909     };
8910
8911     if (IncomingInputs.empty())
8912       return;
8913
8914     if (ExistingInputs.empty()) {
8915       // Map any dwords with inputs from them into the right half.
8916       for (int Input : IncomingInputs) {
8917         // If the source half mask maps over the inputs, turn those into
8918         // swaps and use the swapped lane.
8919         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8920           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8921             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8922                 Input - SourceOffset;
8923             // We have to swap the uses in our half mask in one sweep.
8924             for (int &M : HalfMask)
8925               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8926                 M = Input;
8927               else if (M == Input)
8928                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8929           } else {
8930             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8931                        Input - SourceOffset &&
8932                    "Previous placement doesn't match!");
8933           }
8934           // Note that this correctly re-maps both when we do a swap and when
8935           // we observe the other side of the swap above. We rely on that to
8936           // avoid swapping the members of the input list directly.
8937           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8938         }
8939
8940         // Map the input's dword into the correct half.
8941         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8942           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8943         else
8944           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8945                      Input / 2 &&
8946                  "Previous placement doesn't match!");
8947       }
8948
8949       // And just directly shift any other-half mask elements to be same-half
8950       // as we will have mirrored the dword containing the element into the
8951       // same position within that half.
8952       for (int &M : HalfMask)
8953         if (M >= SourceOffset && M < SourceOffset + 4) {
8954           M = M - SourceOffset + DestOffset;
8955           assert(M >= 0 && "This should never wrap below zero!");
8956         }
8957       return;
8958     }
8959
8960     // Ensure we have the input in a viable dword of its current half. This
8961     // is particularly tricky because the original position may be clobbered
8962     // by inputs being moved and *staying* in that half.
8963     if (IncomingInputs.size() == 1) {
8964       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8965         int InputFixed = std::find(std::begin(SourceHalfMask),
8966                                    std::end(SourceHalfMask), -1) -
8967                          std::begin(SourceHalfMask) + SourceOffset;
8968         SourceHalfMask[InputFixed - SourceOffset] =
8969             IncomingInputs[0] - SourceOffset;
8970         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8971                      InputFixed);
8972         IncomingInputs[0] = InputFixed;
8973       }
8974     } else if (IncomingInputs.size() == 2) {
8975       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8976           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8977         // We have two non-adjacent or clobbered inputs we need to extract from
8978         // the source half. To do this, we need to map them into some adjacent
8979         // dword slot in the source mask.
8980         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8981                               IncomingInputs[1] - SourceOffset};
8982
8983         // If there is a free slot in the source half mask adjacent to one of
8984         // the inputs, place the other input in it. We use (Index XOR 1) to
8985         // compute an adjacent index.
8986         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8987             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8988           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8989           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8990           InputsFixed[1] = InputsFixed[0] ^ 1;
8991         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8992                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8993           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8994           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8995           InputsFixed[0] = InputsFixed[1] ^ 1;
8996         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8997                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8998           // The two inputs are in the same DWord but it is clobbered and the
8999           // adjacent DWord isn't used at all. Move both inputs to the free
9000           // slot.
9001           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9002           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9003           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9004           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9005         } else {
9006           // The only way we hit this point is if there is no clobbering
9007           // (because there are no off-half inputs to this half) and there is no
9008           // free slot adjacent to one of the inputs. In this case, we have to
9009           // swap an input with a non-input.
9010           for (int i = 0; i < 4; ++i)
9011             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9012                    "We can't handle any clobbers here!");
9013           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9014                  "Cannot have adjacent inputs here!");
9015
9016           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9017           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9018
9019           // We also have to update the final source mask in this case because
9020           // it may need to undo the above swap.
9021           for (int &M : FinalSourceHalfMask)
9022             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9023               M = InputsFixed[1] + SourceOffset;
9024             else if (M == InputsFixed[1] + SourceOffset)
9025               M = (InputsFixed[0] ^ 1) + SourceOffset;
9026
9027           InputsFixed[1] = InputsFixed[0] ^ 1;
9028         }
9029
9030         // Point everything at the fixed inputs.
9031         for (int &M : HalfMask)
9032           if (M == IncomingInputs[0])
9033             M = InputsFixed[0] + SourceOffset;
9034           else if (M == IncomingInputs[1])
9035             M = InputsFixed[1] + SourceOffset;
9036
9037         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9038         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9039       }
9040     } else {
9041       llvm_unreachable("Unhandled input size!");
9042     }
9043
9044     // Now hoist the DWord down to the right half.
9045     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9046     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9047     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9048     for (int &M : HalfMask)
9049       for (int Input : IncomingInputs)
9050         if (M == Input)
9051           M = FreeDWord * 2 + Input % 2;
9052   };
9053   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9054                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9055   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9056                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9057
9058   // Now enact all the shuffles we've computed to move the inputs into their
9059   // target half.
9060   if (!isNoopShuffleMask(PSHUFLMask))
9061     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9062                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9063   if (!isNoopShuffleMask(PSHUFHMask))
9064     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9065                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9066   if (!isNoopShuffleMask(PSHUFDMask))
9067     V = DAG.getBitcast(
9068         VT,
9069         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9070                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9071
9072   // At this point, each half should contain all its inputs, and we can then
9073   // just shuffle them into their final position.
9074   assert(std::count_if(LoMask.begin(), LoMask.end(),
9075                        [](int M) { return M >= 4; }) == 0 &&
9076          "Failed to lift all the high half inputs to the low mask!");
9077   assert(std::count_if(HiMask.begin(), HiMask.end(),
9078                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9079          "Failed to lift all the low half inputs to the high mask!");
9080
9081   // Do a half shuffle for the low mask.
9082   if (!isNoopShuffleMask(LoMask))
9083     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9084                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9085
9086   // Do a half shuffle with the high mask after shifting its values down.
9087   for (int &M : HiMask)
9088     if (M >= 0)
9089       M -= 4;
9090   if (!isNoopShuffleMask(HiMask))
9091     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9092                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9093
9094   return V;
9095 }
9096
9097 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9098 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9099                                           SDValue V2, ArrayRef<int> Mask,
9100                                           SelectionDAG &DAG, bool &V1InUse,
9101                                           bool &V2InUse) {
9102   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9103   SDValue V1Mask[16];
9104   SDValue V2Mask[16];
9105   V1InUse = false;
9106   V2InUse = false;
9107
9108   int Size = Mask.size();
9109   int Scale = 16 / Size;
9110   for (int i = 0; i < 16; ++i) {
9111     if (Mask[i / Scale] == -1) {
9112       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9113     } else {
9114       const int ZeroMask = 0x80;
9115       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9116                                           : ZeroMask;
9117       int V2Idx = Mask[i / Scale] < Size
9118                       ? ZeroMask
9119                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9120       if (Zeroable[i / Scale])
9121         V1Idx = V2Idx = ZeroMask;
9122       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9123       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9124       V1InUse |= (ZeroMask != V1Idx);
9125       V2InUse |= (ZeroMask != V2Idx);
9126     }
9127   }
9128
9129   if (V1InUse)
9130     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9131                      DAG.getBitcast(MVT::v16i8, V1),
9132                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9133   if (V2InUse)
9134     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9135                      DAG.getBitcast(MVT::v16i8, V2),
9136                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9137
9138   // If we need shuffled inputs from both, blend the two.
9139   SDValue V;
9140   if (V1InUse && V2InUse)
9141     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9142   else
9143     V = V1InUse ? V1 : V2;
9144
9145   // Cast the result back to the correct type.
9146   return DAG.getBitcast(VT, V);
9147 }
9148
9149 /// \brief Generic lowering of 8-lane i16 shuffles.
9150 ///
9151 /// This handles both single-input shuffles and combined shuffle/blends with
9152 /// two inputs. The single input shuffles are immediately delegated to
9153 /// a dedicated lowering routine.
9154 ///
9155 /// The blends are lowered in one of three fundamental ways. If there are few
9156 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9157 /// of the input is significantly cheaper when lowered as an interleaving of
9158 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9159 /// halves of the inputs separately (making them have relatively few inputs)
9160 /// and then concatenate them.
9161 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9162                                        const X86Subtarget *Subtarget,
9163                                        SelectionDAG &DAG) {
9164   SDLoc DL(Op);
9165   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9166   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9167   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9168   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9169   ArrayRef<int> OrigMask = SVOp->getMask();
9170   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9171                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9172   MutableArrayRef<int> Mask(MaskStorage);
9173
9174   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9175
9176   // Whenever we can lower this as a zext, that instruction is strictly faster
9177   // than any alternative.
9178   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9179           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9180     return ZExt;
9181
9182   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9183   (void)isV1;
9184   auto isV2 = [](int M) { return M >= 8; };
9185
9186   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9187
9188   if (NumV2Inputs == 0) {
9189     // Check for being able to broadcast a single element.
9190     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9191                                                           Mask, Subtarget, DAG))
9192       return Broadcast;
9193
9194     // Try to use shift instructions.
9195     if (SDValue Shift =
9196             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9197       return Shift;
9198
9199     // Use dedicated unpack instructions for masks that match their pattern.
9200     if (SDValue V =
9201             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9202       return V;
9203
9204     // Try to use byte rotation instructions.
9205     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9206                                                         Mask, Subtarget, DAG))
9207       return Rotate;
9208
9209     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9210                                                      Subtarget, DAG);
9211   }
9212
9213   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9214          "All single-input shuffles should be canonicalized to be V1-input "
9215          "shuffles.");
9216
9217   // Try to use shift instructions.
9218   if (SDValue Shift =
9219           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9220     return Shift;
9221
9222   // See if we can use SSE4A Extraction / Insertion.
9223   if (Subtarget->hasSSE4A())
9224     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9225       return V;
9226
9227   // There are special ways we can lower some single-element blends.
9228   if (NumV2Inputs == 1)
9229     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9230                                                          Mask, Subtarget, DAG))
9231       return V;
9232
9233   // We have different paths for blend lowering, but they all must use the
9234   // *exact* same predicate.
9235   bool IsBlendSupported = Subtarget->hasSSE41();
9236   if (IsBlendSupported)
9237     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9238                                                   Subtarget, DAG))
9239       return Blend;
9240
9241   if (SDValue Masked =
9242           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9243     return Masked;
9244
9245   // Use dedicated unpack instructions for masks that match their pattern.
9246   if (SDValue V =
9247           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9248     return V;
9249
9250   // Try to use byte rotation instructions.
9251   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9252           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9253     return Rotate;
9254
9255   if (SDValue BitBlend =
9256           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9257     return BitBlend;
9258
9259   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9260                                                             V2, Mask, DAG))
9261     return Unpack;
9262
9263   // If we can't directly blend but can use PSHUFB, that will be better as it
9264   // can both shuffle and set up the inefficient blend.
9265   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9266     bool V1InUse, V2InUse;
9267     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9268                                       V1InUse, V2InUse);
9269   }
9270
9271   // We can always bit-blend if we have to so the fallback strategy is to
9272   // decompose into single-input permutes and blends.
9273   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9274                                                       Mask, DAG);
9275 }
9276
9277 /// \brief Check whether a compaction lowering can be done by dropping even
9278 /// elements and compute how many times even elements must be dropped.
9279 ///
9280 /// This handles shuffles which take every Nth element where N is a power of
9281 /// two. Example shuffle masks:
9282 ///
9283 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9284 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9285 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9286 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9287 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9288 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9289 ///
9290 /// Any of these lanes can of course be undef.
9291 ///
9292 /// This routine only supports N <= 3.
9293 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9294 /// for larger N.
9295 ///
9296 /// \returns N above, or the number of times even elements must be dropped if
9297 /// there is such a number. Otherwise returns zero.
9298 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9299   // Figure out whether we're looping over two inputs or just one.
9300   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9301
9302   // The modulus for the shuffle vector entries is based on whether this is
9303   // a single input or not.
9304   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9305   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9306          "We should only be called with masks with a power-of-2 size!");
9307
9308   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9309
9310   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9311   // and 2^3 simultaneously. This is because we may have ambiguity with
9312   // partially undef inputs.
9313   bool ViableForN[3] = {true, true, true};
9314
9315   for (int i = 0, e = Mask.size(); i < e; ++i) {
9316     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9317     // want.
9318     if (Mask[i] == -1)
9319       continue;
9320
9321     bool IsAnyViable = false;
9322     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9323       if (ViableForN[j]) {
9324         uint64_t N = j + 1;
9325
9326         // The shuffle mask must be equal to (i * 2^N) % M.
9327         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9328           IsAnyViable = true;
9329         else
9330           ViableForN[j] = false;
9331       }
9332     // Early exit if we exhaust the possible powers of two.
9333     if (!IsAnyViable)
9334       break;
9335   }
9336
9337   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9338     if (ViableForN[j])
9339       return j + 1;
9340
9341   // Return 0 as there is no viable power of two.
9342   return 0;
9343 }
9344
9345 /// \brief Generic lowering of v16i8 shuffles.
9346 ///
9347 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9348 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9349 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9350 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9351 /// back together.
9352 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9353                                        const X86Subtarget *Subtarget,
9354                                        SelectionDAG &DAG) {
9355   SDLoc DL(Op);
9356   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9357   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9358   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9359   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9360   ArrayRef<int> Mask = SVOp->getMask();
9361   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9362
9363   // Try to use shift instructions.
9364   if (SDValue Shift =
9365           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9366     return Shift;
9367
9368   // Try to use byte rotation instructions.
9369   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9370           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9371     return Rotate;
9372
9373   // Try to use a zext lowering.
9374   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9375           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9376     return ZExt;
9377
9378   // See if we can use SSE4A Extraction / Insertion.
9379   if (Subtarget->hasSSE4A())
9380     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9381       return V;
9382
9383   int NumV2Elements =
9384       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9385
9386   // For single-input shuffles, there are some nicer lowering tricks we can use.
9387   if (NumV2Elements == 0) {
9388     // Check for being able to broadcast a single element.
9389     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9390                                                           Mask, Subtarget, DAG))
9391       return Broadcast;
9392
9393     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9394     // Notably, this handles splat and partial-splat shuffles more efficiently.
9395     // However, it only makes sense if the pre-duplication shuffle simplifies
9396     // things significantly. Currently, this means we need to be able to
9397     // express the pre-duplication shuffle as an i16 shuffle.
9398     //
9399     // FIXME: We should check for other patterns which can be widened into an
9400     // i16 shuffle as well.
9401     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9402       for (int i = 0; i < 16; i += 2)
9403         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9404           return false;
9405
9406       return true;
9407     };
9408     auto tryToWidenViaDuplication = [&]() -> SDValue {
9409       if (!canWidenViaDuplication(Mask))
9410         return SDValue();
9411       SmallVector<int, 4> LoInputs;
9412       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9413                    [](int M) { return M >= 0 && M < 8; });
9414       std::sort(LoInputs.begin(), LoInputs.end());
9415       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9416                      LoInputs.end());
9417       SmallVector<int, 4> HiInputs;
9418       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9419                    [](int M) { return M >= 8; });
9420       std::sort(HiInputs.begin(), HiInputs.end());
9421       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9422                      HiInputs.end());
9423
9424       bool TargetLo = LoInputs.size() >= HiInputs.size();
9425       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9426       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9427
9428       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9429       SmallDenseMap<int, int, 8> LaneMap;
9430       for (int I : InPlaceInputs) {
9431         PreDupI16Shuffle[I/2] = I/2;
9432         LaneMap[I] = I;
9433       }
9434       int j = TargetLo ? 0 : 4, je = j + 4;
9435       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9436         // Check if j is already a shuffle of this input. This happens when
9437         // there are two adjacent bytes after we move the low one.
9438         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9439           // If we haven't yet mapped the input, search for a slot into which
9440           // we can map it.
9441           while (j < je && PreDupI16Shuffle[j] != -1)
9442             ++j;
9443
9444           if (j == je)
9445             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9446             return SDValue();
9447
9448           // Map this input with the i16 shuffle.
9449           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9450         }
9451
9452         // Update the lane map based on the mapping we ended up with.
9453         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9454       }
9455       V1 = DAG.getBitcast(
9456           MVT::v16i8,
9457           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9458                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9459
9460       // Unpack the bytes to form the i16s that will be shuffled into place.
9461       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9462                        MVT::v16i8, V1, V1);
9463
9464       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9465       for (int i = 0; i < 16; ++i)
9466         if (Mask[i] != -1) {
9467           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9468           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9469           if (PostDupI16Shuffle[i / 2] == -1)
9470             PostDupI16Shuffle[i / 2] = MappedMask;
9471           else
9472             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9473                    "Conflicting entrties in the original shuffle!");
9474         }
9475       return DAG.getBitcast(
9476           MVT::v16i8,
9477           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9478                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9479     };
9480     if (SDValue V = tryToWidenViaDuplication())
9481       return V;
9482   }
9483
9484   if (SDValue Masked =
9485           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9486     return Masked;
9487
9488   // Use dedicated unpack instructions for masks that match their pattern.
9489   if (SDValue V =
9490           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9491     return V;
9492
9493   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9494   // with PSHUFB. It is important to do this before we attempt to generate any
9495   // blends but after all of the single-input lowerings. If the single input
9496   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9497   // want to preserve that and we can DAG combine any longer sequences into
9498   // a PSHUFB in the end. But once we start blending from multiple inputs,
9499   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9500   // and there are *very* few patterns that would actually be faster than the
9501   // PSHUFB approach because of its ability to zero lanes.
9502   //
9503   // FIXME: The only exceptions to the above are blends which are exact
9504   // interleavings with direct instructions supporting them. We currently don't
9505   // handle those well here.
9506   if (Subtarget->hasSSSE3()) {
9507     bool V1InUse = false;
9508     bool V2InUse = false;
9509
9510     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9511                                                 DAG, V1InUse, V2InUse);
9512
9513     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9514     // do so. This avoids using them to handle blends-with-zero which is
9515     // important as a single pshufb is significantly faster for that.
9516     if (V1InUse && V2InUse) {
9517       if (Subtarget->hasSSE41())
9518         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9519                                                       Mask, Subtarget, DAG))
9520           return Blend;
9521
9522       // We can use an unpack to do the blending rather than an or in some
9523       // cases. Even though the or may be (very minorly) more efficient, we
9524       // preference this lowering because there are common cases where part of
9525       // the complexity of the shuffles goes away when we do the final blend as
9526       // an unpack.
9527       // FIXME: It might be worth trying to detect if the unpack-feeding
9528       // shuffles will both be pshufb, in which case we shouldn't bother with
9529       // this.
9530       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9531               DL, MVT::v16i8, V1, V2, Mask, DAG))
9532         return Unpack;
9533     }
9534
9535     return PSHUFB;
9536   }
9537
9538   // There are special ways we can lower some single-element blends.
9539   if (NumV2Elements == 1)
9540     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9541                                                          Mask, Subtarget, DAG))
9542       return V;
9543
9544   if (SDValue BitBlend =
9545           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9546     return BitBlend;
9547
9548   // Check whether a compaction lowering can be done. This handles shuffles
9549   // which take every Nth element for some even N. See the helper function for
9550   // details.
9551   //
9552   // We special case these as they can be particularly efficiently handled with
9553   // the PACKUSB instruction on x86 and they show up in common patterns of
9554   // rearranging bytes to truncate wide elements.
9555   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9556     // NumEvenDrops is the power of two stride of the elements. Another way of
9557     // thinking about it is that we need to drop the even elements this many
9558     // times to get the original input.
9559     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9560
9561     // First we need to zero all the dropped bytes.
9562     assert(NumEvenDrops <= 3 &&
9563            "No support for dropping even elements more than 3 times.");
9564     // We use the mask type to pick which bytes are preserved based on how many
9565     // elements are dropped.
9566     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9567     SDValue ByteClearMask = DAG.getBitcast(
9568         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9569     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9570     if (!IsSingleInput)
9571       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9572
9573     // Now pack things back together.
9574     V1 = DAG.getBitcast(MVT::v8i16, V1);
9575     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9576     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9577     for (int i = 1; i < NumEvenDrops; ++i) {
9578       Result = DAG.getBitcast(MVT::v8i16, Result);
9579       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9580     }
9581
9582     return Result;
9583   }
9584
9585   // Handle multi-input cases by blending single-input shuffles.
9586   if (NumV2Elements > 0)
9587     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9588                                                       Mask, DAG);
9589
9590   // The fallback path for single-input shuffles widens this into two v8i16
9591   // vectors with unpacks, shuffles those, and then pulls them back together
9592   // with a pack.
9593   SDValue V = V1;
9594
9595   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9596   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9597   for (int i = 0; i < 16; ++i)
9598     if (Mask[i] >= 0)
9599       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9600
9601   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9602
9603   SDValue VLoHalf, VHiHalf;
9604   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9605   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9606   // i16s.
9607   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9608                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9609       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9610                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9611     // Use a mask to drop the high bytes.
9612     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9613     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9614                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9615
9616     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9617     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9618
9619     // Squash the masks to point directly into VLoHalf.
9620     for (int &M : LoBlendMask)
9621       if (M >= 0)
9622         M /= 2;
9623     for (int &M : HiBlendMask)
9624       if (M >= 0)
9625         M /= 2;
9626   } else {
9627     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9628     // VHiHalf so that we can blend them as i16s.
9629     VLoHalf = DAG.getBitcast(
9630         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9631     VHiHalf = DAG.getBitcast(
9632         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9633   }
9634
9635   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9636   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9637
9638   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9639 }
9640
9641 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9642 ///
9643 /// This routine breaks down the specific type of 128-bit shuffle and
9644 /// dispatches to the lowering routines accordingly.
9645 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9646                                         MVT VT, const X86Subtarget *Subtarget,
9647                                         SelectionDAG &DAG) {
9648   switch (VT.SimpleTy) {
9649   case MVT::v2i64:
9650     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9651   case MVT::v2f64:
9652     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9653   case MVT::v4i32:
9654     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9655   case MVT::v4f32:
9656     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9657   case MVT::v8i16:
9658     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9659   case MVT::v16i8:
9660     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9661
9662   default:
9663     llvm_unreachable("Unimplemented!");
9664   }
9665 }
9666
9667 /// \brief Helper function to test whether a shuffle mask could be
9668 /// simplified by widening the elements being shuffled.
9669 ///
9670 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9671 /// leaves it in an unspecified state.
9672 ///
9673 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9674 /// shuffle masks. The latter have the special property of a '-2' representing
9675 /// a zero-ed lane of a vector.
9676 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9677                                     SmallVectorImpl<int> &WidenedMask) {
9678   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9679     // If both elements are undef, its trivial.
9680     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9681       WidenedMask.push_back(SM_SentinelUndef);
9682       continue;
9683     }
9684
9685     // Check for an undef mask and a mask value properly aligned to fit with
9686     // a pair of values. If we find such a case, use the non-undef mask's value.
9687     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9688       WidenedMask.push_back(Mask[i + 1] / 2);
9689       continue;
9690     }
9691     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9692       WidenedMask.push_back(Mask[i] / 2);
9693       continue;
9694     }
9695
9696     // When zeroing, we need to spread the zeroing across both lanes to widen.
9697     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9698       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9699           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9700         WidenedMask.push_back(SM_SentinelZero);
9701         continue;
9702       }
9703       return false;
9704     }
9705
9706     // Finally check if the two mask values are adjacent and aligned with
9707     // a pair.
9708     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9709       WidenedMask.push_back(Mask[i] / 2);
9710       continue;
9711     }
9712
9713     // Otherwise we can't safely widen the elements used in this shuffle.
9714     return false;
9715   }
9716   assert(WidenedMask.size() == Mask.size() / 2 &&
9717          "Incorrect size of mask after widening the elements!");
9718
9719   return true;
9720 }
9721
9722 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9723 ///
9724 /// This routine just extracts two subvectors, shuffles them independently, and
9725 /// then concatenates them back together. This should work effectively with all
9726 /// AVX vector shuffle types.
9727 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9728                                           SDValue V2, ArrayRef<int> Mask,
9729                                           SelectionDAG &DAG) {
9730   assert(VT.getSizeInBits() >= 256 &&
9731          "Only for 256-bit or wider vector shuffles!");
9732   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9733   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9734
9735   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9736   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9737
9738   int NumElements = VT.getVectorNumElements();
9739   int SplitNumElements = NumElements / 2;
9740   MVT ScalarVT = VT.getScalarType();
9741   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9742
9743   // Rather than splitting build-vectors, just build two narrower build
9744   // vectors. This helps shuffling with splats and zeros.
9745   auto SplitVector = [&](SDValue V) {
9746     while (V.getOpcode() == ISD::BITCAST)
9747       V = V->getOperand(0);
9748
9749     MVT OrigVT = V.getSimpleValueType();
9750     int OrigNumElements = OrigVT.getVectorNumElements();
9751     int OrigSplitNumElements = OrigNumElements / 2;
9752     MVT OrigScalarVT = OrigVT.getScalarType();
9753     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9754
9755     SDValue LoV, HiV;
9756
9757     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9758     if (!BV) {
9759       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9760                         DAG.getIntPtrConstant(0, DL));
9761       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9762                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9763     } else {
9764
9765       SmallVector<SDValue, 16> LoOps, HiOps;
9766       for (int i = 0; i < OrigSplitNumElements; ++i) {
9767         LoOps.push_back(BV->getOperand(i));
9768         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9769       }
9770       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9771       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9772     }
9773     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9774                           DAG.getBitcast(SplitVT, HiV));
9775   };
9776
9777   SDValue LoV1, HiV1, LoV2, HiV2;
9778   std::tie(LoV1, HiV1) = SplitVector(V1);
9779   std::tie(LoV2, HiV2) = SplitVector(V2);
9780
9781   // Now create two 4-way blends of these half-width vectors.
9782   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9783     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9784     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9785     for (int i = 0; i < SplitNumElements; ++i) {
9786       int M = HalfMask[i];
9787       if (M >= NumElements) {
9788         if (M >= NumElements + SplitNumElements)
9789           UseHiV2 = true;
9790         else
9791           UseLoV2 = true;
9792         V2BlendMask.push_back(M - NumElements);
9793         V1BlendMask.push_back(-1);
9794         BlendMask.push_back(SplitNumElements + i);
9795       } else if (M >= 0) {
9796         if (M >= SplitNumElements)
9797           UseHiV1 = true;
9798         else
9799           UseLoV1 = true;
9800         V2BlendMask.push_back(-1);
9801         V1BlendMask.push_back(M);
9802         BlendMask.push_back(i);
9803       } else {
9804         V2BlendMask.push_back(-1);
9805         V1BlendMask.push_back(-1);
9806         BlendMask.push_back(-1);
9807       }
9808     }
9809
9810     // Because the lowering happens after all combining takes place, we need to
9811     // manually combine these blend masks as much as possible so that we create
9812     // a minimal number of high-level vector shuffle nodes.
9813
9814     // First try just blending the halves of V1 or V2.
9815     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9816       return DAG.getUNDEF(SplitVT);
9817     if (!UseLoV2 && !UseHiV2)
9818       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9819     if (!UseLoV1 && !UseHiV1)
9820       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9821
9822     SDValue V1Blend, V2Blend;
9823     if (UseLoV1 && UseHiV1) {
9824       V1Blend =
9825         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9826     } else {
9827       // We only use half of V1 so map the usage down into the final blend mask.
9828       V1Blend = UseLoV1 ? LoV1 : HiV1;
9829       for (int i = 0; i < SplitNumElements; ++i)
9830         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9831           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9832     }
9833     if (UseLoV2 && UseHiV2) {
9834       V2Blend =
9835         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9836     } else {
9837       // We only use half of V2 so map the usage down into the final blend mask.
9838       V2Blend = UseLoV2 ? LoV2 : HiV2;
9839       for (int i = 0; i < SplitNumElements; ++i)
9840         if (BlendMask[i] >= SplitNumElements)
9841           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9842     }
9843     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9844   };
9845   SDValue Lo = HalfBlend(LoMask);
9846   SDValue Hi = HalfBlend(HiMask);
9847   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9848 }
9849
9850 /// \brief Either split a vector in halves or decompose the shuffles and the
9851 /// blend.
9852 ///
9853 /// This is provided as a good fallback for many lowerings of non-single-input
9854 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9855 /// between splitting the shuffle into 128-bit components and stitching those
9856 /// back together vs. extracting the single-input shuffles and blending those
9857 /// results.
9858 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9859                                                 SDValue V2, ArrayRef<int> Mask,
9860                                                 SelectionDAG &DAG) {
9861   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9862                                             "lower single-input shuffles as it "
9863                                             "could then recurse on itself.");
9864   int Size = Mask.size();
9865
9866   // If this can be modeled as a broadcast of two elements followed by a blend,
9867   // prefer that lowering. This is especially important because broadcasts can
9868   // often fold with memory operands.
9869   auto DoBothBroadcast = [&] {
9870     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9871     for (int M : Mask)
9872       if (M >= Size) {
9873         if (V2BroadcastIdx == -1)
9874           V2BroadcastIdx = M - Size;
9875         else if (M - Size != V2BroadcastIdx)
9876           return false;
9877       } else if (M >= 0) {
9878         if (V1BroadcastIdx == -1)
9879           V1BroadcastIdx = M;
9880         else if (M != V1BroadcastIdx)
9881           return false;
9882       }
9883     return true;
9884   };
9885   if (DoBothBroadcast())
9886     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9887                                                       DAG);
9888
9889   // If the inputs all stem from a single 128-bit lane of each input, then we
9890   // split them rather than blending because the split will decompose to
9891   // unusually few instructions.
9892   int LaneCount = VT.getSizeInBits() / 128;
9893   int LaneSize = Size / LaneCount;
9894   SmallBitVector LaneInputs[2];
9895   LaneInputs[0].resize(LaneCount, false);
9896   LaneInputs[1].resize(LaneCount, false);
9897   for (int i = 0; i < Size; ++i)
9898     if (Mask[i] >= 0)
9899       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9900   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9901     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9902
9903   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9904   // that the decomposed single-input shuffles don't end up here.
9905   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9906 }
9907
9908 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9909 /// a permutation and blend of those lanes.
9910 ///
9911 /// This essentially blends the out-of-lane inputs to each lane into the lane
9912 /// from a permuted copy of the vector. This lowering strategy results in four
9913 /// instructions in the worst case for a single-input cross lane shuffle which
9914 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9915 /// of. Special cases for each particular shuffle pattern should be handled
9916 /// prior to trying this lowering.
9917 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9918                                                        SDValue V1, SDValue V2,
9919                                                        ArrayRef<int> Mask,
9920                                                        SelectionDAG &DAG) {
9921   // FIXME: This should probably be generalized for 512-bit vectors as well.
9922   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9923   int LaneSize = Mask.size() / 2;
9924
9925   // If there are only inputs from one 128-bit lane, splitting will in fact be
9926   // less expensive. The flags track whether the given lane contains an element
9927   // that crosses to another lane.
9928   bool LaneCrossing[2] = {false, false};
9929   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9930     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9931       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9932   if (!LaneCrossing[0] || !LaneCrossing[1])
9933     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9934
9935   if (isSingleInputShuffleMask(Mask)) {
9936     SmallVector<int, 32> FlippedBlendMask;
9937     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9938       FlippedBlendMask.push_back(
9939           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9940                                   ? Mask[i]
9941                                   : Mask[i] % LaneSize +
9942                                         (i / LaneSize) * LaneSize + Size));
9943
9944     // Flip the vector, and blend the results which should now be in-lane. The
9945     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9946     // 5 for the high source. The value 3 selects the high half of source 2 and
9947     // the value 2 selects the low half of source 2. We only use source 2 to
9948     // allow folding it into a memory operand.
9949     unsigned PERMMask = 3 | 2 << 4;
9950     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9951                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9952     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9953   }
9954
9955   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9956   // will be handled by the above logic and a blend of the results, much like
9957   // other patterns in AVX.
9958   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9959 }
9960
9961 /// \brief Handle lowering 2-lane 128-bit shuffles.
9962 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9963                                         SDValue V2, ArrayRef<int> Mask,
9964                                         const X86Subtarget *Subtarget,
9965                                         SelectionDAG &DAG) {
9966   // TODO: If minimizing size and one of the inputs is a zero vector and the
9967   // the zero vector has only one use, we could use a VPERM2X128 to save the
9968   // instruction bytes needed to explicitly generate the zero vector.
9969
9970   // Blends are faster and handle all the non-lane-crossing cases.
9971   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9972                                                 Subtarget, DAG))
9973     return Blend;
9974
9975   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9976   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9977
9978   // If either input operand is a zero vector, use VPERM2X128 because its mask
9979   // allows us to replace the zero input with an implicit zero.
9980   if (!IsV1Zero && !IsV2Zero) {
9981     // Check for patterns which can be matched with a single insert of a 128-bit
9982     // subvector.
9983     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9984     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9985       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9986                                    VT.getVectorNumElements() / 2);
9987       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9988                                 DAG.getIntPtrConstant(0, DL));
9989       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9990                                 OnlyUsesV1 ? V1 : V2,
9991                                 DAG.getIntPtrConstant(0, DL));
9992       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9993     }
9994   }
9995
9996   // Otherwise form a 128-bit permutation. After accounting for undefs,
9997   // convert the 64-bit shuffle mask selection values into 128-bit
9998   // selection bits by dividing the indexes by 2 and shifting into positions
9999   // defined by a vperm2*128 instruction's immediate control byte.
10000
10001   // The immediate permute control byte looks like this:
10002   //    [1:0] - select 128 bits from sources for low half of destination
10003   //    [2]   - ignore
10004   //    [3]   - zero low half of destination
10005   //    [5:4] - select 128 bits from sources for high half of destination
10006   //    [6]   - ignore
10007   //    [7]   - zero high half of destination
10008
10009   int MaskLO = Mask[0];
10010   if (MaskLO == SM_SentinelUndef)
10011     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10012
10013   int MaskHI = Mask[2];
10014   if (MaskHI == SM_SentinelUndef)
10015     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10016
10017   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10018
10019   // If either input is a zero vector, replace it with an undef input.
10020   // Shuffle mask values <  4 are selecting elements of V1.
10021   // Shuffle mask values >= 4 are selecting elements of V2.
10022   // Adjust each half of the permute mask by clearing the half that was
10023   // selecting the zero vector and setting the zero mask bit.
10024   if (IsV1Zero) {
10025     V1 = DAG.getUNDEF(VT);
10026     if (MaskLO < 4)
10027       PermMask = (PermMask & 0xf0) | 0x08;
10028     if (MaskHI < 4)
10029       PermMask = (PermMask & 0x0f) | 0x80;
10030   }
10031   if (IsV2Zero) {
10032     V2 = DAG.getUNDEF(VT);
10033     if (MaskLO >= 4)
10034       PermMask = (PermMask & 0xf0) | 0x08;
10035     if (MaskHI >= 4)
10036       PermMask = (PermMask & 0x0f) | 0x80;
10037   }
10038
10039   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10040                      DAG.getConstant(PermMask, DL, MVT::i8));
10041 }
10042
10043 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10044 /// shuffling each lane.
10045 ///
10046 /// This will only succeed when the result of fixing the 128-bit lanes results
10047 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10048 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10049 /// the lane crosses early and then use simpler shuffles within each lane.
10050 ///
10051 /// FIXME: It might be worthwhile at some point to support this without
10052 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10053 /// in x86 only floating point has interesting non-repeating shuffles, and even
10054 /// those are still *marginally* more expensive.
10055 static SDValue lowerVectorShuffleByMerging128BitLanes(
10056     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10057     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10058   assert(!isSingleInputShuffleMask(Mask) &&
10059          "This is only useful with multiple inputs.");
10060
10061   int Size = Mask.size();
10062   int LaneSize = 128 / VT.getScalarSizeInBits();
10063   int NumLanes = Size / LaneSize;
10064   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10065
10066   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10067   // check whether the in-128-bit lane shuffles share a repeating pattern.
10068   SmallVector<int, 4> Lanes;
10069   Lanes.resize(NumLanes, -1);
10070   SmallVector<int, 4> InLaneMask;
10071   InLaneMask.resize(LaneSize, -1);
10072   for (int i = 0; i < Size; ++i) {
10073     if (Mask[i] < 0)
10074       continue;
10075
10076     int j = i / LaneSize;
10077
10078     if (Lanes[j] < 0) {
10079       // First entry we've seen for this lane.
10080       Lanes[j] = Mask[i] / LaneSize;
10081     } else if (Lanes[j] != Mask[i] / LaneSize) {
10082       // This doesn't match the lane selected previously!
10083       return SDValue();
10084     }
10085
10086     // Check that within each lane we have a consistent shuffle mask.
10087     int k = i % LaneSize;
10088     if (InLaneMask[k] < 0) {
10089       InLaneMask[k] = Mask[i] % LaneSize;
10090     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10091       // This doesn't fit a repeating in-lane mask.
10092       return SDValue();
10093     }
10094   }
10095
10096   // First shuffle the lanes into place.
10097   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10098                                 VT.getSizeInBits() / 64);
10099   SmallVector<int, 8> LaneMask;
10100   LaneMask.resize(NumLanes * 2, -1);
10101   for (int i = 0; i < NumLanes; ++i)
10102     if (Lanes[i] >= 0) {
10103       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10104       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10105     }
10106
10107   V1 = DAG.getBitcast(LaneVT, V1);
10108   V2 = DAG.getBitcast(LaneVT, V2);
10109   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10110
10111   // Cast it back to the type we actually want.
10112   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10113
10114   // Now do a simple shuffle that isn't lane crossing.
10115   SmallVector<int, 8> NewMask;
10116   NewMask.resize(Size, -1);
10117   for (int i = 0; i < Size; ++i)
10118     if (Mask[i] >= 0)
10119       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10120   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10121          "Must not introduce lane crosses at this point!");
10122
10123   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10124 }
10125
10126 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10127 /// given mask.
10128 ///
10129 /// This returns true if the elements from a particular input are already in the
10130 /// slot required by the given mask and require no permutation.
10131 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10132   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10133   int Size = Mask.size();
10134   for (int i = 0; i < Size; ++i)
10135     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10136       return false;
10137
10138   return true;
10139 }
10140
10141 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10142                                             ArrayRef<int> Mask, SDValue V1,
10143                                             SDValue V2, SelectionDAG &DAG) {
10144
10145   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10146   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10147   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10148   int NumElts = VT.getVectorNumElements();
10149   bool ShufpdMask = true;
10150   bool CommutableMask = true;
10151   unsigned Immediate = 0;
10152   for (int i = 0; i < NumElts; ++i) {
10153     if (Mask[i] < 0)
10154       continue;
10155     int Val = (i & 6) + NumElts * (i & 1);
10156     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10157     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10158       ShufpdMask = false;
10159     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10160       CommutableMask = false;
10161     Immediate |= (Mask[i] % 2) << i;
10162   }
10163   if (ShufpdMask)
10164     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10165                        DAG.getConstant(Immediate, DL, MVT::i8));
10166   if (CommutableMask)
10167     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10168                        DAG.getConstant(Immediate, DL, MVT::i8));
10169   return SDValue();
10170 }
10171
10172 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10173 ///
10174 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10175 /// isn't available.
10176 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10177                                        const X86Subtarget *Subtarget,
10178                                        SelectionDAG &DAG) {
10179   SDLoc DL(Op);
10180   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10181   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10182   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10183   ArrayRef<int> Mask = SVOp->getMask();
10184   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10185
10186   SmallVector<int, 4> WidenedMask;
10187   if (canWidenShuffleElements(Mask, WidenedMask))
10188     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10189                                     DAG);
10190
10191   if (isSingleInputShuffleMask(Mask)) {
10192     // Check for being able to broadcast a single element.
10193     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10194                                                           Mask, Subtarget, DAG))
10195       return Broadcast;
10196
10197     // Use low duplicate instructions for masks that match their pattern.
10198     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10199       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10200
10201     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10202       // Non-half-crossing single input shuffles can be lowerid with an
10203       // interleaved permutation.
10204       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10205                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10206       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10207                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10208     }
10209
10210     // With AVX2 we have direct support for this permutation.
10211     if (Subtarget->hasAVX2())
10212       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10213                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10214
10215     // Otherwise, fall back.
10216     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10217                                                    DAG);
10218   }
10219
10220   // Use dedicated unpack instructions for masks that match their pattern.
10221   if (SDValue V =
10222           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10223     return V;
10224
10225   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10226                                                 Subtarget, DAG))
10227     return Blend;
10228
10229   // Check if the blend happens to exactly fit that of SHUFPD.
10230   if (SDValue Op =
10231       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10232     return Op;
10233
10234   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10235   // shuffle. However, if we have AVX2 and either inputs are already in place,
10236   // we will be able to shuffle even across lanes the other input in a single
10237   // instruction so skip this pattern.
10238   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10239                                  isShuffleMaskInputInPlace(1, Mask))))
10240     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10241             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10242       return Result;
10243
10244   // If we have AVX2 then we always want to lower with a blend because an v4 we
10245   // can fully permute the elements.
10246   if (Subtarget->hasAVX2())
10247     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10248                                                       Mask, DAG);
10249
10250   // Otherwise fall back on generic lowering.
10251   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10252 }
10253
10254 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10255 ///
10256 /// This routine is only called when we have AVX2 and thus a reasonable
10257 /// instruction set for v4i64 shuffling..
10258 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10259                                        const X86Subtarget *Subtarget,
10260                                        SelectionDAG &DAG) {
10261   SDLoc DL(Op);
10262   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10263   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10264   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10265   ArrayRef<int> Mask = SVOp->getMask();
10266   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10267   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10268
10269   SmallVector<int, 4> WidenedMask;
10270   if (canWidenShuffleElements(Mask, WidenedMask))
10271     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10272                                     DAG);
10273
10274   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10275                                                 Subtarget, DAG))
10276     return Blend;
10277
10278   // Check for being able to broadcast a single element.
10279   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10280                                                         Mask, Subtarget, DAG))
10281     return Broadcast;
10282
10283   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10284   // use lower latency instructions that will operate on both 128-bit lanes.
10285   SmallVector<int, 2> RepeatedMask;
10286   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10287     if (isSingleInputShuffleMask(Mask)) {
10288       int PSHUFDMask[] = {-1, -1, -1, -1};
10289       for (int i = 0; i < 2; ++i)
10290         if (RepeatedMask[i] >= 0) {
10291           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10292           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10293         }
10294       return DAG.getBitcast(
10295           MVT::v4i64,
10296           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10297                       DAG.getBitcast(MVT::v8i32, V1),
10298                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10299     }
10300   }
10301
10302   // AVX2 provides a direct instruction for permuting a single input across
10303   // lanes.
10304   if (isSingleInputShuffleMask(Mask))
10305     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10306                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10307
10308   // Try to use shift instructions.
10309   if (SDValue Shift =
10310           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10311     return Shift;
10312
10313   // Use dedicated unpack instructions for masks that match their pattern.
10314   if (SDValue V =
10315           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10316     return V;
10317
10318   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10319   // shuffle. However, if we have AVX2 and either inputs are already in place,
10320   // we will be able to shuffle even across lanes the other input in a single
10321   // instruction so skip this pattern.
10322   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10323                                  isShuffleMaskInputInPlace(1, Mask))))
10324     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10325             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10326       return Result;
10327
10328   // Otherwise fall back on generic blend lowering.
10329   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10330                                                     Mask, DAG);
10331 }
10332
10333 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10334 ///
10335 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10336 /// isn't available.
10337 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10338                                        const X86Subtarget *Subtarget,
10339                                        SelectionDAG &DAG) {
10340   SDLoc DL(Op);
10341   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10342   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10343   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10344   ArrayRef<int> Mask = SVOp->getMask();
10345   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10346
10347   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10348                                                 Subtarget, DAG))
10349     return Blend;
10350
10351   // Check for being able to broadcast a single element.
10352   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10353                                                         Mask, Subtarget, DAG))
10354     return Broadcast;
10355
10356   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10357   // options to efficiently lower the shuffle.
10358   SmallVector<int, 4> RepeatedMask;
10359   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10360     assert(RepeatedMask.size() == 4 &&
10361            "Repeated masks must be half the mask width!");
10362
10363     // Use even/odd duplicate instructions for masks that match their pattern.
10364     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10365       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10366     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10367       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10368
10369     if (isSingleInputShuffleMask(Mask))
10370       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10371                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10372
10373     // Use dedicated unpack instructions for masks that match their pattern.
10374     if (SDValue V =
10375             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10376       return V;
10377
10378     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10379     // have already handled any direct blends. We also need to squash the
10380     // repeated mask into a simulated v4f32 mask.
10381     for (int i = 0; i < 4; ++i)
10382       if (RepeatedMask[i] >= 8)
10383         RepeatedMask[i] -= 4;
10384     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10385   }
10386
10387   // If we have a single input shuffle with different shuffle patterns in the
10388   // two 128-bit lanes use the variable mask to VPERMILPS.
10389   if (isSingleInputShuffleMask(Mask)) {
10390     SDValue VPermMask[8];
10391     for (int i = 0; i < 8; ++i)
10392       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10393                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10394     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10395       return DAG.getNode(
10396           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10397           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10398
10399     if (Subtarget->hasAVX2())
10400       return DAG.getNode(
10401           X86ISD::VPERMV, DL, MVT::v8f32,
10402           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10403                                                  MVT::v8i32, VPermMask)),
10404           V1);
10405
10406     // Otherwise, fall back.
10407     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10408                                                    DAG);
10409   }
10410
10411   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10412   // shuffle.
10413   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10414           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10415     return Result;
10416
10417   // If we have AVX2 then we always want to lower with a blend because at v8 we
10418   // can fully permute the elements.
10419   if (Subtarget->hasAVX2())
10420     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10421                                                       Mask, DAG);
10422
10423   // Otherwise fall back on generic lowering.
10424   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10425 }
10426
10427 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10428 ///
10429 /// This routine is only called when we have AVX2 and thus a reasonable
10430 /// instruction set for v8i32 shuffling..
10431 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10432                                        const X86Subtarget *Subtarget,
10433                                        SelectionDAG &DAG) {
10434   SDLoc DL(Op);
10435   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10436   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10438   ArrayRef<int> Mask = SVOp->getMask();
10439   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10440   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10441
10442   // Whenever we can lower this as a zext, that instruction is strictly faster
10443   // than any alternative. It also allows us to fold memory operands into the
10444   // shuffle in many cases.
10445   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10446                                                          Mask, Subtarget, DAG))
10447     return ZExt;
10448
10449   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10450                                                 Subtarget, DAG))
10451     return Blend;
10452
10453   // Check for being able to broadcast a single element.
10454   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10455                                                         Mask, Subtarget, DAG))
10456     return Broadcast;
10457
10458   // If the shuffle mask is repeated in each 128-bit lane we can use more
10459   // efficient instructions that mirror the shuffles across the two 128-bit
10460   // lanes.
10461   SmallVector<int, 4> RepeatedMask;
10462   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10463     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10464     if (isSingleInputShuffleMask(Mask))
10465       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10466                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10467
10468     // Use dedicated unpack instructions for masks that match their pattern.
10469     if (SDValue V =
10470             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10471       return V;
10472   }
10473
10474   // Try to use shift instructions.
10475   if (SDValue Shift =
10476           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10477     return Shift;
10478
10479   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10480           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10481     return Rotate;
10482
10483   // If the shuffle patterns aren't repeated but it is a single input, directly
10484   // generate a cross-lane VPERMD instruction.
10485   if (isSingleInputShuffleMask(Mask)) {
10486     SDValue VPermMask[8];
10487     for (int i = 0; i < 8; ++i)
10488       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10489                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10490     return DAG.getNode(
10491         X86ISD::VPERMV, DL, MVT::v8i32,
10492         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10493   }
10494
10495   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10496   // shuffle.
10497   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10498           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10499     return Result;
10500
10501   // Otherwise fall back on generic blend lowering.
10502   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10503                                                     Mask, DAG);
10504 }
10505
10506 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10507 ///
10508 /// This routine is only called when we have AVX2 and thus a reasonable
10509 /// instruction set for v16i16 shuffling..
10510 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10511                                         const X86Subtarget *Subtarget,
10512                                         SelectionDAG &DAG) {
10513   SDLoc DL(Op);
10514   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10515   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10516   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10517   ArrayRef<int> Mask = SVOp->getMask();
10518   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10519   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10520
10521   // Whenever we can lower this as a zext, that instruction is strictly faster
10522   // than any alternative. It also allows us to fold memory operands into the
10523   // shuffle in many cases.
10524   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10525                                                          Mask, Subtarget, DAG))
10526     return ZExt;
10527
10528   // Check for being able to broadcast a single element.
10529   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10530                                                         Mask, Subtarget, DAG))
10531     return Broadcast;
10532
10533   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10534                                                 Subtarget, DAG))
10535     return Blend;
10536
10537   // Use dedicated unpack instructions for masks that match their pattern.
10538   if (SDValue V =
10539           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10540     return V;
10541
10542   // Try to use shift instructions.
10543   if (SDValue Shift =
10544           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10545     return Shift;
10546
10547   // Try to use byte rotation instructions.
10548   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10549           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10550     return Rotate;
10551
10552   if (isSingleInputShuffleMask(Mask)) {
10553     // There are no generalized cross-lane shuffle operations available on i16
10554     // element types.
10555     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10556       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10557                                                      Mask, DAG);
10558
10559     SmallVector<int, 8> RepeatedMask;
10560     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10561       // As this is a single-input shuffle, the repeated mask should be
10562       // a strictly valid v8i16 mask that we can pass through to the v8i16
10563       // lowering to handle even the v16 case.
10564       return lowerV8I16GeneralSingleInputVectorShuffle(
10565           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10566     }
10567
10568     SDValue PSHUFBMask[32];
10569     for (int i = 0; i < 16; ++i) {
10570       if (Mask[i] == -1) {
10571         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10572         continue;
10573       }
10574
10575       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10576       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10577       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10578       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10579     }
10580     return DAG.getBitcast(MVT::v16i16,
10581                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10582                                       DAG.getBitcast(MVT::v32i8, V1),
10583                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10584                                                   MVT::v32i8, PSHUFBMask)));
10585   }
10586
10587   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10588   // shuffle.
10589   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10590           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10591     return Result;
10592
10593   // Otherwise fall back on generic lowering.
10594   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10595 }
10596
10597 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10598 ///
10599 /// This routine is only called when we have AVX2 and thus a reasonable
10600 /// instruction set for v32i8 shuffling..
10601 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10602                                        const X86Subtarget *Subtarget,
10603                                        SelectionDAG &DAG) {
10604   SDLoc DL(Op);
10605   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10606   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10607   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10608   ArrayRef<int> Mask = SVOp->getMask();
10609   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10610   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10611
10612   // Whenever we can lower this as a zext, that instruction is strictly faster
10613   // than any alternative. It also allows us to fold memory operands into the
10614   // shuffle in many cases.
10615   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10616                                                          Mask, Subtarget, DAG))
10617     return ZExt;
10618
10619   // Check for being able to broadcast a single element.
10620   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10621                                                         Mask, Subtarget, DAG))
10622     return Broadcast;
10623
10624   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10625                                                 Subtarget, DAG))
10626     return Blend;
10627
10628   // Use dedicated unpack instructions for masks that match their pattern.
10629   if (SDValue V =
10630           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10631     return V;
10632
10633   // Try to use shift instructions.
10634   if (SDValue Shift =
10635           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10636     return Shift;
10637
10638   // Try to use byte rotation instructions.
10639   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10640           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10641     return Rotate;
10642
10643   if (isSingleInputShuffleMask(Mask)) {
10644     // There are no generalized cross-lane shuffle operations available on i8
10645     // element types.
10646     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10647       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10648                                                      Mask, DAG);
10649
10650     SDValue PSHUFBMask[32];
10651     for (int i = 0; i < 32; ++i)
10652       PSHUFBMask[i] =
10653           Mask[i] < 0
10654               ? DAG.getUNDEF(MVT::i8)
10655               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10656                                 MVT::i8);
10657
10658     return DAG.getNode(
10659         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10660         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10661   }
10662
10663   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10664   // shuffle.
10665   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10666           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10667     return Result;
10668
10669   // Otherwise fall back on generic lowering.
10670   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10671 }
10672
10673 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10674 ///
10675 /// This routine either breaks down the specific type of a 256-bit x86 vector
10676 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10677 /// together based on the available instructions.
10678 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10679                                         MVT VT, const X86Subtarget *Subtarget,
10680                                         SelectionDAG &DAG) {
10681   SDLoc DL(Op);
10682   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10683   ArrayRef<int> Mask = SVOp->getMask();
10684
10685   // If we have a single input to the zero element, insert that into V1 if we
10686   // can do so cheaply.
10687   int NumElts = VT.getVectorNumElements();
10688   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10689     return M >= NumElts;
10690   });
10691
10692   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10693     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10694                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10695       return Insertion;
10696
10697   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10698   // can check for those subtargets here and avoid much of the subtarget
10699   // querying in the per-vector-type lowering routines. With AVX1 we have
10700   // essentially *zero* ability to manipulate a 256-bit vector with integer
10701   // types. Since we'll use floating point types there eventually, just
10702   // immediately cast everything to a float and operate entirely in that domain.
10703   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10704     int ElementBits = VT.getScalarSizeInBits();
10705     if (ElementBits < 32)
10706       // No floating point type available, decompose into 128-bit vectors.
10707       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10708
10709     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10710                                 VT.getVectorNumElements());
10711     V1 = DAG.getBitcast(FpVT, V1);
10712     V2 = DAG.getBitcast(FpVT, V2);
10713     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10714   }
10715
10716   switch (VT.SimpleTy) {
10717   case MVT::v4f64:
10718     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10719   case MVT::v4i64:
10720     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10721   case MVT::v8f32:
10722     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10723   case MVT::v8i32:
10724     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10725   case MVT::v16i16:
10726     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10727   case MVT::v32i8:
10728     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10729
10730   default:
10731     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10732   }
10733 }
10734
10735 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10736 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10737                                              ArrayRef<int> Mask,
10738                                              SDValue V1, SDValue V2,
10739                                              SelectionDAG &DAG) {
10740   assert(VT.getScalarSizeInBits() == 64 &&
10741          "Unexpected element type size for 128bit shuffle.");
10742
10743   // To handle 256 bit vector requires VLX and most probably
10744   // function lowerV2X128VectorShuffle() is better solution.
10745   assert(VT.getSizeInBits() == 512 &&
10746          "Unexpected vector size for 128bit shuffle.");
10747
10748   SmallVector<int, 4> WidenedMask;
10749   if (!canWidenShuffleElements(Mask, WidenedMask))
10750     return SDValue();
10751
10752   // Form a 128-bit permutation.
10753   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10754   // bits defined by a vshuf64x2 instruction's immediate control byte.
10755   unsigned PermMask = 0, Imm = 0;
10756   unsigned ControlBitsNum = WidenedMask.size() / 2;
10757
10758   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10759     if (WidenedMask[i] == SM_SentinelZero)
10760       return SDValue();
10761
10762     // Use first element in place of undef mask.
10763     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10764     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10765   }
10766
10767   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10768                      DAG.getConstant(PermMask, DL, MVT::i8));
10769 }
10770
10771 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10772                                            ArrayRef<int> Mask, SDValue V1,
10773                                            SDValue V2, SelectionDAG &DAG) {
10774
10775   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10776
10777   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10778   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10779
10780   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10781   if (isSingleInputShuffleMask(Mask))
10782     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10783
10784   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10785 }
10786
10787 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10788 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10789                                        const X86Subtarget *Subtarget,
10790                                        SelectionDAG &DAG) {
10791   SDLoc DL(Op);
10792   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10793   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10794   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10795   ArrayRef<int> Mask = SVOp->getMask();
10796   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10797
10798   if (SDValue Shuf128 =
10799           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10800     return Shuf128;
10801
10802   if (SDValue Unpck =
10803           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10804     return Unpck;
10805
10806   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10807 }
10808
10809 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10810 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10811                                        const X86Subtarget *Subtarget,
10812                                        SelectionDAG &DAG) {
10813   SDLoc DL(Op);
10814   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10815   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10816   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10817   ArrayRef<int> Mask = SVOp->getMask();
10818   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10819
10820   if (SDValue Unpck =
10821           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10822     return Unpck;
10823
10824   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10825 }
10826
10827 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10828 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10829                                        const X86Subtarget *Subtarget,
10830                                        SelectionDAG &DAG) {
10831   SDLoc DL(Op);
10832   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10833   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10834   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10835   ArrayRef<int> Mask = SVOp->getMask();
10836   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10837
10838   if (SDValue Shuf128 =
10839           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10840     return Shuf128;
10841
10842   if (SDValue Unpck =
10843           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10844     return Unpck;
10845
10846   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10847 }
10848
10849 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10850 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10851                                        const X86Subtarget *Subtarget,
10852                                        SelectionDAG &DAG) {
10853   SDLoc DL(Op);
10854   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10855   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10856   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10857   ArrayRef<int> Mask = SVOp->getMask();
10858   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10859
10860   if (SDValue Unpck =
10861           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10862     return Unpck;
10863
10864   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10865 }
10866
10867 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10868 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10869                                         const X86Subtarget *Subtarget,
10870                                         SelectionDAG &DAG) {
10871   SDLoc DL(Op);
10872   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10873   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10875   ArrayRef<int> Mask = SVOp->getMask();
10876   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10877   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10878
10879   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10880 }
10881
10882 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10883 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10884                                        const X86Subtarget *Subtarget,
10885                                        SelectionDAG &DAG) {
10886   SDLoc DL(Op);
10887   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10888   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10889   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10890   ArrayRef<int> Mask = SVOp->getMask();
10891   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10892   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10893
10894   // FIXME: Implement direct support for this type!
10895   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10896 }
10897
10898 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10899 ///
10900 /// This routine either breaks down the specific type of a 512-bit x86 vector
10901 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10902 /// together based on the available instructions.
10903 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10904                                         MVT VT, const X86Subtarget *Subtarget,
10905                                         SelectionDAG &DAG) {
10906   SDLoc DL(Op);
10907   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10908   ArrayRef<int> Mask = SVOp->getMask();
10909   assert(Subtarget->hasAVX512() &&
10910          "Cannot lower 512-bit vectors w/ basic ISA!");
10911
10912   // Check for being able to broadcast a single element.
10913   if (SDValue Broadcast =
10914           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10915     return Broadcast;
10916
10917   // Dispatch to each element type for lowering. If we don't have supprot for
10918   // specific element type shuffles at 512 bits, immediately split them and
10919   // lower them. Each lowering routine of a given type is allowed to assume that
10920   // the requisite ISA extensions for that element type are available.
10921   switch (VT.SimpleTy) {
10922   case MVT::v8f64:
10923     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10924   case MVT::v16f32:
10925     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10926   case MVT::v8i64:
10927     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10928   case MVT::v16i32:
10929     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10930   case MVT::v32i16:
10931     if (Subtarget->hasBWI())
10932       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10933     break;
10934   case MVT::v64i8:
10935     if (Subtarget->hasBWI())
10936       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10937     break;
10938
10939   default:
10940     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10941   }
10942
10943   // Otherwise fall back on splitting.
10944   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10945 }
10946
10947 // Lower vXi1 vector shuffles.
10948 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10949 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10950 // vector, shuffle and then truncate it back.
10951 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10952                                       MVT VT, const X86Subtarget *Subtarget,
10953                                       SelectionDAG &DAG) {
10954   SDLoc DL(Op);
10955   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10956   ArrayRef<int> Mask = SVOp->getMask();
10957   assert(Subtarget->hasAVX512() &&
10958          "Cannot lower 512-bit vectors w/o basic ISA!");
10959   EVT ExtVT;
10960   switch (VT.SimpleTy) {
10961   default:
10962     llvm_unreachable("Expected a vector of i1 elements");
10963   case MVT::v2i1:
10964     ExtVT = MVT::v2i64;
10965     break;
10966   case MVT::v4i1:
10967     ExtVT = MVT::v4i32;
10968     break;
10969   case MVT::v8i1:
10970     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10971     break;
10972   case MVT::v16i1:
10973     ExtVT = MVT::v16i32;
10974     break;
10975   case MVT::v32i1:
10976     ExtVT = MVT::v32i16;
10977     break;
10978   case MVT::v64i1:
10979     ExtVT = MVT::v64i8;
10980     break;
10981   }
10982
10983   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10984     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10985   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10986     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10987   else
10988     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10989
10990   if (V2.isUndef())
10991     V2 = DAG.getUNDEF(ExtVT);
10992   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10993     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10994   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10995     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10996   else
10997     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10998   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10999                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11000 }
11001 /// \brief Top-level lowering for x86 vector shuffles.
11002 ///
11003 /// This handles decomposition, canonicalization, and lowering of all x86
11004 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11005 /// above in helper routines. The canonicalization attempts to widen shuffles
11006 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11007 /// s.t. only one of the two inputs needs to be tested, etc.
11008 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11009                                   SelectionDAG &DAG) {
11010   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11011   ArrayRef<int> Mask = SVOp->getMask();
11012   SDValue V1 = Op.getOperand(0);
11013   SDValue V2 = Op.getOperand(1);
11014   MVT VT = Op.getSimpleValueType();
11015   int NumElements = VT.getVectorNumElements();
11016   SDLoc dl(Op);
11017   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
11018
11019   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11020          "Can't lower MMX shuffles");
11021
11022   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11023   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11024   if (V1IsUndef && V2IsUndef)
11025     return DAG.getUNDEF(VT);
11026
11027   // When we create a shuffle node we put the UNDEF node to second operand,
11028   // but in some cases the first operand may be transformed to UNDEF.
11029   // In this case we should just commute the node.
11030   if (V1IsUndef)
11031     return DAG.getCommutedVectorShuffle(*SVOp);
11032
11033   // Check for non-undef masks pointing at an undef vector and make the masks
11034   // undef as well. This makes it easier to match the shuffle based solely on
11035   // the mask.
11036   if (V2IsUndef)
11037     for (int M : Mask)
11038       if (M >= NumElements) {
11039         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11040         for (int &M : NewMask)
11041           if (M >= NumElements)
11042             M = -1;
11043         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11044       }
11045
11046   // We actually see shuffles that are entirely re-arrangements of a set of
11047   // zero inputs. This mostly happens while decomposing complex shuffles into
11048   // simple ones. Directly lower these as a buildvector of zeros.
11049   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11050   if (Zeroable.all())
11051     return getZeroVector(VT, Subtarget, DAG, dl);
11052
11053   // Try to collapse shuffles into using a vector type with fewer elements but
11054   // wider element types. We cap this to not form integers or floating point
11055   // elements wider than 64 bits, but it might be interesting to form i128
11056   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11057   SmallVector<int, 16> WidenedMask;
11058   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11059       canWidenShuffleElements(Mask, WidenedMask)) {
11060     MVT NewEltVT = VT.isFloatingPoint()
11061                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11062                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11063     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11064     // Make sure that the new vector type is legal. For example, v2f64 isn't
11065     // legal on SSE1.
11066     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11067       V1 = DAG.getBitcast(NewVT, V1);
11068       V2 = DAG.getBitcast(NewVT, V2);
11069       return DAG.getBitcast(
11070           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11071     }
11072   }
11073
11074   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11075   for (int M : SVOp->getMask())
11076     if (M < 0)
11077       ++NumUndefElements;
11078     else if (M < NumElements)
11079       ++NumV1Elements;
11080     else
11081       ++NumV2Elements;
11082
11083   // Commute the shuffle as needed such that more elements come from V1 than
11084   // V2. This allows us to match the shuffle pattern strictly on how many
11085   // elements come from V1 without handling the symmetric cases.
11086   if (NumV2Elements > NumV1Elements)
11087     return DAG.getCommutedVectorShuffle(*SVOp);
11088
11089   // When the number of V1 and V2 elements are the same, try to minimize the
11090   // number of uses of V2 in the low half of the vector. When that is tied,
11091   // ensure that the sum of indices for V1 is equal to or lower than the sum
11092   // indices for V2. When those are equal, try to ensure that the number of odd
11093   // indices for V1 is lower than the number of odd indices for V2.
11094   if (NumV1Elements == NumV2Elements) {
11095     int LowV1Elements = 0, LowV2Elements = 0;
11096     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11097       if (M >= NumElements)
11098         ++LowV2Elements;
11099       else if (M >= 0)
11100         ++LowV1Elements;
11101     if (LowV2Elements > LowV1Elements) {
11102       return DAG.getCommutedVectorShuffle(*SVOp);
11103     } else if (LowV2Elements == LowV1Elements) {
11104       int SumV1Indices = 0, SumV2Indices = 0;
11105       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11106         if (SVOp->getMask()[i] >= NumElements)
11107           SumV2Indices += i;
11108         else if (SVOp->getMask()[i] >= 0)
11109           SumV1Indices += i;
11110       if (SumV2Indices < SumV1Indices) {
11111         return DAG.getCommutedVectorShuffle(*SVOp);
11112       } else if (SumV2Indices == SumV1Indices) {
11113         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11114         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11115           if (SVOp->getMask()[i] >= NumElements)
11116             NumV2OddIndices += i % 2;
11117           else if (SVOp->getMask()[i] >= 0)
11118             NumV1OddIndices += i % 2;
11119         if (NumV2OddIndices < NumV1OddIndices)
11120           return DAG.getCommutedVectorShuffle(*SVOp);
11121       }
11122     }
11123   }
11124
11125   // For each vector width, delegate to a specialized lowering routine.
11126   if (VT.getSizeInBits() == 128)
11127     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11128
11129   if (VT.getSizeInBits() == 256)
11130     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11131
11132   if (VT.getSizeInBits() == 512)
11133     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11134
11135   if (Is1BitVector)
11136     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11137   llvm_unreachable("Unimplemented!");
11138 }
11139
11140 // This function assumes its argument is a BUILD_VECTOR of constants or
11141 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11142 // true.
11143 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11144                                     unsigned &MaskValue) {
11145   MaskValue = 0;
11146   unsigned NumElems = BuildVector->getNumOperands();
11147   
11148   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11149   // We don't handle the >2 lanes case right now.
11150   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11151   if (NumLanes > 2)
11152     return false;
11153
11154   unsigned NumElemsInLane = NumElems / NumLanes;
11155
11156   // Blend for v16i16 should be symmetric for the both lanes.
11157   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11158     SDValue EltCond = BuildVector->getOperand(i);
11159     SDValue SndLaneEltCond =
11160         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11161
11162     int Lane1Cond = -1, Lane2Cond = -1;
11163     if (isa<ConstantSDNode>(EltCond))
11164       Lane1Cond = !isZero(EltCond);
11165     if (isa<ConstantSDNode>(SndLaneEltCond))
11166       Lane2Cond = !isZero(SndLaneEltCond);
11167
11168     unsigned LaneMask = 0;
11169     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11170       // Lane1Cond != 0, means we want the first argument.
11171       // Lane1Cond == 0, means we want the second argument.
11172       // The encoding of this argument is 0 for the first argument, 1
11173       // for the second. Therefore, invert the condition.
11174       LaneMask = !Lane1Cond << i;
11175     else if (Lane1Cond < 0)
11176       LaneMask = !Lane2Cond << i;
11177     else
11178       return false;
11179
11180     MaskValue |= LaneMask;
11181     if (NumLanes == 2)
11182       MaskValue |= LaneMask << NumElemsInLane;
11183   }
11184   return true;
11185 }
11186
11187 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11188 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11189                                            const X86Subtarget *Subtarget,
11190                                            SelectionDAG &DAG) {
11191   SDValue Cond = Op.getOperand(0);
11192   SDValue LHS = Op.getOperand(1);
11193   SDValue RHS = Op.getOperand(2);
11194   SDLoc dl(Op);
11195   MVT VT = Op.getSimpleValueType();
11196
11197   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11198     return SDValue();
11199   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11200
11201   // Only non-legal VSELECTs reach this lowering, convert those into generic
11202   // shuffles and re-use the shuffle lowering path for blends.
11203   SmallVector<int, 32> Mask;
11204   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11205     SDValue CondElt = CondBV->getOperand(i);
11206     Mask.push_back(
11207         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11208   }
11209   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11210 }
11211
11212 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11213   // A vselect where all conditions and data are constants can be optimized into
11214   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11215   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11216       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11217       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11218     return SDValue();
11219
11220   // Try to lower this to a blend-style vector shuffle. This can handle all
11221   // constant condition cases.
11222   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11223     return BlendOp;
11224
11225   // Variable blends are only legal from SSE4.1 onward.
11226   if (!Subtarget->hasSSE41())
11227     return SDValue();
11228
11229   // Only some types will be legal on some subtargets. If we can emit a legal
11230   // VSELECT-matching blend, return Op, and but if we need to expand, return
11231   // a null value.
11232   switch (Op.getSimpleValueType().SimpleTy) {
11233   default:
11234     // Most of the vector types have blends past SSE4.1.
11235     return Op;
11236
11237   case MVT::v32i8:
11238     // The byte blends for AVX vectors were introduced only in AVX2.
11239     if (Subtarget->hasAVX2())
11240       return Op;
11241
11242     return SDValue();
11243
11244   case MVT::v8i16:
11245   case MVT::v16i16:
11246     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11247     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11248       return Op;
11249
11250     // FIXME: We should custom lower this by fixing the condition and using i8
11251     // blends.
11252     return SDValue();
11253   }
11254 }
11255
11256 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11257   MVT VT = Op.getSimpleValueType();
11258   SDLoc dl(Op);
11259
11260   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11261     return SDValue();
11262
11263   if (VT.getSizeInBits() == 8) {
11264     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11265                                   Op.getOperand(0), Op.getOperand(1));
11266     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11267                                   DAG.getValueType(VT));
11268     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11269   }
11270
11271   if (VT.getSizeInBits() == 16) {
11272     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11273     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11274     if (Idx == 0)
11275       return DAG.getNode(
11276           ISD::TRUNCATE, dl, MVT::i16,
11277           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11278                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11279                       Op.getOperand(1)));
11280     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11281                                   Op.getOperand(0), Op.getOperand(1));
11282     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11283                                   DAG.getValueType(VT));
11284     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11285   }
11286
11287   if (VT == MVT::f32) {
11288     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11289     // the result back to FR32 register. It's only worth matching if the
11290     // result has a single use which is a store or a bitcast to i32.  And in
11291     // the case of a store, it's not worth it if the index is a constant 0,
11292     // because a MOVSSmr can be used instead, which is smaller and faster.
11293     if (!Op.hasOneUse())
11294       return SDValue();
11295     SDNode *User = *Op.getNode()->use_begin();
11296     if ((User->getOpcode() != ISD::STORE ||
11297          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11298           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11299         (User->getOpcode() != ISD::BITCAST ||
11300          User->getValueType(0) != MVT::i32))
11301       return SDValue();
11302     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11303                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11304                                   Op.getOperand(1));
11305     return DAG.getBitcast(MVT::f32, Extract);
11306   }
11307
11308   if (VT == MVT::i32 || VT == MVT::i64) {
11309     // ExtractPS/pextrq works with constant index.
11310     if (isa<ConstantSDNode>(Op.getOperand(1)))
11311       return Op;
11312   }
11313   return SDValue();
11314 }
11315
11316 /// Extract one bit from mask vector, like v16i1 or v8i1.
11317 /// AVX-512 feature.
11318 SDValue
11319 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11320   SDValue Vec = Op.getOperand(0);
11321   SDLoc dl(Vec);
11322   MVT VecVT = Vec.getSimpleValueType();
11323   SDValue Idx = Op.getOperand(1);
11324   MVT EltVT = Op.getSimpleValueType();
11325
11326   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11327   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11328          "Unexpected vector type in ExtractBitFromMaskVector");
11329
11330   // variable index can't be handled in mask registers,
11331   // extend vector to VR512
11332   if (!isa<ConstantSDNode>(Idx)) {
11333     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11334     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11335     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11336                               ExtVT.getVectorElementType(), Ext, Idx);
11337     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11338   }
11339
11340   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11341   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11342   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11343     rc = getRegClassFor(MVT::v16i1);
11344   unsigned MaxSift = rc->getSize()*8 - 1;
11345   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11346                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11347   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11348                     DAG.getConstant(MaxSift, dl, MVT::i8));
11349   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11350                        DAG.getIntPtrConstant(0, dl));
11351 }
11352
11353 SDValue
11354 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11355                                            SelectionDAG &DAG) const {
11356   SDLoc dl(Op);
11357   SDValue Vec = Op.getOperand(0);
11358   MVT VecVT = Vec.getSimpleValueType();
11359   SDValue Idx = Op.getOperand(1);
11360
11361   if (Op.getSimpleValueType() == MVT::i1)
11362     return ExtractBitFromMaskVector(Op, DAG);
11363
11364   if (!isa<ConstantSDNode>(Idx)) {
11365     if (VecVT.is512BitVector() ||
11366         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11367          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11368
11369       MVT MaskEltVT =
11370         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11371       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11372                                     MaskEltVT.getSizeInBits());
11373
11374       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11375       auto PtrVT = getPointerTy(DAG.getDataLayout());
11376       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11377                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11378                                  DAG.getConstant(0, dl, PtrVT));
11379       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11380       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11381                          DAG.getConstant(0, dl, PtrVT));
11382     }
11383     return SDValue();
11384   }
11385
11386   // If this is a 256-bit vector result, first extract the 128-bit vector and
11387   // then extract the element from the 128-bit vector.
11388   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11389
11390     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11391     // Get the 128-bit vector.
11392     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11393     MVT EltVT = VecVT.getVectorElementType();
11394
11395     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11396
11397     //if (IdxVal >= NumElems/2)
11398     //  IdxVal -= NumElems/2;
11399     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11400     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11401                        DAG.getConstant(IdxVal, dl, MVT::i32));
11402   }
11403
11404   assert(VecVT.is128BitVector() && "Unexpected vector length");
11405
11406   if (Subtarget->hasSSE41())
11407     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11408       return Res;
11409
11410   MVT VT = Op.getSimpleValueType();
11411   // TODO: handle v16i8.
11412   if (VT.getSizeInBits() == 16) {
11413     SDValue Vec = Op.getOperand(0);
11414     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11415     if (Idx == 0)
11416       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11417                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11418                                      DAG.getBitcast(MVT::v4i32, Vec),
11419                                      Op.getOperand(1)));
11420     // Transform it so it match pextrw which produces a 32-bit result.
11421     MVT EltVT = MVT::i32;
11422     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11423                                   Op.getOperand(0), Op.getOperand(1));
11424     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11425                                   DAG.getValueType(VT));
11426     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11427   }
11428
11429   if (VT.getSizeInBits() == 32) {
11430     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11431     if (Idx == 0)
11432       return Op;
11433
11434     // SHUFPS the element to the lowest double word, then movss.
11435     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11436     MVT VVT = Op.getOperand(0).getSimpleValueType();
11437     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11438                                        DAG.getUNDEF(VVT), Mask);
11439     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11440                        DAG.getIntPtrConstant(0, dl));
11441   }
11442
11443   if (VT.getSizeInBits() == 64) {
11444     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11445     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11446     //        to match extract_elt for f64.
11447     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11448     if (Idx == 0)
11449       return Op;
11450
11451     // UNPCKHPD the element to the lowest double word, then movsd.
11452     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11453     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11454     int Mask[2] = { 1, -1 };
11455     MVT VVT = Op.getOperand(0).getSimpleValueType();
11456     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11457                                        DAG.getUNDEF(VVT), Mask);
11458     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11459                        DAG.getIntPtrConstant(0, dl));
11460   }
11461
11462   return SDValue();
11463 }
11464
11465 /// Insert one bit to mask vector, like v16i1 or v8i1.
11466 /// AVX-512 feature.
11467 SDValue
11468 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11469   SDLoc dl(Op);
11470   SDValue Vec = Op.getOperand(0);
11471   SDValue Elt = Op.getOperand(1);
11472   SDValue Idx = Op.getOperand(2);
11473   MVT VecVT = Vec.getSimpleValueType();
11474
11475   if (!isa<ConstantSDNode>(Idx)) {
11476     // Non constant index. Extend source and destination,
11477     // insert element and then truncate the result.
11478     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11479     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11480     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11481       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11482       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11483     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11484   }
11485
11486   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11487   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11488   if (IdxVal)
11489     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11490                            DAG.getConstant(IdxVal, dl, MVT::i8));
11491   if (Vec.getOpcode() == ISD::UNDEF)
11492     return EltInVec;
11493   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11494 }
11495
11496 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11497                                                   SelectionDAG &DAG) const {
11498   MVT VT = Op.getSimpleValueType();
11499   MVT EltVT = VT.getVectorElementType();
11500
11501   if (EltVT == MVT::i1)
11502     return InsertBitToMaskVector(Op, DAG);
11503
11504   SDLoc dl(Op);
11505   SDValue N0 = Op.getOperand(0);
11506   SDValue N1 = Op.getOperand(1);
11507   SDValue N2 = Op.getOperand(2);
11508   if (!isa<ConstantSDNode>(N2))
11509     return SDValue();
11510   auto *N2C = cast<ConstantSDNode>(N2);
11511   unsigned IdxVal = N2C->getZExtValue();
11512
11513   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11514   // into that, and then insert the subvector back into the result.
11515   if (VT.is256BitVector() || VT.is512BitVector()) {
11516     // With a 256-bit vector, we can insert into the zero element efficiently
11517     // using a blend if we have AVX or AVX2 and the right data type.
11518     if (VT.is256BitVector() && IdxVal == 0) {
11519       // TODO: It is worthwhile to cast integer to floating point and back
11520       // and incur a domain crossing penalty if that's what we'll end up
11521       // doing anyway after extracting to a 128-bit vector.
11522       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11523           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11524         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11525         N2 = DAG.getIntPtrConstant(1, dl);
11526         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11527       }
11528     }
11529
11530     // Get the desired 128-bit vector chunk.
11531     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11532
11533     // Insert the element into the desired chunk.
11534     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11535     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11536
11537     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11538                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11539
11540     // Insert the changed part back into the bigger vector
11541     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11542   }
11543   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11544
11545   if (Subtarget->hasSSE41()) {
11546     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11547       unsigned Opc;
11548       if (VT == MVT::v8i16) {
11549         Opc = X86ISD::PINSRW;
11550       } else {
11551         assert(VT == MVT::v16i8);
11552         Opc = X86ISD::PINSRB;
11553       }
11554
11555       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11556       // argument.
11557       if (N1.getValueType() != MVT::i32)
11558         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11559       if (N2.getValueType() != MVT::i32)
11560         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11561       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11562     }
11563
11564     if (EltVT == MVT::f32) {
11565       // Bits [7:6] of the constant are the source select. This will always be
11566       //   zero here. The DAG Combiner may combine an extract_elt index into
11567       //   these bits. For example (insert (extract, 3), 2) could be matched by
11568       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11569       // Bits [5:4] of the constant are the destination select. This is the
11570       //   value of the incoming immediate.
11571       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11572       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11573
11574       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11575       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11576         // If this is an insertion of 32-bits into the low 32-bits of
11577         // a vector, we prefer to generate a blend with immediate rather
11578         // than an insertps. Blends are simpler operations in hardware and so
11579         // will always have equal or better performance than insertps.
11580         // But if optimizing for size and there's a load folding opportunity,
11581         // generate insertps because blendps does not have a 32-bit memory
11582         // operand form.
11583         N2 = DAG.getIntPtrConstant(1, dl);
11584         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11585         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11586       }
11587       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11588       // Create this as a scalar to vector..
11589       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11590       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11591     }
11592
11593     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11594       // PINSR* works with constant index.
11595       return Op;
11596     }
11597   }
11598
11599   if (EltVT == MVT::i8)
11600     return SDValue();
11601
11602   if (EltVT.getSizeInBits() == 16) {
11603     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11604     // as its second argument.
11605     if (N1.getValueType() != MVT::i32)
11606       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11607     if (N2.getValueType() != MVT::i32)
11608       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11609     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11610   }
11611   return SDValue();
11612 }
11613
11614 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11615   SDLoc dl(Op);
11616   MVT OpVT = Op.getSimpleValueType();
11617
11618   // If this is a 256-bit vector result, first insert into a 128-bit
11619   // vector and then insert into the 256-bit vector.
11620   if (!OpVT.is128BitVector()) {
11621     // Insert into a 128-bit vector.
11622     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11623     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11624                                  OpVT.getVectorNumElements() / SizeFactor);
11625
11626     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11627
11628     // Insert the 128-bit vector.
11629     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11630   }
11631
11632   if (OpVT == MVT::v1i64 &&
11633       Op.getOperand(0).getValueType() == MVT::i64)
11634     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11635
11636   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11637   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11638   return DAG.getBitcast(
11639       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11640 }
11641
11642 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11643 // a simple subregister reference or explicit instructions to grab
11644 // upper bits of a vector.
11645 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11646                                       SelectionDAG &DAG) {
11647   SDLoc dl(Op);
11648   SDValue In =  Op.getOperand(0);
11649   SDValue Idx = Op.getOperand(1);
11650   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11651   MVT ResVT   = Op.getSimpleValueType();
11652   MVT InVT    = In.getSimpleValueType();
11653
11654   if (Subtarget->hasFp256()) {
11655     if (ResVT.is128BitVector() &&
11656         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11657         isa<ConstantSDNode>(Idx)) {
11658       return Extract128BitVector(In, IdxVal, DAG, dl);
11659     }
11660     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11661         isa<ConstantSDNode>(Idx)) {
11662       return Extract256BitVector(In, IdxVal, DAG, dl);
11663     }
11664   }
11665   return SDValue();
11666 }
11667
11668 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11669 // simple superregister reference or explicit instructions to insert
11670 // the upper bits of a vector.
11671 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11672                                      SelectionDAG &DAG) {
11673   if (!Subtarget->hasAVX())
11674     return SDValue();
11675
11676   SDLoc dl(Op);
11677   SDValue Vec = Op.getOperand(0);
11678   SDValue SubVec = Op.getOperand(1);
11679   SDValue Idx = Op.getOperand(2);
11680
11681   if (!isa<ConstantSDNode>(Idx))
11682     return SDValue();
11683
11684   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11685   MVT OpVT = Op.getSimpleValueType();
11686   MVT SubVecVT = SubVec.getSimpleValueType();
11687
11688   // Fold two 16-byte subvector loads into one 32-byte load:
11689   // (insert_subvector (insert_subvector undef, (load addr), 0),
11690   //                   (load addr + 16), Elts/2)
11691   // --> load32 addr
11692   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11693       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11694       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11695     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11696     if (Idx2 && Idx2->getZExtValue() == 0) {
11697       SDValue SubVec2 = Vec.getOperand(1);
11698       // If needed, look through a bitcast to get to the load.
11699       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11700         SubVec2 = SubVec2.getOperand(0);
11701
11702       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11703         bool Fast;
11704         unsigned Alignment = FirstLd->getAlignment();
11705         unsigned AS = FirstLd->getAddressSpace();
11706         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11707         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11708                                     OpVT, AS, Alignment, &Fast) && Fast) {
11709           SDValue Ops[] = { SubVec2, SubVec };
11710           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11711             return Ld;
11712         }
11713       }
11714     }
11715   }
11716
11717   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11718       SubVecVT.is128BitVector())
11719     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11720
11721   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11722     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11723
11724   if (OpVT.getVectorElementType() == MVT::i1) {
11725     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11726       return Op;
11727     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11728     SDValue Undef = DAG.getUNDEF(OpVT);
11729     unsigned NumElems = OpVT.getVectorNumElements();
11730     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11731
11732     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11733       // Zero upper bits of the Vec
11734       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11735       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11736
11737       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11738                                  SubVec, ZeroIdx);
11739       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11740       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11741     }
11742     if (IdxVal == 0) {
11743       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11744                                  SubVec, ZeroIdx);
11745       // Zero upper bits of the Vec2
11746       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11747       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11748       // Zero lower bits of the Vec
11749       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11750       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11751       // Merge them together
11752       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11753     }
11754   }
11755   return SDValue();
11756 }
11757
11758 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11759 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11760 // one of the above mentioned nodes. It has to be wrapped because otherwise
11761 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11762 // be used to form addressing mode. These wrapped nodes will be selected
11763 // into MOV32ri.
11764 SDValue
11765 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11766   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11767
11768   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11769   // global base reg.
11770   unsigned char OpFlag = 0;
11771   unsigned WrapperKind = X86ISD::Wrapper;
11772   CodeModel::Model M = DAG.getTarget().getCodeModel();
11773
11774   if (Subtarget->isPICStyleRIPRel() &&
11775       (M == CodeModel::Small || M == CodeModel::Kernel))
11776     WrapperKind = X86ISD::WrapperRIP;
11777   else if (Subtarget->isPICStyleGOT())
11778     OpFlag = X86II::MO_GOTOFF;
11779   else if (Subtarget->isPICStyleStubPIC())
11780     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11781
11782   auto PtrVT = getPointerTy(DAG.getDataLayout());
11783   SDValue Result = DAG.getTargetConstantPool(
11784       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11785   SDLoc DL(CP);
11786   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11787   // With PIC, the address is actually $g + Offset.
11788   if (OpFlag) {
11789     Result =
11790         DAG.getNode(ISD::ADD, DL, PtrVT,
11791                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11792   }
11793
11794   return Result;
11795 }
11796
11797 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11798   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11799
11800   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11801   // global base reg.
11802   unsigned char OpFlag = 0;
11803   unsigned WrapperKind = X86ISD::Wrapper;
11804   CodeModel::Model M = DAG.getTarget().getCodeModel();
11805
11806   if (Subtarget->isPICStyleRIPRel() &&
11807       (M == CodeModel::Small || M == CodeModel::Kernel))
11808     WrapperKind = X86ISD::WrapperRIP;
11809   else if (Subtarget->isPICStyleGOT())
11810     OpFlag = X86II::MO_GOTOFF;
11811   else if (Subtarget->isPICStyleStubPIC())
11812     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11813
11814   auto PtrVT = getPointerTy(DAG.getDataLayout());
11815   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11816   SDLoc DL(JT);
11817   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11818
11819   // With PIC, the address is actually $g + Offset.
11820   if (OpFlag)
11821     Result =
11822         DAG.getNode(ISD::ADD, DL, PtrVT,
11823                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11824
11825   return Result;
11826 }
11827
11828 SDValue
11829 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11830   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11831
11832   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11833   // global base reg.
11834   unsigned char OpFlag = 0;
11835   unsigned WrapperKind = X86ISD::Wrapper;
11836   CodeModel::Model M = DAG.getTarget().getCodeModel();
11837
11838   if (Subtarget->isPICStyleRIPRel() &&
11839       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11840     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11841       OpFlag = X86II::MO_GOTPCREL;
11842     WrapperKind = X86ISD::WrapperRIP;
11843   } else if (Subtarget->isPICStyleGOT()) {
11844     OpFlag = X86II::MO_GOT;
11845   } else if (Subtarget->isPICStyleStubPIC()) {
11846     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11847   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11848     OpFlag = X86II::MO_DARWIN_NONLAZY;
11849   }
11850
11851   auto PtrVT = getPointerTy(DAG.getDataLayout());
11852   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11853
11854   SDLoc DL(Op);
11855   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11856
11857   // With PIC, the address is actually $g + Offset.
11858   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11859       !Subtarget->is64Bit()) {
11860     Result =
11861         DAG.getNode(ISD::ADD, DL, PtrVT,
11862                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11863   }
11864
11865   // For symbols that require a load from a stub to get the address, emit the
11866   // load.
11867   if (isGlobalStubReference(OpFlag))
11868     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11869                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11870                          false, false, false, 0);
11871
11872   return Result;
11873 }
11874
11875 SDValue
11876 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11877   // Create the TargetBlockAddressAddress node.
11878   unsigned char OpFlags =
11879     Subtarget->ClassifyBlockAddressReference();
11880   CodeModel::Model M = DAG.getTarget().getCodeModel();
11881   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11882   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11883   SDLoc dl(Op);
11884   auto PtrVT = getPointerTy(DAG.getDataLayout());
11885   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11886
11887   if (Subtarget->isPICStyleRIPRel() &&
11888       (M == CodeModel::Small || M == CodeModel::Kernel))
11889     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11890   else
11891     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11892
11893   // With PIC, the address is actually $g + Offset.
11894   if (isGlobalRelativeToPICBase(OpFlags)) {
11895     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11896                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11897   }
11898
11899   return Result;
11900 }
11901
11902 SDValue
11903 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11904                                       int64_t Offset, SelectionDAG &DAG) const {
11905   // Create the TargetGlobalAddress node, folding in the constant
11906   // offset if it is legal.
11907   unsigned char OpFlags =
11908       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11909   CodeModel::Model M = DAG.getTarget().getCodeModel();
11910   auto PtrVT = getPointerTy(DAG.getDataLayout());
11911   SDValue Result;
11912   if (OpFlags == X86II::MO_NO_FLAG &&
11913       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11914     // A direct static reference to a global.
11915     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11916     Offset = 0;
11917   } else {
11918     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11919   }
11920
11921   if (Subtarget->isPICStyleRIPRel() &&
11922       (M == CodeModel::Small || M == CodeModel::Kernel))
11923     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11924   else
11925     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11926
11927   // With PIC, the address is actually $g + Offset.
11928   if (isGlobalRelativeToPICBase(OpFlags)) {
11929     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11930                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11931   }
11932
11933   // For globals that require a load from a stub to get the address, emit the
11934   // load.
11935   if (isGlobalStubReference(OpFlags))
11936     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11937                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11938                          false, false, false, 0);
11939
11940   // If there was a non-zero offset that we didn't fold, create an explicit
11941   // addition for it.
11942   if (Offset != 0)
11943     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11944                          DAG.getConstant(Offset, dl, PtrVT));
11945
11946   return Result;
11947 }
11948
11949 SDValue
11950 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11951   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11952   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11953   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11954 }
11955
11956 static SDValue
11957 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11958            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11959            unsigned char OperandFlags, bool LocalDynamic = false) {
11960   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11961   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11962   SDLoc dl(GA);
11963   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11964                                            GA->getValueType(0),
11965                                            GA->getOffset(),
11966                                            OperandFlags);
11967
11968   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11969                                            : X86ISD::TLSADDR;
11970
11971   if (InFlag) {
11972     SDValue Ops[] = { Chain,  TGA, *InFlag };
11973     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11974   } else {
11975     SDValue Ops[]  = { Chain, TGA };
11976     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11977   }
11978
11979   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11980   MFI->setAdjustsStack(true);
11981   MFI->setHasCalls(true);
11982
11983   SDValue Flag = Chain.getValue(1);
11984   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11985 }
11986
11987 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11988 static SDValue
11989 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11990                                 const EVT PtrVT) {
11991   SDValue InFlag;
11992   SDLoc dl(GA);  // ? function entry point might be better
11993   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11994                                    DAG.getNode(X86ISD::GlobalBaseReg,
11995                                                SDLoc(), PtrVT), InFlag);
11996   InFlag = Chain.getValue(1);
11997
11998   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11999 }
12000
12001 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12002 static SDValue
12003 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12004                                 const EVT PtrVT) {
12005   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12006                     X86::RAX, X86II::MO_TLSGD);
12007 }
12008
12009 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12010                                            SelectionDAG &DAG,
12011                                            const EVT PtrVT,
12012                                            bool is64Bit) {
12013   SDLoc dl(GA);
12014
12015   // Get the start address of the TLS block for this module.
12016   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12017       .getInfo<X86MachineFunctionInfo>();
12018   MFI->incNumLocalDynamicTLSAccesses();
12019
12020   SDValue Base;
12021   if (is64Bit) {
12022     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12023                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12024   } else {
12025     SDValue InFlag;
12026     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12027         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12028     InFlag = Chain.getValue(1);
12029     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12030                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12031   }
12032
12033   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12034   // of Base.
12035
12036   // Build x@dtpoff.
12037   unsigned char OperandFlags = X86II::MO_DTPOFF;
12038   unsigned WrapperKind = X86ISD::Wrapper;
12039   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12040                                            GA->getValueType(0),
12041                                            GA->getOffset(), OperandFlags);
12042   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12043
12044   // Add x@dtpoff with the base.
12045   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12046 }
12047
12048 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12049 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12050                                    const EVT PtrVT, TLSModel::Model model,
12051                                    bool is64Bit, bool isPIC) {
12052   SDLoc dl(GA);
12053
12054   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12055   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12056                                                          is64Bit ? 257 : 256));
12057
12058   SDValue ThreadPointer =
12059       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12060                   MachinePointerInfo(Ptr), false, false, false, 0);
12061
12062   unsigned char OperandFlags = 0;
12063   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12064   // initialexec.
12065   unsigned WrapperKind = X86ISD::Wrapper;
12066   if (model == TLSModel::LocalExec) {
12067     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12068   } else if (model == TLSModel::InitialExec) {
12069     if (is64Bit) {
12070       OperandFlags = X86II::MO_GOTTPOFF;
12071       WrapperKind = X86ISD::WrapperRIP;
12072     } else {
12073       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12074     }
12075   } else {
12076     llvm_unreachable("Unexpected model");
12077   }
12078
12079   // emit "addl x@ntpoff,%eax" (local exec)
12080   // or "addl x@indntpoff,%eax" (initial exec)
12081   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12082   SDValue TGA =
12083       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12084                                  GA->getOffset(), OperandFlags);
12085   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12086
12087   if (model == TLSModel::InitialExec) {
12088     if (isPIC && !is64Bit) {
12089       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12090                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12091                            Offset);
12092     }
12093
12094     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12095                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12096                          false, false, false, 0);
12097   }
12098
12099   // The address of the thread local variable is the add of the thread
12100   // pointer with the offset of the variable.
12101   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12102 }
12103
12104 SDValue
12105 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12106
12107   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12108   const GlobalValue *GV = GA->getGlobal();
12109   auto PtrVT = getPointerTy(DAG.getDataLayout());
12110
12111   if (Subtarget->isTargetELF()) {
12112     if (DAG.getTarget().Options.EmulatedTLS)
12113       return LowerToTLSEmulatedModel(GA, DAG);
12114     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12115     switch (model) {
12116       case TLSModel::GeneralDynamic:
12117         if (Subtarget->is64Bit())
12118           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12119         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12120       case TLSModel::LocalDynamic:
12121         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12122                                            Subtarget->is64Bit());
12123       case TLSModel::InitialExec:
12124       case TLSModel::LocalExec:
12125         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12126                                    DAG.getTarget().getRelocationModel() ==
12127                                        Reloc::PIC_);
12128     }
12129     llvm_unreachable("Unknown TLS model.");
12130   }
12131
12132   if (Subtarget->isTargetDarwin()) {
12133     // Darwin only has one model of TLS.  Lower to that.
12134     unsigned char OpFlag = 0;
12135     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12136                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12137
12138     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12139     // global base reg.
12140     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12141                  !Subtarget->is64Bit();
12142     if (PIC32)
12143       OpFlag = X86II::MO_TLVP_PIC_BASE;
12144     else
12145       OpFlag = X86II::MO_TLVP;
12146     SDLoc DL(Op);
12147     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12148                                                 GA->getValueType(0),
12149                                                 GA->getOffset(), OpFlag);
12150     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12151
12152     // With PIC32, the address is actually $g + Offset.
12153     if (PIC32)
12154       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12155                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12156                            Offset);
12157
12158     // Lowering the machine isd will make sure everything is in the right
12159     // location.
12160     SDValue Chain = DAG.getEntryNode();
12161     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12162     SDValue Args[] = { Chain, Offset };
12163     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12164
12165     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12166     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12167     MFI->setAdjustsStack(true);
12168
12169     // And our return value (tls address) is in the standard call return value
12170     // location.
12171     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12172     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12173   }
12174
12175   if (Subtarget->isTargetKnownWindowsMSVC() ||
12176       Subtarget->isTargetWindowsGNU()) {
12177     // Just use the implicit TLS architecture
12178     // Need to generate someting similar to:
12179     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12180     //                                  ; from TEB
12181     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12182     //   mov     rcx, qword [rdx+rcx*8]
12183     //   mov     eax, .tls$:tlsvar
12184     //   [rax+rcx] contains the address
12185     // Windows 64bit: gs:0x58
12186     // Windows 32bit: fs:__tls_array
12187
12188     SDLoc dl(GA);
12189     SDValue Chain = DAG.getEntryNode();
12190
12191     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12192     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12193     // use its literal value of 0x2C.
12194     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12195                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12196                                                              256)
12197                                         : Type::getInt32PtrTy(*DAG.getContext(),
12198                                                               257));
12199
12200     SDValue TlsArray = Subtarget->is64Bit()
12201                            ? DAG.getIntPtrConstant(0x58, dl)
12202                            : (Subtarget->isTargetWindowsGNU()
12203                                   ? DAG.getIntPtrConstant(0x2C, dl)
12204                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12205
12206     SDValue ThreadPointer =
12207         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12208                     false, false, 0);
12209
12210     SDValue res;
12211     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12212       res = ThreadPointer;
12213     } else {
12214       // Load the _tls_index variable
12215       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12216       if (Subtarget->is64Bit())
12217         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12218                              MachinePointerInfo(), MVT::i32, false, false,
12219                              false, 0);
12220       else
12221         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12222                           false, false, 0);
12223
12224       auto &DL = DAG.getDataLayout();
12225       SDValue Scale =
12226           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12227       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12228
12229       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12230     }
12231
12232     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12233                       false, 0);
12234
12235     // Get the offset of start of .tls section
12236     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12237                                              GA->getValueType(0),
12238                                              GA->getOffset(), X86II::MO_SECREL);
12239     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12240
12241     // The address of the thread local variable is the add of the thread
12242     // pointer with the offset of the variable.
12243     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12244   }
12245
12246   llvm_unreachable("TLS not implemented for this target.");
12247 }
12248
12249 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12250 /// and take a 2 x i32 value to shift plus a shift amount.
12251 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12252   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12253   MVT VT = Op.getSimpleValueType();
12254   unsigned VTBits = VT.getSizeInBits();
12255   SDLoc dl(Op);
12256   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12257   SDValue ShOpLo = Op.getOperand(0);
12258   SDValue ShOpHi = Op.getOperand(1);
12259   SDValue ShAmt  = Op.getOperand(2);
12260   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12261   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12262   // during isel.
12263   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12264                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12265   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12266                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12267                        : DAG.getConstant(0, dl, VT);
12268
12269   SDValue Tmp2, Tmp3;
12270   if (Op.getOpcode() == ISD::SHL_PARTS) {
12271     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12272     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12273   } else {
12274     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12275     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12276   }
12277
12278   // If the shift amount is larger or equal than the width of a part we can't
12279   // rely on the results of shld/shrd. Insert a test and select the appropriate
12280   // values for large shift amounts.
12281   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12282                                 DAG.getConstant(VTBits, dl, MVT::i8));
12283   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12284                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12285
12286   SDValue Hi, Lo;
12287   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12288   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12289   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12290
12291   if (Op.getOpcode() == ISD::SHL_PARTS) {
12292     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12293     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12294   } else {
12295     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12296     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12297   }
12298
12299   SDValue Ops[2] = { Lo, Hi };
12300   return DAG.getMergeValues(Ops, dl);
12301 }
12302
12303 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12304                                            SelectionDAG &DAG) const {
12305   SDValue Src = Op.getOperand(0);
12306   MVT SrcVT = Src.getSimpleValueType();
12307   MVT VT = Op.getSimpleValueType();
12308   SDLoc dl(Op);
12309
12310   if (SrcVT.isVector()) {
12311     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12312       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12313                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12314                          DAG.getUNDEF(SrcVT)));
12315     }
12316     if (SrcVT.getVectorElementType() == MVT::i1) {
12317       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12318       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12319                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12320     }
12321     return SDValue();
12322   }
12323
12324   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12325          "Unknown SINT_TO_FP to lower!");
12326
12327   // These are really Legal; return the operand so the caller accepts it as
12328   // Legal.
12329   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12330     return Op;
12331   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12332       Subtarget->is64Bit()) {
12333     return Op;
12334   }
12335
12336   unsigned Size = SrcVT.getSizeInBits()/8;
12337   MachineFunction &MF = DAG.getMachineFunction();
12338   auto PtrVT = getPointerTy(MF.getDataLayout());
12339   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12340   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12341   SDValue Chain = DAG.getStore(
12342       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12343       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12344       false, 0);
12345   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12346 }
12347
12348 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12349                                      SDValue StackSlot,
12350                                      SelectionDAG &DAG) const {
12351   // Build the FILD
12352   SDLoc DL(Op);
12353   SDVTList Tys;
12354   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12355   if (useSSE)
12356     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12357   else
12358     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12359
12360   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12361
12362   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12363   MachineMemOperand *MMO;
12364   if (FI) {
12365     int SSFI = FI->getIndex();
12366     MMO = DAG.getMachineFunction().getMachineMemOperand(
12367         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12368         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12369   } else {
12370     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12371     StackSlot = StackSlot.getOperand(1);
12372   }
12373   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12374   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12375                                            X86ISD::FILD, DL,
12376                                            Tys, Ops, SrcVT, MMO);
12377
12378   if (useSSE) {
12379     Chain = Result.getValue(1);
12380     SDValue InFlag = Result.getValue(2);
12381
12382     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12383     // shouldn't be necessary except that RFP cannot be live across
12384     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12385     MachineFunction &MF = DAG.getMachineFunction();
12386     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12387     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12388     auto PtrVT = getPointerTy(MF.getDataLayout());
12389     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12390     Tys = DAG.getVTList(MVT::Other);
12391     SDValue Ops[] = {
12392       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12393     };
12394     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12395         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12396         MachineMemOperand::MOStore, SSFISize, SSFISize);
12397
12398     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12399                                     Ops, Op.getValueType(), MMO);
12400     Result = DAG.getLoad(
12401         Op.getValueType(), DL, Chain, StackSlot,
12402         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12403         false, false, false, 0);
12404   }
12405
12406   return Result;
12407 }
12408
12409 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12410 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12411                                                SelectionDAG &DAG) const {
12412   // This algorithm is not obvious. Here it is what we're trying to output:
12413   /*
12414      movq       %rax,  %xmm0
12415      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12416      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12417      #ifdef __SSE3__
12418        haddpd   %xmm0, %xmm0
12419      #else
12420        pshufd   $0x4e, %xmm0, %xmm1
12421        addpd    %xmm1, %xmm0
12422      #endif
12423   */
12424
12425   SDLoc dl(Op);
12426   LLVMContext *Context = DAG.getContext();
12427
12428   // Build some magic constants.
12429   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12430   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12431   auto PtrVT = getPointerTy(DAG.getDataLayout());
12432   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12433
12434   SmallVector<Constant*,2> CV1;
12435   CV1.push_back(
12436     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12437                                       APInt(64, 0x4330000000000000ULL))));
12438   CV1.push_back(
12439     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12440                                       APInt(64, 0x4530000000000000ULL))));
12441   Constant *C1 = ConstantVector::get(CV1);
12442   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12443
12444   // Load the 64-bit value into an XMM register.
12445   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12446                             Op.getOperand(0));
12447   SDValue CLod0 =
12448       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12449                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12450                   false, false, false, 16);
12451   SDValue Unpck1 =
12452       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12453
12454   SDValue CLod1 =
12455       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12456                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12457                   false, false, false, 16);
12458   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12459   // TODO: Are there any fast-math-flags to propagate here?
12460   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12461   SDValue Result;
12462
12463   if (Subtarget->hasSSE3()) {
12464     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12465     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12466   } else {
12467     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12468     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12469                                            S2F, 0x4E, DAG);
12470     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12471                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12472   }
12473
12474   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12475                      DAG.getIntPtrConstant(0, dl));
12476 }
12477
12478 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12479 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12480                                                SelectionDAG &DAG) const {
12481   SDLoc dl(Op);
12482   // FP constant to bias correct the final result.
12483   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12484                                    MVT::f64);
12485
12486   // Load the 32-bit value into an XMM register.
12487   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12488                              Op.getOperand(0));
12489
12490   // Zero out the upper parts of the register.
12491   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12492
12493   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12494                      DAG.getBitcast(MVT::v2f64, Load),
12495                      DAG.getIntPtrConstant(0, dl));
12496
12497   // Or the load with the bias.
12498   SDValue Or = DAG.getNode(
12499       ISD::OR, dl, MVT::v2i64,
12500       DAG.getBitcast(MVT::v2i64,
12501                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12502       DAG.getBitcast(MVT::v2i64,
12503                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12504   Or =
12505       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12506                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12507
12508   // Subtract the bias.
12509   // TODO: Are there any fast-math-flags to propagate here?
12510   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12511
12512   // Handle final rounding.
12513   EVT DestVT = Op.getValueType();
12514
12515   if (DestVT.bitsLT(MVT::f64))
12516     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12517                        DAG.getIntPtrConstant(0, dl));
12518   if (DestVT.bitsGT(MVT::f64))
12519     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12520
12521   // Handle final rounding.
12522   return Sub;
12523 }
12524
12525 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12526                                      const X86Subtarget &Subtarget) {
12527   // The algorithm is the following:
12528   // #ifdef __SSE4_1__
12529   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12530   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12531   //                                 (uint4) 0x53000000, 0xaa);
12532   // #else
12533   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12534   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12535   // #endif
12536   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12537   //     return (float4) lo + fhi;
12538
12539   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12540   // reassociate the two FADDs, and if we do that, the algorithm fails
12541   // spectacularly (PR24512).
12542   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12543   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12544   // there's also the MachineCombiner reassociations happening on Machine IR.
12545   if (DAG.getTarget().Options.UnsafeFPMath)
12546     return SDValue();
12547
12548   SDLoc DL(Op);
12549   SDValue V = Op->getOperand(0);
12550   EVT VecIntVT = V.getValueType();
12551   bool Is128 = VecIntVT == MVT::v4i32;
12552   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12553   // If we convert to something else than the supported type, e.g., to v4f64,
12554   // abort early.
12555   if (VecFloatVT != Op->getValueType(0))
12556     return SDValue();
12557
12558   unsigned NumElts = VecIntVT.getVectorNumElements();
12559   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12560          "Unsupported custom type");
12561   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12562
12563   // In the #idef/#else code, we have in common:
12564   // - The vector of constants:
12565   // -- 0x4b000000
12566   // -- 0x53000000
12567   // - A shift:
12568   // -- v >> 16
12569
12570   // Create the splat vector for 0x4b000000.
12571   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12572   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12573                            CstLow, CstLow, CstLow, CstLow};
12574   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12575                                   makeArrayRef(&CstLowArray[0], NumElts));
12576   // Create the splat vector for 0x53000000.
12577   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12578   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12579                             CstHigh, CstHigh, CstHigh, CstHigh};
12580   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12581                                    makeArrayRef(&CstHighArray[0], NumElts));
12582
12583   // Create the right shift.
12584   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12585   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12586                              CstShift, CstShift, CstShift, CstShift};
12587   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12588                                     makeArrayRef(&CstShiftArray[0], NumElts));
12589   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12590
12591   SDValue Low, High;
12592   if (Subtarget.hasSSE41()) {
12593     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12594     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12595     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12596     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12597     // Low will be bitcasted right away, so do not bother bitcasting back to its
12598     // original type.
12599     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12600                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12601     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12602     //                                 (uint4) 0x53000000, 0xaa);
12603     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12604     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12605     // High will be bitcasted right away, so do not bother bitcasting back to
12606     // its original type.
12607     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12608                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12609   } else {
12610     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12611     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12612                                      CstMask, CstMask, CstMask);
12613     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12614     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12615     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12616
12617     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12618     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12619   }
12620
12621   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12622   SDValue CstFAdd = DAG.getConstantFP(
12623       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12624   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12625                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12626   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12627                                    makeArrayRef(&CstFAddArray[0], NumElts));
12628
12629   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12630   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12631   // TODO: Are there any fast-math-flags to propagate here?
12632   SDValue FHigh =
12633       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12634   //     return (float4) lo + fhi;
12635   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12636   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12637 }
12638
12639 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12640                                                SelectionDAG &DAG) const {
12641   SDValue N0 = Op.getOperand(0);
12642   MVT SVT = N0.getSimpleValueType();
12643   SDLoc dl(Op);
12644
12645   switch (SVT.SimpleTy) {
12646   default:
12647     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12648   case MVT::v4i8:
12649   case MVT::v4i16:
12650   case MVT::v8i8:
12651   case MVT::v8i16: {
12652     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12653     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12654                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12655   }
12656   case MVT::v4i32:
12657   case MVT::v8i32:
12658     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12659   case MVT::v16i8:
12660   case MVT::v16i16:
12661     if (Subtarget->hasAVX512())
12662       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12663                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12664   }
12665   llvm_unreachable(nullptr);
12666 }
12667
12668 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12669                                            SelectionDAG &DAG) const {
12670   SDValue N0 = Op.getOperand(0);
12671   SDLoc dl(Op);
12672   auto PtrVT = getPointerTy(DAG.getDataLayout());
12673
12674   if (Op.getValueType().isVector())
12675     return lowerUINT_TO_FP_vec(Op, DAG);
12676
12677   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12678   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12679   // the optimization here.
12680   if (DAG.SignBitIsZero(N0))
12681     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12682
12683   MVT SrcVT = N0.getSimpleValueType();
12684   MVT DstVT = Op.getSimpleValueType();
12685
12686   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12687       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12688     // Conversions from unsigned i32 to f32/f64 are legal,
12689     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12690     return Op;
12691   }
12692
12693   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12694     return LowerUINT_TO_FP_i64(Op, DAG);
12695   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12696     return LowerUINT_TO_FP_i32(Op, DAG);
12697   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12698     return SDValue();
12699
12700   // Make a 64-bit buffer, and use it to build an FILD.
12701   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12702   if (SrcVT == MVT::i32) {
12703     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12704     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12705     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12706                                   StackSlot, MachinePointerInfo(),
12707                                   false, false, 0);
12708     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12709                                   OffsetSlot, MachinePointerInfo(),
12710                                   false, false, 0);
12711     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12712     return Fild;
12713   }
12714
12715   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12716   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12717                                StackSlot, MachinePointerInfo(),
12718                                false, false, 0);
12719   // For i64 source, we need to add the appropriate power of 2 if the input
12720   // was negative.  This is the same as the optimization in
12721   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12722   // we must be careful to do the computation in x87 extended precision, not
12723   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12724   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12725   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12726       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12727       MachineMemOperand::MOLoad, 8, 8);
12728
12729   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12730   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12731   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12732                                          MVT::i64, MMO);
12733
12734   APInt FF(32, 0x5F800000ULL);
12735
12736   // Check whether the sign bit is set.
12737   SDValue SignSet = DAG.getSetCC(
12738       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12739       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12740
12741   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12742   SDValue FudgePtr = DAG.getConstantPool(
12743       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12744
12745   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12746   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12747   SDValue Four = DAG.getIntPtrConstant(4, dl);
12748   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12749                                Zero, Four);
12750   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12751
12752   // Load the value out, extending it from f32 to f80.
12753   // FIXME: Avoid the extend by constructing the right constant pool?
12754   SDValue Fudge = DAG.getExtLoad(
12755       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12756       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12757       false, false, false, 4);
12758   // Extend everything to 80 bits to force it to be done on x87.
12759   // TODO: Are there any fast-math-flags to propagate here?
12760   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12761   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12762                      DAG.getIntPtrConstant(0, dl));
12763 }
12764
12765 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12766 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12767 // just return an <SDValue(), SDValue()> pair.
12768 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12769 // to i16, i32 or i64, and we lower it to a legal sequence.
12770 // If lowered to the final integer result we return a <result, SDValue()> pair.
12771 // Otherwise we lower it to a sequence ending with a FIST, return a
12772 // <FIST, StackSlot> pair, and the caller is responsible for loading
12773 // the final integer result from StackSlot.
12774 std::pair<SDValue,SDValue>
12775 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12776                                    bool IsSigned, bool IsReplace) const {
12777   SDLoc DL(Op);
12778
12779   EVT DstTy = Op.getValueType();
12780   EVT TheVT = Op.getOperand(0).getValueType();
12781   auto PtrVT = getPointerTy(DAG.getDataLayout());
12782
12783   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12784     // f16 must be promoted before using the lowering in this routine.
12785     // fp128 does not use this lowering.
12786     return std::make_pair(SDValue(), SDValue());
12787   }
12788
12789   // If using FIST to compute an unsigned i64, we'll need some fixup
12790   // to handle values above the maximum signed i64.  A FIST is always
12791   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12792   bool UnsignedFixup = !IsSigned &&
12793                        DstTy == MVT::i64 &&
12794                        (!Subtarget->is64Bit() ||
12795                         !isScalarFPTypeInSSEReg(TheVT));
12796
12797   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12798     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12799     // The low 32 bits of the fist result will have the correct uint32 result.
12800     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12801     DstTy = MVT::i64;
12802   }
12803
12804   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12805          DstTy.getSimpleVT() >= MVT::i16 &&
12806          "Unknown FP_TO_INT to lower!");
12807
12808   // These are really Legal.
12809   if (DstTy == MVT::i32 &&
12810       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12811     return std::make_pair(SDValue(), SDValue());
12812   if (Subtarget->is64Bit() &&
12813       DstTy == MVT::i64 &&
12814       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12815     return std::make_pair(SDValue(), SDValue());
12816
12817   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12818   // stack slot.
12819   MachineFunction &MF = DAG.getMachineFunction();
12820   unsigned MemSize = DstTy.getSizeInBits()/8;
12821   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12822   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12823
12824   unsigned Opc;
12825   switch (DstTy.getSimpleVT().SimpleTy) {
12826   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12827   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12828   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12829   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12830   }
12831
12832   SDValue Chain = DAG.getEntryNode();
12833   SDValue Value = Op.getOperand(0);
12834   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12835
12836   if (UnsignedFixup) {
12837     //
12838     // Conversion to unsigned i64 is implemented with a select,
12839     // depending on whether the source value fits in the range
12840     // of a signed i64.  Let Thresh be the FP equivalent of
12841     // 0x8000000000000000ULL.
12842     //
12843     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12844     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12845     //  Fist-to-mem64 FistSrc
12846     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12847     //  to XOR'ing the high 32 bits with Adjust.
12848     //
12849     // Being a power of 2, Thresh is exactly representable in all FP formats.
12850     // For X87 we'd like to use the smallest FP type for this constant, but
12851     // for DAG type consistency we have to match the FP operand type.
12852
12853     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12854     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12855     bool LosesInfo = false;
12856     if (TheVT == MVT::f64)
12857       // The rounding mode is irrelevant as the conversion should be exact.
12858       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12859                               &LosesInfo);
12860     else if (TheVT == MVT::f80)
12861       Status = Thresh.convert(APFloat::x87DoubleExtended,
12862                               APFloat::rmNearestTiesToEven, &LosesInfo);
12863
12864     assert(Status == APFloat::opOK && !LosesInfo &&
12865            "FP conversion should have been exact");
12866
12867     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12868
12869     SDValue Cmp = DAG.getSetCC(DL,
12870                                getSetCCResultType(DAG.getDataLayout(),
12871                                                   *DAG.getContext(), TheVT),
12872                                Value, ThreshVal, ISD::SETLT);
12873     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12874                            DAG.getConstant(0, DL, MVT::i32),
12875                            DAG.getConstant(0x80000000, DL, MVT::i32));
12876     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12877     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12878                                               *DAG.getContext(), TheVT),
12879                        Value, ThreshVal, ISD::SETLT);
12880     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12881   }
12882
12883   // FIXME This causes a redundant load/store if the SSE-class value is already
12884   // in memory, such as if it is on the callstack.
12885   if (isScalarFPTypeInSSEReg(TheVT)) {
12886     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12887     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12888                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12889                          false, 0);
12890     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12891     SDValue Ops[] = {
12892       Chain, StackSlot, DAG.getValueType(TheVT)
12893     };
12894
12895     MachineMemOperand *MMO =
12896         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12897                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12898     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12899     Chain = Value.getValue(1);
12900     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12901     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12902   }
12903
12904   MachineMemOperand *MMO =
12905       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12906                               MachineMemOperand::MOStore, MemSize, MemSize);
12907
12908   if (UnsignedFixup) {
12909
12910     // Insert the FIST, load its result as two i32's,
12911     // and XOR the high i32 with Adjust.
12912
12913     SDValue FistOps[] = { Chain, Value, StackSlot };
12914     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12915                                            FistOps, DstTy, MMO);
12916
12917     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12918                                 MachinePointerInfo(),
12919                                 false, false, false, 0);
12920     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12921                                    DAG.getConstant(4, DL, PtrVT));
12922
12923     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12924                                  MachinePointerInfo(),
12925                                  false, false, false, 0);
12926     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12927
12928     if (Subtarget->is64Bit()) {
12929       // Join High32 and Low32 into a 64-bit result.
12930       // (High32 << 32) | Low32
12931       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12932       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12933       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12934                            DAG.getConstant(32, DL, MVT::i8));
12935       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12936       return std::make_pair(Result, SDValue());
12937     }
12938
12939     SDValue ResultOps[] = { Low32, High32 };
12940
12941     SDValue pair = IsReplace
12942       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12943       : DAG.getMergeValues(ResultOps, DL);
12944     return std::make_pair(pair, SDValue());
12945   } else {
12946     // Build the FP_TO_INT*_IN_MEM
12947     SDValue Ops[] = { Chain, Value, StackSlot };
12948     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12949                                            Ops, DstTy, MMO);
12950     return std::make_pair(FIST, StackSlot);
12951   }
12952 }
12953
12954 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12955                               const X86Subtarget *Subtarget) {
12956   MVT VT = Op->getSimpleValueType(0);
12957   SDValue In = Op->getOperand(0);
12958   MVT InVT = In.getSimpleValueType();
12959   SDLoc dl(Op);
12960
12961   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12962     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12963
12964   // Optimize vectors in AVX mode:
12965   //
12966   //   v8i16 -> v8i32
12967   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12968   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12969   //   Concat upper and lower parts.
12970   //
12971   //   v4i32 -> v4i64
12972   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12973   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12974   //   Concat upper and lower parts.
12975   //
12976
12977   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12978       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12979       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12980     return SDValue();
12981
12982   if (Subtarget->hasInt256())
12983     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12984
12985   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12986   SDValue Undef = DAG.getUNDEF(InVT);
12987   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12988   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12989   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12990
12991   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12992                              VT.getVectorNumElements()/2);
12993
12994   OpLo = DAG.getBitcast(HVT, OpLo);
12995   OpHi = DAG.getBitcast(HVT, OpHi);
12996
12997   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12998 }
12999
13000 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13001                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13002   MVT VT = Op->getSimpleValueType(0);
13003   SDValue In = Op->getOperand(0);
13004   MVT InVT = In.getSimpleValueType();
13005   SDLoc DL(Op);
13006   unsigned int NumElts = VT.getVectorNumElements();
13007   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13008     return SDValue();
13009
13010   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13011     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13012
13013   assert(InVT.getVectorElementType() == MVT::i1);
13014   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13015   SDValue One =
13016    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13017   SDValue Zero =
13018    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13019
13020   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13021   if (VT.is512BitVector())
13022     return V;
13023   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13024 }
13025
13026 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13027                                SelectionDAG &DAG) {
13028   if (Subtarget->hasFp256())
13029     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13030       return Res;
13031
13032   return SDValue();
13033 }
13034
13035 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13036                                 SelectionDAG &DAG) {
13037   SDLoc DL(Op);
13038   MVT VT = Op.getSimpleValueType();
13039   SDValue In = Op.getOperand(0);
13040   MVT SVT = In.getSimpleValueType();
13041
13042   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13043     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13044
13045   if (Subtarget->hasFp256())
13046     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13047       return Res;
13048
13049   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13050          VT.getVectorNumElements() != SVT.getVectorNumElements());
13051   return SDValue();
13052 }
13053
13054 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13055   SDLoc DL(Op);
13056   MVT VT = Op.getSimpleValueType();
13057   SDValue In = Op.getOperand(0);
13058   MVT InVT = In.getSimpleValueType();
13059
13060   if (VT == MVT::i1) {
13061     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13062            "Invalid scalar TRUNCATE operation");
13063     if (InVT.getSizeInBits() >= 32)
13064       return SDValue();
13065     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13066     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13067   }
13068   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13069          "Invalid TRUNCATE operation");
13070
13071   // move vector to mask - truncate solution for SKX
13072   if (VT.getVectorElementType() == MVT::i1) {
13073     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13074         Subtarget->hasBWI())
13075       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13076     if ((InVT.is256BitVector() || InVT.is128BitVector())
13077         && InVT.getScalarSizeInBits() <= 16 &&
13078         Subtarget->hasBWI() && Subtarget->hasVLX())
13079       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13080     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13081         Subtarget->hasDQI())
13082       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13083     if ((InVT.is256BitVector() || InVT.is128BitVector())
13084         && InVT.getScalarSizeInBits() >= 32 &&
13085         Subtarget->hasDQI() && Subtarget->hasVLX())
13086       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13087   }
13088
13089   if (VT.getVectorElementType() == MVT::i1) {
13090     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13091     unsigned NumElts = InVT.getVectorNumElements();
13092     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13093     if (InVT.getSizeInBits() < 512) {
13094       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13095       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13096       InVT = ExtVT;
13097     }
13098
13099     SDValue OneV =
13100      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13101     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13102     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13103   }
13104
13105   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13106   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13107       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13108     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13109
13110   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13111     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13112     if (Subtarget->hasInt256()) {
13113       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13114       In = DAG.getBitcast(MVT::v8i32, In);
13115       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13116                                 ShufMask);
13117       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13118                          DAG.getIntPtrConstant(0, DL));
13119     }
13120
13121     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13122                                DAG.getIntPtrConstant(0, DL));
13123     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13124                                DAG.getIntPtrConstant(2, DL));
13125     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13126     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13127     static const int ShufMask[] = {0, 2, 4, 6};
13128     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13129   }
13130
13131   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13132     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13133     if (Subtarget->hasInt256()) {
13134       In = DAG.getBitcast(MVT::v32i8, In);
13135
13136       SmallVector<SDValue,32> pshufbMask;
13137       for (unsigned i = 0; i < 2; ++i) {
13138         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13139         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13140         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13141         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13142         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13143         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13144         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13145         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13146         for (unsigned j = 0; j < 8; ++j)
13147           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13148       }
13149       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13150       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13151       In = DAG.getBitcast(MVT::v4i64, In);
13152
13153       static const int ShufMask[] = {0,  2,  -1,  -1};
13154       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13155                                 &ShufMask[0]);
13156       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13157                        DAG.getIntPtrConstant(0, DL));
13158       return DAG.getBitcast(VT, In);
13159     }
13160
13161     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13162                                DAG.getIntPtrConstant(0, DL));
13163
13164     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13165                                DAG.getIntPtrConstant(4, DL));
13166
13167     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13168     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13169
13170     // The PSHUFB mask:
13171     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13172                                    -1, -1, -1, -1, -1, -1, -1, -1};
13173
13174     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13175     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13176     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13177
13178     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13179     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13180
13181     // The MOVLHPS Mask:
13182     static const int ShufMask2[] = {0, 1, 4, 5};
13183     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13184     return DAG.getBitcast(MVT::v8i16, res);
13185   }
13186
13187   // Handle truncation of V256 to V128 using shuffles.
13188   if (!VT.is128BitVector() || !InVT.is256BitVector())
13189     return SDValue();
13190
13191   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13192
13193   unsigned NumElems = VT.getVectorNumElements();
13194   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13195
13196   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13197   // Prepare truncation shuffle mask
13198   for (unsigned i = 0; i != NumElems; ++i)
13199     MaskVec[i] = i * 2;
13200   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13201                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13202   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13203                      DAG.getIntPtrConstant(0, DL));
13204 }
13205
13206 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13207                                            SelectionDAG &DAG) const {
13208   assert(!Op.getSimpleValueType().isVector());
13209
13210   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13211     /*IsSigned=*/ true, /*IsReplace=*/ false);
13212   SDValue FIST = Vals.first, StackSlot = Vals.second;
13213   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13214   if (!FIST.getNode())
13215     return Op;
13216
13217   if (StackSlot.getNode())
13218     // Load the result.
13219     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13220                        FIST, StackSlot, MachinePointerInfo(),
13221                        false, false, false, 0);
13222
13223   // The node is the result.
13224   return FIST;
13225 }
13226
13227 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13228                                            SelectionDAG &DAG) const {
13229   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13230     /*IsSigned=*/ false, /*IsReplace=*/ false);
13231   SDValue FIST = Vals.first, StackSlot = Vals.second;
13232   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13233   if (!FIST.getNode())
13234     return Op;
13235
13236   if (StackSlot.getNode())
13237     // Load the result.
13238     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13239                        FIST, StackSlot, MachinePointerInfo(),
13240                        false, false, false, 0);
13241
13242   // The node is the result.
13243   return FIST;
13244 }
13245
13246 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13247   SDLoc DL(Op);
13248   MVT VT = Op.getSimpleValueType();
13249   SDValue In = Op.getOperand(0);
13250   MVT SVT = In.getSimpleValueType();
13251
13252   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13253
13254   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13255                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13256                                  In, DAG.getUNDEF(SVT)));
13257 }
13258
13259 /// The only differences between FABS and FNEG are the mask and the logic op.
13260 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13261 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13262   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13263          "Wrong opcode for lowering FABS or FNEG.");
13264
13265   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13266
13267   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13268   // into an FNABS. We'll lower the FABS after that if it is still in use.
13269   if (IsFABS)
13270     for (SDNode *User : Op->uses())
13271       if (User->getOpcode() == ISD::FNEG)
13272         return Op;
13273
13274   SDLoc dl(Op);
13275   MVT VT = Op.getSimpleValueType();
13276
13277   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13278   // decide if we should generate a 16-byte constant mask when we only need 4 or
13279   // 8 bytes for the scalar case.
13280
13281   MVT LogicVT;
13282   MVT EltVT;
13283   unsigned NumElts;
13284
13285   if (VT.isVector()) {
13286     LogicVT = VT;
13287     EltVT = VT.getVectorElementType();
13288     NumElts = VT.getVectorNumElements();
13289   } else {
13290     // There are no scalar bitwise logical SSE/AVX instructions, so we
13291     // generate a 16-byte vector constant and logic op even for the scalar case.
13292     // Using a 16-byte mask allows folding the load of the mask with
13293     // the logic op, so it can save (~4 bytes) on code size.
13294     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13295     EltVT = VT;
13296     NumElts = (VT == MVT::f64) ? 2 : 4;
13297   }
13298
13299   unsigned EltBits = EltVT.getSizeInBits();
13300   LLVMContext *Context = DAG.getContext();
13301   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13302   APInt MaskElt =
13303     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13304   Constant *C = ConstantInt::get(*Context, MaskElt);
13305   C = ConstantVector::getSplat(NumElts, C);
13306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13307   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13308   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13309   SDValue Mask =
13310       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13311                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13312                   false, false, false, Alignment);
13313
13314   SDValue Op0 = Op.getOperand(0);
13315   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13316   unsigned LogicOp =
13317     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13318   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13319
13320   if (VT.isVector())
13321     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13322
13323   // For the scalar case extend to a 128-bit vector, perform the logic op,
13324   // and extract the scalar result back out.
13325   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13326   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13327   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13328                      DAG.getIntPtrConstant(0, dl));
13329 }
13330
13331 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13333   LLVMContext *Context = DAG.getContext();
13334   SDValue Op0 = Op.getOperand(0);
13335   SDValue Op1 = Op.getOperand(1);
13336   SDLoc dl(Op);
13337   MVT VT = Op.getSimpleValueType();
13338   MVT SrcVT = Op1.getSimpleValueType();
13339
13340   // If second operand is smaller, extend it first.
13341   if (SrcVT.bitsLT(VT)) {
13342     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13343     SrcVT = VT;
13344   }
13345   // And if it is bigger, shrink it first.
13346   if (SrcVT.bitsGT(VT)) {
13347     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13348     SrcVT = VT;
13349   }
13350
13351   // At this point the operands and the result should have the same
13352   // type, and that won't be f80 since that is not custom lowered.
13353
13354   const fltSemantics &Sem =
13355       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13356   const unsigned SizeInBits = VT.getSizeInBits();
13357
13358   SmallVector<Constant *, 4> CV(
13359       VT == MVT::f64 ? 2 : 4,
13360       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13361
13362   // First, clear all bits but the sign bit from the second operand (sign).
13363   CV[0] = ConstantFP::get(*Context,
13364                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13365   Constant *C = ConstantVector::get(CV);
13366   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13367   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13368
13369   // Perform all logic operations as 16-byte vectors because there are no
13370   // scalar FP logic instructions in SSE. This allows load folding of the
13371   // constants into the logic instructions.
13372   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13373   SDValue Mask1 =
13374       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13375                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13376                   false, false, false, 16);
13377   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13378   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13379
13380   // Next, clear the sign bit from the first operand (magnitude).
13381   // If it's a constant, we can clear it here.
13382   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13383     APFloat APF = Op0CN->getValueAPF();
13384     // If the magnitude is a positive zero, the sign bit alone is enough.
13385     if (APF.isPosZero())
13386       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13387                          DAG.getIntPtrConstant(0, dl));
13388     APF.clearSign();
13389     CV[0] = ConstantFP::get(*Context, APF);
13390   } else {
13391     CV[0] = ConstantFP::get(
13392         *Context,
13393         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13394   }
13395   C = ConstantVector::get(CV);
13396   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13397   SDValue Val =
13398       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13399                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13400                   false, false, false, 16);
13401   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13402   if (!isa<ConstantFPSDNode>(Op0)) {
13403     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13404     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13405   }
13406   // OR the magnitude value with the sign bit.
13407   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13408   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13409                      DAG.getIntPtrConstant(0, dl));
13410 }
13411
13412 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13413   SDValue N0 = Op.getOperand(0);
13414   SDLoc dl(Op);
13415   MVT VT = Op.getSimpleValueType();
13416
13417   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13418   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13419                                   DAG.getConstant(1, dl, VT));
13420   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13421 }
13422
13423 // Check whether an OR'd tree is PTEST-able.
13424 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13425                                       SelectionDAG &DAG) {
13426   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13427
13428   if (!Subtarget->hasSSE41())
13429     return SDValue();
13430
13431   if (!Op->hasOneUse())
13432     return SDValue();
13433
13434   SDNode *N = Op.getNode();
13435   SDLoc DL(N);
13436
13437   SmallVector<SDValue, 8> Opnds;
13438   DenseMap<SDValue, unsigned> VecInMap;
13439   SmallVector<SDValue, 8> VecIns;
13440   EVT VT = MVT::Other;
13441
13442   // Recognize a special case where a vector is casted into wide integer to
13443   // test all 0s.
13444   Opnds.push_back(N->getOperand(0));
13445   Opnds.push_back(N->getOperand(1));
13446
13447   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13448     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13449     // BFS traverse all OR'd operands.
13450     if (I->getOpcode() == ISD::OR) {
13451       Opnds.push_back(I->getOperand(0));
13452       Opnds.push_back(I->getOperand(1));
13453       // Re-evaluate the number of nodes to be traversed.
13454       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13455       continue;
13456     }
13457
13458     // Quit if a non-EXTRACT_VECTOR_ELT
13459     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13460       return SDValue();
13461
13462     // Quit if without a constant index.
13463     SDValue Idx = I->getOperand(1);
13464     if (!isa<ConstantSDNode>(Idx))
13465       return SDValue();
13466
13467     SDValue ExtractedFromVec = I->getOperand(0);
13468     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13469     if (M == VecInMap.end()) {
13470       VT = ExtractedFromVec.getValueType();
13471       // Quit if not 128/256-bit vector.
13472       if (!VT.is128BitVector() && !VT.is256BitVector())
13473         return SDValue();
13474       // Quit if not the same type.
13475       if (VecInMap.begin() != VecInMap.end() &&
13476           VT != VecInMap.begin()->first.getValueType())
13477         return SDValue();
13478       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13479       VecIns.push_back(ExtractedFromVec);
13480     }
13481     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13482   }
13483
13484   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13485          "Not extracted from 128-/256-bit vector.");
13486
13487   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13488
13489   for (DenseMap<SDValue, unsigned>::const_iterator
13490         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13491     // Quit if not all elements are used.
13492     if (I->second != FullMask)
13493       return SDValue();
13494   }
13495
13496   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13497
13498   // Cast all vectors into TestVT for PTEST.
13499   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13500     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13501
13502   // If more than one full vectors are evaluated, OR them first before PTEST.
13503   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13504     // Each iteration will OR 2 nodes and append the result until there is only
13505     // 1 node left, i.e. the final OR'd value of all vectors.
13506     SDValue LHS = VecIns[Slot];
13507     SDValue RHS = VecIns[Slot + 1];
13508     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13509   }
13510
13511   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13512                      VecIns.back(), VecIns.back());
13513 }
13514
13515 /// \brief return true if \c Op has a use that doesn't just read flags.
13516 static bool hasNonFlagsUse(SDValue Op) {
13517   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13518        ++UI) {
13519     SDNode *User = *UI;
13520     unsigned UOpNo = UI.getOperandNo();
13521     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13522       // Look pass truncate.
13523       UOpNo = User->use_begin().getOperandNo();
13524       User = *User->use_begin();
13525     }
13526
13527     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13528         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13529       return true;
13530   }
13531   return false;
13532 }
13533
13534 /// Emit nodes that will be selected as "test Op0,Op0", or something
13535 /// equivalent.
13536 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13537                                     SelectionDAG &DAG) const {
13538   if (Op.getValueType() == MVT::i1) {
13539     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13540     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13541                        DAG.getConstant(0, dl, MVT::i8));
13542   }
13543   // CF and OF aren't always set the way we want. Determine which
13544   // of these we need.
13545   bool NeedCF = false;
13546   bool NeedOF = false;
13547   switch (X86CC) {
13548   default: break;
13549   case X86::COND_A: case X86::COND_AE:
13550   case X86::COND_B: case X86::COND_BE:
13551     NeedCF = true;
13552     break;
13553   case X86::COND_G: case X86::COND_GE:
13554   case X86::COND_L: case X86::COND_LE:
13555   case X86::COND_O: case X86::COND_NO: {
13556     // Check if we really need to set the
13557     // Overflow flag. If NoSignedWrap is present
13558     // that is not actually needed.
13559     switch (Op->getOpcode()) {
13560     case ISD::ADD:
13561     case ISD::SUB:
13562     case ISD::MUL:
13563     case ISD::SHL: {
13564       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13565       if (BinNode->Flags.hasNoSignedWrap())
13566         break;
13567     }
13568     default:
13569       NeedOF = true;
13570       break;
13571     }
13572     break;
13573   }
13574   }
13575   // See if we can use the EFLAGS value from the operand instead of
13576   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13577   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13578   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13579     // Emit a CMP with 0, which is the TEST pattern.
13580     //if (Op.getValueType() == MVT::i1)
13581     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13582     //                     DAG.getConstant(0, MVT::i1));
13583     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13584                        DAG.getConstant(0, dl, Op.getValueType()));
13585   }
13586   unsigned Opcode = 0;
13587   unsigned NumOperands = 0;
13588
13589   // Truncate operations may prevent the merge of the SETCC instruction
13590   // and the arithmetic instruction before it. Attempt to truncate the operands
13591   // of the arithmetic instruction and use a reduced bit-width instruction.
13592   bool NeedTruncation = false;
13593   SDValue ArithOp = Op;
13594   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13595     SDValue Arith = Op->getOperand(0);
13596     // Both the trunc and the arithmetic op need to have one user each.
13597     if (Arith->hasOneUse())
13598       switch (Arith.getOpcode()) {
13599         default: break;
13600         case ISD::ADD:
13601         case ISD::SUB:
13602         case ISD::AND:
13603         case ISD::OR:
13604         case ISD::XOR: {
13605           NeedTruncation = true;
13606           ArithOp = Arith;
13607         }
13608       }
13609   }
13610
13611   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13612   // which may be the result of a CAST.  We use the variable 'Op', which is the
13613   // non-casted variable when we check for possible users.
13614   switch (ArithOp.getOpcode()) {
13615   case ISD::ADD:
13616     // Due to an isel shortcoming, be conservative if this add is likely to be
13617     // selected as part of a load-modify-store instruction. When the root node
13618     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13619     // uses of other nodes in the match, such as the ADD in this case. This
13620     // leads to the ADD being left around and reselected, with the result being
13621     // two adds in the output.  Alas, even if none our users are stores, that
13622     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13623     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13624     // climbing the DAG back to the root, and it doesn't seem to be worth the
13625     // effort.
13626     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13627          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13628       if (UI->getOpcode() != ISD::CopyToReg &&
13629           UI->getOpcode() != ISD::SETCC &&
13630           UI->getOpcode() != ISD::STORE)
13631         goto default_case;
13632
13633     if (ConstantSDNode *C =
13634         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13635       // An add of one will be selected as an INC.
13636       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13637         Opcode = X86ISD::INC;
13638         NumOperands = 1;
13639         break;
13640       }
13641
13642       // An add of negative one (subtract of one) will be selected as a DEC.
13643       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13644         Opcode = X86ISD::DEC;
13645         NumOperands = 1;
13646         break;
13647       }
13648     }
13649
13650     // Otherwise use a regular EFLAGS-setting add.
13651     Opcode = X86ISD::ADD;
13652     NumOperands = 2;
13653     break;
13654   case ISD::SHL:
13655   case ISD::SRL:
13656     // If we have a constant logical shift that's only used in a comparison
13657     // against zero turn it into an equivalent AND. This allows turning it into
13658     // a TEST instruction later.
13659     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13660         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13661       EVT VT = Op.getValueType();
13662       unsigned BitWidth = VT.getSizeInBits();
13663       unsigned ShAmt = Op->getConstantOperandVal(1);
13664       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13665         break;
13666       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13667                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13668                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13669       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13670         break;
13671       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13672                                 DAG.getConstant(Mask, dl, VT));
13673       DAG.ReplaceAllUsesWith(Op, New);
13674       Op = New;
13675     }
13676     break;
13677
13678   case ISD::AND:
13679     // If the primary and result isn't used, don't bother using X86ISD::AND,
13680     // because a TEST instruction will be better.
13681     if (!hasNonFlagsUse(Op))
13682       break;
13683     // FALL THROUGH
13684   case ISD::SUB:
13685   case ISD::OR:
13686   case ISD::XOR:
13687     // Due to the ISEL shortcoming noted above, be conservative if this op is
13688     // likely to be selected as part of a load-modify-store instruction.
13689     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13690            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13691       if (UI->getOpcode() == ISD::STORE)
13692         goto default_case;
13693
13694     // Otherwise use a regular EFLAGS-setting instruction.
13695     switch (ArithOp.getOpcode()) {
13696     default: llvm_unreachable("unexpected operator!");
13697     case ISD::SUB: Opcode = X86ISD::SUB; break;
13698     case ISD::XOR: Opcode = X86ISD::XOR; break;
13699     case ISD::AND: Opcode = X86ISD::AND; break;
13700     case ISD::OR: {
13701       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13702         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13703         if (EFLAGS.getNode())
13704           return EFLAGS;
13705       }
13706       Opcode = X86ISD::OR;
13707       break;
13708     }
13709     }
13710
13711     NumOperands = 2;
13712     break;
13713   case X86ISD::ADD:
13714   case X86ISD::SUB:
13715   case X86ISD::INC:
13716   case X86ISD::DEC:
13717   case X86ISD::OR:
13718   case X86ISD::XOR:
13719   case X86ISD::AND:
13720     return SDValue(Op.getNode(), 1);
13721   default:
13722   default_case:
13723     break;
13724   }
13725
13726   // If we found that truncation is beneficial, perform the truncation and
13727   // update 'Op'.
13728   if (NeedTruncation) {
13729     EVT VT = Op.getValueType();
13730     SDValue WideVal = Op->getOperand(0);
13731     EVT WideVT = WideVal.getValueType();
13732     unsigned ConvertedOp = 0;
13733     // Use a target machine opcode to prevent further DAGCombine
13734     // optimizations that may separate the arithmetic operations
13735     // from the setcc node.
13736     switch (WideVal.getOpcode()) {
13737       default: break;
13738       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13739       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13740       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13741       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13742       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13743     }
13744
13745     if (ConvertedOp) {
13746       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13747       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13748         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13749         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13750         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13751       }
13752     }
13753   }
13754
13755   if (Opcode == 0)
13756     // Emit a CMP with 0, which is the TEST pattern.
13757     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13758                        DAG.getConstant(0, dl, Op.getValueType()));
13759
13760   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13761   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13762
13763   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13764   DAG.ReplaceAllUsesWith(Op, New);
13765   return SDValue(New.getNode(), 1);
13766 }
13767
13768 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13769 /// equivalent.
13770 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13771                                    SDLoc dl, SelectionDAG &DAG) const {
13772   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13773     if (C->getAPIntValue() == 0)
13774       return EmitTest(Op0, X86CC, dl, DAG);
13775
13776      if (Op0.getValueType() == MVT::i1)
13777        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13778   }
13779
13780   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13781        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13782     // Do the comparison at i32 if it's smaller, besides the Atom case.
13783     // This avoids subregister aliasing issues. Keep the smaller reference
13784     // if we're optimizing for size, however, as that'll allow better folding
13785     // of memory operations.
13786     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13787         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13788         !Subtarget->isAtom()) {
13789       unsigned ExtendOp =
13790           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13791       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13792       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13793     }
13794     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13795     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13796     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13797                               Op0, Op1);
13798     return SDValue(Sub.getNode(), 1);
13799   }
13800   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13801 }
13802
13803 /// Convert a comparison if required by the subtarget.
13804 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13805                                                  SelectionDAG &DAG) const {
13806   // If the subtarget does not support the FUCOMI instruction, floating-point
13807   // comparisons have to be converted.
13808   if (Subtarget->hasCMov() ||
13809       Cmp.getOpcode() != X86ISD::CMP ||
13810       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13811       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13812     return Cmp;
13813
13814   // The instruction selector will select an FUCOM instruction instead of
13815   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13816   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13817   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13818   SDLoc dl(Cmp);
13819   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13820   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13821   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13822                             DAG.getConstant(8, dl, MVT::i8));
13823   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13824   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13825 }
13826
13827 /// The minimum architected relative accuracy is 2^-12. We need one
13828 /// Newton-Raphson step to have a good float result (24 bits of precision).
13829 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13830                                             DAGCombinerInfo &DCI,
13831                                             unsigned &RefinementSteps,
13832                                             bool &UseOneConstNR) const {
13833   EVT VT = Op.getValueType();
13834   const char *RecipOp;
13835
13836   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13837   // TODO: Add support for AVX512 (v16f32).
13838   // It is likely not profitable to do this for f64 because a double-precision
13839   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13840   // instructions: convert to single, rsqrtss, convert back to double, refine
13841   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13842   // along with FMA, this could be a throughput win.
13843   if (VT == MVT::f32 && Subtarget->hasSSE1())
13844     RecipOp = "sqrtf";
13845   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13846            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13847     RecipOp = "vec-sqrtf";
13848   else
13849     return SDValue();
13850
13851   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13852   if (!Recips.isEnabled(RecipOp))
13853     return SDValue();
13854
13855   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13856   UseOneConstNR = false;
13857   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13858 }
13859
13860 /// The minimum architected relative accuracy is 2^-12. We need one
13861 /// Newton-Raphson step to have a good float result (24 bits of precision).
13862 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13863                                             DAGCombinerInfo &DCI,
13864                                             unsigned &RefinementSteps) const {
13865   EVT VT = Op.getValueType();
13866   const char *RecipOp;
13867
13868   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13869   // TODO: Add support for AVX512 (v16f32).
13870   // It is likely not profitable to do this for f64 because a double-precision
13871   // reciprocal estimate with refinement on x86 prior to FMA requires
13872   // 15 instructions: convert to single, rcpss, convert back to double, refine
13873   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13874   // along with FMA, this could be a throughput win.
13875   if (VT == MVT::f32 && Subtarget->hasSSE1())
13876     RecipOp = "divf";
13877   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13878            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13879     RecipOp = "vec-divf";
13880   else
13881     return SDValue();
13882
13883   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13884   if (!Recips.isEnabled(RecipOp))
13885     return SDValue();
13886
13887   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13888   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13889 }
13890
13891 /// If we have at least two divisions that use the same divisor, convert to
13892 /// multplication by a reciprocal. This may need to be adjusted for a given
13893 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13894 /// This is because we still need one division to calculate the reciprocal and
13895 /// then we need two multiplies by that reciprocal as replacements for the
13896 /// original divisions.
13897 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13898   return 2;
13899 }
13900
13901 static bool isAllOnes(SDValue V) {
13902   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13903   return C && C->isAllOnesValue();
13904 }
13905
13906 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13907 /// if it's possible.
13908 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13909                                      SDLoc dl, SelectionDAG &DAG) const {
13910   SDValue Op0 = And.getOperand(0);
13911   SDValue Op1 = And.getOperand(1);
13912   if (Op0.getOpcode() == ISD::TRUNCATE)
13913     Op0 = Op0.getOperand(0);
13914   if (Op1.getOpcode() == ISD::TRUNCATE)
13915     Op1 = Op1.getOperand(0);
13916
13917   SDValue LHS, RHS;
13918   if (Op1.getOpcode() == ISD::SHL)
13919     std::swap(Op0, Op1);
13920   if (Op0.getOpcode() == ISD::SHL) {
13921     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13922       if (And00C->getZExtValue() == 1) {
13923         // If we looked past a truncate, check that it's only truncating away
13924         // known zeros.
13925         unsigned BitWidth = Op0.getValueSizeInBits();
13926         unsigned AndBitWidth = And.getValueSizeInBits();
13927         if (BitWidth > AndBitWidth) {
13928           APInt Zeros, Ones;
13929           DAG.computeKnownBits(Op0, Zeros, Ones);
13930           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13931             return SDValue();
13932         }
13933         LHS = Op1;
13934         RHS = Op0.getOperand(1);
13935       }
13936   } else if (Op1.getOpcode() == ISD::Constant) {
13937     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13938     uint64_t AndRHSVal = AndRHS->getZExtValue();
13939     SDValue AndLHS = Op0;
13940
13941     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13942       LHS = AndLHS.getOperand(0);
13943       RHS = AndLHS.getOperand(1);
13944     }
13945
13946     // Use BT if the immediate can't be encoded in a TEST instruction.
13947     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13948       LHS = AndLHS;
13949       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13950     }
13951   }
13952
13953   if (LHS.getNode()) {
13954     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13955     // instruction.  Since the shift amount is in-range-or-undefined, we know
13956     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13957     // the encoding for the i16 version is larger than the i32 version.
13958     // Also promote i16 to i32 for performance / code size reason.
13959     if (LHS.getValueType() == MVT::i8 ||
13960         LHS.getValueType() == MVT::i16)
13961       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13962
13963     // If the operand types disagree, extend the shift amount to match.  Since
13964     // BT ignores high bits (like shifts) we can use anyextend.
13965     if (LHS.getValueType() != RHS.getValueType())
13966       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13967
13968     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13969     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13970     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13971                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13972   }
13973
13974   return SDValue();
13975 }
13976
13977 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13978 /// mask CMPs.
13979 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13980                               SDValue &Op1) {
13981   unsigned SSECC;
13982   bool Swap = false;
13983
13984   // SSE Condition code mapping:
13985   //  0 - EQ
13986   //  1 - LT
13987   //  2 - LE
13988   //  3 - UNORD
13989   //  4 - NEQ
13990   //  5 - NLT
13991   //  6 - NLE
13992   //  7 - ORD
13993   switch (SetCCOpcode) {
13994   default: llvm_unreachable("Unexpected SETCC condition");
13995   case ISD::SETOEQ:
13996   case ISD::SETEQ:  SSECC = 0; break;
13997   case ISD::SETOGT:
13998   case ISD::SETGT:  Swap = true; // Fallthrough
13999   case ISD::SETLT:
14000   case ISD::SETOLT: SSECC = 1; break;
14001   case ISD::SETOGE:
14002   case ISD::SETGE:  Swap = true; // Fallthrough
14003   case ISD::SETLE:
14004   case ISD::SETOLE: SSECC = 2; break;
14005   case ISD::SETUO:  SSECC = 3; break;
14006   case ISD::SETUNE:
14007   case ISD::SETNE:  SSECC = 4; break;
14008   case ISD::SETULE: Swap = true; // Fallthrough
14009   case ISD::SETUGE: SSECC = 5; break;
14010   case ISD::SETULT: Swap = true; // Fallthrough
14011   case ISD::SETUGT: SSECC = 6; break;
14012   case ISD::SETO:   SSECC = 7; break;
14013   case ISD::SETUEQ:
14014   case ISD::SETONE: SSECC = 8; break;
14015   }
14016   if (Swap)
14017     std::swap(Op0, Op1);
14018
14019   return SSECC;
14020 }
14021
14022 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14023 // ones, and then concatenate the result back.
14024 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14025   MVT VT = Op.getSimpleValueType();
14026
14027   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14028          "Unsupported value type for operation");
14029
14030   unsigned NumElems = VT.getVectorNumElements();
14031   SDLoc dl(Op);
14032   SDValue CC = Op.getOperand(2);
14033
14034   // Extract the LHS vectors
14035   SDValue LHS = Op.getOperand(0);
14036   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14037   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14038
14039   // Extract the RHS vectors
14040   SDValue RHS = Op.getOperand(1);
14041   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14042   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14043
14044   // Issue the operation on the smaller types and concatenate the result back
14045   MVT EltVT = VT.getVectorElementType();
14046   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14047   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14048                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14049                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14050 }
14051
14052 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14053   SDValue Op0 = Op.getOperand(0);
14054   SDValue Op1 = Op.getOperand(1);
14055   SDValue CC = Op.getOperand(2);
14056   MVT VT = Op.getSimpleValueType();
14057   SDLoc dl(Op);
14058
14059   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
14060          "Unexpected type for boolean compare operation");
14061   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14062   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14063                                DAG.getConstant(-1, dl, VT));
14064   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14065                                DAG.getConstant(-1, dl, VT));
14066   switch (SetCCOpcode) {
14067   default: llvm_unreachable("Unexpected SETCC condition");
14068   case ISD::SETEQ:
14069     // (x == y) -> ~(x ^ y)
14070     return DAG.getNode(ISD::XOR, dl, VT,
14071                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14072                        DAG.getConstant(-1, dl, VT));
14073   case ISD::SETNE:
14074     // (x != y) -> (x ^ y)
14075     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14076   case ISD::SETUGT:
14077   case ISD::SETGT:
14078     // (x > y) -> (x & ~y)
14079     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14080   case ISD::SETULT:
14081   case ISD::SETLT:
14082     // (x < y) -> (~x & y)
14083     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14084   case ISD::SETULE:
14085   case ISD::SETLE:
14086     // (x <= y) -> (~x | y)
14087     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14088   case ISD::SETUGE:
14089   case ISD::SETGE:
14090     // (x >=y) -> (x | ~y)
14091     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14092   }
14093 }
14094
14095 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14096                                      const X86Subtarget *Subtarget) {
14097   SDValue Op0 = Op.getOperand(0);
14098   SDValue Op1 = Op.getOperand(1);
14099   SDValue CC = Op.getOperand(2);
14100   MVT VT = Op.getSimpleValueType();
14101   SDLoc dl(Op);
14102
14103   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14104          Op.getValueType().getScalarType() == MVT::i1 &&
14105          "Cannot set masked compare for this operation");
14106
14107   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14108   unsigned  Opc = 0;
14109   bool Unsigned = false;
14110   bool Swap = false;
14111   unsigned SSECC;
14112   switch (SetCCOpcode) {
14113   default: llvm_unreachable("Unexpected SETCC condition");
14114   case ISD::SETNE:  SSECC = 4; break;
14115   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14116   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14117   case ISD::SETLT:  Swap = true; //fall-through
14118   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14119   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14120   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14121   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14122   case ISD::SETULE: Unsigned = true; //fall-through
14123   case ISD::SETLE:  SSECC = 2; break;
14124   }
14125
14126   if (Swap)
14127     std::swap(Op0, Op1);
14128   if (Opc)
14129     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14130   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14131   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14132                      DAG.getConstant(SSECC, dl, MVT::i8));
14133 }
14134
14135 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14136 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14137 /// return an empty value.
14138 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14139 {
14140   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14141   if (!BV)
14142     return SDValue();
14143
14144   MVT VT = Op1.getSimpleValueType();
14145   MVT EVT = VT.getVectorElementType();
14146   unsigned n = VT.getVectorNumElements();
14147   SmallVector<SDValue, 8> ULTOp1;
14148
14149   for (unsigned i = 0; i < n; ++i) {
14150     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14151     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14152       return SDValue();
14153
14154     // Avoid underflow.
14155     APInt Val = Elt->getAPIntValue();
14156     if (Val == 0)
14157       return SDValue();
14158
14159     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14160   }
14161
14162   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14163 }
14164
14165 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14166                            SelectionDAG &DAG) {
14167   SDValue Op0 = Op.getOperand(0);
14168   SDValue Op1 = Op.getOperand(1);
14169   SDValue CC = Op.getOperand(2);
14170   MVT VT = Op.getSimpleValueType();
14171   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14172   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14173   SDLoc dl(Op);
14174
14175   if (isFP) {
14176 #ifndef NDEBUG
14177     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14178     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14179 #endif
14180
14181     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14182     unsigned Opc = X86ISD::CMPP;
14183     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14184       assert(VT.getVectorNumElements() <= 16);
14185       Opc = X86ISD::CMPM;
14186     }
14187     // In the two special cases we can't handle, emit two comparisons.
14188     if (SSECC == 8) {
14189       unsigned CC0, CC1;
14190       unsigned CombineOpc;
14191       if (SetCCOpcode == ISD::SETUEQ) {
14192         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14193       } else {
14194         assert(SetCCOpcode == ISD::SETONE);
14195         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14196       }
14197
14198       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14199                                  DAG.getConstant(CC0, dl, MVT::i8));
14200       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14201                                  DAG.getConstant(CC1, dl, MVT::i8));
14202       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14203     }
14204     // Handle all other FP comparisons here.
14205     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14206                        DAG.getConstant(SSECC, dl, MVT::i8));
14207   }
14208
14209   MVT VTOp0 = Op0.getSimpleValueType();
14210   assert(VTOp0 == Op1.getSimpleValueType() &&
14211          "Expected operands with same type!");
14212   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14213          "Invalid number of packed elements for source and destination!");
14214
14215   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14216     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14217     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14218     // legalizer firstly checks if the first operand in input to the setcc has
14219     // a legal type. If so, then it promotes the return type to that same type.
14220     // Otherwise, the return type is promoted to the 'next legal type' which,
14221     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14222     //
14223     // We reach this code only if the following two conditions are met:
14224     // 1. Both return type and operand type have been promoted to wider types
14225     //    by the type legalizer.
14226     // 2. The original operand type has been promoted to a 256-bit vector.
14227     //
14228     // Note that condition 2. only applies for AVX targets.
14229     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14230     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14231   }
14232
14233   // The non-AVX512 code below works under the assumption that source and
14234   // destination types are the same.
14235   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14236          "Value types for source and destination must be the same!");
14237
14238   // Break 256-bit integer vector compare into smaller ones.
14239   if (VT.is256BitVector() && !Subtarget->hasInt256())
14240     return Lower256IntVSETCC(Op, DAG);
14241
14242   EVT OpVT = Op1.getValueType();
14243   if (OpVT.getVectorElementType() == MVT::i1)
14244     return LowerBoolVSETCC_AVX512(Op, DAG);
14245
14246   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14247   if (Subtarget->hasAVX512()) {
14248     if (Op1.getValueType().is512BitVector() ||
14249         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14250         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14251       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14252
14253     // In AVX-512 architecture setcc returns mask with i1 elements,
14254     // But there is no compare instruction for i8 and i16 elements in KNL.
14255     // We are not talking about 512-bit operands in this case, these
14256     // types are illegal.
14257     if (MaskResult &&
14258         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14259          OpVT.getVectorElementType().getSizeInBits() >= 8))
14260       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14261                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14262   }
14263
14264   // Lower using XOP integer comparisons.
14265   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14266        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14267     // Translate compare code to XOP PCOM compare mode.
14268     unsigned CmpMode = 0;
14269     switch (SetCCOpcode) {
14270     default: llvm_unreachable("Unexpected SETCC condition");
14271     case ISD::SETULT:
14272     case ISD::SETLT: CmpMode = 0x00; break;
14273     case ISD::SETULE:
14274     case ISD::SETLE: CmpMode = 0x01; break;
14275     case ISD::SETUGT:
14276     case ISD::SETGT: CmpMode = 0x02; break;
14277     case ISD::SETUGE:
14278     case ISD::SETGE: CmpMode = 0x03; break;
14279     case ISD::SETEQ: CmpMode = 0x04; break;
14280     case ISD::SETNE: CmpMode = 0x05; break;
14281     }
14282
14283     // Are we comparing unsigned or signed integers?
14284     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14285       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14286
14287     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14288                        DAG.getConstant(CmpMode, dl, MVT::i8));
14289   }
14290
14291   // We are handling one of the integer comparisons here.  Since SSE only has
14292   // GT and EQ comparisons for integer, swapping operands and multiple
14293   // operations may be required for some comparisons.
14294   unsigned Opc;
14295   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14296   bool Subus = false;
14297
14298   switch (SetCCOpcode) {
14299   default: llvm_unreachable("Unexpected SETCC condition");
14300   case ISD::SETNE:  Invert = true;
14301   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14302   case ISD::SETLT:  Swap = true;
14303   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14304   case ISD::SETGE:  Swap = true;
14305   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14306                     Invert = true; break;
14307   case ISD::SETULT: Swap = true;
14308   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14309                     FlipSigns = true; break;
14310   case ISD::SETUGE: Swap = true;
14311   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14312                     FlipSigns = true; Invert = true; break;
14313   }
14314
14315   // Special case: Use min/max operations for SETULE/SETUGE
14316   MVT VET = VT.getVectorElementType();
14317   bool hasMinMax =
14318        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14319     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14320
14321   if (hasMinMax) {
14322     switch (SetCCOpcode) {
14323     default: break;
14324     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14325     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14326     }
14327
14328     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14329   }
14330
14331   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14332   if (!MinMax && hasSubus) {
14333     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14334     // Op0 u<= Op1:
14335     //   t = psubus Op0, Op1
14336     //   pcmpeq t, <0..0>
14337     switch (SetCCOpcode) {
14338     default: break;
14339     case ISD::SETULT: {
14340       // If the comparison is against a constant we can turn this into a
14341       // setule.  With psubus, setule does not require a swap.  This is
14342       // beneficial because the constant in the register is no longer
14343       // destructed as the destination so it can be hoisted out of a loop.
14344       // Only do this pre-AVX since vpcmp* is no longer destructive.
14345       if (Subtarget->hasAVX())
14346         break;
14347       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14348       if (ULEOp1.getNode()) {
14349         Op1 = ULEOp1;
14350         Subus = true; Invert = false; Swap = false;
14351       }
14352       break;
14353     }
14354     // Psubus is better than flip-sign because it requires no inversion.
14355     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14356     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14357     }
14358
14359     if (Subus) {
14360       Opc = X86ISD::SUBUS;
14361       FlipSigns = false;
14362     }
14363   }
14364
14365   if (Swap)
14366     std::swap(Op0, Op1);
14367
14368   // Check that the operation in question is available (most are plain SSE2,
14369   // but PCMPGTQ and PCMPEQQ have different requirements).
14370   if (VT == MVT::v2i64) {
14371     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14372       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14373
14374       // First cast everything to the right type.
14375       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14376       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14377
14378       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14379       // bits of the inputs before performing those operations. The lower
14380       // compare is always unsigned.
14381       SDValue SB;
14382       if (FlipSigns) {
14383         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14384       } else {
14385         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14386         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14387         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14388                          Sign, Zero, Sign, Zero);
14389       }
14390       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14391       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14392
14393       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14394       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14395       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14396
14397       // Create masks for only the low parts/high parts of the 64 bit integers.
14398       static const int MaskHi[] = { 1, 1, 3, 3 };
14399       static const int MaskLo[] = { 0, 0, 2, 2 };
14400       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14401       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14402       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14403
14404       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14405       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14406
14407       if (Invert)
14408         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14409
14410       return DAG.getBitcast(VT, Result);
14411     }
14412
14413     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14414       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14415       // pcmpeqd + pshufd + pand.
14416       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14417
14418       // First cast everything to the right type.
14419       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14420       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14421
14422       // Do the compare.
14423       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14424
14425       // Make sure the lower and upper halves are both all-ones.
14426       static const int Mask[] = { 1, 0, 3, 2 };
14427       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14428       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14429
14430       if (Invert)
14431         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14432
14433       return DAG.getBitcast(VT, Result);
14434     }
14435   }
14436
14437   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14438   // bits of the inputs before performing those operations.
14439   if (FlipSigns) {
14440     EVT EltVT = VT.getVectorElementType();
14441     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14442                                  VT);
14443     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14444     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14445   }
14446
14447   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14448
14449   // If the logical-not of the result is required, perform that now.
14450   if (Invert)
14451     Result = DAG.getNOT(dl, Result, VT);
14452
14453   if (MinMax)
14454     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14455
14456   if (Subus)
14457     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14458                          getZeroVector(VT, Subtarget, DAG, dl));
14459
14460   return Result;
14461 }
14462
14463 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14464
14465   MVT VT = Op.getSimpleValueType();
14466
14467   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14468
14469   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14470          && "SetCC type must be 8-bit or 1-bit integer");
14471   SDValue Op0 = Op.getOperand(0);
14472   SDValue Op1 = Op.getOperand(1);
14473   SDLoc dl(Op);
14474   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14475
14476   // Optimize to BT if possible.
14477   // Lower (X & (1 << N)) == 0 to BT(X, N).
14478   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14479   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14480   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14481       Op1.getOpcode() == ISD::Constant &&
14482       cast<ConstantSDNode>(Op1)->isNullValue() &&
14483       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14484     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14485     if (NewSetCC.getNode()) {
14486       if (VT == MVT::i1)
14487         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14488       return NewSetCC;
14489     }
14490   }
14491
14492   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14493   // these.
14494   if (Op1.getOpcode() == ISD::Constant &&
14495       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14496        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14497       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14498
14499     // If the input is a setcc, then reuse the input setcc or use a new one with
14500     // the inverted condition.
14501     if (Op0.getOpcode() == X86ISD::SETCC) {
14502       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14503       bool Invert = (CC == ISD::SETNE) ^
14504         cast<ConstantSDNode>(Op1)->isNullValue();
14505       if (!Invert)
14506         return Op0;
14507
14508       CCode = X86::GetOppositeBranchCondition(CCode);
14509       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14510                                   DAG.getConstant(CCode, dl, MVT::i8),
14511                                   Op0.getOperand(1));
14512       if (VT == MVT::i1)
14513         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14514       return SetCC;
14515     }
14516   }
14517   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14518       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14519       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14520
14521     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14522     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14523   }
14524
14525   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14526   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14527   if (X86CC == X86::COND_INVALID)
14528     return SDValue();
14529
14530   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14531   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14532   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14533                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14534   if (VT == MVT::i1)
14535     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14536   return SetCC;
14537 }
14538
14539 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14540 static bool isX86LogicalCmp(SDValue Op) {
14541   unsigned Opc = Op.getNode()->getOpcode();
14542   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14543       Opc == X86ISD::SAHF)
14544     return true;
14545   if (Op.getResNo() == 1 &&
14546       (Opc == X86ISD::ADD ||
14547        Opc == X86ISD::SUB ||
14548        Opc == X86ISD::ADC ||
14549        Opc == X86ISD::SBB ||
14550        Opc == X86ISD::SMUL ||
14551        Opc == X86ISD::UMUL ||
14552        Opc == X86ISD::INC ||
14553        Opc == X86ISD::DEC ||
14554        Opc == X86ISD::OR ||
14555        Opc == X86ISD::XOR ||
14556        Opc == X86ISD::AND))
14557     return true;
14558
14559   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14560     return true;
14561
14562   return false;
14563 }
14564
14565 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14566   if (V.getOpcode() != ISD::TRUNCATE)
14567     return false;
14568
14569   SDValue VOp0 = V.getOperand(0);
14570   unsigned InBits = VOp0.getValueSizeInBits();
14571   unsigned Bits = V.getValueSizeInBits();
14572   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14573 }
14574
14575 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14576   bool addTest = true;
14577   SDValue Cond  = Op.getOperand(0);
14578   SDValue Op1 = Op.getOperand(1);
14579   SDValue Op2 = Op.getOperand(2);
14580   SDLoc DL(Op);
14581   EVT VT = Op1.getValueType();
14582   SDValue CC;
14583
14584   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14585   // are available or VBLENDV if AVX is available.
14586   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14587   if (Cond.getOpcode() == ISD::SETCC &&
14588       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14589        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14590       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14591     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14592     int SSECC = translateX86FSETCC(
14593         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14594
14595     if (SSECC != 8) {
14596       if (Subtarget->hasAVX512()) {
14597         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14598                                   DAG.getConstant(SSECC, DL, MVT::i8));
14599         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14600       }
14601
14602       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14603                                 DAG.getConstant(SSECC, DL, MVT::i8));
14604
14605       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14606       // of 3 logic instructions for size savings and potentially speed.
14607       // Unfortunately, there is no scalar form of VBLENDV.
14608
14609       // If either operand is a constant, don't try this. We can expect to
14610       // optimize away at least one of the logic instructions later in that
14611       // case, so that sequence would be faster than a variable blend.
14612
14613       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14614       // uses XMM0 as the selection register. That may need just as many
14615       // instructions as the AND/ANDN/OR sequence due to register moves, so
14616       // don't bother.
14617
14618       if (Subtarget->hasAVX() &&
14619           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14620
14621         // Convert to vectors, do a VSELECT, and convert back to scalar.
14622         // All of the conversions should be optimized away.
14623
14624         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14625         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14626         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14627         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14628
14629         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14630         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14631
14632         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14633
14634         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14635                            VSel, DAG.getIntPtrConstant(0, DL));
14636       }
14637       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14638       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14639       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14640     }
14641   }
14642
14643   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14644     SDValue Op1Scalar;
14645     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14646       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14647     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14648       Op1Scalar = Op1.getOperand(0);
14649     SDValue Op2Scalar;
14650     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14651       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14652     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14653       Op2Scalar = Op2.getOperand(0);
14654     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14655       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14656                                       Op1Scalar.getValueType(),
14657                                       Cond, Op1Scalar, Op2Scalar);
14658       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14659         return DAG.getBitcast(VT, newSelect);
14660       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14661       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14662                          DAG.getIntPtrConstant(0, DL));
14663     }
14664   }
14665
14666   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14667     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14668     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14669                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14670     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14671                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14672     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14673                                     Cond, Op1, Op2);
14674     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14675   }
14676
14677   if (Cond.getOpcode() == ISD::SETCC) {
14678     SDValue NewCond = LowerSETCC(Cond, DAG);
14679     if (NewCond.getNode())
14680       Cond = NewCond;
14681   }
14682
14683   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14684   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14685   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14686   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14687   if (Cond.getOpcode() == X86ISD::SETCC &&
14688       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14689       isZero(Cond.getOperand(1).getOperand(1))) {
14690     SDValue Cmp = Cond.getOperand(1);
14691
14692     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14693
14694     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14695         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14696       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14697
14698       SDValue CmpOp0 = Cmp.getOperand(0);
14699       // Apply further optimizations for special cases
14700       // (select (x != 0), -1, 0) -> neg & sbb
14701       // (select (x == 0), 0, -1) -> neg & sbb
14702       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14703         if (YC->isNullValue() &&
14704             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14705           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14706           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14707                                     DAG.getConstant(0, DL,
14708                                                     CmpOp0.getValueType()),
14709                                     CmpOp0);
14710           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14711                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14712                                     SDValue(Neg.getNode(), 1));
14713           return Res;
14714         }
14715
14716       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14717                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14718       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14719
14720       SDValue Res =   // Res = 0 or -1.
14721         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14722                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14723
14724       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14725         Res = DAG.getNOT(DL, Res, Res.getValueType());
14726
14727       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14728       if (!N2C || !N2C->isNullValue())
14729         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14730       return Res;
14731     }
14732   }
14733
14734   // Look past (and (setcc_carry (cmp ...)), 1).
14735   if (Cond.getOpcode() == ISD::AND &&
14736       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14737     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14738     if (C && C->getAPIntValue() == 1)
14739       Cond = Cond.getOperand(0);
14740   }
14741
14742   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14743   // setting operand in place of the X86ISD::SETCC.
14744   unsigned CondOpcode = Cond.getOpcode();
14745   if (CondOpcode == X86ISD::SETCC ||
14746       CondOpcode == X86ISD::SETCC_CARRY) {
14747     CC = Cond.getOperand(0);
14748
14749     SDValue Cmp = Cond.getOperand(1);
14750     unsigned Opc = Cmp.getOpcode();
14751     MVT VT = Op.getSimpleValueType();
14752
14753     bool IllegalFPCMov = false;
14754     if (VT.isFloatingPoint() && !VT.isVector() &&
14755         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14756       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14757
14758     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14759         Opc == X86ISD::BT) { // FIXME
14760       Cond = Cmp;
14761       addTest = false;
14762     }
14763   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14764              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14765              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14766               Cond.getOperand(0).getValueType() != MVT::i8)) {
14767     SDValue LHS = Cond.getOperand(0);
14768     SDValue RHS = Cond.getOperand(1);
14769     unsigned X86Opcode;
14770     unsigned X86Cond;
14771     SDVTList VTs;
14772     switch (CondOpcode) {
14773     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14774     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14775     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14776     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14777     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14778     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14779     default: llvm_unreachable("unexpected overflowing operator");
14780     }
14781     if (CondOpcode == ISD::UMULO)
14782       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14783                           MVT::i32);
14784     else
14785       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14786
14787     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14788
14789     if (CondOpcode == ISD::UMULO)
14790       Cond = X86Op.getValue(2);
14791     else
14792       Cond = X86Op.getValue(1);
14793
14794     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14795     addTest = false;
14796   }
14797
14798   if (addTest) {
14799     // Look past the truncate if the high bits are known zero.
14800     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14801       Cond = Cond.getOperand(0);
14802
14803     // We know the result of AND is compared against zero. Try to match
14804     // it to BT.
14805     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14806       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14807       if (NewSetCC.getNode()) {
14808         CC = NewSetCC.getOperand(0);
14809         Cond = NewSetCC.getOperand(1);
14810         addTest = false;
14811       }
14812     }
14813   }
14814
14815   if (addTest) {
14816     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14817     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14818   }
14819
14820   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14821   // a <  b ?  0 : -1 -> RES = setcc_carry
14822   // a >= b ? -1 :  0 -> RES = setcc_carry
14823   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14824   if (Cond.getOpcode() == X86ISD::SUB) {
14825     Cond = ConvertCmpIfNecessary(Cond, DAG);
14826     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14827
14828     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14829         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14830       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14831                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14832                                 Cond);
14833       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14834         return DAG.getNOT(DL, Res, Res.getValueType());
14835       return Res;
14836     }
14837   }
14838
14839   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14840   // widen the cmov and push the truncate through. This avoids introducing a new
14841   // branch during isel and doesn't add any extensions.
14842   if (Op.getValueType() == MVT::i8 &&
14843       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14844     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14845     if (T1.getValueType() == T2.getValueType() &&
14846         // Blacklist CopyFromReg to avoid partial register stalls.
14847         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14848       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14849       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14850       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14851     }
14852   }
14853
14854   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14855   // condition is true.
14856   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14857   SDValue Ops[] = { Op2, Op1, CC, Cond };
14858   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14859 }
14860
14861 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14862                                        const X86Subtarget *Subtarget,
14863                                        SelectionDAG &DAG) {
14864   MVT VT = Op->getSimpleValueType(0);
14865   SDValue In = Op->getOperand(0);
14866   MVT InVT = In.getSimpleValueType();
14867   MVT VTElt = VT.getVectorElementType();
14868   MVT InVTElt = InVT.getVectorElementType();
14869   SDLoc dl(Op);
14870
14871   // SKX processor
14872   if ((InVTElt == MVT::i1) &&
14873       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14874         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14875
14876        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14877         VTElt.getSizeInBits() <= 16)) ||
14878
14879        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14880         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14881
14882        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14883         VTElt.getSizeInBits() >= 32))))
14884     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14885
14886   unsigned int NumElts = VT.getVectorNumElements();
14887
14888   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14889     return SDValue();
14890
14891   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14892     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14893       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14894     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14895   }
14896
14897   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14898   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14899   SDValue NegOne =
14900    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14901                    ExtVT);
14902   SDValue Zero =
14903    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14904
14905   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14906   if (VT.is512BitVector())
14907     return V;
14908   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14909 }
14910
14911 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14912                                              const X86Subtarget *Subtarget,
14913                                              SelectionDAG &DAG) {
14914   SDValue In = Op->getOperand(0);
14915   MVT VT = Op->getSimpleValueType(0);
14916   MVT InVT = In.getSimpleValueType();
14917   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14918
14919   MVT InSVT = InVT.getScalarType();
14920   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14921
14922   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14923     return SDValue();
14924   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14925     return SDValue();
14926
14927   SDLoc dl(Op);
14928
14929   // SSE41 targets can use the pmovsx* instructions directly.
14930   if (Subtarget->hasSSE41())
14931     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14932
14933   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14934   SDValue Curr = In;
14935   MVT CurrVT = InVT;
14936
14937   // As SRAI is only available on i16/i32 types, we expand only up to i32
14938   // and handle i64 separately.
14939   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14940     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14941     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14942     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14943     Curr = DAG.getBitcast(CurrVT, Curr);
14944   }
14945
14946   SDValue SignExt = Curr;
14947   if (CurrVT != InVT) {
14948     unsigned SignExtShift =
14949         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14950     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14951                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14952   }
14953
14954   if (CurrVT == VT)
14955     return SignExt;
14956
14957   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14958     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14959                                DAG.getConstant(31, dl, MVT::i8));
14960     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14961     return DAG.getBitcast(VT, Ext);
14962   }
14963
14964   return SDValue();
14965 }
14966
14967 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14968                                 SelectionDAG &DAG) {
14969   MVT VT = Op->getSimpleValueType(0);
14970   SDValue In = Op->getOperand(0);
14971   MVT InVT = In.getSimpleValueType();
14972   SDLoc dl(Op);
14973
14974   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14975     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14976
14977   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14978       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14979       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14980     return SDValue();
14981
14982   if (Subtarget->hasInt256())
14983     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14984
14985   // Optimize vectors in AVX mode
14986   // Sign extend  v8i16 to v8i32 and
14987   //              v4i32 to v4i64
14988   //
14989   // Divide input vector into two parts
14990   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14991   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14992   // concat the vectors to original VT
14993
14994   unsigned NumElems = InVT.getVectorNumElements();
14995   SDValue Undef = DAG.getUNDEF(InVT);
14996
14997   SmallVector<int,8> ShufMask1(NumElems, -1);
14998   for (unsigned i = 0; i != NumElems/2; ++i)
14999     ShufMask1[i] = i;
15000
15001   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15002
15003   SmallVector<int,8> ShufMask2(NumElems, -1);
15004   for (unsigned i = 0; i != NumElems/2; ++i)
15005     ShufMask2[i] = i + NumElems/2;
15006
15007   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15008
15009   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15010                                 VT.getVectorNumElements()/2);
15011
15012   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15013   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15014
15015   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15016 }
15017
15018 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15019 // may emit an illegal shuffle but the expansion is still better than scalar
15020 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15021 // we'll emit a shuffle and a arithmetic shift.
15022 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15023 // TODO: It is possible to support ZExt by zeroing the undef values during
15024 // the shuffle phase or after the shuffle.
15025 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15026                                  SelectionDAG &DAG) {
15027   MVT RegVT = Op.getSimpleValueType();
15028   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15029   assert(RegVT.isInteger() &&
15030          "We only custom lower integer vector sext loads.");
15031
15032   // Nothing useful we can do without SSE2 shuffles.
15033   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15034
15035   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15036   SDLoc dl(Ld);
15037   EVT MemVT = Ld->getMemoryVT();
15038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15039   unsigned RegSz = RegVT.getSizeInBits();
15040
15041   ISD::LoadExtType Ext = Ld->getExtensionType();
15042
15043   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15044          && "Only anyext and sext are currently implemented.");
15045   assert(MemVT != RegVT && "Cannot extend to the same type");
15046   assert(MemVT.isVector() && "Must load a vector from memory");
15047
15048   unsigned NumElems = RegVT.getVectorNumElements();
15049   unsigned MemSz = MemVT.getSizeInBits();
15050   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15051
15052   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15053     // The only way in which we have a legal 256-bit vector result but not the
15054     // integer 256-bit operations needed to directly lower a sextload is if we
15055     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15056     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15057     // correctly legalized. We do this late to allow the canonical form of
15058     // sextload to persist throughout the rest of the DAG combiner -- it wants
15059     // to fold together any extensions it can, and so will fuse a sign_extend
15060     // of an sextload into a sextload targeting a wider value.
15061     SDValue Load;
15062     if (MemSz == 128) {
15063       // Just switch this to a normal load.
15064       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15065                                        "it must be a legal 128-bit vector "
15066                                        "type!");
15067       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15068                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15069                   Ld->isInvariant(), Ld->getAlignment());
15070     } else {
15071       assert(MemSz < 128 &&
15072              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15073       // Do an sext load to a 128-bit vector type. We want to use the same
15074       // number of elements, but elements half as wide. This will end up being
15075       // recursively lowered by this routine, but will succeed as we definitely
15076       // have all the necessary features if we're using AVX1.
15077       EVT HalfEltVT =
15078           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15079       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15080       Load =
15081           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15082                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15083                          Ld->isNonTemporal(), Ld->isInvariant(),
15084                          Ld->getAlignment());
15085     }
15086
15087     // Replace chain users with the new chain.
15088     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15089     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15090
15091     // Finally, do a normal sign-extend to the desired register.
15092     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15093   }
15094
15095   // All sizes must be a power of two.
15096   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15097          "Non-power-of-two elements are not custom lowered!");
15098
15099   // Attempt to load the original value using scalar loads.
15100   // Find the largest scalar type that divides the total loaded size.
15101   MVT SclrLoadTy = MVT::i8;
15102   for (MVT Tp : MVT::integer_valuetypes()) {
15103     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15104       SclrLoadTy = Tp;
15105     }
15106   }
15107
15108   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15109   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15110       (64 <= MemSz))
15111     SclrLoadTy = MVT::f64;
15112
15113   // Calculate the number of scalar loads that we need to perform
15114   // in order to load our vector from memory.
15115   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15116
15117   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15118          "Can only lower sext loads with a single scalar load!");
15119
15120   unsigned loadRegZize = RegSz;
15121   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15122     loadRegZize = 128;
15123
15124   // Represent our vector as a sequence of elements which are the
15125   // largest scalar that we can load.
15126   EVT LoadUnitVecVT = EVT::getVectorVT(
15127       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15128
15129   // Represent the data using the same element type that is stored in
15130   // memory. In practice, we ''widen'' MemVT.
15131   EVT WideVecVT =
15132       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15133                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15134
15135   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15136          "Invalid vector type");
15137
15138   // We can't shuffle using an illegal type.
15139   assert(TLI.isTypeLegal(WideVecVT) &&
15140          "We only lower types that form legal widened vector types");
15141
15142   SmallVector<SDValue, 8> Chains;
15143   SDValue Ptr = Ld->getBasePtr();
15144   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15145                                       TLI.getPointerTy(DAG.getDataLayout()));
15146   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15147
15148   for (unsigned i = 0; i < NumLoads; ++i) {
15149     // Perform a single load.
15150     SDValue ScalarLoad =
15151         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15152                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15153                     Ld->getAlignment());
15154     Chains.push_back(ScalarLoad.getValue(1));
15155     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15156     // another round of DAGCombining.
15157     if (i == 0)
15158       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15159     else
15160       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15161                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15162
15163     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15164   }
15165
15166   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15167
15168   // Bitcast the loaded value to a vector of the original element type, in
15169   // the size of the target vector type.
15170   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15171   unsigned SizeRatio = RegSz / MemSz;
15172
15173   if (Ext == ISD::SEXTLOAD) {
15174     // If we have SSE4.1, we can directly emit a VSEXT node.
15175     if (Subtarget->hasSSE41()) {
15176       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15177       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15178       return Sext;
15179     }
15180
15181     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15182     // lanes.
15183     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15184            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15185
15186     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15187     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15188     return Shuff;
15189   }
15190
15191   // Redistribute the loaded elements into the different locations.
15192   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15193   for (unsigned i = 0; i != NumElems; ++i)
15194     ShuffleVec[i * SizeRatio] = i;
15195
15196   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15197                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15198
15199   // Bitcast to the requested type.
15200   Shuff = DAG.getBitcast(RegVT, Shuff);
15201   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15202   return Shuff;
15203 }
15204
15205 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15206 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15207 // from the AND / OR.
15208 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15209   Opc = Op.getOpcode();
15210   if (Opc != ISD::OR && Opc != ISD::AND)
15211     return false;
15212   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15213           Op.getOperand(0).hasOneUse() &&
15214           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15215           Op.getOperand(1).hasOneUse());
15216 }
15217
15218 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15219 // 1 and that the SETCC node has a single use.
15220 static bool isXor1OfSetCC(SDValue Op) {
15221   if (Op.getOpcode() != ISD::XOR)
15222     return false;
15223   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15224   if (N1C && N1C->getAPIntValue() == 1) {
15225     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15226       Op.getOperand(0).hasOneUse();
15227   }
15228   return false;
15229 }
15230
15231 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15232   bool addTest = true;
15233   SDValue Chain = Op.getOperand(0);
15234   SDValue Cond  = Op.getOperand(1);
15235   SDValue Dest  = Op.getOperand(2);
15236   SDLoc dl(Op);
15237   SDValue CC;
15238   bool Inverted = false;
15239
15240   if (Cond.getOpcode() == ISD::SETCC) {
15241     // Check for setcc([su]{add,sub,mul}o == 0).
15242     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15243         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15244         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15245         Cond.getOperand(0).getResNo() == 1 &&
15246         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15247          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15248          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15249          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15250          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15251          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15252       Inverted = true;
15253       Cond = Cond.getOperand(0);
15254     } else {
15255       SDValue NewCond = LowerSETCC(Cond, DAG);
15256       if (NewCond.getNode())
15257         Cond = NewCond;
15258     }
15259   }
15260 #if 0
15261   // FIXME: LowerXALUO doesn't handle these!!
15262   else if (Cond.getOpcode() == X86ISD::ADD  ||
15263            Cond.getOpcode() == X86ISD::SUB  ||
15264            Cond.getOpcode() == X86ISD::SMUL ||
15265            Cond.getOpcode() == X86ISD::UMUL)
15266     Cond = LowerXALUO(Cond, DAG);
15267 #endif
15268
15269   // Look pass (and (setcc_carry (cmp ...)), 1).
15270   if (Cond.getOpcode() == ISD::AND &&
15271       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15272     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15273     if (C && C->getAPIntValue() == 1)
15274       Cond = Cond.getOperand(0);
15275   }
15276
15277   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15278   // setting operand in place of the X86ISD::SETCC.
15279   unsigned CondOpcode = Cond.getOpcode();
15280   if (CondOpcode == X86ISD::SETCC ||
15281       CondOpcode == X86ISD::SETCC_CARRY) {
15282     CC = Cond.getOperand(0);
15283
15284     SDValue Cmp = Cond.getOperand(1);
15285     unsigned Opc = Cmp.getOpcode();
15286     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15287     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15288       Cond = Cmp;
15289       addTest = false;
15290     } else {
15291       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15292       default: break;
15293       case X86::COND_O:
15294       case X86::COND_B:
15295         // These can only come from an arithmetic instruction with overflow,
15296         // e.g. SADDO, UADDO.
15297         Cond = Cond.getNode()->getOperand(1);
15298         addTest = false;
15299         break;
15300       }
15301     }
15302   }
15303   CondOpcode = Cond.getOpcode();
15304   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15305       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15306       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15307        Cond.getOperand(0).getValueType() != MVT::i8)) {
15308     SDValue LHS = Cond.getOperand(0);
15309     SDValue RHS = Cond.getOperand(1);
15310     unsigned X86Opcode;
15311     unsigned X86Cond;
15312     SDVTList VTs;
15313     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15314     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15315     // X86ISD::INC).
15316     switch (CondOpcode) {
15317     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15318     case ISD::SADDO:
15319       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15320         if (C->isOne()) {
15321           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15322           break;
15323         }
15324       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15325     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15326     case ISD::SSUBO:
15327       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15328         if (C->isOne()) {
15329           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15330           break;
15331         }
15332       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15333     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15334     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15335     default: llvm_unreachable("unexpected overflowing operator");
15336     }
15337     if (Inverted)
15338       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15339     if (CondOpcode == ISD::UMULO)
15340       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15341                           MVT::i32);
15342     else
15343       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15344
15345     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15346
15347     if (CondOpcode == ISD::UMULO)
15348       Cond = X86Op.getValue(2);
15349     else
15350       Cond = X86Op.getValue(1);
15351
15352     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15353     addTest = false;
15354   } else {
15355     unsigned CondOpc;
15356     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15357       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15358       if (CondOpc == ISD::OR) {
15359         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15360         // two branches instead of an explicit OR instruction with a
15361         // separate test.
15362         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15363             isX86LogicalCmp(Cmp)) {
15364           CC = Cond.getOperand(0).getOperand(0);
15365           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15366                               Chain, Dest, CC, Cmp);
15367           CC = Cond.getOperand(1).getOperand(0);
15368           Cond = Cmp;
15369           addTest = false;
15370         }
15371       } else { // ISD::AND
15372         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15373         // two branches instead of an explicit AND instruction with a
15374         // separate test. However, we only do this if this block doesn't
15375         // have a fall-through edge, because this requires an explicit
15376         // jmp when the condition is false.
15377         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15378             isX86LogicalCmp(Cmp) &&
15379             Op.getNode()->hasOneUse()) {
15380           X86::CondCode CCode =
15381             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15382           CCode = X86::GetOppositeBranchCondition(CCode);
15383           CC = DAG.getConstant(CCode, dl, MVT::i8);
15384           SDNode *User = *Op.getNode()->use_begin();
15385           // Look for an unconditional branch following this conditional branch.
15386           // We need this because we need to reverse the successors in order
15387           // to implement FCMP_OEQ.
15388           if (User->getOpcode() == ISD::BR) {
15389             SDValue FalseBB = User->getOperand(1);
15390             SDNode *NewBR =
15391               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15392             assert(NewBR == User);
15393             (void)NewBR;
15394             Dest = FalseBB;
15395
15396             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15397                                 Chain, Dest, CC, Cmp);
15398             X86::CondCode CCode =
15399               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15400             CCode = X86::GetOppositeBranchCondition(CCode);
15401             CC = DAG.getConstant(CCode, dl, MVT::i8);
15402             Cond = Cmp;
15403             addTest = false;
15404           }
15405         }
15406       }
15407     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15408       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15409       // It should be transformed during dag combiner except when the condition
15410       // is set by a arithmetics with overflow node.
15411       X86::CondCode CCode =
15412         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15413       CCode = X86::GetOppositeBranchCondition(CCode);
15414       CC = DAG.getConstant(CCode, dl, MVT::i8);
15415       Cond = Cond.getOperand(0).getOperand(1);
15416       addTest = false;
15417     } else if (Cond.getOpcode() == ISD::SETCC &&
15418                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15419       // For FCMP_OEQ, we can emit
15420       // two branches instead of an explicit AND instruction with a
15421       // separate test. However, we only do this if this block doesn't
15422       // have a fall-through edge, because this requires an explicit
15423       // jmp when the condition is false.
15424       if (Op.getNode()->hasOneUse()) {
15425         SDNode *User = *Op.getNode()->use_begin();
15426         // Look for an unconditional branch following this conditional branch.
15427         // We need this because we need to reverse the successors in order
15428         // to implement FCMP_OEQ.
15429         if (User->getOpcode() == ISD::BR) {
15430           SDValue FalseBB = User->getOperand(1);
15431           SDNode *NewBR =
15432             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15433           assert(NewBR == User);
15434           (void)NewBR;
15435           Dest = FalseBB;
15436
15437           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15438                                     Cond.getOperand(0), Cond.getOperand(1));
15439           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15440           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15441           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15442                               Chain, Dest, CC, Cmp);
15443           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15444           Cond = Cmp;
15445           addTest = false;
15446         }
15447       }
15448     } else if (Cond.getOpcode() == ISD::SETCC &&
15449                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15450       // For FCMP_UNE, we can emit
15451       // two branches instead of an explicit AND instruction with a
15452       // separate test. However, we only do this if this block doesn't
15453       // have a fall-through edge, because this requires an explicit
15454       // jmp when the condition is false.
15455       if (Op.getNode()->hasOneUse()) {
15456         SDNode *User = *Op.getNode()->use_begin();
15457         // Look for an unconditional branch following this conditional branch.
15458         // We need this because we need to reverse the successors in order
15459         // to implement FCMP_UNE.
15460         if (User->getOpcode() == ISD::BR) {
15461           SDValue FalseBB = User->getOperand(1);
15462           SDNode *NewBR =
15463             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15464           assert(NewBR == User);
15465           (void)NewBR;
15466
15467           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15468                                     Cond.getOperand(0), Cond.getOperand(1));
15469           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15470           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15471           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15472                               Chain, Dest, CC, Cmp);
15473           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15474           Cond = Cmp;
15475           addTest = false;
15476           Dest = FalseBB;
15477         }
15478       }
15479     }
15480   }
15481
15482   if (addTest) {
15483     // Look pass the truncate if the high bits are known zero.
15484     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15485         Cond = Cond.getOperand(0);
15486
15487     // We know the result of AND is compared against zero. Try to match
15488     // it to BT.
15489     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15490       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15491       if (NewSetCC.getNode()) {
15492         CC = NewSetCC.getOperand(0);
15493         Cond = NewSetCC.getOperand(1);
15494         addTest = false;
15495       }
15496     }
15497   }
15498
15499   if (addTest) {
15500     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15501     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15502     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15503   }
15504   Cond = ConvertCmpIfNecessary(Cond, DAG);
15505   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15506                      Chain, Dest, CC, Cond);
15507 }
15508
15509 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15510 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15511 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15512 // that the guard pages used by the OS virtual memory manager are allocated in
15513 // correct sequence.
15514 SDValue
15515 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15516                                            SelectionDAG &DAG) const {
15517   MachineFunction &MF = DAG.getMachineFunction();
15518   bool SplitStack = MF.shouldSplitStack();
15519   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15520                SplitStack;
15521   SDLoc dl(Op);
15522
15523   if (!Lower) {
15524     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15525     SDNode* Node = Op.getNode();
15526
15527     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15528     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15529         " not tell us which reg is the stack pointer!");
15530     EVT VT = Node->getValueType(0);
15531     SDValue Tmp1 = SDValue(Node, 0);
15532     SDValue Tmp2 = SDValue(Node, 1);
15533     SDValue Tmp3 = Node->getOperand(2);
15534     SDValue Chain = Tmp1.getOperand(0);
15535
15536     // Chain the dynamic stack allocation so that it doesn't modify the stack
15537     // pointer when other instructions are using the stack.
15538     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15539         SDLoc(Node));
15540
15541     SDValue Size = Tmp2.getOperand(1);
15542     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15543     Chain = SP.getValue(1);
15544     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15545     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15546     unsigned StackAlign = TFI.getStackAlignment();
15547     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15548     if (Align > StackAlign)
15549       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15550           DAG.getConstant(-(uint64_t)Align, dl, VT));
15551     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15552
15553     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15554         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15555         SDLoc(Node));
15556
15557     SDValue Ops[2] = { Tmp1, Tmp2 };
15558     return DAG.getMergeValues(Ops, dl);
15559   }
15560
15561   // Get the inputs.
15562   SDValue Chain = Op.getOperand(0);
15563   SDValue Size  = Op.getOperand(1);
15564   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15565   EVT VT = Op.getNode()->getValueType(0);
15566
15567   bool Is64Bit = Subtarget->is64Bit();
15568   MVT SPTy = getPointerTy(DAG.getDataLayout());
15569
15570   if (SplitStack) {
15571     MachineRegisterInfo &MRI = MF.getRegInfo();
15572
15573     if (Is64Bit) {
15574       // The 64 bit implementation of segmented stacks needs to clobber both r10
15575       // r11. This makes it impossible to use it along with nested parameters.
15576       const Function *F = MF.getFunction();
15577
15578       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15579            I != E; ++I)
15580         if (I->hasNestAttr())
15581           report_fatal_error("Cannot use segmented stacks with functions that "
15582                              "have nested arguments.");
15583     }
15584
15585     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15586     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15587     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15588     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15589                                 DAG.getRegister(Vreg, SPTy));
15590     SDValue Ops1[2] = { Value, Chain };
15591     return DAG.getMergeValues(Ops1, dl);
15592   } else {
15593     SDValue Flag;
15594     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15595
15596     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15597     Flag = Chain.getValue(1);
15598     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15599
15600     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15601
15602     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15603     unsigned SPReg = RegInfo->getStackRegister();
15604     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15605     Chain = SP.getValue(1);
15606
15607     if (Align) {
15608       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15609                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15610       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15611     }
15612
15613     SDValue Ops1[2] = { SP, Chain };
15614     return DAG.getMergeValues(Ops1, dl);
15615   }
15616 }
15617
15618 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15619   MachineFunction &MF = DAG.getMachineFunction();
15620   auto PtrVT = getPointerTy(MF.getDataLayout());
15621   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15622
15623   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15624   SDLoc DL(Op);
15625
15626   if (!Subtarget->is64Bit() ||
15627       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15628     // vastart just stores the address of the VarArgsFrameIndex slot into the
15629     // memory location argument.
15630     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15631     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15632                         MachinePointerInfo(SV), false, false, 0);
15633   }
15634
15635   // __va_list_tag:
15636   //   gp_offset         (0 - 6 * 8)
15637   //   fp_offset         (48 - 48 + 8 * 16)
15638   //   overflow_arg_area (point to parameters coming in memory).
15639   //   reg_save_area
15640   SmallVector<SDValue, 8> MemOps;
15641   SDValue FIN = Op.getOperand(1);
15642   // Store gp_offset
15643   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15644                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15645                                                DL, MVT::i32),
15646                                FIN, MachinePointerInfo(SV), false, false, 0);
15647   MemOps.push_back(Store);
15648
15649   // Store fp_offset
15650   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15651   Store = DAG.getStore(Op.getOperand(0), DL,
15652                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15653                                        MVT::i32),
15654                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15655   MemOps.push_back(Store);
15656
15657   // Store ptr to overflow_arg_area
15658   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15659   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15660   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15661                        MachinePointerInfo(SV, 8),
15662                        false, false, 0);
15663   MemOps.push_back(Store);
15664
15665   // Store ptr to reg_save_area.
15666   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15667       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15668   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15669   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15670       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15671   MemOps.push_back(Store);
15672   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15673 }
15674
15675 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15676   assert(Subtarget->is64Bit() &&
15677          "LowerVAARG only handles 64-bit va_arg!");
15678   assert(Op.getNode()->getNumOperands() == 4);
15679
15680   MachineFunction &MF = DAG.getMachineFunction();
15681   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15682     // The Win64 ABI uses char* instead of a structure.
15683     return DAG.expandVAArg(Op.getNode());
15684
15685   SDValue Chain = Op.getOperand(0);
15686   SDValue SrcPtr = Op.getOperand(1);
15687   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15688   unsigned Align = Op.getConstantOperandVal(3);
15689   SDLoc dl(Op);
15690
15691   EVT ArgVT = Op.getNode()->getValueType(0);
15692   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15693   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15694   uint8_t ArgMode;
15695
15696   // Decide which area this value should be read from.
15697   // TODO: Implement the AMD64 ABI in its entirety. This simple
15698   // selection mechanism works only for the basic types.
15699   if (ArgVT == MVT::f80) {
15700     llvm_unreachable("va_arg for f80 not yet implemented");
15701   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15702     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15703   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15704     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15705   } else {
15706     llvm_unreachable("Unhandled argument type in LowerVAARG");
15707   }
15708
15709   if (ArgMode == 2) {
15710     // Sanity Check: Make sure using fp_offset makes sense.
15711     assert(!Subtarget->useSoftFloat() &&
15712            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15713            Subtarget->hasSSE1());
15714   }
15715
15716   // Insert VAARG_64 node into the DAG
15717   // VAARG_64 returns two values: Variable Argument Address, Chain
15718   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15719                        DAG.getConstant(ArgMode, dl, MVT::i8),
15720                        DAG.getConstant(Align, dl, MVT::i32)};
15721   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15722   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15723                                           VTs, InstOps, MVT::i64,
15724                                           MachinePointerInfo(SV),
15725                                           /*Align=*/0,
15726                                           /*Volatile=*/false,
15727                                           /*ReadMem=*/true,
15728                                           /*WriteMem=*/true);
15729   Chain = VAARG.getValue(1);
15730
15731   // Load the next argument and return it
15732   return DAG.getLoad(ArgVT, dl,
15733                      Chain,
15734                      VAARG,
15735                      MachinePointerInfo(),
15736                      false, false, false, 0);
15737 }
15738
15739 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15740                            SelectionDAG &DAG) {
15741   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15742   // where a va_list is still an i8*.
15743   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15744   if (Subtarget->isCallingConvWin64(
15745         DAG.getMachineFunction().getFunction()->getCallingConv()))
15746     // Probably a Win64 va_copy.
15747     return DAG.expandVACopy(Op.getNode());
15748
15749   SDValue Chain = Op.getOperand(0);
15750   SDValue DstPtr = Op.getOperand(1);
15751   SDValue SrcPtr = Op.getOperand(2);
15752   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15753   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15754   SDLoc DL(Op);
15755
15756   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15757                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15758                        false, false,
15759                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15760 }
15761
15762 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15763 // amount is a constant. Takes immediate version of shift as input.
15764 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15765                                           SDValue SrcOp, uint64_t ShiftAmt,
15766                                           SelectionDAG &DAG) {
15767   MVT ElementType = VT.getVectorElementType();
15768
15769   // Fold this packed shift into its first operand if ShiftAmt is 0.
15770   if (ShiftAmt == 0)
15771     return SrcOp;
15772
15773   // Check for ShiftAmt >= element width
15774   if (ShiftAmt >= ElementType.getSizeInBits()) {
15775     if (Opc == X86ISD::VSRAI)
15776       ShiftAmt = ElementType.getSizeInBits() - 1;
15777     else
15778       return DAG.getConstant(0, dl, VT);
15779   }
15780
15781   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15782          && "Unknown target vector shift-by-constant node");
15783
15784   // Fold this packed vector shift into a build vector if SrcOp is a
15785   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15786   if (VT == SrcOp.getSimpleValueType() &&
15787       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15788     SmallVector<SDValue, 8> Elts;
15789     unsigned NumElts = SrcOp->getNumOperands();
15790     ConstantSDNode *ND;
15791
15792     switch(Opc) {
15793     default: llvm_unreachable(nullptr);
15794     case X86ISD::VSHLI:
15795       for (unsigned i=0; i!=NumElts; ++i) {
15796         SDValue CurrentOp = SrcOp->getOperand(i);
15797         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15798           Elts.push_back(CurrentOp);
15799           continue;
15800         }
15801         ND = cast<ConstantSDNode>(CurrentOp);
15802         const APInt &C = ND->getAPIntValue();
15803         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15804       }
15805       break;
15806     case X86ISD::VSRLI:
15807       for (unsigned i=0; i!=NumElts; ++i) {
15808         SDValue CurrentOp = SrcOp->getOperand(i);
15809         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15810           Elts.push_back(CurrentOp);
15811           continue;
15812         }
15813         ND = cast<ConstantSDNode>(CurrentOp);
15814         const APInt &C = ND->getAPIntValue();
15815         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15816       }
15817       break;
15818     case X86ISD::VSRAI:
15819       for (unsigned i=0; i!=NumElts; ++i) {
15820         SDValue CurrentOp = SrcOp->getOperand(i);
15821         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15822           Elts.push_back(CurrentOp);
15823           continue;
15824         }
15825         ND = cast<ConstantSDNode>(CurrentOp);
15826         const APInt &C = ND->getAPIntValue();
15827         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15828       }
15829       break;
15830     }
15831
15832     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15833   }
15834
15835   return DAG.getNode(Opc, dl, VT, SrcOp,
15836                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15837 }
15838
15839 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15840 // may or may not be a constant. Takes immediate version of shift as input.
15841 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15842                                    SDValue SrcOp, SDValue ShAmt,
15843                                    SelectionDAG &DAG) {
15844   MVT SVT = ShAmt.getSimpleValueType();
15845   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15846
15847   // Catch shift-by-constant.
15848   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15849     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15850                                       CShAmt->getZExtValue(), DAG);
15851
15852   // Change opcode to non-immediate version
15853   switch (Opc) {
15854     default: llvm_unreachable("Unknown target vector shift node");
15855     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15856     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15857     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15858   }
15859
15860   const X86Subtarget &Subtarget =
15861       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15862   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15863       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15864     // Let the shuffle legalizer expand this shift amount node.
15865     SDValue Op0 = ShAmt.getOperand(0);
15866     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15867     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15868   } else {
15869     // Need to build a vector containing shift amount.
15870     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15871     SmallVector<SDValue, 4> ShOps;
15872     ShOps.push_back(ShAmt);
15873     if (SVT == MVT::i32) {
15874       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15875       ShOps.push_back(DAG.getUNDEF(SVT));
15876     }
15877     ShOps.push_back(DAG.getUNDEF(SVT));
15878
15879     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15880     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15881   }
15882
15883   // The return type has to be a 128-bit type with the same element
15884   // type as the input type.
15885   MVT EltVT = VT.getVectorElementType();
15886   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15887
15888   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15889   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15890 }
15891
15892 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15893 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15894 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15895 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15896                                     SDValue PreservedSrc,
15897                                     const X86Subtarget *Subtarget,
15898                                     SelectionDAG &DAG) {
15899     EVT VT = Op.getValueType();
15900     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15901                                   MVT::i1, VT.getVectorNumElements());
15902     SDValue VMask = SDValue();
15903     unsigned OpcodeSelect = ISD::VSELECT;
15904     SDLoc dl(Op);
15905
15906     assert(MaskVT.isSimple() && "invalid mask type");
15907
15908     if (isAllOnes(Mask))
15909       return Op;
15910
15911     if (MaskVT.bitsGT(Mask.getValueType())) {
15912       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15913                                          MaskVT.getSizeInBits());
15914       VMask = DAG.getBitcast(MaskVT,
15915                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15916     } else {
15917       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15918                                        Mask.getValueType().getSizeInBits());
15919       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15920       // are extracted by EXTRACT_SUBVECTOR.
15921       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15922                           DAG.getBitcast(BitcastVT, Mask),
15923                           DAG.getIntPtrConstant(0, dl));
15924     }
15925
15926     switch (Op.getOpcode()) {
15927       default: break;
15928       case X86ISD::PCMPEQM:
15929       case X86ISD::PCMPGTM:
15930       case X86ISD::CMPM:
15931       case X86ISD::CMPMU:
15932         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15933       case X86ISD::VFPCLASS:
15934         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15935       case X86ISD::VTRUNC:
15936       case X86ISD::VTRUNCS:
15937       case X86ISD::VTRUNCUS:
15938         // We can't use ISD::VSELECT here because it is not always "Legal"
15939         // for the destination type. For example vpmovqb require only AVX512
15940         // and vselect that can operate on byte element type require BWI
15941         OpcodeSelect = X86ISD::SELECT;
15942         break;
15943     }
15944     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15945       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15946     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15947 }
15948
15949 /// \brief Creates an SDNode for a predicated scalar operation.
15950 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15951 /// The mask is coming as MVT::i8 and it should be truncated
15952 /// to MVT::i1 while lowering masking intrinsics.
15953 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15954 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15955 /// for a scalar instruction.
15956 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15957                                     SDValue PreservedSrc,
15958                                     const X86Subtarget *Subtarget,
15959                                     SelectionDAG &DAG) {
15960   if (isAllOnes(Mask))
15961     return Op;
15962
15963   EVT VT = Op.getValueType();
15964   SDLoc dl(Op);
15965   // The mask should be of type MVT::i1
15966   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15967
15968   if (Op.getOpcode() == X86ISD::FSETCC)
15969     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15970   if (Op.getOpcode() == X86ISD::VFPCLASS)
15971     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
15972
15973   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15974     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15975   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15976 }
15977
15978 static int getSEHRegistrationNodeSize(const Function *Fn) {
15979   if (!Fn->hasPersonalityFn())
15980     report_fatal_error(
15981         "querying registration node size for function without personality");
15982   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15983   // WinEHStatePass for the full struct definition.
15984   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15985   case EHPersonality::MSVC_X86SEH: return 24;
15986   case EHPersonality::MSVC_CXX: return 16;
15987   default: break;
15988   }
15989   report_fatal_error("can only recover FP for MSVC EH personality functions");
15990 }
15991
15992 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15993 /// function or when returning to a parent frame after catching an exception, we
15994 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15995 /// Here's the math:
15996 ///   RegNodeBase = EntryEBP - RegNodeSize
15997 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15998 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15999 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16000 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16001                                    SDValue EntryEBP) {
16002   MachineFunction &MF = DAG.getMachineFunction();
16003   SDLoc dl;
16004
16005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16006   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16007
16008   // It's possible that the parent function no longer has a personality function
16009   // if the exceptional code was optimized away, in which case we just return
16010   // the incoming EBP.
16011   if (!Fn->hasPersonalityFn())
16012     return EntryEBP;
16013
16014   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16015
16016   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16017   // registration.
16018   MCSymbol *OffsetSym =
16019       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16020           GlobalValue::getRealLinkageName(Fn->getName()));
16021   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16022   SDValue RegNodeFrameOffset =
16023       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16024
16025   // RegNodeBase = EntryEBP - RegNodeSize
16026   // ParentFP = RegNodeBase - RegNodeFrameOffset
16027   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16028                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16029   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16030 }
16031
16032 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16033                                        SelectionDAG &DAG) {
16034   SDLoc dl(Op);
16035   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16036   EVT VT = Op.getValueType();
16037   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16038   if (IntrData) {
16039     switch(IntrData->Type) {
16040     case INTR_TYPE_1OP:
16041       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16042     case INTR_TYPE_2OP:
16043       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16044         Op.getOperand(2));
16045     case INTR_TYPE_2OP_IMM8:
16046       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16047                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16048     case INTR_TYPE_3OP:
16049       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16050         Op.getOperand(2), Op.getOperand(3));
16051     case INTR_TYPE_4OP:
16052       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16053         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16054     case INTR_TYPE_1OP_MASK_RM: {
16055       SDValue Src = Op.getOperand(1);
16056       SDValue PassThru = Op.getOperand(2);
16057       SDValue Mask = Op.getOperand(3);
16058       SDValue RoundingMode;
16059       // We allways add rounding mode to the Node.
16060       // If the rounding mode is not specified, we add the
16061       // "current direction" mode.
16062       if (Op.getNumOperands() == 4)
16063         RoundingMode =
16064           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16065       else
16066         RoundingMode = Op.getOperand(4);
16067       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16068       if (IntrWithRoundingModeOpcode != 0)
16069         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16070             X86::STATIC_ROUNDING::CUR_DIRECTION)
16071           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16072                                       dl, Op.getValueType(), Src, RoundingMode),
16073                                       Mask, PassThru, Subtarget, DAG);
16074       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16075                                               RoundingMode),
16076                                   Mask, PassThru, Subtarget, DAG);
16077     }
16078     case INTR_TYPE_1OP_MASK: {
16079       SDValue Src = Op.getOperand(1);
16080       SDValue PassThru = Op.getOperand(2);
16081       SDValue Mask = Op.getOperand(3);
16082       // We add rounding mode to the Node when
16083       //   - RM Opcode is specified and
16084       //   - RM is not "current direction".
16085       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16086       if (IntrWithRoundingModeOpcode != 0) {
16087         SDValue Rnd = Op.getOperand(4);
16088         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16089         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16090           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16091                                       dl, Op.getValueType(),
16092                                       Src, Rnd),
16093                                       Mask, PassThru, Subtarget, DAG);
16094         }
16095       }
16096       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16097                                   Mask, PassThru, Subtarget, DAG);
16098     }
16099     case INTR_TYPE_SCALAR_MASK: {
16100       SDValue Src1 = Op.getOperand(1);
16101       SDValue Src2 = Op.getOperand(2);
16102       SDValue passThru = Op.getOperand(3);
16103       SDValue Mask = Op.getOperand(4);
16104       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16105                                   Mask, passThru, Subtarget, DAG);
16106     }
16107     case INTR_TYPE_SCALAR_MASK_RM: {
16108       SDValue Src1 = Op.getOperand(1);
16109       SDValue Src2 = Op.getOperand(2);
16110       SDValue Src0 = Op.getOperand(3);
16111       SDValue Mask = Op.getOperand(4);
16112       // There are 2 kinds of intrinsics in this group:
16113       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16114       // (2) With rounding mode and sae - 7 operands.
16115       if (Op.getNumOperands() == 6) {
16116         SDValue Sae  = Op.getOperand(5);
16117         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16118         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16119                                                 Sae),
16120                                     Mask, Src0, Subtarget, DAG);
16121       }
16122       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16123       SDValue RoundingMode  = Op.getOperand(5);
16124       SDValue Sae  = Op.getOperand(6);
16125       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16126                                               RoundingMode, Sae),
16127                                   Mask, Src0, Subtarget, DAG);
16128     }
16129     case INTR_TYPE_2OP_MASK:
16130     case INTR_TYPE_2OP_IMM8_MASK: {
16131       SDValue Src1 = Op.getOperand(1);
16132       SDValue Src2 = Op.getOperand(2);
16133       SDValue PassThru = Op.getOperand(3);
16134       SDValue Mask = Op.getOperand(4);
16135
16136       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16137         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16138
16139       // We specify 2 possible opcodes for intrinsics with rounding modes.
16140       // First, we check if the intrinsic may have non-default rounding mode,
16141       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16142       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16143       if (IntrWithRoundingModeOpcode != 0) {
16144         SDValue Rnd = Op.getOperand(5);
16145         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16146         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16147           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16148                                       dl, Op.getValueType(),
16149                                       Src1, Src2, Rnd),
16150                                       Mask, PassThru, Subtarget, DAG);
16151         }
16152       }
16153       // TODO: Intrinsics should have fast-math-flags to propagate.
16154       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16155                                   Mask, PassThru, Subtarget, DAG);
16156     }
16157     case INTR_TYPE_2OP_MASK_RM: {
16158       SDValue Src1 = Op.getOperand(1);
16159       SDValue Src2 = Op.getOperand(2);
16160       SDValue PassThru = Op.getOperand(3);
16161       SDValue Mask = Op.getOperand(4);
16162       // We specify 2 possible modes for intrinsics, with/without rounding
16163       // modes.
16164       // First, we check if the intrinsic have rounding mode (6 operands),
16165       // if not, we set rounding mode to "current".
16166       SDValue Rnd;
16167       if (Op.getNumOperands() == 6)
16168         Rnd = Op.getOperand(5);
16169       else
16170         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16171       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16172                                               Src1, Src2, Rnd),
16173                                   Mask, PassThru, Subtarget, DAG);
16174     }
16175     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16176       SDValue Src1 = Op.getOperand(1);
16177       SDValue Src2 = Op.getOperand(2);
16178       SDValue Src3 = Op.getOperand(3);
16179       SDValue PassThru = Op.getOperand(4);
16180       SDValue Mask = Op.getOperand(5);
16181       SDValue Sae  = Op.getOperand(6);
16182
16183       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16184                                               Src2, Src3, Sae),
16185                                   Mask, PassThru, Subtarget, DAG);
16186     }
16187     case INTR_TYPE_3OP_MASK_RM: {
16188       SDValue Src1 = Op.getOperand(1);
16189       SDValue Src2 = Op.getOperand(2);
16190       SDValue Imm = Op.getOperand(3);
16191       SDValue PassThru = Op.getOperand(4);
16192       SDValue Mask = Op.getOperand(5);
16193       // We specify 2 possible modes for intrinsics, with/without rounding
16194       // modes.
16195       // First, we check if the intrinsic have rounding mode (7 operands),
16196       // if not, we set rounding mode to "current".
16197       SDValue Rnd;
16198       if (Op.getNumOperands() == 7)
16199         Rnd = Op.getOperand(6);
16200       else
16201         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16202       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16203         Src1, Src2, Imm, Rnd),
16204         Mask, PassThru, Subtarget, DAG);
16205     }
16206     case INTR_TYPE_3OP_IMM8_MASK:
16207     case INTR_TYPE_3OP_MASK:
16208     case INSERT_SUBVEC: {
16209       SDValue Src1 = Op.getOperand(1);
16210       SDValue Src2 = Op.getOperand(2);
16211       SDValue Src3 = Op.getOperand(3);
16212       SDValue PassThru = Op.getOperand(4);
16213       SDValue Mask = Op.getOperand(5);
16214
16215       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16216         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16217       else if (IntrData->Type == INSERT_SUBVEC) {
16218         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16219         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16220         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16221         Imm *= Src2.getValueType().getVectorNumElements();
16222         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16223       }
16224
16225       // We specify 2 possible opcodes for intrinsics with rounding modes.
16226       // First, we check if the intrinsic may have non-default rounding mode,
16227       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16228       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16229       if (IntrWithRoundingModeOpcode != 0) {
16230         SDValue Rnd = Op.getOperand(6);
16231         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16232         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16233           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16234                                       dl, Op.getValueType(),
16235                                       Src1, Src2, Src3, Rnd),
16236                                       Mask, PassThru, Subtarget, DAG);
16237         }
16238       }
16239       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16240                                               Src1, Src2, Src3),
16241                                   Mask, PassThru, Subtarget, DAG);
16242     }
16243     case VPERM_3OP_MASKZ:
16244     case VPERM_3OP_MASK:
16245     case FMA_OP_MASK3:
16246     case FMA_OP_MASKZ:
16247     case FMA_OP_MASK: {
16248       SDValue Src1 = Op.getOperand(1);
16249       SDValue Src2 = Op.getOperand(2);
16250       SDValue Src3 = Op.getOperand(3);
16251       SDValue Mask = Op.getOperand(4);
16252       EVT VT = Op.getValueType();
16253       SDValue PassThru = SDValue();
16254
16255       // set PassThru element
16256       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16257         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16258       else if (IntrData->Type == FMA_OP_MASK3)
16259         PassThru = Src3;
16260       else
16261         PassThru = Src1;
16262
16263       // We specify 2 possible opcodes for intrinsics with rounding modes.
16264       // First, we check if the intrinsic may have non-default rounding mode,
16265       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16266       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16267       if (IntrWithRoundingModeOpcode != 0) {
16268         SDValue Rnd = Op.getOperand(5);
16269         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16270             X86::STATIC_ROUNDING::CUR_DIRECTION)
16271           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16272                                                   dl, Op.getValueType(),
16273                                                   Src1, Src2, Src3, Rnd),
16274                                       Mask, PassThru, Subtarget, DAG);
16275       }
16276       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16277                                               dl, Op.getValueType(),
16278                                               Src1, Src2, Src3),
16279                                   Mask, PassThru, Subtarget, DAG);
16280     }
16281     case TERLOG_OP_MASK:
16282     case TERLOG_OP_MASKZ: {
16283       SDValue Src1 = Op.getOperand(1);
16284       SDValue Src2 = Op.getOperand(2);
16285       SDValue Src3 = Op.getOperand(3);
16286       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16287       SDValue Mask = Op.getOperand(5);
16288       EVT VT = Op.getValueType();
16289       SDValue PassThru = Src1;
16290       // Set PassThru element.
16291       if (IntrData->Type == TERLOG_OP_MASKZ)
16292         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16293
16294       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16295                                               Src1, Src2, Src3, Src4),
16296                                   Mask, PassThru, Subtarget, DAG);
16297     }
16298     case FPCLASS: {
16299       // FPclass intrinsics with mask
16300        SDValue Src1 = Op.getOperand(1);
16301        EVT VT = Src1.getValueType();
16302        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16303                                       VT.getVectorNumElements());
16304        SDValue Imm = Op.getOperand(2);
16305        SDValue Mask = Op.getOperand(3);
16306        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16307                                         Mask.getValueType().getSizeInBits());
16308        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16309        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16310                                                  DAG.getTargetConstant(0, dl, MaskVT),
16311                                                  Subtarget, DAG);
16312        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16313                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16314                                  DAG.getIntPtrConstant(0, dl));
16315        return DAG.getBitcast(Op.getValueType(), Res);
16316     }
16317     case FPCLASSS: {
16318       SDValue Src1 = Op.getOperand(1);
16319       SDValue Imm = Op.getOperand(2);
16320       SDValue Mask = Op.getOperand(3);
16321       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16322       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16323         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16324       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16325     }
16326     case CMP_MASK:
16327     case CMP_MASK_CC: {
16328       // Comparison intrinsics with masks.
16329       // Example of transformation:
16330       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16331       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16332       // (i8 (bitcast
16333       //   (v8i1 (insert_subvector undef,
16334       //           (v2i1 (and (PCMPEQM %a, %b),
16335       //                      (extract_subvector
16336       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16337       EVT VT = Op.getOperand(1).getValueType();
16338       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16339                                     VT.getVectorNumElements());
16340       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16341       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16342                                        Mask.getValueType().getSizeInBits());
16343       SDValue Cmp;
16344       if (IntrData->Type == CMP_MASK_CC) {
16345         SDValue CC = Op.getOperand(3);
16346         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16347         // We specify 2 possible opcodes for intrinsics with rounding modes.
16348         // First, we check if the intrinsic may have non-default rounding mode,
16349         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16350         if (IntrData->Opc1 != 0) {
16351           SDValue Rnd = Op.getOperand(5);
16352           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16353               X86::STATIC_ROUNDING::CUR_DIRECTION)
16354             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16355                               Op.getOperand(2), CC, Rnd);
16356         }
16357         //default rounding mode
16358         if(!Cmp.getNode())
16359             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16360                               Op.getOperand(2), CC);
16361
16362       } else {
16363         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16364         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16365                           Op.getOperand(2));
16366       }
16367       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16368                                              DAG.getTargetConstant(0, dl,
16369                                                                    MaskVT),
16370                                              Subtarget, DAG);
16371       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16372                                 DAG.getUNDEF(BitcastVT), CmpMask,
16373                                 DAG.getIntPtrConstant(0, dl));
16374       return DAG.getBitcast(Op.getValueType(), Res);
16375     }
16376     case CMP_MASK_SCALAR_CC: {
16377       SDValue Src1 = Op.getOperand(1);
16378       SDValue Src2 = Op.getOperand(2);
16379       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16380       SDValue Mask = Op.getOperand(4);
16381
16382       SDValue Cmp;
16383       if (IntrData->Opc1 != 0) {
16384         SDValue Rnd = Op.getOperand(5);
16385         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16386             X86::STATIC_ROUNDING::CUR_DIRECTION)
16387           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16388       }
16389       //default rounding mode
16390       if(!Cmp.getNode())
16391         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16392
16393       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16394                                              DAG.getTargetConstant(0, dl,
16395                                                                    MVT::i1),
16396                                              Subtarget, DAG);
16397
16398       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16399                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16400                          DAG.getValueType(MVT::i1));
16401     }
16402     case COMI: { // Comparison intrinsics
16403       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16404       SDValue LHS = Op.getOperand(1);
16405       SDValue RHS = Op.getOperand(2);
16406       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16407       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16408       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16409       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16410                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16411       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16412     }
16413     case VSHIFT:
16414       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16415                                  Op.getOperand(1), Op.getOperand(2), DAG);
16416     case VSHIFT_MASK:
16417       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16418                                                       Op.getSimpleValueType(),
16419                                                       Op.getOperand(1),
16420                                                       Op.getOperand(2), DAG),
16421                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16422                                   DAG);
16423     case COMPRESS_EXPAND_IN_REG: {
16424       SDValue Mask = Op.getOperand(3);
16425       SDValue DataToCompress = Op.getOperand(1);
16426       SDValue PassThru = Op.getOperand(2);
16427       if (isAllOnes(Mask)) // return data as is
16428         return Op.getOperand(1);
16429
16430       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16431                                               DataToCompress),
16432                                   Mask, PassThru, Subtarget, DAG);
16433     }
16434     case BLEND: {
16435       SDValue Mask = Op.getOperand(3);
16436       EVT VT = Op.getValueType();
16437       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16438                                     VT.getVectorNumElements());
16439       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16440                                        Mask.getValueType().getSizeInBits());
16441       SDLoc dl(Op);
16442       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16443                                   DAG.getBitcast(BitcastVT, Mask),
16444                                   DAG.getIntPtrConstant(0, dl));
16445       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16446                          Op.getOperand(2));
16447     }
16448     default:
16449       break;
16450     }
16451   }
16452
16453   switch (IntNo) {
16454   default: return SDValue();    // Don't custom lower most intrinsics.
16455
16456   case Intrinsic::x86_avx2_permd:
16457   case Intrinsic::x86_avx2_permps:
16458     // Operands intentionally swapped. Mask is last operand to intrinsic,
16459     // but second operand for node/instruction.
16460     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16461                        Op.getOperand(2), Op.getOperand(1));
16462
16463   // ptest and testp intrinsics. The intrinsic these come from are designed to
16464   // return an integer value, not just an instruction so lower it to the ptest
16465   // or testp pattern and a setcc for the result.
16466   case Intrinsic::x86_sse41_ptestz:
16467   case Intrinsic::x86_sse41_ptestc:
16468   case Intrinsic::x86_sse41_ptestnzc:
16469   case Intrinsic::x86_avx_ptestz_256:
16470   case Intrinsic::x86_avx_ptestc_256:
16471   case Intrinsic::x86_avx_ptestnzc_256:
16472   case Intrinsic::x86_avx_vtestz_ps:
16473   case Intrinsic::x86_avx_vtestc_ps:
16474   case Intrinsic::x86_avx_vtestnzc_ps:
16475   case Intrinsic::x86_avx_vtestz_pd:
16476   case Intrinsic::x86_avx_vtestc_pd:
16477   case Intrinsic::x86_avx_vtestnzc_pd:
16478   case Intrinsic::x86_avx_vtestz_ps_256:
16479   case Intrinsic::x86_avx_vtestc_ps_256:
16480   case Intrinsic::x86_avx_vtestnzc_ps_256:
16481   case Intrinsic::x86_avx_vtestz_pd_256:
16482   case Intrinsic::x86_avx_vtestc_pd_256:
16483   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16484     bool IsTestPacked = false;
16485     unsigned X86CC;
16486     switch (IntNo) {
16487     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16488     case Intrinsic::x86_avx_vtestz_ps:
16489     case Intrinsic::x86_avx_vtestz_pd:
16490     case Intrinsic::x86_avx_vtestz_ps_256:
16491     case Intrinsic::x86_avx_vtestz_pd_256:
16492       IsTestPacked = true; // Fallthrough
16493     case Intrinsic::x86_sse41_ptestz:
16494     case Intrinsic::x86_avx_ptestz_256:
16495       // ZF = 1
16496       X86CC = X86::COND_E;
16497       break;
16498     case Intrinsic::x86_avx_vtestc_ps:
16499     case Intrinsic::x86_avx_vtestc_pd:
16500     case Intrinsic::x86_avx_vtestc_ps_256:
16501     case Intrinsic::x86_avx_vtestc_pd_256:
16502       IsTestPacked = true; // Fallthrough
16503     case Intrinsic::x86_sse41_ptestc:
16504     case Intrinsic::x86_avx_ptestc_256:
16505       // CF = 1
16506       X86CC = X86::COND_B;
16507       break;
16508     case Intrinsic::x86_avx_vtestnzc_ps:
16509     case Intrinsic::x86_avx_vtestnzc_pd:
16510     case Intrinsic::x86_avx_vtestnzc_ps_256:
16511     case Intrinsic::x86_avx_vtestnzc_pd_256:
16512       IsTestPacked = true; // Fallthrough
16513     case Intrinsic::x86_sse41_ptestnzc:
16514     case Intrinsic::x86_avx_ptestnzc_256:
16515       // ZF and CF = 0
16516       X86CC = X86::COND_A;
16517       break;
16518     }
16519
16520     SDValue LHS = Op.getOperand(1);
16521     SDValue RHS = Op.getOperand(2);
16522     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16523     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16524     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16525     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16526     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16527   }
16528   case Intrinsic::x86_avx512_kortestz_w:
16529   case Intrinsic::x86_avx512_kortestc_w: {
16530     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16531     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16532     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16533     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16534     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16535     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16536     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16537   }
16538
16539   case Intrinsic::x86_sse42_pcmpistria128:
16540   case Intrinsic::x86_sse42_pcmpestria128:
16541   case Intrinsic::x86_sse42_pcmpistric128:
16542   case Intrinsic::x86_sse42_pcmpestric128:
16543   case Intrinsic::x86_sse42_pcmpistrio128:
16544   case Intrinsic::x86_sse42_pcmpestrio128:
16545   case Intrinsic::x86_sse42_pcmpistris128:
16546   case Intrinsic::x86_sse42_pcmpestris128:
16547   case Intrinsic::x86_sse42_pcmpistriz128:
16548   case Intrinsic::x86_sse42_pcmpestriz128: {
16549     unsigned Opcode;
16550     unsigned X86CC;
16551     switch (IntNo) {
16552     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16553     case Intrinsic::x86_sse42_pcmpistria128:
16554       Opcode = X86ISD::PCMPISTRI;
16555       X86CC = X86::COND_A;
16556       break;
16557     case Intrinsic::x86_sse42_pcmpestria128:
16558       Opcode = X86ISD::PCMPESTRI;
16559       X86CC = X86::COND_A;
16560       break;
16561     case Intrinsic::x86_sse42_pcmpistric128:
16562       Opcode = X86ISD::PCMPISTRI;
16563       X86CC = X86::COND_B;
16564       break;
16565     case Intrinsic::x86_sse42_pcmpestric128:
16566       Opcode = X86ISD::PCMPESTRI;
16567       X86CC = X86::COND_B;
16568       break;
16569     case Intrinsic::x86_sse42_pcmpistrio128:
16570       Opcode = X86ISD::PCMPISTRI;
16571       X86CC = X86::COND_O;
16572       break;
16573     case Intrinsic::x86_sse42_pcmpestrio128:
16574       Opcode = X86ISD::PCMPESTRI;
16575       X86CC = X86::COND_O;
16576       break;
16577     case Intrinsic::x86_sse42_pcmpistris128:
16578       Opcode = X86ISD::PCMPISTRI;
16579       X86CC = X86::COND_S;
16580       break;
16581     case Intrinsic::x86_sse42_pcmpestris128:
16582       Opcode = X86ISD::PCMPESTRI;
16583       X86CC = X86::COND_S;
16584       break;
16585     case Intrinsic::x86_sse42_pcmpistriz128:
16586       Opcode = X86ISD::PCMPISTRI;
16587       X86CC = X86::COND_E;
16588       break;
16589     case Intrinsic::x86_sse42_pcmpestriz128:
16590       Opcode = X86ISD::PCMPESTRI;
16591       X86CC = X86::COND_E;
16592       break;
16593     }
16594     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16595     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16596     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16597     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16598                                 DAG.getConstant(X86CC, dl, MVT::i8),
16599                                 SDValue(PCMP.getNode(), 1));
16600     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16601   }
16602
16603   case Intrinsic::x86_sse42_pcmpistri128:
16604   case Intrinsic::x86_sse42_pcmpestri128: {
16605     unsigned Opcode;
16606     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16607       Opcode = X86ISD::PCMPISTRI;
16608     else
16609       Opcode = X86ISD::PCMPESTRI;
16610
16611     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16612     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16613     return DAG.getNode(Opcode, dl, VTs, NewOps);
16614   }
16615
16616   case Intrinsic::x86_seh_lsda: {
16617     // Compute the symbol for the LSDA. We know it'll get emitted later.
16618     MachineFunction &MF = DAG.getMachineFunction();
16619     SDValue Op1 = Op.getOperand(1);
16620     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16621     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16622         GlobalValue::getRealLinkageName(Fn->getName()));
16623
16624     // Generate a simple absolute symbol reference. This intrinsic is only
16625     // supported on 32-bit Windows, which isn't PIC.
16626     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16627     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16628   }
16629
16630   case Intrinsic::x86_seh_recoverfp: {
16631     SDValue FnOp = Op.getOperand(1);
16632     SDValue IncomingFPOp = Op.getOperand(2);
16633     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16634     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16635     if (!Fn)
16636       report_fatal_error(
16637           "llvm.x86.seh.recoverfp must take a function as the first argument");
16638     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16639   }
16640
16641   case Intrinsic::localaddress: {
16642     // Returns one of the stack, base, or frame pointer registers, depending on
16643     // which is used to reference local variables.
16644     MachineFunction &MF = DAG.getMachineFunction();
16645     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16646     unsigned Reg;
16647     if (RegInfo->hasBasePointer(MF))
16648       Reg = RegInfo->getBaseRegister();
16649     else // This function handles the SP or FP case.
16650       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16651     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16652   }
16653   }
16654 }
16655
16656 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16657                               SDValue Src, SDValue Mask, SDValue Base,
16658                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16659                               const X86Subtarget * Subtarget) {
16660   SDLoc dl(Op);
16661   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16662   if (!C)
16663     llvm_unreachable("Invalid scale type");
16664   unsigned ScaleVal = C->getZExtValue();
16665   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16666     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16667
16668   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16669   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16670                              Index.getSimpleValueType().getVectorNumElements());
16671   SDValue MaskInReg;
16672   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16673   if (MaskC)
16674     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16675   else {
16676     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16677                                      Mask.getValueType().getSizeInBits());
16678
16679     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16680     // are extracted by EXTRACT_SUBVECTOR.
16681     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16682                             DAG.getBitcast(BitcastVT, Mask),
16683                             DAG.getIntPtrConstant(0, dl));
16684   }
16685   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16686   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16687   SDValue Segment = DAG.getRegister(0, MVT::i32);
16688   if (Src.getOpcode() == ISD::UNDEF)
16689     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16690   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16691   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16692   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16693   return DAG.getMergeValues(RetOps, dl);
16694 }
16695
16696 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16697                                SDValue Src, SDValue Mask, SDValue Base,
16698                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16699   SDLoc dl(Op);
16700   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16701   if (!C)
16702     llvm_unreachable("Invalid scale type");
16703   unsigned ScaleVal = C->getZExtValue();
16704   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16705     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16706
16707   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16708   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16709   SDValue Segment = DAG.getRegister(0, MVT::i32);
16710   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16711                              Index.getSimpleValueType().getVectorNumElements());
16712   SDValue MaskInReg;
16713   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16714   if (MaskC)
16715     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16716   else {
16717     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16718                                      Mask.getValueType().getSizeInBits());
16719
16720     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16721     // are extracted by EXTRACT_SUBVECTOR.
16722     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16723                             DAG.getBitcast(BitcastVT, Mask),
16724                             DAG.getIntPtrConstant(0, dl));
16725   }
16726   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16727   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16728   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16729   return SDValue(Res, 1);
16730 }
16731
16732 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16733                                SDValue Mask, SDValue Base, SDValue Index,
16734                                SDValue ScaleOp, SDValue Chain) {
16735   SDLoc dl(Op);
16736   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16737   assert(C && "Invalid scale type");
16738   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16739   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16740   SDValue Segment = DAG.getRegister(0, MVT::i32);
16741   EVT MaskVT =
16742     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16743   SDValue MaskInReg;
16744   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16745   if (MaskC)
16746     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16747   else
16748     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16749   //SDVTList VTs = DAG.getVTList(MVT::Other);
16750   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16751   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16752   return SDValue(Res, 0);
16753 }
16754
16755 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16756 // read performance monitor counters (x86_rdpmc).
16757 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16758                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16759                               SmallVectorImpl<SDValue> &Results) {
16760   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16761   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16762   SDValue LO, HI;
16763
16764   // The ECX register is used to select the index of the performance counter
16765   // to read.
16766   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16767                                    N->getOperand(2));
16768   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16769
16770   // Reads the content of a 64-bit performance counter and returns it in the
16771   // registers EDX:EAX.
16772   if (Subtarget->is64Bit()) {
16773     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16774     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16775                             LO.getValue(2));
16776   } else {
16777     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16778     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16779                             LO.getValue(2));
16780   }
16781   Chain = HI.getValue(1);
16782
16783   if (Subtarget->is64Bit()) {
16784     // The EAX register is loaded with the low-order 32 bits. The EDX register
16785     // is loaded with the supported high-order bits of the counter.
16786     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16787                               DAG.getConstant(32, DL, MVT::i8));
16788     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16789     Results.push_back(Chain);
16790     return;
16791   }
16792
16793   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16794   SDValue Ops[] = { LO, HI };
16795   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16796   Results.push_back(Pair);
16797   Results.push_back(Chain);
16798 }
16799
16800 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16801 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16802 // also used to custom lower READCYCLECOUNTER nodes.
16803 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16804                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16805                               SmallVectorImpl<SDValue> &Results) {
16806   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16807   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16808   SDValue LO, HI;
16809
16810   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16811   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16812   // and the EAX register is loaded with the low-order 32 bits.
16813   if (Subtarget->is64Bit()) {
16814     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16815     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16816                             LO.getValue(2));
16817   } else {
16818     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16819     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16820                             LO.getValue(2));
16821   }
16822   SDValue Chain = HI.getValue(1);
16823
16824   if (Opcode == X86ISD::RDTSCP_DAG) {
16825     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16826
16827     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16828     // the ECX register. Add 'ecx' explicitly to the chain.
16829     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16830                                      HI.getValue(2));
16831     // Explicitly store the content of ECX at the location passed in input
16832     // to the 'rdtscp' intrinsic.
16833     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16834                          MachinePointerInfo(), false, false, 0);
16835   }
16836
16837   if (Subtarget->is64Bit()) {
16838     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16839     // the EAX register is loaded with the low-order 32 bits.
16840     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16841                               DAG.getConstant(32, DL, MVT::i8));
16842     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16843     Results.push_back(Chain);
16844     return;
16845   }
16846
16847   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16848   SDValue Ops[] = { LO, HI };
16849   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16850   Results.push_back(Pair);
16851   Results.push_back(Chain);
16852 }
16853
16854 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16855                                      SelectionDAG &DAG) {
16856   SmallVector<SDValue, 2> Results;
16857   SDLoc DL(Op);
16858   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16859                           Results);
16860   return DAG.getMergeValues(Results, DL);
16861 }
16862
16863 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16864                                     SelectionDAG &DAG) {
16865   MachineFunction &MF = DAG.getMachineFunction();
16866   const Function *Fn = MF.getFunction();
16867   SDLoc dl(Op);
16868   SDValue Chain = Op.getOperand(0);
16869
16870   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16871          "using llvm.x86.seh.restoreframe requires a frame pointer");
16872
16873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16874   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16875
16876   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16877   unsigned FrameReg =
16878       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16879   unsigned SPReg = RegInfo->getStackRegister();
16880   unsigned SlotSize = RegInfo->getSlotSize();
16881
16882   // Get incoming EBP.
16883   SDValue IncomingEBP =
16884       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16885
16886   // SP is saved in the first field of every registration node, so load
16887   // [EBP-RegNodeSize] into SP.
16888   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16889   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16890                                DAG.getConstant(-RegNodeSize, dl, VT));
16891   SDValue NewSP =
16892       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16893                   false, VT.getScalarSizeInBits() / 8);
16894   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16895
16896   if (!RegInfo->needsStackRealignment(MF)) {
16897     // Adjust EBP to point back to the original frame position.
16898     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16899     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16900   } else {
16901     assert(RegInfo->hasBasePointer(MF) &&
16902            "functions with Win32 EH must use frame or base pointer register");
16903
16904     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16905     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16906     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16907
16908     // Reload the spilled EBP value, now that the stack and base pointers are
16909     // set up.
16910     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16911     X86FI->setHasSEHFramePtrSave(true);
16912     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16913     X86FI->setSEHFramePtrSaveIndex(FI);
16914     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16915                                 MachinePointerInfo(), false, false, false,
16916                                 VT.getScalarSizeInBits() / 8);
16917     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16918   }
16919
16920   return Chain;
16921 }
16922
16923 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16924 /// return truncate Store/MaskedStore Node
16925 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16926                                                SelectionDAG &DAG,
16927                                                MVT ElementType) {
16928   SDLoc dl(Op);
16929   SDValue Mask = Op.getOperand(4);
16930   SDValue DataToTruncate = Op.getOperand(3);
16931   SDValue Addr = Op.getOperand(2);
16932   SDValue Chain = Op.getOperand(0);
16933
16934   EVT VT  = DataToTruncate.getValueType();
16935   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16936                              ElementType, VT.getVectorNumElements());
16937
16938   if (isAllOnes(Mask)) // return just a truncate store
16939     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16940                              MachinePointerInfo(), SVT, false, false,
16941                              SVT.getScalarSizeInBits()/8);
16942
16943   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16944                                 MVT::i1, VT.getVectorNumElements());
16945   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16946                                    Mask.getValueType().getSizeInBits());
16947   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16948   // are extracted by EXTRACT_SUBVECTOR.
16949   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16950                               DAG.getBitcast(BitcastVT, Mask),
16951                               DAG.getIntPtrConstant(0, dl));
16952
16953   MachineMemOperand *MMO = DAG.getMachineFunction().
16954     getMachineMemOperand(MachinePointerInfo(),
16955                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16956                          SVT.getScalarSizeInBits()/8);
16957
16958   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16959                             VMask, SVT, MMO, true);
16960 }
16961
16962 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16963                                       SelectionDAG &DAG) {
16964   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16965
16966   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16967   if (!IntrData) {
16968     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16969       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16970     return SDValue();
16971   }
16972
16973   SDLoc dl(Op);
16974   switch(IntrData->Type) {
16975   default:
16976     llvm_unreachable("Unknown Intrinsic Type");
16977     break;
16978   case RDSEED:
16979   case RDRAND: {
16980     // Emit the node with the right value type.
16981     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16982     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16983
16984     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16985     // Otherwise return the value from Rand, which is always 0, casted to i32.
16986     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16987                       DAG.getConstant(1, dl, Op->getValueType(1)),
16988                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16989                       SDValue(Result.getNode(), 1) };
16990     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16991                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16992                                   Ops);
16993
16994     // Return { result, isValid, chain }.
16995     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16996                        SDValue(Result.getNode(), 2));
16997   }
16998   case GATHER: {
16999   //gather(v1, mask, index, base, scale);
17000     SDValue Chain = Op.getOperand(0);
17001     SDValue Src   = Op.getOperand(2);
17002     SDValue Base  = Op.getOperand(3);
17003     SDValue Index = Op.getOperand(4);
17004     SDValue Mask  = Op.getOperand(5);
17005     SDValue Scale = Op.getOperand(6);
17006     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17007                          Chain, Subtarget);
17008   }
17009   case SCATTER: {
17010   //scatter(base, mask, index, v1, scale);
17011     SDValue Chain = Op.getOperand(0);
17012     SDValue Base  = Op.getOperand(2);
17013     SDValue Mask  = Op.getOperand(3);
17014     SDValue Index = Op.getOperand(4);
17015     SDValue Src   = Op.getOperand(5);
17016     SDValue Scale = Op.getOperand(6);
17017     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17018                           Scale, Chain);
17019   }
17020   case PREFETCH: {
17021     SDValue Hint = Op.getOperand(6);
17022     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17023     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17024     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17025     SDValue Chain = Op.getOperand(0);
17026     SDValue Mask  = Op.getOperand(2);
17027     SDValue Index = Op.getOperand(3);
17028     SDValue Base  = Op.getOperand(4);
17029     SDValue Scale = Op.getOperand(5);
17030     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17031   }
17032   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17033   case RDTSC: {
17034     SmallVector<SDValue, 2> Results;
17035     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17036                             Results);
17037     return DAG.getMergeValues(Results, dl);
17038   }
17039   // Read Performance Monitoring Counters.
17040   case RDPMC: {
17041     SmallVector<SDValue, 2> Results;
17042     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17043     return DAG.getMergeValues(Results, dl);
17044   }
17045   // XTEST intrinsics.
17046   case XTEST: {
17047     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17048     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17049     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17050                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17051                                 InTrans);
17052     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17053     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17054                        Ret, SDValue(InTrans.getNode(), 1));
17055   }
17056   // ADC/ADCX/SBB
17057   case ADX: {
17058     SmallVector<SDValue, 2> Results;
17059     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17060     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17061     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17062                                 DAG.getConstant(-1, dl, MVT::i8));
17063     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17064                               Op.getOperand(4), GenCF.getValue(1));
17065     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17066                                  Op.getOperand(5), MachinePointerInfo(),
17067                                  false, false, 0);
17068     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17069                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17070                                 Res.getValue(1));
17071     Results.push_back(SetCC);
17072     Results.push_back(Store);
17073     return DAG.getMergeValues(Results, dl);
17074   }
17075   case COMPRESS_TO_MEM: {
17076     SDLoc dl(Op);
17077     SDValue Mask = Op.getOperand(4);
17078     SDValue DataToCompress = Op.getOperand(3);
17079     SDValue Addr = Op.getOperand(2);
17080     SDValue Chain = Op.getOperand(0);
17081
17082     EVT VT = DataToCompress.getValueType();
17083     if (isAllOnes(Mask)) // return just a store
17084       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17085                           MachinePointerInfo(), false, false,
17086                           VT.getScalarSizeInBits()/8);
17087
17088     SDValue Compressed =
17089       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17090                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17091     return DAG.getStore(Chain, dl, Compressed, Addr,
17092                         MachinePointerInfo(), false, false,
17093                         VT.getScalarSizeInBits()/8);
17094   }
17095   case TRUNCATE_TO_MEM_VI8:
17096     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17097   case TRUNCATE_TO_MEM_VI16:
17098     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17099   case TRUNCATE_TO_MEM_VI32:
17100     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17101   case EXPAND_FROM_MEM: {
17102     SDLoc dl(Op);
17103     SDValue Mask = Op.getOperand(4);
17104     SDValue PassThru = Op.getOperand(3);
17105     SDValue Addr = Op.getOperand(2);
17106     SDValue Chain = Op.getOperand(0);
17107     EVT VT = Op.getValueType();
17108
17109     if (isAllOnes(Mask)) // return just a load
17110       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17111                          false, VT.getScalarSizeInBits()/8);
17112
17113     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17114                                        false, false, false,
17115                                        VT.getScalarSizeInBits()/8);
17116
17117     SDValue Results[] = {
17118       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17119                            Mask, PassThru, Subtarget, DAG), Chain};
17120     return DAG.getMergeValues(Results, dl);
17121   }
17122   }
17123 }
17124
17125 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17126                                            SelectionDAG &DAG) const {
17127   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17128   MFI->setReturnAddressIsTaken(true);
17129
17130   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17131     return SDValue();
17132
17133   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17134   SDLoc dl(Op);
17135   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17136
17137   if (Depth > 0) {
17138     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17139     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17140     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17141     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17142                        DAG.getNode(ISD::ADD, dl, PtrVT,
17143                                    FrameAddr, Offset),
17144                        MachinePointerInfo(), false, false, false, 0);
17145   }
17146
17147   // Just load the return address.
17148   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17149   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17150                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17151 }
17152
17153 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17154   MachineFunction &MF = DAG.getMachineFunction();
17155   MachineFrameInfo *MFI = MF.getFrameInfo();
17156   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17157   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17158   EVT VT = Op.getValueType();
17159
17160   MFI->setFrameAddressIsTaken(true);
17161
17162   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17163     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17164     // is not possible to crawl up the stack without looking at the unwind codes
17165     // simultaneously.
17166     int FrameAddrIndex = FuncInfo->getFAIndex();
17167     if (!FrameAddrIndex) {
17168       // Set up a frame object for the return address.
17169       unsigned SlotSize = RegInfo->getSlotSize();
17170       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17171           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17172       FuncInfo->setFAIndex(FrameAddrIndex);
17173     }
17174     return DAG.getFrameIndex(FrameAddrIndex, VT);
17175   }
17176
17177   unsigned FrameReg =
17178       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17179   SDLoc dl(Op);  // FIXME probably not meaningful
17180   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17181   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17182           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17183          "Invalid Frame Register!");
17184   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17185   while (Depth--)
17186     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17187                             MachinePointerInfo(),
17188                             false, false, false, 0);
17189   return FrameAddr;
17190 }
17191
17192 // FIXME? Maybe this could be a TableGen attribute on some registers and
17193 // this table could be generated automatically from RegInfo.
17194 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17195                                               SelectionDAG &DAG) const {
17196   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17197   const MachineFunction &MF = DAG.getMachineFunction();
17198
17199   unsigned Reg = StringSwitch<unsigned>(RegName)
17200                        .Case("esp", X86::ESP)
17201                        .Case("rsp", X86::RSP)
17202                        .Case("ebp", X86::EBP)
17203                        .Case("rbp", X86::RBP)
17204                        .Default(0);
17205
17206   if (Reg == X86::EBP || Reg == X86::RBP) {
17207     if (!TFI.hasFP(MF))
17208       report_fatal_error("register " + StringRef(RegName) +
17209                          " is allocatable: function has no frame pointer");
17210 #ifndef NDEBUG
17211     else {
17212       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17213       unsigned FrameReg =
17214           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17215       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17216              "Invalid Frame Register!");
17217     }
17218 #endif
17219   }
17220
17221   if (Reg)
17222     return Reg;
17223
17224   report_fatal_error("Invalid register name global variable");
17225 }
17226
17227 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17228                                                      SelectionDAG &DAG) const {
17229   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17230   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17231 }
17232
17233 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17234   SDValue Chain     = Op.getOperand(0);
17235   SDValue Offset    = Op.getOperand(1);
17236   SDValue Handler   = Op.getOperand(2);
17237   SDLoc dl      (Op);
17238
17239   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17240   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17241   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17242   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17243           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17244          "Invalid Frame Register!");
17245   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17246   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17247
17248   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17249                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17250                                                        dl));
17251   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17252   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17253                        false, false, 0);
17254   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17255
17256   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17257                      DAG.getRegister(StoreAddrReg, PtrVT));
17258 }
17259
17260 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17261                                                SelectionDAG &DAG) const {
17262   SDLoc DL(Op);
17263   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17264                      DAG.getVTList(MVT::i32, MVT::Other),
17265                      Op.getOperand(0), Op.getOperand(1));
17266 }
17267
17268 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17269                                                 SelectionDAG &DAG) const {
17270   SDLoc DL(Op);
17271   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17272                      Op.getOperand(0), Op.getOperand(1));
17273 }
17274
17275 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17276   return Op.getOperand(0);
17277 }
17278
17279 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17280                                                 SelectionDAG &DAG) const {
17281   SDValue Root = Op.getOperand(0);
17282   SDValue Trmp = Op.getOperand(1); // trampoline
17283   SDValue FPtr = Op.getOperand(2); // nested function
17284   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17285   SDLoc dl (Op);
17286
17287   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17288   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17289
17290   if (Subtarget->is64Bit()) {
17291     SDValue OutChains[6];
17292
17293     // Large code-model.
17294     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17295     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17296
17297     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17298     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17299
17300     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17301
17302     // Load the pointer to the nested function into R11.
17303     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17304     SDValue Addr = Trmp;
17305     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17306                                 Addr, MachinePointerInfo(TrmpAddr),
17307                                 false, false, 0);
17308
17309     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17310                        DAG.getConstant(2, dl, MVT::i64));
17311     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17312                                 MachinePointerInfo(TrmpAddr, 2),
17313                                 false, false, 2);
17314
17315     // Load the 'nest' parameter value into R10.
17316     // R10 is specified in X86CallingConv.td
17317     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17318     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17319                        DAG.getConstant(10, dl, MVT::i64));
17320     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17321                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17322                                 false, false, 0);
17323
17324     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17325                        DAG.getConstant(12, dl, MVT::i64));
17326     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17327                                 MachinePointerInfo(TrmpAddr, 12),
17328                                 false, false, 2);
17329
17330     // Jump to the nested function.
17331     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17332     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17333                        DAG.getConstant(20, dl, MVT::i64));
17334     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17335                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17336                                 false, false, 0);
17337
17338     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17339     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17340                        DAG.getConstant(22, dl, MVT::i64));
17341     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17342                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17343                                 false, false, 0);
17344
17345     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17346   } else {
17347     const Function *Func =
17348       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17349     CallingConv::ID CC = Func->getCallingConv();
17350     unsigned NestReg;
17351
17352     switch (CC) {
17353     default:
17354       llvm_unreachable("Unsupported calling convention");
17355     case CallingConv::C:
17356     case CallingConv::X86_StdCall: {
17357       // Pass 'nest' parameter in ECX.
17358       // Must be kept in sync with X86CallingConv.td
17359       NestReg = X86::ECX;
17360
17361       // Check that ECX wasn't needed by an 'inreg' parameter.
17362       FunctionType *FTy = Func->getFunctionType();
17363       const AttributeSet &Attrs = Func->getAttributes();
17364
17365       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17366         unsigned InRegCount = 0;
17367         unsigned Idx = 1;
17368
17369         for (FunctionType::param_iterator I = FTy->param_begin(),
17370              E = FTy->param_end(); I != E; ++I, ++Idx)
17371           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17372             auto &DL = DAG.getDataLayout();
17373             // FIXME: should only count parameters that are lowered to integers.
17374             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17375           }
17376
17377         if (InRegCount > 2) {
17378           report_fatal_error("Nest register in use - reduce number of inreg"
17379                              " parameters!");
17380         }
17381       }
17382       break;
17383     }
17384     case CallingConv::X86_FastCall:
17385     case CallingConv::X86_ThisCall:
17386     case CallingConv::Fast:
17387       // Pass 'nest' parameter in EAX.
17388       // Must be kept in sync with X86CallingConv.td
17389       NestReg = X86::EAX;
17390       break;
17391     }
17392
17393     SDValue OutChains[4];
17394     SDValue Addr, Disp;
17395
17396     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17397                        DAG.getConstant(10, dl, MVT::i32));
17398     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17399
17400     // This is storing the opcode for MOV32ri.
17401     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17402     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17403     OutChains[0] = DAG.getStore(Root, dl,
17404                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17405                                 Trmp, MachinePointerInfo(TrmpAddr),
17406                                 false, false, 0);
17407
17408     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17409                        DAG.getConstant(1, dl, MVT::i32));
17410     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17411                                 MachinePointerInfo(TrmpAddr, 1),
17412                                 false, false, 1);
17413
17414     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17415     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17416                        DAG.getConstant(5, dl, MVT::i32));
17417     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17418                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17419                                 false, false, 1);
17420
17421     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17422                        DAG.getConstant(6, dl, MVT::i32));
17423     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17424                                 MachinePointerInfo(TrmpAddr, 6),
17425                                 false, false, 1);
17426
17427     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17428   }
17429 }
17430
17431 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17432                                             SelectionDAG &DAG) const {
17433   /*
17434    The rounding mode is in bits 11:10 of FPSR, and has the following
17435    settings:
17436      00 Round to nearest
17437      01 Round to -inf
17438      10 Round to +inf
17439      11 Round to 0
17440
17441   FLT_ROUNDS, on the other hand, expects the following:
17442     -1 Undefined
17443      0 Round to 0
17444      1 Round to nearest
17445      2 Round to +inf
17446      3 Round to -inf
17447
17448   To perform the conversion, we do:
17449     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17450   */
17451
17452   MachineFunction &MF = DAG.getMachineFunction();
17453   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17454   unsigned StackAlignment = TFI.getStackAlignment();
17455   MVT VT = Op.getSimpleValueType();
17456   SDLoc DL(Op);
17457
17458   // Save FP Control Word to stack slot
17459   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17460   SDValue StackSlot =
17461       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17462
17463   MachineMemOperand *MMO =
17464       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17465                               MachineMemOperand::MOStore, 2, 2);
17466
17467   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17468   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17469                                           DAG.getVTList(MVT::Other),
17470                                           Ops, MVT::i16, MMO);
17471
17472   // Load FP Control Word from stack slot
17473   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17474                             MachinePointerInfo(), false, false, false, 0);
17475
17476   // Transform as necessary
17477   SDValue CWD1 =
17478     DAG.getNode(ISD::SRL, DL, MVT::i16,
17479                 DAG.getNode(ISD::AND, DL, MVT::i16,
17480                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17481                 DAG.getConstant(11, DL, MVT::i8));
17482   SDValue CWD2 =
17483     DAG.getNode(ISD::SRL, DL, MVT::i16,
17484                 DAG.getNode(ISD::AND, DL, MVT::i16,
17485                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17486                 DAG.getConstant(9, DL, MVT::i8));
17487
17488   SDValue RetVal =
17489     DAG.getNode(ISD::AND, DL, MVT::i16,
17490                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17491                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17492                             DAG.getConstant(1, DL, MVT::i16)),
17493                 DAG.getConstant(3, DL, MVT::i16));
17494
17495   return DAG.getNode((VT.getSizeInBits() < 16 ?
17496                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17497 }
17498
17499 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17500 //
17501 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17502 //    to 512-bit vector.
17503 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17504 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17505 //    split the vector, perform operation on it's Lo a Hi part and
17506 //    concatenate the results.
17507 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17508   SDLoc dl(Op);
17509   MVT VT = Op.getSimpleValueType();
17510   MVT EltVT = VT.getVectorElementType();
17511   unsigned NumElems = VT.getVectorNumElements();
17512
17513   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17514     // Extend to 512 bit vector.
17515     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17516               "Unsupported value type for operation");
17517
17518     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17519     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17520                                  DAG.getUNDEF(NewVT),
17521                                  Op.getOperand(0),
17522                                  DAG.getIntPtrConstant(0, dl));
17523     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17524
17525     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17526                        DAG.getIntPtrConstant(0, dl));
17527   }
17528
17529   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17530           "Unsupported element type");
17531
17532   if (16 < NumElems) {
17533     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17534     SDValue Lo, Hi;
17535     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17536     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17537
17538     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17539     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17540
17541     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17542   }
17543
17544   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17545
17546   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17547           "Unsupported value type for operation");
17548
17549   // Use native supported vector instruction vplzcntd.
17550   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17551   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17552   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17553   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17554
17555   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17556 }
17557
17558 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17559                          SelectionDAG &DAG) {
17560   MVT VT = Op.getSimpleValueType();
17561   EVT OpVT = VT;
17562   unsigned NumBits = VT.getSizeInBits();
17563   SDLoc dl(Op);
17564
17565   if (VT.isVector() && Subtarget->hasAVX512())
17566     return LowerVectorCTLZ_AVX512(Op, DAG);
17567
17568   Op = Op.getOperand(0);
17569   if (VT == MVT::i8) {
17570     // Zero extend to i32 since there is not an i8 bsr.
17571     OpVT = MVT::i32;
17572     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17573   }
17574
17575   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17576   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17577   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17578
17579   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17580   SDValue Ops[] = {
17581     Op,
17582     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17583     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17584     Op.getValue(1)
17585   };
17586   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17587
17588   // Finally xor with NumBits-1.
17589   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17590                    DAG.getConstant(NumBits - 1, dl, OpVT));
17591
17592   if (VT == MVT::i8)
17593     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17594   return Op;
17595 }
17596
17597 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17598                                     SelectionDAG &DAG) {
17599   MVT VT = Op.getSimpleValueType();
17600   EVT OpVT = VT;
17601   unsigned NumBits = VT.getSizeInBits();
17602   SDLoc dl(Op);
17603
17604   if (VT.isVector() && Subtarget->hasAVX512())
17605     return LowerVectorCTLZ_AVX512(Op, DAG);
17606
17607   Op = Op.getOperand(0);
17608   if (VT == MVT::i8) {
17609     // Zero extend to i32 since there is not an i8 bsr.
17610     OpVT = MVT::i32;
17611     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17612   }
17613
17614   // Issue a bsr (scan bits in reverse).
17615   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17616   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17617
17618   // And xor with NumBits-1.
17619   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17620                    DAG.getConstant(NumBits - 1, dl, OpVT));
17621
17622   if (VT == MVT::i8)
17623     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17624   return Op;
17625 }
17626
17627 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17628   MVT VT = Op.getSimpleValueType();
17629   unsigned NumBits = VT.getScalarSizeInBits();
17630   SDLoc dl(Op);
17631
17632   if (VT.isVector()) {
17633     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17634
17635     SDValue N0 = Op.getOperand(0);
17636     SDValue Zero = DAG.getConstant(0, dl, VT);
17637
17638     // lsb(x) = (x & -x)
17639     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17640                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17641
17642     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17643     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17644         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17645       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17646       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17647                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17648     }
17649
17650     // cttz(x) = ctpop(lsb - 1)
17651     SDValue One = DAG.getConstant(1, dl, VT);
17652     return DAG.getNode(ISD::CTPOP, dl, VT,
17653                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17654   }
17655
17656   assert(Op.getOpcode() == ISD::CTTZ &&
17657          "Only scalar CTTZ requires custom lowering");
17658
17659   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17660   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17661   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17662
17663   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17664   SDValue Ops[] = {
17665     Op,
17666     DAG.getConstant(NumBits, dl, VT),
17667     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17668     Op.getValue(1)
17669   };
17670   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17671 }
17672
17673 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17674 // ones, and then concatenate the result back.
17675 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17676   MVT VT = Op.getSimpleValueType();
17677
17678   assert(VT.is256BitVector() && VT.isInteger() &&
17679          "Unsupported value type for operation");
17680
17681   unsigned NumElems = VT.getVectorNumElements();
17682   SDLoc dl(Op);
17683
17684   // Extract the LHS vectors
17685   SDValue LHS = Op.getOperand(0);
17686   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17687   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17688
17689   // Extract the RHS vectors
17690   SDValue RHS = Op.getOperand(1);
17691   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17692   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17693
17694   MVT EltVT = VT.getVectorElementType();
17695   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17696
17697   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17698                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17699                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17700 }
17701
17702 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17703   if (Op.getValueType() == MVT::i1)
17704     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17705                        Op.getOperand(0), Op.getOperand(1));
17706   assert(Op.getSimpleValueType().is256BitVector() &&
17707          Op.getSimpleValueType().isInteger() &&
17708          "Only handle AVX 256-bit vector integer operation");
17709   return Lower256IntArith(Op, DAG);
17710 }
17711
17712 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17713   if (Op.getValueType() == MVT::i1)
17714     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17715                        Op.getOperand(0), Op.getOperand(1));
17716   assert(Op.getSimpleValueType().is256BitVector() &&
17717          Op.getSimpleValueType().isInteger() &&
17718          "Only handle AVX 256-bit vector integer operation");
17719   return Lower256IntArith(Op, DAG);
17720 }
17721
17722 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17723   assert(Op.getSimpleValueType().is256BitVector() &&
17724          Op.getSimpleValueType().isInteger() &&
17725          "Only handle AVX 256-bit vector integer operation");
17726   return Lower256IntArith(Op, DAG);
17727 }
17728
17729 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17730                         SelectionDAG &DAG) {
17731   SDLoc dl(Op);
17732   MVT VT = Op.getSimpleValueType();
17733
17734   if (VT == MVT::i1)
17735     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17736
17737   // Decompose 256-bit ops into smaller 128-bit ops.
17738   if (VT.is256BitVector() && !Subtarget->hasInt256())
17739     return Lower256IntArith(Op, DAG);
17740
17741   SDValue A = Op.getOperand(0);
17742   SDValue B = Op.getOperand(1);
17743
17744   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17745   // pairs, multiply and truncate.
17746   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17747     if (Subtarget->hasInt256()) {
17748       if (VT == MVT::v32i8) {
17749         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17750         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17751         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17752         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17753         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17754         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17755         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17756         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17757                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17758                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17759       }
17760
17761       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17762       return DAG.getNode(
17763           ISD::TRUNCATE, dl, VT,
17764           DAG.getNode(ISD::MUL, dl, ExVT,
17765                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17766                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17767     }
17768
17769     assert(VT == MVT::v16i8 &&
17770            "Pre-AVX2 support only supports v16i8 multiplication");
17771     MVT ExVT = MVT::v8i16;
17772
17773     // Extract the lo parts and sign extend to i16
17774     SDValue ALo, BLo;
17775     if (Subtarget->hasSSE41()) {
17776       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17777       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17778     } else {
17779       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17780                               -1, 4, -1, 5, -1, 6, -1, 7};
17781       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17782       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17783       ALo = DAG.getBitcast(ExVT, ALo);
17784       BLo = DAG.getBitcast(ExVT, BLo);
17785       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17786       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17787     }
17788
17789     // Extract the hi parts and sign extend to i16
17790     SDValue AHi, BHi;
17791     if (Subtarget->hasSSE41()) {
17792       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17793                               -1, -1, -1, -1, -1, -1, -1, -1};
17794       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17795       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17796       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17797       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17798     } else {
17799       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17800                               -1, 12, -1, 13, -1, 14, -1, 15};
17801       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17802       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17803       AHi = DAG.getBitcast(ExVT, AHi);
17804       BHi = DAG.getBitcast(ExVT, BHi);
17805       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17806       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17807     }
17808
17809     // Multiply, mask the lower 8bits of the lo/hi results and pack
17810     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17811     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17812     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17813     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17814     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17815   }
17816
17817   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17818   if (VT == MVT::v4i32) {
17819     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17820            "Should not custom lower when pmuldq is available!");
17821
17822     // Extract the odd parts.
17823     static const int UnpackMask[] = { 1, -1, 3, -1 };
17824     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17825     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17826
17827     // Multiply the even parts.
17828     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17829     // Now multiply odd parts.
17830     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17831
17832     Evens = DAG.getBitcast(VT, Evens);
17833     Odds = DAG.getBitcast(VT, Odds);
17834
17835     // Merge the two vectors back together with a shuffle. This expands into 2
17836     // shuffles.
17837     static const int ShufMask[] = { 0, 4, 2, 6 };
17838     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17839   }
17840
17841   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17842          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17843
17844   //  Ahi = psrlqi(a, 32);
17845   //  Bhi = psrlqi(b, 32);
17846   //
17847   //  AloBlo = pmuludq(a, b);
17848   //  AloBhi = pmuludq(a, Bhi);
17849   //  AhiBlo = pmuludq(Ahi, b);
17850
17851   //  AloBhi = psllqi(AloBhi, 32);
17852   //  AhiBlo = psllqi(AhiBlo, 32);
17853   //  return AloBlo + AloBhi + AhiBlo;
17854
17855   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17856   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17857
17858   SDValue AhiBlo = Ahi;
17859   SDValue AloBhi = Bhi;
17860   // Bit cast to 32-bit vectors for MULUDQ
17861   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17862                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17863   A = DAG.getBitcast(MulVT, A);
17864   B = DAG.getBitcast(MulVT, B);
17865   Ahi = DAG.getBitcast(MulVT, Ahi);
17866   Bhi = DAG.getBitcast(MulVT, Bhi);
17867
17868   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17869   // After shifting right const values the result may be all-zero.
17870   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17871     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17872     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17873   }
17874   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17875     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17876     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17877   }
17878
17879   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17880   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17881 }
17882
17883 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17884   assert(Subtarget->isTargetWin64() && "Unexpected target");
17885   EVT VT = Op.getValueType();
17886   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17887          "Unexpected return type for lowering");
17888
17889   RTLIB::Libcall LC;
17890   bool isSigned;
17891   switch (Op->getOpcode()) {
17892   default: llvm_unreachable("Unexpected request for libcall!");
17893   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17894   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17895   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17896   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17897   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17898   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17899   }
17900
17901   SDLoc dl(Op);
17902   SDValue InChain = DAG.getEntryNode();
17903
17904   TargetLowering::ArgListTy Args;
17905   TargetLowering::ArgListEntry Entry;
17906   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17907     EVT ArgVT = Op->getOperand(i).getValueType();
17908     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17909            "Unexpected argument type for lowering");
17910     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17911     Entry.Node = StackPtr;
17912     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17913                            false, false, 16);
17914     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17915     Entry.Ty = PointerType::get(ArgTy,0);
17916     Entry.isSExt = false;
17917     Entry.isZExt = false;
17918     Args.push_back(Entry);
17919   }
17920
17921   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17922                                          getPointerTy(DAG.getDataLayout()));
17923
17924   TargetLowering::CallLoweringInfo CLI(DAG);
17925   CLI.setDebugLoc(dl).setChain(InChain)
17926     .setCallee(getLibcallCallingConv(LC),
17927                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17928                Callee, std::move(Args), 0)
17929     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17930
17931   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17932   return DAG.getBitcast(VT, CallInfo.first);
17933 }
17934
17935 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17936                              SelectionDAG &DAG) {
17937   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17938   EVT VT = Op0.getValueType();
17939   SDLoc dl(Op);
17940
17941   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17942          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17943
17944   // PMULxD operations multiply each even value (starting at 0) of LHS with
17945   // the related value of RHS and produce a widen result.
17946   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17947   // => <2 x i64> <ae|cg>
17948   //
17949   // In other word, to have all the results, we need to perform two PMULxD:
17950   // 1. one with the even values.
17951   // 2. one with the odd values.
17952   // To achieve #2, with need to place the odd values at an even position.
17953   //
17954   // Place the odd value at an even position (basically, shift all values 1
17955   // step to the left):
17956   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17957   // <a|b|c|d> => <b|undef|d|undef>
17958   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17959   // <e|f|g|h> => <f|undef|h|undef>
17960   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17961
17962   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17963   // ints.
17964   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17965   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17966   unsigned Opcode =
17967       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17968   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17969   // => <2 x i64> <ae|cg>
17970   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17971   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17972   // => <2 x i64> <bf|dh>
17973   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17974
17975   // Shuffle it back into the right order.
17976   SDValue Highs, Lows;
17977   if (VT == MVT::v8i32) {
17978     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17979     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17980     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17981     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17982   } else {
17983     const int HighMask[] = {1, 5, 3, 7};
17984     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17985     const int LowMask[] = {0, 4, 2, 6};
17986     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17987   }
17988
17989   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17990   // unsigned multiply.
17991   if (IsSigned && !Subtarget->hasSSE41()) {
17992     SDValue ShAmt = DAG.getConstant(
17993         31, dl,
17994         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17995     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17996                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17997     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17998                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17999
18000     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18001     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18002   }
18003
18004   // The first result of MUL_LOHI is actually the low value, followed by the
18005   // high value.
18006   SDValue Ops[] = {Lows, Highs};
18007   return DAG.getMergeValues(Ops, dl);
18008 }
18009
18010 // Return true if the required (according to Opcode) shift-imm form is natively
18011 // supported by the Subtarget
18012 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18013                                         unsigned Opcode) {
18014   if (VT.getScalarSizeInBits() < 16)
18015     return false;
18016
18017   if (VT.is512BitVector() &&
18018       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18019     return true;
18020
18021   bool LShift = VT.is128BitVector() ||
18022     (VT.is256BitVector() && Subtarget->hasInt256());
18023
18024   bool AShift = LShift && (Subtarget->hasVLX() ||
18025     (VT != MVT::v2i64 && VT != MVT::v4i64));
18026   return (Opcode == ISD::SRA) ? AShift : LShift;
18027 }
18028
18029 // The shift amount is a variable, but it is the same for all vector lanes.
18030 // These instructions are defined together with shift-immediate.
18031 static
18032 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18033                                       unsigned Opcode) {
18034   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18035 }
18036
18037 // Return true if the required (according to Opcode) variable-shift form is
18038 // natively supported by the Subtarget
18039 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18040                                     unsigned Opcode) {
18041
18042   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18043     return false;
18044
18045   // vXi16 supported only on AVX-512, BWI
18046   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18047     return false;
18048
18049   if (VT.is512BitVector() || Subtarget->hasVLX())
18050     return true;
18051
18052   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18053   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18054   return (Opcode == ISD::SRA) ? AShift : LShift;
18055 }
18056
18057 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18058                                          const X86Subtarget *Subtarget) {
18059   MVT VT = Op.getSimpleValueType();
18060   SDLoc dl(Op);
18061   SDValue R = Op.getOperand(0);
18062   SDValue Amt = Op.getOperand(1);
18063
18064   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18065     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18066
18067   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18068     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18069     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18070     SDValue Ex = DAG.getBitcast(ExVT, R);
18071
18072     if (ShiftAmt >= 32) {
18073       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18074       SDValue Upper =
18075           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18076       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18077                                                  ShiftAmt - 32, DAG);
18078       if (VT == MVT::v2i64)
18079         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18080       if (VT == MVT::v4i64)
18081         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18082                                   {9, 1, 11, 3, 13, 5, 15, 7});
18083     } else {
18084       // SRA upper i32, SHL whole i64 and select lower i32.
18085       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18086                                                  ShiftAmt, DAG);
18087       SDValue Lower =
18088           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18089       Lower = DAG.getBitcast(ExVT, Lower);
18090       if (VT == MVT::v2i64)
18091         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18092       if (VT == MVT::v4i64)
18093         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18094                                   {8, 1, 10, 3, 12, 5, 14, 7});
18095     }
18096     return DAG.getBitcast(VT, Ex);
18097   };
18098
18099   // Optimize shl/srl/sra with constant shift amount.
18100   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18101     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18102       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18103
18104       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18105         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18106
18107       // i64 SRA needs to be performed as partial shifts.
18108       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18109           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18110         return ArithmeticShiftRight64(ShiftAmt);
18111
18112       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18113         unsigned NumElts = VT.getVectorNumElements();
18114         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18115
18116         // Simple i8 add case
18117         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18118           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18119
18120         // ashr(R, 7)  === cmp_slt(R, 0)
18121         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18122           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18123           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18124         }
18125
18126         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18127         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18128           return SDValue();
18129
18130         if (Op.getOpcode() == ISD::SHL) {
18131           // Make a large shift.
18132           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18133                                                    R, ShiftAmt, DAG);
18134           SHL = DAG.getBitcast(VT, SHL);
18135           // Zero out the rightmost bits.
18136           SmallVector<SDValue, 32> V(
18137               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18138           return DAG.getNode(ISD::AND, dl, VT, SHL,
18139                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18140         }
18141         if (Op.getOpcode() == ISD::SRL) {
18142           // Make a large shift.
18143           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18144                                                    R, ShiftAmt, DAG);
18145           SRL = DAG.getBitcast(VT, SRL);
18146           // Zero out the leftmost bits.
18147           SmallVector<SDValue, 32> V(
18148               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18149           return DAG.getNode(ISD::AND, dl, VT, SRL,
18150                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18151         }
18152         if (Op.getOpcode() == ISD::SRA) {
18153           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18154           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18155           SmallVector<SDValue, 32> V(NumElts,
18156                                      DAG.getConstant(128 >> ShiftAmt, dl,
18157                                                      MVT::i8));
18158           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18159           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18160           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18161           return Res;
18162         }
18163         llvm_unreachable("Unknown shift opcode.");
18164       }
18165     }
18166   }
18167
18168   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18169   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18170       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18171
18172     // Peek through any splat that was introduced for i64 shift vectorization.
18173     int SplatIndex = -1;
18174     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18175       if (SVN->isSplat()) {
18176         SplatIndex = SVN->getSplatIndex();
18177         Amt = Amt.getOperand(0);
18178         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18179                "Splat shuffle referencing second operand");
18180       }
18181
18182     if (Amt.getOpcode() != ISD::BITCAST ||
18183         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18184       return SDValue();
18185
18186     Amt = Amt.getOperand(0);
18187     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18188                      VT.getVectorNumElements();
18189     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18190     uint64_t ShiftAmt = 0;
18191     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18192     for (unsigned i = 0; i != Ratio; ++i) {
18193       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18194       if (!C)
18195         return SDValue();
18196       // 6 == Log2(64)
18197       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18198     }
18199
18200     // Check remaining shift amounts (if not a splat).
18201     if (SplatIndex < 0) {
18202       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18203         uint64_t ShAmt = 0;
18204         for (unsigned j = 0; j != Ratio; ++j) {
18205           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18206           if (!C)
18207             return SDValue();
18208           // 6 == Log2(64)
18209           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18210         }
18211         if (ShAmt != ShiftAmt)
18212           return SDValue();
18213       }
18214     }
18215
18216     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18217       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18218
18219     if (Op.getOpcode() == ISD::SRA)
18220       return ArithmeticShiftRight64(ShiftAmt);
18221   }
18222
18223   return SDValue();
18224 }
18225
18226 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18227                                         const X86Subtarget* Subtarget) {
18228   MVT VT = Op.getSimpleValueType();
18229   SDLoc dl(Op);
18230   SDValue R = Op.getOperand(0);
18231   SDValue Amt = Op.getOperand(1);
18232
18233   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18234     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18235
18236   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18237     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18238
18239   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18240     SDValue BaseShAmt;
18241     EVT EltVT = VT.getVectorElementType();
18242
18243     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18244       // Check if this build_vector node is doing a splat.
18245       // If so, then set BaseShAmt equal to the splat value.
18246       BaseShAmt = BV->getSplatValue();
18247       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18248         BaseShAmt = SDValue();
18249     } else {
18250       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18251         Amt = Amt.getOperand(0);
18252
18253       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18254       if (SVN && SVN->isSplat()) {
18255         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18256         SDValue InVec = Amt.getOperand(0);
18257         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18258           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18259                  "Unexpected shuffle index found!");
18260           BaseShAmt = InVec.getOperand(SplatIdx);
18261         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18262            if (ConstantSDNode *C =
18263                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18264              if (C->getZExtValue() == SplatIdx)
18265                BaseShAmt = InVec.getOperand(1);
18266            }
18267         }
18268
18269         if (!BaseShAmt)
18270           // Avoid introducing an extract element from a shuffle.
18271           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18272                                   DAG.getIntPtrConstant(SplatIdx, dl));
18273       }
18274     }
18275
18276     if (BaseShAmt.getNode()) {
18277       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18278       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18279         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18280       else if (EltVT.bitsLT(MVT::i32))
18281         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18282
18283       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18284     }
18285   }
18286
18287   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18288   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18289       Amt.getOpcode() == ISD::BITCAST &&
18290       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18291     Amt = Amt.getOperand(0);
18292     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18293                      VT.getVectorNumElements();
18294     std::vector<SDValue> Vals(Ratio);
18295     for (unsigned i = 0; i != Ratio; ++i)
18296       Vals[i] = Amt.getOperand(i);
18297     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18298       for (unsigned j = 0; j != Ratio; ++j)
18299         if (Vals[j] != Amt.getOperand(i + j))
18300           return SDValue();
18301     }
18302
18303     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18304       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18305   }
18306   return SDValue();
18307 }
18308
18309 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18310                           SelectionDAG &DAG) {
18311   MVT VT = Op.getSimpleValueType();
18312   SDLoc dl(Op);
18313   SDValue R = Op.getOperand(0);
18314   SDValue Amt = Op.getOperand(1);
18315
18316   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18317   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18318
18319   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18320     return V;
18321
18322   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18323     return V;
18324
18325   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18326     return Op;
18327
18328   // XOP has 128-bit variable logical/arithmetic shifts.
18329   // +ve/-ve Amt = shift left/right.
18330   if (Subtarget->hasXOP() &&
18331       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18332        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18333     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18334       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18335       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18336     }
18337     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18338       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18339     if (Op.getOpcode() == ISD::SRA)
18340       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18341   }
18342
18343   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18344   // shifts per-lane and then shuffle the partial results back together.
18345   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18346     // Splat the shift amounts so the scalar shifts above will catch it.
18347     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18348     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18349     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18350     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18351     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18352   }
18353
18354   // i64 vector arithmetic shift can be emulated with the transform:
18355   // M = lshr(SIGN_BIT, Amt)
18356   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18357   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18358       Op.getOpcode() == ISD::SRA) {
18359     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18360     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18361     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18362     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18363     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18364     return R;
18365   }
18366
18367   // If possible, lower this packed shift into a vector multiply instead of
18368   // expanding it into a sequence of scalar shifts.
18369   // Do this only if the vector shift count is a constant build_vector.
18370   if (Op.getOpcode() == ISD::SHL &&
18371       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18372        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18373       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18374     SmallVector<SDValue, 8> Elts;
18375     EVT SVT = VT.getScalarType();
18376     unsigned SVTBits = SVT.getSizeInBits();
18377     const APInt &One = APInt(SVTBits, 1);
18378     unsigned NumElems = VT.getVectorNumElements();
18379
18380     for (unsigned i=0; i !=NumElems; ++i) {
18381       SDValue Op = Amt->getOperand(i);
18382       if (Op->getOpcode() == ISD::UNDEF) {
18383         Elts.push_back(Op);
18384         continue;
18385       }
18386
18387       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18388       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18389       uint64_t ShAmt = C.getZExtValue();
18390       if (ShAmt >= SVTBits) {
18391         Elts.push_back(DAG.getUNDEF(SVT));
18392         continue;
18393       }
18394       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18395     }
18396     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18397     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18398   }
18399
18400   // Lower SHL with variable shift amount.
18401   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18402     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18403
18404     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18405                      DAG.getConstant(0x3f800000U, dl, VT));
18406     Op = DAG.getBitcast(MVT::v4f32, Op);
18407     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18408     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18409   }
18410
18411   // If possible, lower this shift as a sequence of two shifts by
18412   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18413   // Example:
18414   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18415   //
18416   // Could be rewritten as:
18417   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18418   //
18419   // The advantage is that the two shifts from the example would be
18420   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18421   // the vector shift into four scalar shifts plus four pairs of vector
18422   // insert/extract.
18423   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18424       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18425     unsigned TargetOpcode = X86ISD::MOVSS;
18426     bool CanBeSimplified;
18427     // The splat value for the first packed shift (the 'X' from the example).
18428     SDValue Amt1 = Amt->getOperand(0);
18429     // The splat value for the second packed shift (the 'Y' from the example).
18430     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18431                                         Amt->getOperand(2);
18432
18433     // See if it is possible to replace this node with a sequence of
18434     // two shifts followed by a MOVSS/MOVSD
18435     if (VT == MVT::v4i32) {
18436       // Check if it is legal to use a MOVSS.
18437       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18438                         Amt2 == Amt->getOperand(3);
18439       if (!CanBeSimplified) {
18440         // Otherwise, check if we can still simplify this node using a MOVSD.
18441         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18442                           Amt->getOperand(2) == Amt->getOperand(3);
18443         TargetOpcode = X86ISD::MOVSD;
18444         Amt2 = Amt->getOperand(2);
18445       }
18446     } else {
18447       // Do similar checks for the case where the machine value type
18448       // is MVT::v8i16.
18449       CanBeSimplified = Amt1 == Amt->getOperand(1);
18450       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18451         CanBeSimplified = Amt2 == Amt->getOperand(i);
18452
18453       if (!CanBeSimplified) {
18454         TargetOpcode = X86ISD::MOVSD;
18455         CanBeSimplified = true;
18456         Amt2 = Amt->getOperand(4);
18457         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18458           CanBeSimplified = Amt1 == Amt->getOperand(i);
18459         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18460           CanBeSimplified = Amt2 == Amt->getOperand(j);
18461       }
18462     }
18463
18464     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18465         isa<ConstantSDNode>(Amt2)) {
18466       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18467       EVT CastVT = MVT::v4i32;
18468       SDValue Splat1 =
18469         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18470       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18471       SDValue Splat2 =
18472         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18473       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18474       if (TargetOpcode == X86ISD::MOVSD)
18475         CastVT = MVT::v2i64;
18476       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18477       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18478       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18479                                             BitCast1, DAG);
18480       return DAG.getBitcast(VT, Result);
18481     }
18482   }
18483
18484   // v4i32 Non Uniform Shifts.
18485   // If the shift amount is constant we can shift each lane using the SSE2
18486   // immediate shifts, else we need to zero-extend each lane to the lower i64
18487   // and shift using the SSE2 variable shifts.
18488   // The separate results can then be blended together.
18489   if (VT == MVT::v4i32) {
18490     unsigned Opc = Op.getOpcode();
18491     SDValue Amt0, Amt1, Amt2, Amt3;
18492     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18493       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18494       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18495       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18496       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18497     } else {
18498       // ISD::SHL is handled above but we include it here for completeness.
18499       switch (Opc) {
18500       default:
18501         llvm_unreachable("Unknown target vector shift node");
18502       case ISD::SHL:
18503         Opc = X86ISD::VSHL;
18504         break;
18505       case ISD::SRL:
18506         Opc = X86ISD::VSRL;
18507         break;
18508       case ISD::SRA:
18509         Opc = X86ISD::VSRA;
18510         break;
18511       }
18512       // The SSE2 shifts use the lower i64 as the same shift amount for
18513       // all lanes and the upper i64 is ignored. These shuffle masks
18514       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18515       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18516       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18517       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18518       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18519       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18520     }
18521
18522     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18523     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18524     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18525     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18526     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18527     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18528     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18529   }
18530
18531   if (VT == MVT::v16i8 ||
18532       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18533     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18534     unsigned ShiftOpcode = Op->getOpcode();
18535
18536     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18537       // On SSE41 targets we make use of the fact that VSELECT lowers
18538       // to PBLENDVB which selects bytes based just on the sign bit.
18539       if (Subtarget->hasSSE41()) {
18540         V0 = DAG.getBitcast(VT, V0);
18541         V1 = DAG.getBitcast(VT, V1);
18542         Sel = DAG.getBitcast(VT, Sel);
18543         return DAG.getBitcast(SelVT,
18544                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18545       }
18546       // On pre-SSE41 targets we test for the sign bit by comparing to
18547       // zero - a negative value will set all bits of the lanes to true
18548       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18549       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18550       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18551       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18552     };
18553
18554     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18555     // We can safely do this using i16 shifts as we're only interested in
18556     // the 3 lower bits of each byte.
18557     Amt = DAG.getBitcast(ExtVT, Amt);
18558     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18559     Amt = DAG.getBitcast(VT, Amt);
18560
18561     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18562       // r = VSELECT(r, shift(r, 4), a);
18563       SDValue M =
18564           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18565       R = SignBitSelect(VT, Amt, M, R);
18566
18567       // a += a
18568       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18569
18570       // r = VSELECT(r, shift(r, 2), a);
18571       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18572       R = SignBitSelect(VT, Amt, M, R);
18573
18574       // a += a
18575       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18576
18577       // return VSELECT(r, shift(r, 1), a);
18578       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18579       R = SignBitSelect(VT, Amt, M, R);
18580       return R;
18581     }
18582
18583     if (Op->getOpcode() == ISD::SRA) {
18584       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18585       // so we can correctly sign extend. We don't care what happens to the
18586       // lower byte.
18587       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18588       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18589       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18590       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18591       ALo = DAG.getBitcast(ExtVT, ALo);
18592       AHi = DAG.getBitcast(ExtVT, AHi);
18593       RLo = DAG.getBitcast(ExtVT, RLo);
18594       RHi = DAG.getBitcast(ExtVT, RHi);
18595
18596       // r = VSELECT(r, shift(r, 4), a);
18597       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18598                                 DAG.getConstant(4, dl, ExtVT));
18599       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18600                                 DAG.getConstant(4, dl, ExtVT));
18601       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18602       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18603
18604       // a += a
18605       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18606       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18607
18608       // r = VSELECT(r, shift(r, 2), a);
18609       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18610                         DAG.getConstant(2, dl, ExtVT));
18611       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18612                         DAG.getConstant(2, dl, ExtVT));
18613       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18614       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18615
18616       // a += a
18617       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18618       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18619
18620       // r = VSELECT(r, shift(r, 1), a);
18621       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18622                         DAG.getConstant(1, dl, ExtVT));
18623       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18624                         DAG.getConstant(1, dl, ExtVT));
18625       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18626       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18627
18628       // Logical shift the result back to the lower byte, leaving a zero upper
18629       // byte
18630       // meaning that we can safely pack with PACKUSWB.
18631       RLo =
18632           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18633       RHi =
18634           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18635       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18636     }
18637   }
18638
18639   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18640   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18641   // solution better.
18642   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18643     MVT ExtVT = MVT::v8i32;
18644     unsigned ExtOpc =
18645         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18646     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18647     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18648     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18649                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18650   }
18651
18652   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18653     MVT ExtVT = MVT::v8i32;
18654     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18655     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18656     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18657     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18658     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18659     ALo = DAG.getBitcast(ExtVT, ALo);
18660     AHi = DAG.getBitcast(ExtVT, AHi);
18661     RLo = DAG.getBitcast(ExtVT, RLo);
18662     RHi = DAG.getBitcast(ExtVT, RHi);
18663     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18664     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18665     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18666     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18667     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18668   }
18669
18670   if (VT == MVT::v8i16) {
18671     unsigned ShiftOpcode = Op->getOpcode();
18672
18673     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18674       // On SSE41 targets we make use of the fact that VSELECT lowers
18675       // to PBLENDVB which selects bytes based just on the sign bit.
18676       if (Subtarget->hasSSE41()) {
18677         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18678         V0 = DAG.getBitcast(ExtVT, V0);
18679         V1 = DAG.getBitcast(ExtVT, V1);
18680         Sel = DAG.getBitcast(ExtVT, Sel);
18681         return DAG.getBitcast(
18682             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18683       }
18684       // On pre-SSE41 targets we splat the sign bit - a negative value will
18685       // set all bits of the lanes to true and VSELECT uses that in
18686       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18687       SDValue C =
18688           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18689       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18690     };
18691
18692     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18693     if (Subtarget->hasSSE41()) {
18694       // On SSE41 targets we need to replicate the shift mask in both
18695       // bytes for PBLENDVB.
18696       Amt = DAG.getNode(
18697           ISD::OR, dl, VT,
18698           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18699           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18700     } else {
18701       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18702     }
18703
18704     // r = VSELECT(r, shift(r, 8), a);
18705     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18706     R = SignBitSelect(Amt, M, R);
18707
18708     // a += a
18709     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18710
18711     // r = VSELECT(r, shift(r, 4), a);
18712     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18713     R = SignBitSelect(Amt, M, R);
18714
18715     // a += a
18716     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18717
18718     // r = VSELECT(r, shift(r, 2), a);
18719     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18720     R = SignBitSelect(Amt, M, R);
18721
18722     // a += a
18723     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18724
18725     // return VSELECT(r, shift(r, 1), a);
18726     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18727     R = SignBitSelect(Amt, M, R);
18728     return R;
18729   }
18730
18731   // Decompose 256-bit shifts into smaller 128-bit shifts.
18732   if (VT.is256BitVector()) {
18733     unsigned NumElems = VT.getVectorNumElements();
18734     MVT EltVT = VT.getVectorElementType();
18735     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18736
18737     // Extract the two vectors
18738     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18739     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18740
18741     // Recreate the shift amount vectors
18742     SDValue Amt1, Amt2;
18743     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18744       // Constant shift amount
18745       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18746       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18747       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18748
18749       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18750       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18751     } else {
18752       // Variable shift amount
18753       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18754       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18755     }
18756
18757     // Issue new vector shifts for the smaller types
18758     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18759     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18760
18761     // Concatenate the result back
18762     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18763   }
18764
18765   return SDValue();
18766 }
18767
18768 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18769                            SelectionDAG &DAG) {
18770   MVT VT = Op.getSimpleValueType();
18771   SDLoc DL(Op);
18772   SDValue R = Op.getOperand(0);
18773   SDValue Amt = Op.getOperand(1);
18774
18775   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18776   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18777   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18778
18779   // XOP has 128-bit vector variable + immediate rotates.
18780   // +ve/-ve Amt = rotate left/right.
18781
18782   // Split 256-bit integers.
18783   if (VT.getSizeInBits() == 256)
18784     return Lower256IntArith(Op, DAG);
18785
18786   assert(VT.getSizeInBits() == 128 && "Only rotate 128-bit vectors!");
18787
18788   // Attempt to rotate by immediate.
18789   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18790     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18791       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18792       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18793       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18794                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18795     }
18796   }
18797
18798   // Use general rotate by variable (per-element).
18799   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18800 }
18801
18802 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18803   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18804   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18805   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18806   // has only one use.
18807   SDNode *N = Op.getNode();
18808   SDValue LHS = N->getOperand(0);
18809   SDValue RHS = N->getOperand(1);
18810   unsigned BaseOp = 0;
18811   unsigned Cond = 0;
18812   SDLoc DL(Op);
18813   switch (Op.getOpcode()) {
18814   default: llvm_unreachable("Unknown ovf instruction!");
18815   case ISD::SADDO:
18816     // A subtract of one will be selected as a INC. Note that INC doesn't
18817     // set CF, so we can't do this for UADDO.
18818     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18819       if (C->isOne()) {
18820         BaseOp = X86ISD::INC;
18821         Cond = X86::COND_O;
18822         break;
18823       }
18824     BaseOp = X86ISD::ADD;
18825     Cond = X86::COND_O;
18826     break;
18827   case ISD::UADDO:
18828     BaseOp = X86ISD::ADD;
18829     Cond = X86::COND_B;
18830     break;
18831   case ISD::SSUBO:
18832     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18833     // set CF, so we can't do this for USUBO.
18834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18835       if (C->isOne()) {
18836         BaseOp = X86ISD::DEC;
18837         Cond = X86::COND_O;
18838         break;
18839       }
18840     BaseOp = X86ISD::SUB;
18841     Cond = X86::COND_O;
18842     break;
18843   case ISD::USUBO:
18844     BaseOp = X86ISD::SUB;
18845     Cond = X86::COND_B;
18846     break;
18847   case ISD::SMULO:
18848     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18849     Cond = X86::COND_O;
18850     break;
18851   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18852     if (N->getValueType(0) == MVT::i8) {
18853       BaseOp = X86ISD::UMUL8;
18854       Cond = X86::COND_O;
18855       break;
18856     }
18857     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18858                                  MVT::i32);
18859     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18860
18861     SDValue SetCC =
18862       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18863                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18864                   SDValue(Sum.getNode(), 2));
18865
18866     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18867   }
18868   }
18869
18870   // Also sets EFLAGS.
18871   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18872   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18873
18874   SDValue SetCC =
18875     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18876                 DAG.getConstant(Cond, DL, MVT::i32),
18877                 SDValue(Sum.getNode(), 1));
18878
18879   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18880 }
18881
18882 /// Returns true if the operand type is exactly twice the native width, and
18883 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18884 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18885 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18886 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18887   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18888
18889   if (OpWidth == 64)
18890     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18891   else if (OpWidth == 128)
18892     return Subtarget->hasCmpxchg16b();
18893   else
18894     return false;
18895 }
18896
18897 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18898   return needsCmpXchgNb(SI->getValueOperand()->getType());
18899 }
18900
18901 // Note: this turns large loads into lock cmpxchg8b/16b.
18902 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18903 TargetLowering::AtomicExpansionKind
18904 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18905   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18906   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18907                                                : AtomicExpansionKind::None;
18908 }
18909
18910 TargetLowering::AtomicExpansionKind
18911 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18912   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18913   Type *MemType = AI->getType();
18914
18915   // If the operand is too big, we must see if cmpxchg8/16b is available
18916   // and default to library calls otherwise.
18917   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18918     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18919                                    : AtomicExpansionKind::None;
18920   }
18921
18922   AtomicRMWInst::BinOp Op = AI->getOperation();
18923   switch (Op) {
18924   default:
18925     llvm_unreachable("Unknown atomic operation");
18926   case AtomicRMWInst::Xchg:
18927   case AtomicRMWInst::Add:
18928   case AtomicRMWInst::Sub:
18929     // It's better to use xadd, xsub or xchg for these in all cases.
18930     return AtomicExpansionKind::None;
18931   case AtomicRMWInst::Or:
18932   case AtomicRMWInst::And:
18933   case AtomicRMWInst::Xor:
18934     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18935     // prefix to a normal instruction for these operations.
18936     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18937                             : AtomicExpansionKind::None;
18938   case AtomicRMWInst::Nand:
18939   case AtomicRMWInst::Max:
18940   case AtomicRMWInst::Min:
18941   case AtomicRMWInst::UMax:
18942   case AtomicRMWInst::UMin:
18943     // These always require a non-trivial set of data operations on x86. We must
18944     // use a cmpxchg loop.
18945     return AtomicExpansionKind::CmpXChg;
18946   }
18947 }
18948
18949 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18950   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18951   // no-sse2). There isn't any reason to disable it if the target processor
18952   // supports it.
18953   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18954 }
18955
18956 LoadInst *
18957 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18958   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18959   Type *MemType = AI->getType();
18960   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18961   // there is no benefit in turning such RMWs into loads, and it is actually
18962   // harmful as it introduces a mfence.
18963   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18964     return nullptr;
18965
18966   auto Builder = IRBuilder<>(AI);
18967   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18968   auto SynchScope = AI->getSynchScope();
18969   // We must restrict the ordering to avoid generating loads with Release or
18970   // ReleaseAcquire orderings.
18971   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18972   auto Ptr = AI->getPointerOperand();
18973
18974   // Before the load we need a fence. Here is an example lifted from
18975   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18976   // is required:
18977   // Thread 0:
18978   //   x.store(1, relaxed);
18979   //   r1 = y.fetch_add(0, release);
18980   // Thread 1:
18981   //   y.fetch_add(42, acquire);
18982   //   r2 = x.load(relaxed);
18983   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18984   // lowered to just a load without a fence. A mfence flushes the store buffer,
18985   // making the optimization clearly correct.
18986   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18987   // otherwise, we might be able to be more aggressive on relaxed idempotent
18988   // rmw. In practice, they do not look useful, so we don't try to be
18989   // especially clever.
18990   if (SynchScope == SingleThread)
18991     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18992     // the IR level, so we must wrap it in an intrinsic.
18993     return nullptr;
18994
18995   if (!hasMFENCE(*Subtarget))
18996     // FIXME: it might make sense to use a locked operation here but on a
18997     // different cache-line to prevent cache-line bouncing. In practice it
18998     // is probably a small win, and x86 processors without mfence are rare
18999     // enough that we do not bother.
19000     return nullptr;
19001
19002   Function *MFence =
19003       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19004   Builder.CreateCall(MFence, {});
19005
19006   // Finally we can emit the atomic load.
19007   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19008           AI->getType()->getPrimitiveSizeInBits());
19009   Loaded->setAtomic(Order, SynchScope);
19010   AI->replaceAllUsesWith(Loaded);
19011   AI->eraseFromParent();
19012   return Loaded;
19013 }
19014
19015 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19016                                  SelectionDAG &DAG) {
19017   SDLoc dl(Op);
19018   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19019     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19020   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19021     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19022
19023   // The only fence that needs an instruction is a sequentially-consistent
19024   // cross-thread fence.
19025   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19026     if (hasMFENCE(*Subtarget))
19027       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19028
19029     SDValue Chain = Op.getOperand(0);
19030     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19031     SDValue Ops[] = {
19032       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19033       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19034       DAG.getRegister(0, MVT::i32),            // Index
19035       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19036       DAG.getRegister(0, MVT::i32),            // Segment.
19037       Zero,
19038       Chain
19039     };
19040     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19041     return SDValue(Res, 0);
19042   }
19043
19044   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19045   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19046 }
19047
19048 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19049                              SelectionDAG &DAG) {
19050   MVT T = Op.getSimpleValueType();
19051   SDLoc DL(Op);
19052   unsigned Reg = 0;
19053   unsigned size = 0;
19054   switch(T.SimpleTy) {
19055   default: llvm_unreachable("Invalid value type!");
19056   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19057   case MVT::i16: Reg = X86::AX;  size = 2; break;
19058   case MVT::i32: Reg = X86::EAX; size = 4; break;
19059   case MVT::i64:
19060     assert(Subtarget->is64Bit() && "Node not type legal!");
19061     Reg = X86::RAX; size = 8;
19062     break;
19063   }
19064   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19065                                   Op.getOperand(2), SDValue());
19066   SDValue Ops[] = { cpIn.getValue(0),
19067                     Op.getOperand(1),
19068                     Op.getOperand(3),
19069                     DAG.getTargetConstant(size, DL, MVT::i8),
19070                     cpIn.getValue(1) };
19071   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19072   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19073   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19074                                            Ops, T, MMO);
19075
19076   SDValue cpOut =
19077     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19078   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19079                                       MVT::i32, cpOut.getValue(2));
19080   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19081                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19082                                 EFLAGS);
19083
19084   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19085   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19086   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19087   return SDValue();
19088 }
19089
19090 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19091                             SelectionDAG &DAG) {
19092   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19093   MVT DstVT = Op.getSimpleValueType();
19094
19095   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19096     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19097     if (DstVT != MVT::f64)
19098       // This conversion needs to be expanded.
19099       return SDValue();
19100
19101     SDValue InVec = Op->getOperand(0);
19102     SDLoc dl(Op);
19103     unsigned NumElts = SrcVT.getVectorNumElements();
19104     EVT SVT = SrcVT.getVectorElementType();
19105
19106     // Widen the vector in input in the case of MVT::v2i32.
19107     // Example: from MVT::v2i32 to MVT::v4i32.
19108     SmallVector<SDValue, 16> Elts;
19109     for (unsigned i = 0, e = NumElts; i != e; ++i)
19110       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19111                                  DAG.getIntPtrConstant(i, dl)));
19112
19113     // Explicitly mark the extra elements as Undef.
19114     Elts.append(NumElts, DAG.getUNDEF(SVT));
19115
19116     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19117     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19118     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19119     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19120                        DAG.getIntPtrConstant(0, dl));
19121   }
19122
19123   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19124          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19125   assert((DstVT == MVT::i64 ||
19126           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19127          "Unexpected custom BITCAST");
19128   // i64 <=> MMX conversions are Legal.
19129   if (SrcVT==MVT::i64 && DstVT.isVector())
19130     return Op;
19131   if (DstVT==MVT::i64 && SrcVT.isVector())
19132     return Op;
19133   // MMX <=> MMX conversions are Legal.
19134   if (SrcVT.isVector() && DstVT.isVector())
19135     return Op;
19136   // All other conversions need to be expanded.
19137   return SDValue();
19138 }
19139
19140 /// Compute the horizontal sum of bytes in V for the elements of VT.
19141 ///
19142 /// Requires V to be a byte vector and VT to be an integer vector type with
19143 /// wider elements than V's type. The width of the elements of VT determines
19144 /// how many bytes of V are summed horizontally to produce each element of the
19145 /// result.
19146 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19147                                       const X86Subtarget *Subtarget,
19148                                       SelectionDAG &DAG) {
19149   SDLoc DL(V);
19150   MVT ByteVecVT = V.getSimpleValueType();
19151   MVT EltVT = VT.getVectorElementType();
19152   int NumElts = VT.getVectorNumElements();
19153   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19154          "Expected value to have byte element type.");
19155   assert(EltVT != MVT::i8 &&
19156          "Horizontal byte sum only makes sense for wider elements!");
19157   unsigned VecSize = VT.getSizeInBits();
19158   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19159
19160   // PSADBW instruction horizontally add all bytes and leave the result in i64
19161   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19162   if (EltVT == MVT::i64) {
19163     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19164     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19165     return DAG.getBitcast(VT, V);
19166   }
19167
19168   if (EltVT == MVT::i32) {
19169     // We unpack the low half and high half into i32s interleaved with zeros so
19170     // that we can use PSADBW to horizontally sum them. The most useful part of
19171     // this is that it lines up the results of two PSADBW instructions to be
19172     // two v2i64 vectors which concatenated are the 4 population counts. We can
19173     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19174     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19175     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19176     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19177
19178     // Do the horizontal sums into two v2i64s.
19179     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19180     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19181                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19182     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19183                        DAG.getBitcast(ByteVecVT, High), Zeros);
19184
19185     // Merge them together.
19186     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19187     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19188                     DAG.getBitcast(ShortVecVT, Low),
19189                     DAG.getBitcast(ShortVecVT, High));
19190
19191     return DAG.getBitcast(VT, V);
19192   }
19193
19194   // The only element type left is i16.
19195   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19196
19197   // To obtain pop count for each i16 element starting from the pop count for
19198   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19199   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19200   // directly supported.
19201   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19202   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19203   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19204   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19205                   DAG.getBitcast(ByteVecVT, V));
19206   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19207 }
19208
19209 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19210                                         const X86Subtarget *Subtarget,
19211                                         SelectionDAG &DAG) {
19212   MVT VT = Op.getSimpleValueType();
19213   MVT EltVT = VT.getVectorElementType();
19214   unsigned VecSize = VT.getSizeInBits();
19215
19216   // Implement a lookup table in register by using an algorithm based on:
19217   // http://wm.ite.pl/articles/sse-popcount.html
19218   //
19219   // The general idea is that every lower byte nibble in the input vector is an
19220   // index into a in-register pre-computed pop count table. We then split up the
19221   // input vector in two new ones: (1) a vector with only the shifted-right
19222   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19223   // masked out higher ones) for each byte. PSHUB is used separately with both
19224   // to index the in-register table. Next, both are added and the result is a
19225   // i8 vector where each element contains the pop count for input byte.
19226   //
19227   // To obtain the pop count for elements != i8, we follow up with the same
19228   // approach and use additional tricks as described below.
19229   //
19230   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19231                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19232                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19233                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19234
19235   int NumByteElts = VecSize / 8;
19236   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19237   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19238   SmallVector<SDValue, 16> LUTVec;
19239   for (int i = 0; i < NumByteElts; ++i)
19240     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19241   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19242   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19243                                   DAG.getConstant(0x0F, DL, MVT::i8));
19244   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19245
19246   // High nibbles
19247   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19248   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19249   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19250
19251   // Low nibbles
19252   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19253
19254   // The input vector is used as the shuffle mask that index elements into the
19255   // LUT. After counting low and high nibbles, add the vector to obtain the
19256   // final pop count per i8 element.
19257   SDValue HighPopCnt =
19258       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19259   SDValue LowPopCnt =
19260       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19261   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19262
19263   if (EltVT == MVT::i8)
19264     return PopCnt;
19265
19266   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19267 }
19268
19269 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19270                                        const X86Subtarget *Subtarget,
19271                                        SelectionDAG &DAG) {
19272   MVT VT = Op.getSimpleValueType();
19273   assert(VT.is128BitVector() &&
19274          "Only 128-bit vector bitmath lowering supported.");
19275
19276   int VecSize = VT.getSizeInBits();
19277   MVT EltVT = VT.getVectorElementType();
19278   int Len = EltVT.getSizeInBits();
19279
19280   // This is the vectorized version of the "best" algorithm from
19281   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19282   // with a minor tweak to use a series of adds + shifts instead of vector
19283   // multiplications. Implemented for all integer vector types. We only use
19284   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19285   // much faster, even faster than using native popcnt instructions.
19286
19287   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19288     MVT VT = V.getSimpleValueType();
19289     SmallVector<SDValue, 32> Shifters(
19290         VT.getVectorNumElements(),
19291         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19292     return DAG.getNode(OpCode, DL, VT, V,
19293                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19294   };
19295   auto GetMask = [&](SDValue V, APInt Mask) {
19296     MVT VT = V.getSimpleValueType();
19297     SmallVector<SDValue, 32> Masks(
19298         VT.getVectorNumElements(),
19299         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19300     return DAG.getNode(ISD::AND, DL, VT, V,
19301                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19302   };
19303
19304   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19305   // x86, so set the SRL type to have elements at least i16 wide. This is
19306   // correct because all of our SRLs are followed immediately by a mask anyways
19307   // that handles any bits that sneak into the high bits of the byte elements.
19308   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19309
19310   SDValue V = Op;
19311
19312   // v = v - ((v >> 1) & 0x55555555...)
19313   SDValue Srl =
19314       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19315   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19316   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19317
19318   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19319   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19320   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19321   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19322   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19323
19324   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19325   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19326   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19327   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19328
19329   // At this point, V contains the byte-wise population count, and we are
19330   // merely doing a horizontal sum if necessary to get the wider element
19331   // counts.
19332   if (EltVT == MVT::i8)
19333     return V;
19334
19335   return LowerHorizontalByteSum(
19336       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19337       DAG);
19338 }
19339
19340 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19341                                 SelectionDAG &DAG) {
19342   MVT VT = Op.getSimpleValueType();
19343   // FIXME: Need to add AVX-512 support here!
19344   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19345          "Unknown CTPOP type to handle");
19346   SDLoc DL(Op.getNode());
19347   SDValue Op0 = Op.getOperand(0);
19348
19349   if (!Subtarget->hasSSSE3()) {
19350     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19351     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19352     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19353   }
19354
19355   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19356     unsigned NumElems = VT.getVectorNumElements();
19357
19358     // Extract each 128-bit vector, compute pop count and concat the result.
19359     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19360     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19361
19362     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19363                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19364                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19365   }
19366
19367   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19368 }
19369
19370 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19371                           SelectionDAG &DAG) {
19372   assert(Op.getValueType().isVector() &&
19373          "We only do custom lowering for vector population count.");
19374   return LowerVectorCTPOP(Op, Subtarget, DAG);
19375 }
19376
19377 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19378   SDNode *Node = Op.getNode();
19379   SDLoc dl(Node);
19380   EVT T = Node->getValueType(0);
19381   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19382                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19383   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19384                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19385                        Node->getOperand(0),
19386                        Node->getOperand(1), negOp,
19387                        cast<AtomicSDNode>(Node)->getMemOperand(),
19388                        cast<AtomicSDNode>(Node)->getOrdering(),
19389                        cast<AtomicSDNode>(Node)->getSynchScope());
19390 }
19391
19392 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19393   SDNode *Node = Op.getNode();
19394   SDLoc dl(Node);
19395   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19396
19397   // Convert seq_cst store -> xchg
19398   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19399   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19400   //        (The only way to get a 16-byte store is cmpxchg16b)
19401   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19402   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19403       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19404     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19405                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19406                                  Node->getOperand(0),
19407                                  Node->getOperand(1), Node->getOperand(2),
19408                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19409                                  cast<AtomicSDNode>(Node)->getOrdering(),
19410                                  cast<AtomicSDNode>(Node)->getSynchScope());
19411     return Swap.getValue(1);
19412   }
19413   // Other atomic stores have a simple pattern.
19414   return Op;
19415 }
19416
19417 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19418   EVT VT = Op.getNode()->getSimpleValueType(0);
19419
19420   // Let legalize expand this if it isn't a legal type yet.
19421   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19422     return SDValue();
19423
19424   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19425
19426   unsigned Opc;
19427   bool ExtraOp = false;
19428   switch (Op.getOpcode()) {
19429   default: llvm_unreachable("Invalid code");
19430   case ISD::ADDC: Opc = X86ISD::ADD; break;
19431   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19432   case ISD::SUBC: Opc = X86ISD::SUB; break;
19433   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19434   }
19435
19436   if (!ExtraOp)
19437     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19438                        Op.getOperand(1));
19439   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19440                      Op.getOperand(1), Op.getOperand(2));
19441 }
19442
19443 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19444                             SelectionDAG &DAG) {
19445   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19446
19447   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19448   // which returns the values as { float, float } (in XMM0) or
19449   // { double, double } (which is returned in XMM0, XMM1).
19450   SDLoc dl(Op);
19451   SDValue Arg = Op.getOperand(0);
19452   EVT ArgVT = Arg.getValueType();
19453   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19454
19455   TargetLowering::ArgListTy Args;
19456   TargetLowering::ArgListEntry Entry;
19457
19458   Entry.Node = Arg;
19459   Entry.Ty = ArgTy;
19460   Entry.isSExt = false;
19461   Entry.isZExt = false;
19462   Args.push_back(Entry);
19463
19464   bool isF64 = ArgVT == MVT::f64;
19465   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19466   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19467   // the results are returned via SRet in memory.
19468   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19470   SDValue Callee =
19471       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19472
19473   Type *RetTy = isF64
19474     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19475     : (Type*)VectorType::get(ArgTy, 4);
19476
19477   TargetLowering::CallLoweringInfo CLI(DAG);
19478   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19479     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19480
19481   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19482
19483   if (isF64)
19484     // Returned in xmm0 and xmm1.
19485     return CallResult.first;
19486
19487   // Returned in bits 0:31 and 32:64 xmm0.
19488   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19489                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19490   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19491                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19492   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19493   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19494 }
19495
19496 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19497                              SelectionDAG &DAG) {
19498   assert(Subtarget->hasAVX512() &&
19499          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19500
19501   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19502   EVT VT = N->getValue().getValueType();
19503   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19504   SDLoc dl(Op);
19505
19506   // X86 scatter kills mask register, so its type should be added to
19507   // the list of return values
19508   if (N->getNumValues() == 1) {
19509     SDValue Index = N->getIndex();
19510     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19511         !Index.getValueType().is512BitVector())
19512       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19513
19514     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19515     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19516                       N->getOperand(3), Index };
19517
19518     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19519     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19520     return SDValue(NewScatter.getNode(), 0);
19521   }
19522   return Op;
19523 }
19524
19525 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19526                             SelectionDAG &DAG) {
19527   assert(Subtarget->hasAVX512() &&
19528          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19529
19530   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19531   EVT VT = Op.getValueType();
19532   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19533   SDLoc dl(Op);
19534
19535   SDValue Index = N->getIndex();
19536   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19537       !Index.getValueType().is512BitVector()) {
19538     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19539     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19540                       N->getOperand(3), Index };
19541     DAG.UpdateNodeOperands(N, Ops);
19542   }
19543   return Op;
19544 }
19545
19546 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19547                                                     SelectionDAG &DAG) const {
19548   // TODO: Eventually, the lowering of these nodes should be informed by or
19549   // deferred to the GC strategy for the function in which they appear. For
19550   // now, however, they must be lowered to something. Since they are logically
19551   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19552   // require special handling for these nodes), lower them as literal NOOPs for
19553   // the time being.
19554   SmallVector<SDValue, 2> Ops;
19555
19556   Ops.push_back(Op.getOperand(0));
19557   if (Op->getGluedNode())
19558     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19559
19560   SDLoc OpDL(Op);
19561   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19562   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19563
19564   return NOOP;
19565 }
19566
19567 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19568                                                   SelectionDAG &DAG) const {
19569   // TODO: Eventually, the lowering of these nodes should be informed by or
19570   // deferred to the GC strategy for the function in which they appear. For
19571   // now, however, they must be lowered to something. Since they are logically
19572   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19573   // require special handling for these nodes), lower them as literal NOOPs for
19574   // the time being.
19575   SmallVector<SDValue, 2> Ops;
19576
19577   Ops.push_back(Op.getOperand(0));
19578   if (Op->getGluedNode())
19579     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19580
19581   SDLoc OpDL(Op);
19582   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19583   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19584
19585   return NOOP;
19586 }
19587
19588 /// LowerOperation - Provide custom lowering hooks for some operations.
19589 ///
19590 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19591   switch (Op.getOpcode()) {
19592   default: llvm_unreachable("Should not custom lower this!");
19593   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19594   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19595     return LowerCMP_SWAP(Op, Subtarget, DAG);
19596   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19597   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19598   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19599   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19600   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19601   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19602   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19603   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19604   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19605   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19606   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19607   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19608   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19609   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19610   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19611   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19612   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19613   case ISD::SHL_PARTS:
19614   case ISD::SRA_PARTS:
19615   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19616   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19617   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19618   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19619   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19620   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19621   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19622   case ISD::SIGN_EXTEND_VECTOR_INREG:
19623     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19624   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19625   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19626   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19627   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19628   case ISD::FABS:
19629   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19630   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19631   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19632   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19633   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19634   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19635   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19636   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19637   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19638   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19639   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19640   case ISD::INTRINSIC_VOID:
19641   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19642   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19643   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19644   case ISD::FRAME_TO_ARGS_OFFSET:
19645                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19646   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19647   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19648   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19649   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19650   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19651   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19652   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19653   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19654   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19655   case ISD::CTTZ:
19656   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19657   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19658   case ISD::UMUL_LOHI:
19659   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19660   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19661   case ISD::SRA:
19662   case ISD::SRL:
19663   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19664   case ISD::SADDO:
19665   case ISD::UADDO:
19666   case ISD::SSUBO:
19667   case ISD::USUBO:
19668   case ISD::SMULO:
19669   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19670   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19671   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19672   case ISD::ADDC:
19673   case ISD::ADDE:
19674   case ISD::SUBC:
19675   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19676   case ISD::ADD:                return LowerADD(Op, DAG);
19677   case ISD::SUB:                return LowerSUB(Op, DAG);
19678   case ISD::SMAX:
19679   case ISD::SMIN:
19680   case ISD::UMAX:
19681   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19682   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19683   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19684   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19685   case ISD::GC_TRANSITION_START:
19686                                 return LowerGC_TRANSITION_START(Op, DAG);
19687   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19688   }
19689 }
19690
19691 /// ReplaceNodeResults - Replace a node with an illegal result type
19692 /// with a new node built out of custom code.
19693 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19694                                            SmallVectorImpl<SDValue>&Results,
19695                                            SelectionDAG &DAG) const {
19696   SDLoc dl(N);
19697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19698   switch (N->getOpcode()) {
19699   default:
19700     llvm_unreachable("Do not know how to custom type legalize this operation!");
19701   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19702   case X86ISD::FMINC:
19703   case X86ISD::FMIN:
19704   case X86ISD::FMAXC:
19705   case X86ISD::FMAX: {
19706     EVT VT = N->getValueType(0);
19707     if (VT != MVT::v2f32)
19708       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19709     SDValue UNDEF = DAG.getUNDEF(VT);
19710     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19711                               N->getOperand(0), UNDEF);
19712     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19713                               N->getOperand(1), UNDEF);
19714     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19715     return;
19716   }
19717   case ISD::SIGN_EXTEND_INREG:
19718   case ISD::ADDC:
19719   case ISD::ADDE:
19720   case ISD::SUBC:
19721   case ISD::SUBE:
19722     // We don't want to expand or promote these.
19723     return;
19724   case ISD::SDIV:
19725   case ISD::UDIV:
19726   case ISD::SREM:
19727   case ISD::UREM:
19728   case ISD::SDIVREM:
19729   case ISD::UDIVREM: {
19730     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19731     Results.push_back(V);
19732     return;
19733   }
19734   case ISD::FP_TO_SINT:
19735   case ISD::FP_TO_UINT: {
19736     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19737
19738     std::pair<SDValue,SDValue> Vals =
19739         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19740     SDValue FIST = Vals.first, StackSlot = Vals.second;
19741     if (FIST.getNode()) {
19742       EVT VT = N->getValueType(0);
19743       // Return a load from the stack slot.
19744       if (StackSlot.getNode())
19745         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19746                                       MachinePointerInfo(),
19747                                       false, false, false, 0));
19748       else
19749         Results.push_back(FIST);
19750     }
19751     return;
19752   }
19753   case ISD::UINT_TO_FP: {
19754     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19755     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19756         N->getValueType(0) != MVT::v2f32)
19757       return;
19758     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19759                                  N->getOperand(0));
19760     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19761                                      MVT::f64);
19762     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19763     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19764                              DAG.getBitcast(MVT::v2i64, VBias));
19765     Or = DAG.getBitcast(MVT::v2f64, Or);
19766     // TODO: Are there any fast-math-flags to propagate here?
19767     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19768     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19769     return;
19770   }
19771   case ISD::FP_ROUND: {
19772     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19773         return;
19774     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19775     Results.push_back(V);
19776     return;
19777   }
19778   case ISD::FP_EXTEND: {
19779     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19780     // No other ValueType for FP_EXTEND should reach this point.
19781     assert(N->getValueType(0) == MVT::v2f32 &&
19782            "Do not know how to legalize this Node");
19783     return;
19784   }
19785   case ISD::INTRINSIC_W_CHAIN: {
19786     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19787     switch (IntNo) {
19788     default : llvm_unreachable("Do not know how to custom type "
19789                                "legalize this intrinsic operation!");
19790     case Intrinsic::x86_rdtsc:
19791       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19792                                      Results);
19793     case Intrinsic::x86_rdtscp:
19794       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19795                                      Results);
19796     case Intrinsic::x86_rdpmc:
19797       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19798     }
19799   }
19800   case ISD::READCYCLECOUNTER: {
19801     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19802                                    Results);
19803   }
19804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19805     EVT T = N->getValueType(0);
19806     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19807     bool Regs64bit = T == MVT::i128;
19808     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19809     SDValue cpInL, cpInH;
19810     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19811                         DAG.getConstant(0, dl, HalfT));
19812     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19813                         DAG.getConstant(1, dl, HalfT));
19814     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19815                              Regs64bit ? X86::RAX : X86::EAX,
19816                              cpInL, SDValue());
19817     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19818                              Regs64bit ? X86::RDX : X86::EDX,
19819                              cpInH, cpInL.getValue(1));
19820     SDValue swapInL, swapInH;
19821     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19822                           DAG.getConstant(0, dl, HalfT));
19823     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19824                           DAG.getConstant(1, dl, HalfT));
19825     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19826                                Regs64bit ? X86::RBX : X86::EBX,
19827                                swapInL, cpInH.getValue(1));
19828     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19829                                Regs64bit ? X86::RCX : X86::ECX,
19830                                swapInH, swapInL.getValue(1));
19831     SDValue Ops[] = { swapInH.getValue(0),
19832                       N->getOperand(1),
19833                       swapInH.getValue(1) };
19834     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19835     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19836     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19837                                   X86ISD::LCMPXCHG8_DAG;
19838     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19839     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19840                                         Regs64bit ? X86::RAX : X86::EAX,
19841                                         HalfT, Result.getValue(1));
19842     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19843                                         Regs64bit ? X86::RDX : X86::EDX,
19844                                         HalfT, cpOutL.getValue(2));
19845     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19846
19847     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19848                                         MVT::i32, cpOutH.getValue(2));
19849     SDValue Success =
19850         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19851                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19852     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19853
19854     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19855     Results.push_back(Success);
19856     Results.push_back(EFLAGS.getValue(1));
19857     return;
19858   }
19859   case ISD::ATOMIC_SWAP:
19860   case ISD::ATOMIC_LOAD_ADD:
19861   case ISD::ATOMIC_LOAD_SUB:
19862   case ISD::ATOMIC_LOAD_AND:
19863   case ISD::ATOMIC_LOAD_OR:
19864   case ISD::ATOMIC_LOAD_XOR:
19865   case ISD::ATOMIC_LOAD_NAND:
19866   case ISD::ATOMIC_LOAD_MIN:
19867   case ISD::ATOMIC_LOAD_MAX:
19868   case ISD::ATOMIC_LOAD_UMIN:
19869   case ISD::ATOMIC_LOAD_UMAX:
19870   case ISD::ATOMIC_LOAD: {
19871     // Delegate to generic TypeLegalization. Situations we can really handle
19872     // should have already been dealt with by AtomicExpandPass.cpp.
19873     break;
19874   }
19875   case ISD::BITCAST: {
19876     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19877     EVT DstVT = N->getValueType(0);
19878     EVT SrcVT = N->getOperand(0)->getValueType(0);
19879
19880     if (SrcVT != MVT::f64 ||
19881         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19882       return;
19883
19884     unsigned NumElts = DstVT.getVectorNumElements();
19885     EVT SVT = DstVT.getVectorElementType();
19886     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19887     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19888                                    MVT::v2f64, N->getOperand(0));
19889     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19890
19891     if (ExperimentalVectorWideningLegalization) {
19892       // If we are legalizing vectors by widening, we already have the desired
19893       // legal vector type, just return it.
19894       Results.push_back(ToVecInt);
19895       return;
19896     }
19897
19898     SmallVector<SDValue, 8> Elts;
19899     for (unsigned i = 0, e = NumElts; i != e; ++i)
19900       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19901                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19902
19903     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19904   }
19905   }
19906 }
19907
19908 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19909   switch ((X86ISD::NodeType)Opcode) {
19910   case X86ISD::FIRST_NUMBER:       break;
19911   case X86ISD::BSF:                return "X86ISD::BSF";
19912   case X86ISD::BSR:                return "X86ISD::BSR";
19913   case X86ISD::SHLD:               return "X86ISD::SHLD";
19914   case X86ISD::SHRD:               return "X86ISD::SHRD";
19915   case X86ISD::FAND:               return "X86ISD::FAND";
19916   case X86ISD::FANDN:              return "X86ISD::FANDN";
19917   case X86ISD::FOR:                return "X86ISD::FOR";
19918   case X86ISD::FXOR:               return "X86ISD::FXOR";
19919   case X86ISD::FILD:               return "X86ISD::FILD";
19920   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19921   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19922   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19923   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19924   case X86ISD::FLD:                return "X86ISD::FLD";
19925   case X86ISD::FST:                return "X86ISD::FST";
19926   case X86ISD::CALL:               return "X86ISD::CALL";
19927   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19928   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19929   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19930   case X86ISD::BT:                 return "X86ISD::BT";
19931   case X86ISD::CMP:                return "X86ISD::CMP";
19932   case X86ISD::COMI:               return "X86ISD::COMI";
19933   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19934   case X86ISD::CMPM:               return "X86ISD::CMPM";
19935   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19936   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19937   case X86ISD::SETCC:              return "X86ISD::SETCC";
19938   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19939   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19940   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19941   case X86ISD::CMOV:               return "X86ISD::CMOV";
19942   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19943   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19944   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19945   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19946   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19947   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19948   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19949   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19950   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19951   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19952   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19953   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19954   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19955   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19956   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19957   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19958   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19959   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19960   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19961   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19962   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19963   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19964   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19965   case X86ISD::HADD:               return "X86ISD::HADD";
19966   case X86ISD::HSUB:               return "X86ISD::HSUB";
19967   case X86ISD::FHADD:              return "X86ISD::FHADD";
19968   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19969   case X86ISD::ABS:                return "X86ISD::ABS";
19970   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19971   case X86ISD::FMAX:               return "X86ISD::FMAX";
19972   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19973   case X86ISD::FMIN:               return "X86ISD::FMIN";
19974   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19975   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19976   case X86ISD::FMINC:              return "X86ISD::FMINC";
19977   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19978   case X86ISD::FRCP:               return "X86ISD::FRCP";
19979   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19980   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19981   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19982   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19983   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19984   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19985   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19986   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19987   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19988   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19989   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19990   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19991   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19992   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19993   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19994   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19995   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19996   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19997   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19998   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19999   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20000   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20001   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20002   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20003   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20004   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20005   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20006   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20007   case X86ISD::VSHL:               return "X86ISD::VSHL";
20008   case X86ISD::VSRL:               return "X86ISD::VSRL";
20009   case X86ISD::VSRA:               return "X86ISD::VSRA";
20010   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20011   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20012   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20013   case X86ISD::CMPP:               return "X86ISD::CMPP";
20014   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20015   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20016   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20017   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20018   case X86ISD::ADD:                return "X86ISD::ADD";
20019   case X86ISD::SUB:                return "X86ISD::SUB";
20020   case X86ISD::ADC:                return "X86ISD::ADC";
20021   case X86ISD::SBB:                return "X86ISD::SBB";
20022   case X86ISD::SMUL:               return "X86ISD::SMUL";
20023   case X86ISD::UMUL:               return "X86ISD::UMUL";
20024   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20025   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20026   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20027   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20028   case X86ISD::INC:                return "X86ISD::INC";
20029   case X86ISD::DEC:                return "X86ISD::DEC";
20030   case X86ISD::OR:                 return "X86ISD::OR";
20031   case X86ISD::XOR:                return "X86ISD::XOR";
20032   case X86ISD::AND:                return "X86ISD::AND";
20033   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20034   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20035   case X86ISD::PTEST:              return "X86ISD::PTEST";
20036   case X86ISD::TESTP:              return "X86ISD::TESTP";
20037   case X86ISD::TESTM:              return "X86ISD::TESTM";
20038   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20039   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20040   case X86ISD::KTEST:              return "X86ISD::KTEST";
20041   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20042   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20043   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20044   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20045   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20046   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20047   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20048   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20049   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20050   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20051   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20052   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20053   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20054   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20055   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20056   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20057   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20058   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20059   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20060   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20061   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20062   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20063   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20064   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20065   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20066   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20067   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20068   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20069   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20070   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20071   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20072   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20073   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20074   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20075   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20076   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20077   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20078   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20079   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20080   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20081   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20082   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20083   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20084   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20085   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20086   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20087   case X86ISD::SAHF:               return "X86ISD::SAHF";
20088   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20089   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20090   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20091   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20092   case X86ISD::VPROT:              return "X86ISD::VPROT";
20093   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20094   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20095   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20096   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20097   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20098   case X86ISD::FMADD:              return "X86ISD::FMADD";
20099   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20100   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20101   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20102   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20103   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20104   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20105   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20106   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20107   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20108   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20109   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20110   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20111   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20112   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20113   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20114   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20115   case X86ISD::XTEST:              return "X86ISD::XTEST";
20116   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20117   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20118   case X86ISD::SELECT:             return "X86ISD::SELECT";
20119   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20120   case X86ISD::RCP28:              return "X86ISD::RCP28";
20121   case X86ISD::EXP2:               return "X86ISD::EXP2";
20122   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20123   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20124   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20125   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20126   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20127   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20128   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20129   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20130   case X86ISD::ADDS:               return "X86ISD::ADDS";
20131   case X86ISD::SUBS:               return "X86ISD::SUBS";
20132   case X86ISD::AVG:                return "X86ISD::AVG";
20133   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20134   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20135   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20136   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20137   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20138   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20139   }
20140   return nullptr;
20141 }
20142
20143 // isLegalAddressingMode - Return true if the addressing mode represented
20144 // by AM is legal for this target, for a load/store of the specified type.
20145 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20146                                               const AddrMode &AM, Type *Ty,
20147                                               unsigned AS) const {
20148   // X86 supports extremely general addressing modes.
20149   CodeModel::Model M = getTargetMachine().getCodeModel();
20150   Reloc::Model R = getTargetMachine().getRelocationModel();
20151
20152   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20153   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20154     return false;
20155
20156   if (AM.BaseGV) {
20157     unsigned GVFlags =
20158       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20159
20160     // If a reference to this global requires an extra load, we can't fold it.
20161     if (isGlobalStubReference(GVFlags))
20162       return false;
20163
20164     // If BaseGV requires a register for the PIC base, we cannot also have a
20165     // BaseReg specified.
20166     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20167       return false;
20168
20169     // If lower 4G is not available, then we must use rip-relative addressing.
20170     if ((M != CodeModel::Small || R != Reloc::Static) &&
20171         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20172       return false;
20173   }
20174
20175   switch (AM.Scale) {
20176   case 0:
20177   case 1:
20178   case 2:
20179   case 4:
20180   case 8:
20181     // These scales always work.
20182     break;
20183   case 3:
20184   case 5:
20185   case 9:
20186     // These scales are formed with basereg+scalereg.  Only accept if there is
20187     // no basereg yet.
20188     if (AM.HasBaseReg)
20189       return false;
20190     break;
20191   default:  // Other stuff never works.
20192     return false;
20193   }
20194
20195   return true;
20196 }
20197
20198 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20199   unsigned Bits = Ty->getScalarSizeInBits();
20200
20201   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20202   // particularly cheaper than those without.
20203   if (Bits == 8)
20204     return false;
20205
20206   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20207   // variable shifts just as cheap as scalar ones.
20208   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20209     return false;
20210
20211   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20212   // fully general vector.
20213   return true;
20214 }
20215
20216 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20217   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20218     return false;
20219   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20220   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20221   return NumBits1 > NumBits2;
20222 }
20223
20224 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20225   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20226     return false;
20227
20228   if (!isTypeLegal(EVT::getEVT(Ty1)))
20229     return false;
20230
20231   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20232
20233   // Assuming the caller doesn't have a zeroext or signext return parameter,
20234   // truncation all the way down to i1 is valid.
20235   return true;
20236 }
20237
20238 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20239   return isInt<32>(Imm);
20240 }
20241
20242 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20243   // Can also use sub to handle negated immediates.
20244   return isInt<32>(Imm);
20245 }
20246
20247 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20248   if (!VT1.isInteger() || !VT2.isInteger())
20249     return false;
20250   unsigned NumBits1 = VT1.getSizeInBits();
20251   unsigned NumBits2 = VT2.getSizeInBits();
20252   return NumBits1 > NumBits2;
20253 }
20254
20255 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20256   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20257   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20258 }
20259
20260 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20261   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20262   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20263 }
20264
20265 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20266   EVT VT1 = Val.getValueType();
20267   if (isZExtFree(VT1, VT2))
20268     return true;
20269
20270   if (Val.getOpcode() != ISD::LOAD)
20271     return false;
20272
20273   if (!VT1.isSimple() || !VT1.isInteger() ||
20274       !VT2.isSimple() || !VT2.isInteger())
20275     return false;
20276
20277   switch (VT1.getSimpleVT().SimpleTy) {
20278   default: break;
20279   case MVT::i8:
20280   case MVT::i16:
20281   case MVT::i32:
20282     // X86 has 8, 16, and 32-bit zero-extending loads.
20283     return true;
20284   }
20285
20286   return false;
20287 }
20288
20289 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20290
20291 bool
20292 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20293   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20294     return false;
20295
20296   VT = VT.getScalarType();
20297
20298   if (!VT.isSimple())
20299     return false;
20300
20301   switch (VT.getSimpleVT().SimpleTy) {
20302   case MVT::f32:
20303   case MVT::f64:
20304     return true;
20305   default:
20306     break;
20307   }
20308
20309   return false;
20310 }
20311
20312 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20313   // i16 instructions are longer (0x66 prefix) and potentially slower.
20314   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20315 }
20316
20317 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20318 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20319 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20320 /// are assumed to be legal.
20321 bool
20322 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20323                                       EVT VT) const {
20324   if (!VT.isSimple())
20325     return false;
20326
20327   // Not for i1 vectors
20328   if (VT.getScalarType() == MVT::i1)
20329     return false;
20330
20331   // Very little shuffling can be done for 64-bit vectors right now.
20332   if (VT.getSizeInBits() == 64)
20333     return false;
20334
20335   // We only care that the types being shuffled are legal. The lowering can
20336   // handle any possible shuffle mask that results.
20337   return isTypeLegal(VT.getSimpleVT());
20338 }
20339
20340 bool
20341 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20342                                           EVT VT) const {
20343   // Just delegate to the generic legality, clear masks aren't special.
20344   return isShuffleMaskLegal(Mask, VT);
20345 }
20346
20347 //===----------------------------------------------------------------------===//
20348 //                           X86 Scheduler Hooks
20349 //===----------------------------------------------------------------------===//
20350
20351 /// Utility function to emit xbegin specifying the start of an RTM region.
20352 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20353                                      const TargetInstrInfo *TII) {
20354   DebugLoc DL = MI->getDebugLoc();
20355
20356   const BasicBlock *BB = MBB->getBasicBlock();
20357   MachineFunction::iterator I = ++MBB->getIterator();
20358
20359   // For the v = xbegin(), we generate
20360   //
20361   // thisMBB:
20362   //  xbegin sinkMBB
20363   //
20364   // mainMBB:
20365   //  eax = -1
20366   //
20367   // sinkMBB:
20368   //  v = eax
20369
20370   MachineBasicBlock *thisMBB = MBB;
20371   MachineFunction *MF = MBB->getParent();
20372   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20373   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20374   MF->insert(I, mainMBB);
20375   MF->insert(I, sinkMBB);
20376
20377   // Transfer the remainder of BB and its successor edges to sinkMBB.
20378   sinkMBB->splice(sinkMBB->begin(), MBB,
20379                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20380   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20381
20382   // thisMBB:
20383   //  xbegin sinkMBB
20384   //  # fallthrough to mainMBB
20385   //  # abortion to sinkMBB
20386   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20387   thisMBB->addSuccessor(mainMBB);
20388   thisMBB->addSuccessor(sinkMBB);
20389
20390   // mainMBB:
20391   //  EAX = -1
20392   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20393   mainMBB->addSuccessor(sinkMBB);
20394
20395   // sinkMBB:
20396   // EAX is live into the sinkMBB
20397   sinkMBB->addLiveIn(X86::EAX);
20398   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20399           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20400     .addReg(X86::EAX);
20401
20402   MI->eraseFromParent();
20403   return sinkMBB;
20404 }
20405
20406 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20407 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20408 // in the .td file.
20409 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20410                                        const TargetInstrInfo *TII) {
20411   unsigned Opc;
20412   switch (MI->getOpcode()) {
20413   default: llvm_unreachable("illegal opcode!");
20414   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20415   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20416   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20417   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20418   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20419   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20420   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20421   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20422   }
20423
20424   DebugLoc dl = MI->getDebugLoc();
20425   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20426
20427   unsigned NumArgs = MI->getNumOperands();
20428   for (unsigned i = 1; i < NumArgs; ++i) {
20429     MachineOperand &Op = MI->getOperand(i);
20430     if (!(Op.isReg() && Op.isImplicit()))
20431       MIB.addOperand(Op);
20432   }
20433   if (MI->hasOneMemOperand())
20434     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20435
20436   BuildMI(*BB, MI, dl,
20437     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20438     .addReg(X86::XMM0);
20439
20440   MI->eraseFromParent();
20441   return BB;
20442 }
20443
20444 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20445 // defs in an instruction pattern
20446 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20447                                        const TargetInstrInfo *TII) {
20448   unsigned Opc;
20449   switch (MI->getOpcode()) {
20450   default: llvm_unreachable("illegal opcode!");
20451   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20452   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20453   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20454   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20455   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20456   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20457   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20458   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20459   }
20460
20461   DebugLoc dl = MI->getDebugLoc();
20462   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20463
20464   unsigned NumArgs = MI->getNumOperands(); // remove the results
20465   for (unsigned i = 1; i < NumArgs; ++i) {
20466     MachineOperand &Op = MI->getOperand(i);
20467     if (!(Op.isReg() && Op.isImplicit()))
20468       MIB.addOperand(Op);
20469   }
20470   if (MI->hasOneMemOperand())
20471     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20472
20473   BuildMI(*BB, MI, dl,
20474     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20475     .addReg(X86::ECX);
20476
20477   MI->eraseFromParent();
20478   return BB;
20479 }
20480
20481 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20482                                       const X86Subtarget *Subtarget) {
20483   DebugLoc dl = MI->getDebugLoc();
20484   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20485   // Address into RAX/EAX, other two args into ECX, EDX.
20486   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20487   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20488   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20489   for (int i = 0; i < X86::AddrNumOperands; ++i)
20490     MIB.addOperand(MI->getOperand(i));
20491
20492   unsigned ValOps = X86::AddrNumOperands;
20493   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20494     .addReg(MI->getOperand(ValOps).getReg());
20495   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20496     .addReg(MI->getOperand(ValOps+1).getReg());
20497
20498   // The instruction doesn't actually take any operands though.
20499   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20500
20501   MI->eraseFromParent(); // The pseudo is gone now.
20502   return BB;
20503 }
20504
20505 MachineBasicBlock *
20506 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20507                                                  MachineBasicBlock *MBB) const {
20508   // Emit va_arg instruction on X86-64.
20509
20510   // Operands to this pseudo-instruction:
20511   // 0  ) Output        : destination address (reg)
20512   // 1-5) Input         : va_list address (addr, i64mem)
20513   // 6  ) ArgSize       : Size (in bytes) of vararg type
20514   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20515   // 8  ) Align         : Alignment of type
20516   // 9  ) EFLAGS (implicit-def)
20517
20518   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20519   static_assert(X86::AddrNumOperands == 5,
20520                 "VAARG_64 assumes 5 address operands");
20521
20522   unsigned DestReg = MI->getOperand(0).getReg();
20523   MachineOperand &Base = MI->getOperand(1);
20524   MachineOperand &Scale = MI->getOperand(2);
20525   MachineOperand &Index = MI->getOperand(3);
20526   MachineOperand &Disp = MI->getOperand(4);
20527   MachineOperand &Segment = MI->getOperand(5);
20528   unsigned ArgSize = MI->getOperand(6).getImm();
20529   unsigned ArgMode = MI->getOperand(7).getImm();
20530   unsigned Align = MI->getOperand(8).getImm();
20531
20532   // Memory Reference
20533   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20534   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20535   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20536
20537   // Machine Information
20538   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20539   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20540   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20541   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20542   DebugLoc DL = MI->getDebugLoc();
20543
20544   // struct va_list {
20545   //   i32   gp_offset
20546   //   i32   fp_offset
20547   //   i64   overflow_area (address)
20548   //   i64   reg_save_area (address)
20549   // }
20550   // sizeof(va_list) = 24
20551   // alignment(va_list) = 8
20552
20553   unsigned TotalNumIntRegs = 6;
20554   unsigned TotalNumXMMRegs = 8;
20555   bool UseGPOffset = (ArgMode == 1);
20556   bool UseFPOffset = (ArgMode == 2);
20557   unsigned MaxOffset = TotalNumIntRegs * 8 +
20558                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20559
20560   /* Align ArgSize to a multiple of 8 */
20561   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20562   bool NeedsAlign = (Align > 8);
20563
20564   MachineBasicBlock *thisMBB = MBB;
20565   MachineBasicBlock *overflowMBB;
20566   MachineBasicBlock *offsetMBB;
20567   MachineBasicBlock *endMBB;
20568
20569   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20570   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20571   unsigned OffsetReg = 0;
20572
20573   if (!UseGPOffset && !UseFPOffset) {
20574     // If we only pull from the overflow region, we don't create a branch.
20575     // We don't need to alter control flow.
20576     OffsetDestReg = 0; // unused
20577     OverflowDestReg = DestReg;
20578
20579     offsetMBB = nullptr;
20580     overflowMBB = thisMBB;
20581     endMBB = thisMBB;
20582   } else {
20583     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20584     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20585     // If not, pull from overflow_area. (branch to overflowMBB)
20586     //
20587     //       thisMBB
20588     //         |     .
20589     //         |        .
20590     //     offsetMBB   overflowMBB
20591     //         |        .
20592     //         |     .
20593     //        endMBB
20594
20595     // Registers for the PHI in endMBB
20596     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20597     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20598
20599     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20600     MachineFunction *MF = MBB->getParent();
20601     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20602     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20603     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20604
20605     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20606
20607     // Insert the new basic blocks
20608     MF->insert(MBBIter, offsetMBB);
20609     MF->insert(MBBIter, overflowMBB);
20610     MF->insert(MBBIter, endMBB);
20611
20612     // Transfer the remainder of MBB and its successor edges to endMBB.
20613     endMBB->splice(endMBB->begin(), thisMBB,
20614                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20615     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20616
20617     // Make offsetMBB and overflowMBB successors of thisMBB
20618     thisMBB->addSuccessor(offsetMBB);
20619     thisMBB->addSuccessor(overflowMBB);
20620
20621     // endMBB is a successor of both offsetMBB and overflowMBB
20622     offsetMBB->addSuccessor(endMBB);
20623     overflowMBB->addSuccessor(endMBB);
20624
20625     // Load the offset value into a register
20626     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20627     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20628       .addOperand(Base)
20629       .addOperand(Scale)
20630       .addOperand(Index)
20631       .addDisp(Disp, UseFPOffset ? 4 : 0)
20632       .addOperand(Segment)
20633       .setMemRefs(MMOBegin, MMOEnd);
20634
20635     // Check if there is enough room left to pull this argument.
20636     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20637       .addReg(OffsetReg)
20638       .addImm(MaxOffset + 8 - ArgSizeA8);
20639
20640     // Branch to "overflowMBB" if offset >= max
20641     // Fall through to "offsetMBB" otherwise
20642     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20643       .addMBB(overflowMBB);
20644   }
20645
20646   // In offsetMBB, emit code to use the reg_save_area.
20647   if (offsetMBB) {
20648     assert(OffsetReg != 0);
20649
20650     // Read the reg_save_area address.
20651     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20652     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20653       .addOperand(Base)
20654       .addOperand(Scale)
20655       .addOperand(Index)
20656       .addDisp(Disp, 16)
20657       .addOperand(Segment)
20658       .setMemRefs(MMOBegin, MMOEnd);
20659
20660     // Zero-extend the offset
20661     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20662       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20663         .addImm(0)
20664         .addReg(OffsetReg)
20665         .addImm(X86::sub_32bit);
20666
20667     // Add the offset to the reg_save_area to get the final address.
20668     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20669       .addReg(OffsetReg64)
20670       .addReg(RegSaveReg);
20671
20672     // Compute the offset for the next argument
20673     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20674     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20675       .addReg(OffsetReg)
20676       .addImm(UseFPOffset ? 16 : 8);
20677
20678     // Store it back into the va_list.
20679     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20680       .addOperand(Base)
20681       .addOperand(Scale)
20682       .addOperand(Index)
20683       .addDisp(Disp, UseFPOffset ? 4 : 0)
20684       .addOperand(Segment)
20685       .addReg(NextOffsetReg)
20686       .setMemRefs(MMOBegin, MMOEnd);
20687
20688     // Jump to endMBB
20689     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20690       .addMBB(endMBB);
20691   }
20692
20693   //
20694   // Emit code to use overflow area
20695   //
20696
20697   // Load the overflow_area address into a register.
20698   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20699   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20700     .addOperand(Base)
20701     .addOperand(Scale)
20702     .addOperand(Index)
20703     .addDisp(Disp, 8)
20704     .addOperand(Segment)
20705     .setMemRefs(MMOBegin, MMOEnd);
20706
20707   // If we need to align it, do so. Otherwise, just copy the address
20708   // to OverflowDestReg.
20709   if (NeedsAlign) {
20710     // Align the overflow address
20711     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20712     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20713
20714     // aligned_addr = (addr + (align-1)) & ~(align-1)
20715     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20716       .addReg(OverflowAddrReg)
20717       .addImm(Align-1);
20718
20719     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20720       .addReg(TmpReg)
20721       .addImm(~(uint64_t)(Align-1));
20722   } else {
20723     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20724       .addReg(OverflowAddrReg);
20725   }
20726
20727   // Compute the next overflow address after this argument.
20728   // (the overflow address should be kept 8-byte aligned)
20729   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20730   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20731     .addReg(OverflowDestReg)
20732     .addImm(ArgSizeA8);
20733
20734   // Store the new overflow address.
20735   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20736     .addOperand(Base)
20737     .addOperand(Scale)
20738     .addOperand(Index)
20739     .addDisp(Disp, 8)
20740     .addOperand(Segment)
20741     .addReg(NextAddrReg)
20742     .setMemRefs(MMOBegin, MMOEnd);
20743
20744   // If we branched, emit the PHI to the front of endMBB.
20745   if (offsetMBB) {
20746     BuildMI(*endMBB, endMBB->begin(), DL,
20747             TII->get(X86::PHI), DestReg)
20748       .addReg(OffsetDestReg).addMBB(offsetMBB)
20749       .addReg(OverflowDestReg).addMBB(overflowMBB);
20750   }
20751
20752   // Erase the pseudo instruction
20753   MI->eraseFromParent();
20754
20755   return endMBB;
20756 }
20757
20758 MachineBasicBlock *
20759 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20760                                                  MachineInstr *MI,
20761                                                  MachineBasicBlock *MBB) const {
20762   // Emit code to save XMM registers to the stack. The ABI says that the
20763   // number of registers to save is given in %al, so it's theoretically
20764   // possible to do an indirect jump trick to avoid saving all of them,
20765   // however this code takes a simpler approach and just executes all
20766   // of the stores if %al is non-zero. It's less code, and it's probably
20767   // easier on the hardware branch predictor, and stores aren't all that
20768   // expensive anyway.
20769
20770   // Create the new basic blocks. One block contains all the XMM stores,
20771   // and one block is the final destination regardless of whether any
20772   // stores were performed.
20773   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20774   MachineFunction *F = MBB->getParent();
20775   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20776   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20777   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20778   F->insert(MBBIter, XMMSaveMBB);
20779   F->insert(MBBIter, EndMBB);
20780
20781   // Transfer the remainder of MBB and its successor edges to EndMBB.
20782   EndMBB->splice(EndMBB->begin(), MBB,
20783                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20784   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20785
20786   // The original block will now fall through to the XMM save block.
20787   MBB->addSuccessor(XMMSaveMBB);
20788   // The XMMSaveMBB will fall through to the end block.
20789   XMMSaveMBB->addSuccessor(EndMBB);
20790
20791   // Now add the instructions.
20792   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20793   DebugLoc DL = MI->getDebugLoc();
20794
20795   unsigned CountReg = MI->getOperand(0).getReg();
20796   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20797   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20798
20799   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20800     // If %al is 0, branch around the XMM save block.
20801     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20802     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20803     MBB->addSuccessor(EndMBB);
20804   }
20805
20806   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20807   // that was just emitted, but clearly shouldn't be "saved".
20808   assert((MI->getNumOperands() <= 3 ||
20809           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20810           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20811          && "Expected last argument to be EFLAGS");
20812   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20813   // In the XMM save block, save all the XMM argument registers.
20814   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20815     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20816     MachineMemOperand *MMO = F->getMachineMemOperand(
20817         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20818         MachineMemOperand::MOStore,
20819         /*Size=*/16, /*Align=*/16);
20820     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20821       .addFrameIndex(RegSaveFrameIndex)
20822       .addImm(/*Scale=*/1)
20823       .addReg(/*IndexReg=*/0)
20824       .addImm(/*Disp=*/Offset)
20825       .addReg(/*Segment=*/0)
20826       .addReg(MI->getOperand(i).getReg())
20827       .addMemOperand(MMO);
20828   }
20829
20830   MI->eraseFromParent();   // The pseudo instruction is gone now.
20831
20832   return EndMBB;
20833 }
20834
20835 // The EFLAGS operand of SelectItr might be missing a kill marker
20836 // because there were multiple uses of EFLAGS, and ISel didn't know
20837 // which to mark. Figure out whether SelectItr should have had a
20838 // kill marker, and set it if it should. Returns the correct kill
20839 // marker value.
20840 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20841                                      MachineBasicBlock* BB,
20842                                      const TargetRegisterInfo* TRI) {
20843   // Scan forward through BB for a use/def of EFLAGS.
20844   MachineBasicBlock::iterator miI(std::next(SelectItr));
20845   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20846     const MachineInstr& mi = *miI;
20847     if (mi.readsRegister(X86::EFLAGS))
20848       return false;
20849     if (mi.definesRegister(X86::EFLAGS))
20850       break; // Should have kill-flag - update below.
20851   }
20852
20853   // If we hit the end of the block, check whether EFLAGS is live into a
20854   // successor.
20855   if (miI == BB->end()) {
20856     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20857                                           sEnd = BB->succ_end();
20858          sItr != sEnd; ++sItr) {
20859       MachineBasicBlock* succ = *sItr;
20860       if (succ->isLiveIn(X86::EFLAGS))
20861         return false;
20862     }
20863   }
20864
20865   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20866   // out. SelectMI should have a kill flag on EFLAGS.
20867   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20868   return true;
20869 }
20870
20871 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20872 // together with other CMOV pseudo-opcodes into a single basic-block with
20873 // conditional jump around it.
20874 static bool isCMOVPseudo(MachineInstr *MI) {
20875   switch (MI->getOpcode()) {
20876   case X86::CMOV_FR32:
20877   case X86::CMOV_FR64:
20878   case X86::CMOV_GR8:
20879   case X86::CMOV_GR16:
20880   case X86::CMOV_GR32:
20881   case X86::CMOV_RFP32:
20882   case X86::CMOV_RFP64:
20883   case X86::CMOV_RFP80:
20884   case X86::CMOV_V2F64:
20885   case X86::CMOV_V2I64:
20886   case X86::CMOV_V4F32:
20887   case X86::CMOV_V4F64:
20888   case X86::CMOV_V4I64:
20889   case X86::CMOV_V16F32:
20890   case X86::CMOV_V8F32:
20891   case X86::CMOV_V8F64:
20892   case X86::CMOV_V8I64:
20893   case X86::CMOV_V8I1:
20894   case X86::CMOV_V16I1:
20895   case X86::CMOV_V32I1:
20896   case X86::CMOV_V64I1:
20897     return true;
20898
20899   default:
20900     return false;
20901   }
20902 }
20903
20904 MachineBasicBlock *
20905 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20906                                      MachineBasicBlock *BB) const {
20907   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20908   DebugLoc DL = MI->getDebugLoc();
20909
20910   // To "insert" a SELECT_CC instruction, we actually have to insert the
20911   // diamond control-flow pattern.  The incoming instruction knows the
20912   // destination vreg to set, the condition code register to branch on, the
20913   // true/false values to select between, and a branch opcode to use.
20914   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20915   MachineFunction::iterator It = ++BB->getIterator();
20916
20917   //  thisMBB:
20918   //  ...
20919   //   TrueVal = ...
20920   //   cmpTY ccX, r1, r2
20921   //   bCC copy1MBB
20922   //   fallthrough --> copy0MBB
20923   MachineBasicBlock *thisMBB = BB;
20924   MachineFunction *F = BB->getParent();
20925
20926   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20927   // as described above, by inserting a BB, and then making a PHI at the join
20928   // point to select the true and false operands of the CMOV in the PHI.
20929   //
20930   // The code also handles two different cases of multiple CMOV opcodes
20931   // in a row.
20932   //
20933   // Case 1:
20934   // In this case, there are multiple CMOVs in a row, all which are based on
20935   // the same condition setting (or the exact opposite condition setting).
20936   // In this case we can lower all the CMOVs using a single inserted BB, and
20937   // then make a number of PHIs at the join point to model the CMOVs. The only
20938   // trickiness here, is that in a case like:
20939   //
20940   // t2 = CMOV cond1 t1, f1
20941   // t3 = CMOV cond1 t2, f2
20942   //
20943   // when rewriting this into PHIs, we have to perform some renaming on the
20944   // temps since you cannot have a PHI operand refer to a PHI result earlier
20945   // in the same block.  The "simple" but wrong lowering would be:
20946   //
20947   // t2 = PHI t1(BB1), f1(BB2)
20948   // t3 = PHI t2(BB1), f2(BB2)
20949   //
20950   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20951   // renaming is to note that on the path through BB1, t2 is really just a
20952   // copy of t1, and do that renaming, properly generating:
20953   //
20954   // t2 = PHI t1(BB1), f1(BB2)
20955   // t3 = PHI t1(BB1), f2(BB2)
20956   //
20957   // Case 2, we lower cascaded CMOVs such as
20958   //
20959   //   (CMOV (CMOV F, T, cc1), T, cc2)
20960   //
20961   // to two successives branches.  For that, we look for another CMOV as the
20962   // following instruction.
20963   //
20964   // Without this, we would add a PHI between the two jumps, which ends up
20965   // creating a few copies all around. For instance, for
20966   //
20967   //    (sitofp (zext (fcmp une)))
20968   //
20969   // we would generate:
20970   //
20971   //         ucomiss %xmm1, %xmm0
20972   //         movss  <1.0f>, %xmm0
20973   //         movaps  %xmm0, %xmm1
20974   //         jne     .LBB5_2
20975   //         xorps   %xmm1, %xmm1
20976   // .LBB5_2:
20977   //         jp      .LBB5_4
20978   //         movaps  %xmm1, %xmm0
20979   // .LBB5_4:
20980   //         retq
20981   //
20982   // because this custom-inserter would have generated:
20983   //
20984   //   A
20985   //   | \
20986   //   |  B
20987   //   | /
20988   //   C
20989   //   | \
20990   //   |  D
20991   //   | /
20992   //   E
20993   //
20994   // A: X = ...; Y = ...
20995   // B: empty
20996   // C: Z = PHI [X, A], [Y, B]
20997   // D: empty
20998   // E: PHI [X, C], [Z, D]
20999   //
21000   // If we lower both CMOVs in a single step, we can instead generate:
21001   //
21002   //   A
21003   //   | \
21004   //   |  C
21005   //   | /|
21006   //   |/ |
21007   //   |  |
21008   //   |  D
21009   //   | /
21010   //   E
21011   //
21012   // A: X = ...; Y = ...
21013   // D: empty
21014   // E: PHI [X, A], [X, C], [Y, D]
21015   //
21016   // Which, in our sitofp/fcmp example, gives us something like:
21017   //
21018   //         ucomiss %xmm1, %xmm0
21019   //         movss  <1.0f>, %xmm0
21020   //         jne     .LBB5_4
21021   //         jp      .LBB5_4
21022   //         xorps   %xmm0, %xmm0
21023   // .LBB5_4:
21024   //         retq
21025   //
21026   MachineInstr *CascadedCMOV = nullptr;
21027   MachineInstr *LastCMOV = MI;
21028   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21029   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21030   MachineBasicBlock::iterator NextMIIt =
21031       std::next(MachineBasicBlock::iterator(MI));
21032
21033   // Check for case 1, where there are multiple CMOVs with the same condition
21034   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21035   // number of jumps the most.
21036
21037   if (isCMOVPseudo(MI)) {
21038     // See if we have a string of CMOVS with the same condition.
21039     while (NextMIIt != BB->end() &&
21040            isCMOVPseudo(NextMIIt) &&
21041            (NextMIIt->getOperand(3).getImm() == CC ||
21042             NextMIIt->getOperand(3).getImm() == OppCC)) {
21043       LastCMOV = &*NextMIIt;
21044       ++NextMIIt;
21045     }
21046   }
21047
21048   // This checks for case 2, but only do this if we didn't already find
21049   // case 1, as indicated by LastCMOV == MI.
21050   if (LastCMOV == MI &&
21051       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21052       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21053       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21054     CascadedCMOV = &*NextMIIt;
21055   }
21056
21057   MachineBasicBlock *jcc1MBB = nullptr;
21058
21059   // If we have a cascaded CMOV, we lower it to two successive branches to
21060   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21061   if (CascadedCMOV) {
21062     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21063     F->insert(It, jcc1MBB);
21064     jcc1MBB->addLiveIn(X86::EFLAGS);
21065   }
21066
21067   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21068   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21069   F->insert(It, copy0MBB);
21070   F->insert(It, sinkMBB);
21071
21072   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21073   // live into the sink and copy blocks.
21074   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21075
21076   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21077   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21078       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21079     copy0MBB->addLiveIn(X86::EFLAGS);
21080     sinkMBB->addLiveIn(X86::EFLAGS);
21081   }
21082
21083   // Transfer the remainder of BB and its successor edges to sinkMBB.
21084   sinkMBB->splice(sinkMBB->begin(), BB,
21085                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21086   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21087
21088   // Add the true and fallthrough blocks as its successors.
21089   if (CascadedCMOV) {
21090     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21091     BB->addSuccessor(jcc1MBB);
21092
21093     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21094     // jump to the sinkMBB.
21095     jcc1MBB->addSuccessor(copy0MBB);
21096     jcc1MBB->addSuccessor(sinkMBB);
21097   } else {
21098     BB->addSuccessor(copy0MBB);
21099   }
21100
21101   // The true block target of the first (or only) branch is always sinkMBB.
21102   BB->addSuccessor(sinkMBB);
21103
21104   // Create the conditional branch instruction.
21105   unsigned Opc = X86::GetCondBranchFromCond(CC);
21106   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21107
21108   if (CascadedCMOV) {
21109     unsigned Opc2 = X86::GetCondBranchFromCond(
21110         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21111     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21112   }
21113
21114   //  copy0MBB:
21115   //   %FalseValue = ...
21116   //   # fallthrough to sinkMBB
21117   copy0MBB->addSuccessor(sinkMBB);
21118
21119   //  sinkMBB:
21120   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21121   //  ...
21122   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21123   MachineBasicBlock::iterator MIItEnd =
21124     std::next(MachineBasicBlock::iterator(LastCMOV));
21125   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21126   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21127   MachineInstrBuilder MIB;
21128
21129   // As we are creating the PHIs, we have to be careful if there is more than
21130   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21131   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21132   // That also means that PHI construction must work forward from earlier to
21133   // later, and that the code must maintain a mapping from earlier PHI's
21134   // destination registers, and the registers that went into the PHI.
21135
21136   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21137     unsigned DestReg = MIIt->getOperand(0).getReg();
21138     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21139     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21140
21141     // If this CMOV we are generating is the opposite condition from
21142     // the jump we generated, then we have to swap the operands for the
21143     // PHI that is going to be generated.
21144     if (MIIt->getOperand(3).getImm() == OppCC)
21145         std::swap(Op1Reg, Op2Reg);
21146
21147     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21148       Op1Reg = RegRewriteTable[Op1Reg].first;
21149
21150     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21151       Op2Reg = RegRewriteTable[Op2Reg].second;
21152
21153     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21154                   TII->get(X86::PHI), DestReg)
21155           .addReg(Op1Reg).addMBB(copy0MBB)
21156           .addReg(Op2Reg).addMBB(thisMBB);
21157
21158     // Add this PHI to the rewrite table.
21159     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21160   }
21161
21162   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21163   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21164   if (CascadedCMOV) {
21165     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21166     // Copy the PHI result to the register defined by the second CMOV.
21167     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21168             DL, TII->get(TargetOpcode::COPY),
21169             CascadedCMOV->getOperand(0).getReg())
21170         .addReg(MI->getOperand(0).getReg());
21171     CascadedCMOV->eraseFromParent();
21172   }
21173
21174   // Now remove the CMOV(s).
21175   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21176     (MIIt++)->eraseFromParent();
21177
21178   return sinkMBB;
21179 }
21180
21181 MachineBasicBlock *
21182 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21183                                        MachineBasicBlock *BB) const {
21184   // Combine the following atomic floating-point modification pattern:
21185   //   a.store(reg OP a.load(acquire), release)
21186   // Transform them into:
21187   //   OPss (%gpr), %xmm
21188   //   movss %xmm, (%gpr)
21189   // Or sd equivalent for 64-bit operations.
21190   unsigned MOp, FOp;
21191   switch (MI->getOpcode()) {
21192   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21193   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21194   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21195   }
21196   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21197   DebugLoc DL = MI->getDebugLoc();
21198   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21199   MachineOperand MSrc = MI->getOperand(0);
21200   unsigned VSrc = MI->getOperand(5).getReg();
21201   const MachineOperand &Disp = MI->getOperand(3);
21202   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21203   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21204   if (hasDisp && MSrc.isReg())
21205     MSrc.setIsKill(false);
21206   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21207                                 .addOperand(/*Base=*/MSrc)
21208                                 .addImm(/*Scale=*/1)
21209                                 .addReg(/*Index=*/0)
21210                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21211                                 .addReg(0);
21212   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21213                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21214                           .addReg(VSrc)
21215                           .addOperand(/*Base=*/MSrc)
21216                           .addImm(/*Scale=*/1)
21217                           .addReg(/*Index=*/0)
21218                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21219                           .addReg(/*Segment=*/0);
21220   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21221   MI->eraseFromParent(); // The pseudo instruction is gone now.
21222   return BB;
21223 }
21224
21225 MachineBasicBlock *
21226 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21227                                         MachineBasicBlock *BB) const {
21228   MachineFunction *MF = BB->getParent();
21229   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21230   DebugLoc DL = MI->getDebugLoc();
21231   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21232
21233   assert(MF->shouldSplitStack());
21234
21235   const bool Is64Bit = Subtarget->is64Bit();
21236   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21237
21238   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21239   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21240
21241   // BB:
21242   //  ... [Till the alloca]
21243   // If stacklet is not large enough, jump to mallocMBB
21244   //
21245   // bumpMBB:
21246   //  Allocate by subtracting from RSP
21247   //  Jump to continueMBB
21248   //
21249   // mallocMBB:
21250   //  Allocate by call to runtime
21251   //
21252   // continueMBB:
21253   //  ...
21254   //  [rest of original BB]
21255   //
21256
21257   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21258   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21259   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21260
21261   MachineRegisterInfo &MRI = MF->getRegInfo();
21262   const TargetRegisterClass *AddrRegClass =
21263       getRegClassFor(getPointerTy(MF->getDataLayout()));
21264
21265   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21266     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21267     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21268     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21269     sizeVReg = MI->getOperand(1).getReg(),
21270     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21271
21272   MachineFunction::iterator MBBIter = ++BB->getIterator();
21273
21274   MF->insert(MBBIter, bumpMBB);
21275   MF->insert(MBBIter, mallocMBB);
21276   MF->insert(MBBIter, continueMBB);
21277
21278   continueMBB->splice(continueMBB->begin(), BB,
21279                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21280   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21281
21282   // Add code to the main basic block to check if the stack limit has been hit,
21283   // and if so, jump to mallocMBB otherwise to bumpMBB.
21284   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21285   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21286     .addReg(tmpSPVReg).addReg(sizeVReg);
21287   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21288     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21289     .addReg(SPLimitVReg);
21290   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21291
21292   // bumpMBB simply decreases the stack pointer, since we know the current
21293   // stacklet has enough space.
21294   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21295     .addReg(SPLimitVReg);
21296   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21297     .addReg(SPLimitVReg);
21298   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21299
21300   // Calls into a routine in libgcc to allocate more space from the heap.
21301   const uint32_t *RegMask =
21302       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21303   if (IsLP64) {
21304     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21305       .addReg(sizeVReg);
21306     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21307       .addExternalSymbol("__morestack_allocate_stack_space")
21308       .addRegMask(RegMask)
21309       .addReg(X86::RDI, RegState::Implicit)
21310       .addReg(X86::RAX, RegState::ImplicitDefine);
21311   } else if (Is64Bit) {
21312     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21313       .addReg(sizeVReg);
21314     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21315       .addExternalSymbol("__morestack_allocate_stack_space")
21316       .addRegMask(RegMask)
21317       .addReg(X86::EDI, RegState::Implicit)
21318       .addReg(X86::EAX, RegState::ImplicitDefine);
21319   } else {
21320     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21321       .addImm(12);
21322     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21323     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21324       .addExternalSymbol("__morestack_allocate_stack_space")
21325       .addRegMask(RegMask)
21326       .addReg(X86::EAX, RegState::ImplicitDefine);
21327   }
21328
21329   if (!Is64Bit)
21330     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21331       .addImm(16);
21332
21333   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21334     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21335   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21336
21337   // Set up the CFG correctly.
21338   BB->addSuccessor(bumpMBB);
21339   BB->addSuccessor(mallocMBB);
21340   mallocMBB->addSuccessor(continueMBB);
21341   bumpMBB->addSuccessor(continueMBB);
21342
21343   // Take care of the PHI nodes.
21344   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21345           MI->getOperand(0).getReg())
21346     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21347     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21348
21349   // Delete the original pseudo instruction.
21350   MI->eraseFromParent();
21351
21352   // And we're done.
21353   return continueMBB;
21354 }
21355
21356 MachineBasicBlock *
21357 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21358                                         MachineBasicBlock *BB) const {
21359   DebugLoc DL = MI->getDebugLoc();
21360
21361   assert(!Subtarget->isTargetMachO());
21362
21363   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21364                                                     DL);
21365
21366   MI->eraseFromParent();   // The pseudo instruction is gone now.
21367   return BB;
21368 }
21369
21370 MachineBasicBlock *
21371 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21372                                       MachineBasicBlock *BB) const {
21373   // This is pretty easy.  We're taking the value that we received from
21374   // our load from the relocation, sticking it in either RDI (x86-64)
21375   // or EAX and doing an indirect call.  The return value will then
21376   // be in the normal return register.
21377   MachineFunction *F = BB->getParent();
21378   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21379   DebugLoc DL = MI->getDebugLoc();
21380
21381   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21382   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21383
21384   // Get a register mask for the lowered call.
21385   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21386   // proper register mask.
21387   const uint32_t *RegMask =
21388       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21389   if (Subtarget->is64Bit()) {
21390     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21391                                       TII->get(X86::MOV64rm), X86::RDI)
21392     .addReg(X86::RIP)
21393     .addImm(0).addReg(0)
21394     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21395                       MI->getOperand(3).getTargetFlags())
21396     .addReg(0);
21397     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21398     addDirectMem(MIB, X86::RDI);
21399     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21400   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21401     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21402                                       TII->get(X86::MOV32rm), X86::EAX)
21403     .addReg(0)
21404     .addImm(0).addReg(0)
21405     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21406                       MI->getOperand(3).getTargetFlags())
21407     .addReg(0);
21408     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21409     addDirectMem(MIB, X86::EAX);
21410     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21411   } else {
21412     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21413                                       TII->get(X86::MOV32rm), X86::EAX)
21414     .addReg(TII->getGlobalBaseReg(F))
21415     .addImm(0).addReg(0)
21416     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21417                       MI->getOperand(3).getTargetFlags())
21418     .addReg(0);
21419     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21420     addDirectMem(MIB, X86::EAX);
21421     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21422   }
21423
21424   MI->eraseFromParent(); // The pseudo instruction is gone now.
21425   return BB;
21426 }
21427
21428 MachineBasicBlock *
21429 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21430                                     MachineBasicBlock *MBB) const {
21431   DebugLoc DL = MI->getDebugLoc();
21432   MachineFunction *MF = MBB->getParent();
21433   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21434   MachineRegisterInfo &MRI = MF->getRegInfo();
21435
21436   const BasicBlock *BB = MBB->getBasicBlock();
21437   MachineFunction::iterator I = ++MBB->getIterator();
21438
21439   // Memory Reference
21440   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21441   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21442
21443   unsigned DstReg;
21444   unsigned MemOpndSlot = 0;
21445
21446   unsigned CurOp = 0;
21447
21448   DstReg = MI->getOperand(CurOp++).getReg();
21449   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21450   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21451   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21452   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21453
21454   MemOpndSlot = CurOp;
21455
21456   MVT PVT = getPointerTy(MF->getDataLayout());
21457   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21458          "Invalid Pointer Size!");
21459
21460   // For v = setjmp(buf), we generate
21461   //
21462   // thisMBB:
21463   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21464   //  SjLjSetup restoreMBB
21465   //
21466   // mainMBB:
21467   //  v_main = 0
21468   //
21469   // sinkMBB:
21470   //  v = phi(main, restore)
21471   //
21472   // restoreMBB:
21473   //  if base pointer being used, load it from frame
21474   //  v_restore = 1
21475
21476   MachineBasicBlock *thisMBB = MBB;
21477   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21478   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21479   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21480   MF->insert(I, mainMBB);
21481   MF->insert(I, sinkMBB);
21482   MF->push_back(restoreMBB);
21483   restoreMBB->setHasAddressTaken();
21484
21485   MachineInstrBuilder MIB;
21486
21487   // Transfer the remainder of BB and its successor edges to sinkMBB.
21488   sinkMBB->splice(sinkMBB->begin(), MBB,
21489                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21490   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21491
21492   // thisMBB:
21493   unsigned PtrStoreOpc = 0;
21494   unsigned LabelReg = 0;
21495   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21496   Reloc::Model RM = MF->getTarget().getRelocationModel();
21497   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21498                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21499
21500   // Prepare IP either in reg or imm.
21501   if (!UseImmLabel) {
21502     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21503     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21504     LabelReg = MRI.createVirtualRegister(PtrRC);
21505     if (Subtarget->is64Bit()) {
21506       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21507               .addReg(X86::RIP)
21508               .addImm(0)
21509               .addReg(0)
21510               .addMBB(restoreMBB)
21511               .addReg(0);
21512     } else {
21513       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21514       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21515               .addReg(XII->getGlobalBaseReg(MF))
21516               .addImm(0)
21517               .addReg(0)
21518               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21519               .addReg(0);
21520     }
21521   } else
21522     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21523   // Store IP
21524   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21525   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21526     if (i == X86::AddrDisp)
21527       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21528     else
21529       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21530   }
21531   if (!UseImmLabel)
21532     MIB.addReg(LabelReg);
21533   else
21534     MIB.addMBB(restoreMBB);
21535   MIB.setMemRefs(MMOBegin, MMOEnd);
21536   // Setup
21537   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21538           .addMBB(restoreMBB);
21539
21540   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21541   MIB.addRegMask(RegInfo->getNoPreservedMask());
21542   thisMBB->addSuccessor(mainMBB);
21543   thisMBB->addSuccessor(restoreMBB);
21544
21545   // mainMBB:
21546   //  EAX = 0
21547   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21548   mainMBB->addSuccessor(sinkMBB);
21549
21550   // sinkMBB:
21551   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21552           TII->get(X86::PHI), DstReg)
21553     .addReg(mainDstReg).addMBB(mainMBB)
21554     .addReg(restoreDstReg).addMBB(restoreMBB);
21555
21556   // restoreMBB:
21557   if (RegInfo->hasBasePointer(*MF)) {
21558     const bool Uses64BitFramePtr =
21559         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21560     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21561     X86FI->setRestoreBasePointer(MF);
21562     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21563     unsigned BasePtr = RegInfo->getBaseRegister();
21564     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21565     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21566                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21567       .setMIFlag(MachineInstr::FrameSetup);
21568   }
21569   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21570   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21571   restoreMBB->addSuccessor(sinkMBB);
21572
21573   MI->eraseFromParent();
21574   return sinkMBB;
21575 }
21576
21577 MachineBasicBlock *
21578 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21579                                      MachineBasicBlock *MBB) const {
21580   DebugLoc DL = MI->getDebugLoc();
21581   MachineFunction *MF = MBB->getParent();
21582   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21583   MachineRegisterInfo &MRI = MF->getRegInfo();
21584
21585   // Memory Reference
21586   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21587   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21588
21589   MVT PVT = getPointerTy(MF->getDataLayout());
21590   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21591          "Invalid Pointer Size!");
21592
21593   const TargetRegisterClass *RC =
21594     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21595   unsigned Tmp = MRI.createVirtualRegister(RC);
21596   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21597   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21598   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21599   unsigned SP = RegInfo->getStackRegister();
21600
21601   MachineInstrBuilder MIB;
21602
21603   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21604   const int64_t SPOffset = 2 * PVT.getStoreSize();
21605
21606   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21607   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21608
21609   // Reload FP
21610   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21611   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21612     MIB.addOperand(MI->getOperand(i));
21613   MIB.setMemRefs(MMOBegin, MMOEnd);
21614   // Reload IP
21615   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21616   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21617     if (i == X86::AddrDisp)
21618       MIB.addDisp(MI->getOperand(i), LabelOffset);
21619     else
21620       MIB.addOperand(MI->getOperand(i));
21621   }
21622   MIB.setMemRefs(MMOBegin, MMOEnd);
21623   // Reload SP
21624   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21625   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21626     if (i == X86::AddrDisp)
21627       MIB.addDisp(MI->getOperand(i), SPOffset);
21628     else
21629       MIB.addOperand(MI->getOperand(i));
21630   }
21631   MIB.setMemRefs(MMOBegin, MMOEnd);
21632   // Jump
21633   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21634
21635   MI->eraseFromParent();
21636   return MBB;
21637 }
21638
21639 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21640 // accumulator loops. Writing back to the accumulator allows the coalescer
21641 // to remove extra copies in the loop.
21642 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21643 MachineBasicBlock *
21644 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21645                                  MachineBasicBlock *MBB) const {
21646   MachineOperand &AddendOp = MI->getOperand(3);
21647
21648   // Bail out early if the addend isn't a register - we can't switch these.
21649   if (!AddendOp.isReg())
21650     return MBB;
21651
21652   MachineFunction &MF = *MBB->getParent();
21653   MachineRegisterInfo &MRI = MF.getRegInfo();
21654
21655   // Check whether the addend is defined by a PHI:
21656   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21657   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21658   if (!AddendDef.isPHI())
21659     return MBB;
21660
21661   // Look for the following pattern:
21662   // loop:
21663   //   %addend = phi [%entry, 0], [%loop, %result]
21664   //   ...
21665   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21666
21667   // Replace with:
21668   //   loop:
21669   //   %addend = phi [%entry, 0], [%loop, %result]
21670   //   ...
21671   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21672
21673   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21674     assert(AddendDef.getOperand(i).isReg());
21675     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21676     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21677     if (&PHISrcInst == MI) {
21678       // Found a matching instruction.
21679       unsigned NewFMAOpc = 0;
21680       switch (MI->getOpcode()) {
21681         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21682         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21683         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21684         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21685         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21686         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21687         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21688         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21689         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21690         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21691         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21692         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21693         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21694         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21695         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21696         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21697         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21698         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21699         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21700         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21701
21702         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21703         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21704         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21705         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21706         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21707         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21708         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21709         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21710         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21711         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21712         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21713         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21714         default: llvm_unreachable("Unrecognized FMA variant.");
21715       }
21716
21717       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21718       MachineInstrBuilder MIB =
21719         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21720         .addOperand(MI->getOperand(0))
21721         .addOperand(MI->getOperand(3))
21722         .addOperand(MI->getOperand(2))
21723         .addOperand(MI->getOperand(1));
21724       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21725       MI->eraseFromParent();
21726     }
21727   }
21728
21729   return MBB;
21730 }
21731
21732 MachineBasicBlock *
21733 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21734                                                MachineBasicBlock *BB) const {
21735   switch (MI->getOpcode()) {
21736   default: llvm_unreachable("Unexpected instr type to insert");
21737   case X86::TAILJMPd64:
21738   case X86::TAILJMPr64:
21739   case X86::TAILJMPm64:
21740   case X86::TAILJMPd64_REX:
21741   case X86::TAILJMPr64_REX:
21742   case X86::TAILJMPm64_REX:
21743     llvm_unreachable("TAILJMP64 would not be touched here.");
21744   case X86::TCRETURNdi64:
21745   case X86::TCRETURNri64:
21746   case X86::TCRETURNmi64:
21747     return BB;
21748   case X86::WIN_ALLOCA:
21749     return EmitLoweredWinAlloca(MI, BB);
21750   case X86::SEG_ALLOCA_32:
21751   case X86::SEG_ALLOCA_64:
21752     return EmitLoweredSegAlloca(MI, BB);
21753   case X86::TLSCall_32:
21754   case X86::TLSCall_64:
21755     return EmitLoweredTLSCall(MI, BB);
21756   case X86::CMOV_FR32:
21757   case X86::CMOV_FR64:
21758   case X86::CMOV_GR8:
21759   case X86::CMOV_GR16:
21760   case X86::CMOV_GR32:
21761   case X86::CMOV_RFP32:
21762   case X86::CMOV_RFP64:
21763   case X86::CMOV_RFP80:
21764   case X86::CMOV_V2F64:
21765   case X86::CMOV_V2I64:
21766   case X86::CMOV_V4F32:
21767   case X86::CMOV_V4F64:
21768   case X86::CMOV_V4I64:
21769   case X86::CMOV_V16F32:
21770   case X86::CMOV_V8F32:
21771   case X86::CMOV_V8F64:
21772   case X86::CMOV_V8I64:
21773   case X86::CMOV_V8I1:
21774   case X86::CMOV_V16I1:
21775   case X86::CMOV_V32I1:
21776   case X86::CMOV_V64I1:
21777     return EmitLoweredSelect(MI, BB);
21778
21779   case X86::RELEASE_FADD32mr:
21780   case X86::RELEASE_FADD64mr:
21781     return EmitLoweredAtomicFP(MI, BB);
21782
21783   case X86::FP32_TO_INT16_IN_MEM:
21784   case X86::FP32_TO_INT32_IN_MEM:
21785   case X86::FP32_TO_INT64_IN_MEM:
21786   case X86::FP64_TO_INT16_IN_MEM:
21787   case X86::FP64_TO_INT32_IN_MEM:
21788   case X86::FP64_TO_INT64_IN_MEM:
21789   case X86::FP80_TO_INT16_IN_MEM:
21790   case X86::FP80_TO_INT32_IN_MEM:
21791   case X86::FP80_TO_INT64_IN_MEM: {
21792     MachineFunction *F = BB->getParent();
21793     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21794     DebugLoc DL = MI->getDebugLoc();
21795
21796     // Change the floating point control register to use "round towards zero"
21797     // mode when truncating to an integer value.
21798     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21799     addFrameReference(BuildMI(*BB, MI, DL,
21800                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21801
21802     // Load the old value of the high byte of the control word...
21803     unsigned OldCW =
21804       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21805     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21806                       CWFrameIdx);
21807
21808     // Set the high part to be round to zero...
21809     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21810       .addImm(0xC7F);
21811
21812     // Reload the modified control word now...
21813     addFrameReference(BuildMI(*BB, MI, DL,
21814                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21815
21816     // Restore the memory image of control word to original value
21817     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21818       .addReg(OldCW);
21819
21820     // Get the X86 opcode to use.
21821     unsigned Opc;
21822     switch (MI->getOpcode()) {
21823     default: llvm_unreachable("illegal opcode!");
21824     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21825     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21826     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21827     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21828     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21829     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21830     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21831     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21832     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21833     }
21834
21835     X86AddressMode AM;
21836     MachineOperand &Op = MI->getOperand(0);
21837     if (Op.isReg()) {
21838       AM.BaseType = X86AddressMode::RegBase;
21839       AM.Base.Reg = Op.getReg();
21840     } else {
21841       AM.BaseType = X86AddressMode::FrameIndexBase;
21842       AM.Base.FrameIndex = Op.getIndex();
21843     }
21844     Op = MI->getOperand(1);
21845     if (Op.isImm())
21846       AM.Scale = Op.getImm();
21847     Op = MI->getOperand(2);
21848     if (Op.isImm())
21849       AM.IndexReg = Op.getImm();
21850     Op = MI->getOperand(3);
21851     if (Op.isGlobal()) {
21852       AM.GV = Op.getGlobal();
21853     } else {
21854       AM.Disp = Op.getImm();
21855     }
21856     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21857                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21858
21859     // Reload the original control word now.
21860     addFrameReference(BuildMI(*BB, MI, DL,
21861                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21862
21863     MI->eraseFromParent();   // The pseudo instruction is gone now.
21864     return BB;
21865   }
21866     // String/text processing lowering.
21867   case X86::PCMPISTRM128REG:
21868   case X86::VPCMPISTRM128REG:
21869   case X86::PCMPISTRM128MEM:
21870   case X86::VPCMPISTRM128MEM:
21871   case X86::PCMPESTRM128REG:
21872   case X86::VPCMPESTRM128REG:
21873   case X86::PCMPESTRM128MEM:
21874   case X86::VPCMPESTRM128MEM:
21875     assert(Subtarget->hasSSE42() &&
21876            "Target must have SSE4.2 or AVX features enabled");
21877     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21878
21879   // String/text processing lowering.
21880   case X86::PCMPISTRIREG:
21881   case X86::VPCMPISTRIREG:
21882   case X86::PCMPISTRIMEM:
21883   case X86::VPCMPISTRIMEM:
21884   case X86::PCMPESTRIREG:
21885   case X86::VPCMPESTRIREG:
21886   case X86::PCMPESTRIMEM:
21887   case X86::VPCMPESTRIMEM:
21888     assert(Subtarget->hasSSE42() &&
21889            "Target must have SSE4.2 or AVX features enabled");
21890     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21891
21892   // Thread synchronization.
21893   case X86::MONITOR:
21894     return EmitMonitor(MI, BB, Subtarget);
21895
21896   // xbegin
21897   case X86::XBEGIN:
21898     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21899
21900   case X86::VASTART_SAVE_XMM_REGS:
21901     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21902
21903   case X86::VAARG_64:
21904     return EmitVAARG64WithCustomInserter(MI, BB);
21905
21906   case X86::EH_SjLj_SetJmp32:
21907   case X86::EH_SjLj_SetJmp64:
21908     return emitEHSjLjSetJmp(MI, BB);
21909
21910   case X86::EH_SjLj_LongJmp32:
21911   case X86::EH_SjLj_LongJmp64:
21912     return emitEHSjLjLongJmp(MI, BB);
21913
21914   case TargetOpcode::STATEPOINT:
21915     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21916     // this point in the process.  We diverge later.
21917     return emitPatchPoint(MI, BB);
21918
21919   case TargetOpcode::STACKMAP:
21920   case TargetOpcode::PATCHPOINT:
21921     return emitPatchPoint(MI, BB);
21922
21923   case X86::VFMADDPDr213r:
21924   case X86::VFMADDPSr213r:
21925   case X86::VFMADDSDr213r:
21926   case X86::VFMADDSSr213r:
21927   case X86::VFMSUBPDr213r:
21928   case X86::VFMSUBPSr213r:
21929   case X86::VFMSUBSDr213r:
21930   case X86::VFMSUBSSr213r:
21931   case X86::VFNMADDPDr213r:
21932   case X86::VFNMADDPSr213r:
21933   case X86::VFNMADDSDr213r:
21934   case X86::VFNMADDSSr213r:
21935   case X86::VFNMSUBPDr213r:
21936   case X86::VFNMSUBPSr213r:
21937   case X86::VFNMSUBSDr213r:
21938   case X86::VFNMSUBSSr213r:
21939   case X86::VFMADDSUBPDr213r:
21940   case X86::VFMADDSUBPSr213r:
21941   case X86::VFMSUBADDPDr213r:
21942   case X86::VFMSUBADDPSr213r:
21943   case X86::VFMADDPDr213rY:
21944   case X86::VFMADDPSr213rY:
21945   case X86::VFMSUBPDr213rY:
21946   case X86::VFMSUBPSr213rY:
21947   case X86::VFNMADDPDr213rY:
21948   case X86::VFNMADDPSr213rY:
21949   case X86::VFNMSUBPDr213rY:
21950   case X86::VFNMSUBPSr213rY:
21951   case X86::VFMADDSUBPDr213rY:
21952   case X86::VFMADDSUBPSr213rY:
21953   case X86::VFMSUBADDPDr213rY:
21954   case X86::VFMSUBADDPSr213rY:
21955     return emitFMA3Instr(MI, BB);
21956   }
21957 }
21958
21959 //===----------------------------------------------------------------------===//
21960 //                           X86 Optimization Hooks
21961 //===----------------------------------------------------------------------===//
21962
21963 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21964                                                       APInt &KnownZero,
21965                                                       APInt &KnownOne,
21966                                                       const SelectionDAG &DAG,
21967                                                       unsigned Depth) const {
21968   unsigned BitWidth = KnownZero.getBitWidth();
21969   unsigned Opc = Op.getOpcode();
21970   assert((Opc >= ISD::BUILTIN_OP_END ||
21971           Opc == ISD::INTRINSIC_WO_CHAIN ||
21972           Opc == ISD::INTRINSIC_W_CHAIN ||
21973           Opc == ISD::INTRINSIC_VOID) &&
21974          "Should use MaskedValueIsZero if you don't know whether Op"
21975          " is a target node!");
21976
21977   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21978   switch (Opc) {
21979   default: break;
21980   case X86ISD::ADD:
21981   case X86ISD::SUB:
21982   case X86ISD::ADC:
21983   case X86ISD::SBB:
21984   case X86ISD::SMUL:
21985   case X86ISD::UMUL:
21986   case X86ISD::INC:
21987   case X86ISD::DEC:
21988   case X86ISD::OR:
21989   case X86ISD::XOR:
21990   case X86ISD::AND:
21991     // These nodes' second result is a boolean.
21992     if (Op.getResNo() == 0)
21993       break;
21994     // Fallthrough
21995   case X86ISD::SETCC:
21996     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21997     break;
21998   case ISD::INTRINSIC_WO_CHAIN: {
21999     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22000     unsigned NumLoBits = 0;
22001     switch (IntId) {
22002     default: break;
22003     case Intrinsic::x86_sse_movmsk_ps:
22004     case Intrinsic::x86_avx_movmsk_ps_256:
22005     case Intrinsic::x86_sse2_movmsk_pd:
22006     case Intrinsic::x86_avx_movmsk_pd_256:
22007     case Intrinsic::x86_mmx_pmovmskb:
22008     case Intrinsic::x86_sse2_pmovmskb_128:
22009     case Intrinsic::x86_avx2_pmovmskb: {
22010       // High bits of movmskp{s|d}, pmovmskb are known zero.
22011       switch (IntId) {
22012         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22013         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22014         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22015         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22016         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22017         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22018         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22019         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22020       }
22021       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22022       break;
22023     }
22024     }
22025     break;
22026   }
22027   }
22028 }
22029
22030 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22031   SDValue Op,
22032   const SelectionDAG &,
22033   unsigned Depth) const {
22034   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22035   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22036     return Op.getValueType().getScalarType().getSizeInBits();
22037
22038   // Fallback case.
22039   return 1;
22040 }
22041
22042 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22043 /// node is a GlobalAddress + offset.
22044 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22045                                        const GlobalValue* &GA,
22046                                        int64_t &Offset) const {
22047   if (N->getOpcode() == X86ISD::Wrapper) {
22048     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22049       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22050       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22051       return true;
22052     }
22053   }
22054   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22055 }
22056
22057 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22058 /// same as extracting the high 128-bit part of 256-bit vector and then
22059 /// inserting the result into the low part of a new 256-bit vector
22060 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22061   EVT VT = SVOp->getValueType(0);
22062   unsigned NumElems = VT.getVectorNumElements();
22063
22064   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22065   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22066     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22067         SVOp->getMaskElt(j) >= 0)
22068       return false;
22069
22070   return true;
22071 }
22072
22073 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22074 /// same as extracting the low 128-bit part of 256-bit vector and then
22075 /// inserting the result into the high part of a new 256-bit vector
22076 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22077   EVT VT = SVOp->getValueType(0);
22078   unsigned NumElems = VT.getVectorNumElements();
22079
22080   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22081   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22082     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22083         SVOp->getMaskElt(j) >= 0)
22084       return false;
22085
22086   return true;
22087 }
22088
22089 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22090 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22091                                         TargetLowering::DAGCombinerInfo &DCI,
22092                                         const X86Subtarget* Subtarget) {
22093   SDLoc dl(N);
22094   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22095   SDValue V1 = SVOp->getOperand(0);
22096   SDValue V2 = SVOp->getOperand(1);
22097   EVT VT = SVOp->getValueType(0);
22098   unsigned NumElems = VT.getVectorNumElements();
22099
22100   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22101       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22102     //
22103     //                   0,0,0,...
22104     //                      |
22105     //    V      UNDEF    BUILD_VECTOR    UNDEF
22106     //     \      /           \           /
22107     //  CONCAT_VECTOR         CONCAT_VECTOR
22108     //         \                  /
22109     //          \                /
22110     //          RESULT: V + zero extended
22111     //
22112     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22113         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22114         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22115       return SDValue();
22116
22117     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22118       return SDValue();
22119
22120     // To match the shuffle mask, the first half of the mask should
22121     // be exactly the first vector, and all the rest a splat with the
22122     // first element of the second one.
22123     for (unsigned i = 0; i != NumElems/2; ++i)
22124       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22125           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22126         return SDValue();
22127
22128     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22129     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22130       if (Ld->hasNUsesOfValue(1, 0)) {
22131         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22132         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22133         SDValue ResNode =
22134           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22135                                   Ld->getMemoryVT(),
22136                                   Ld->getPointerInfo(),
22137                                   Ld->getAlignment(),
22138                                   false/*isVolatile*/, true/*ReadMem*/,
22139                                   false/*WriteMem*/);
22140
22141         // Make sure the newly-created LOAD is in the same position as Ld in
22142         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22143         // and update uses of Ld's output chain to use the TokenFactor.
22144         if (Ld->hasAnyUseOfValue(1)) {
22145           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22146                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22147           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22148           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22149                                  SDValue(ResNode.getNode(), 1));
22150         }
22151
22152         return DAG.getBitcast(VT, ResNode);
22153       }
22154     }
22155
22156     // Emit a zeroed vector and insert the desired subvector on its
22157     // first half.
22158     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22159     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22160     return DCI.CombineTo(N, InsV);
22161   }
22162
22163   //===--------------------------------------------------------------------===//
22164   // Combine some shuffles into subvector extracts and inserts:
22165   //
22166
22167   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22168   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22169     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22170     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22171     return DCI.CombineTo(N, InsV);
22172   }
22173
22174   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22175   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22176     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22177     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22178     return DCI.CombineTo(N, InsV);
22179   }
22180
22181   return SDValue();
22182 }
22183
22184 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22185 /// possible.
22186 ///
22187 /// This is the leaf of the recursive combinine below. When we have found some
22188 /// chain of single-use x86 shuffle instructions and accumulated the combined
22189 /// shuffle mask represented by them, this will try to pattern match that mask
22190 /// into either a single instruction if there is a special purpose instruction
22191 /// for this operation, or into a PSHUFB instruction which is a fully general
22192 /// instruction but should only be used to replace chains over a certain depth.
22193 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22194                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22195                                    TargetLowering::DAGCombinerInfo &DCI,
22196                                    const X86Subtarget *Subtarget) {
22197   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22198
22199   // Find the operand that enters the chain. Note that multiple uses are OK
22200   // here, we're not going to remove the operand we find.
22201   SDValue Input = Op.getOperand(0);
22202   while (Input.getOpcode() == ISD::BITCAST)
22203     Input = Input.getOperand(0);
22204
22205   MVT VT = Input.getSimpleValueType();
22206   MVT RootVT = Root.getSimpleValueType();
22207   SDLoc DL(Root);
22208
22209   if (Mask.size() == 1) {
22210     int Index = Mask[0];
22211     assert((Index >= 0 || Index == SM_SentinelUndef ||
22212             Index == SM_SentinelZero) &&
22213            "Invalid shuffle index found!");
22214
22215     // We may end up with an accumulated mask of size 1 as a result of
22216     // widening of shuffle operands (see function canWidenShuffleElements).
22217     // If the only shuffle index is equal to SM_SentinelZero then propagate
22218     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22219     // mask, and therefore the entire chain of shuffles can be folded away.
22220     if (Index == SM_SentinelZero)
22221       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22222     else
22223       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22224                     /*AddTo*/ true);
22225     return true;
22226   }
22227
22228   // Use the float domain if the operand type is a floating point type.
22229   bool FloatDomain = VT.isFloatingPoint();
22230
22231   // For floating point shuffles, we don't have free copies in the shuffle
22232   // instructions or the ability to load as part of the instruction, so
22233   // canonicalize their shuffles to UNPCK or MOV variants.
22234   //
22235   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22236   // vectors because it can have a load folded into it that UNPCK cannot. This
22237   // doesn't preclude something switching to the shorter encoding post-RA.
22238   //
22239   // FIXME: Should teach these routines about AVX vector widths.
22240   if (FloatDomain && VT.getSizeInBits() == 128) {
22241     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22242       bool Lo = Mask.equals({0, 0});
22243       unsigned Shuffle;
22244       MVT ShuffleVT;
22245       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22246       // is no slower than UNPCKLPD but has the option to fold the input operand
22247       // into even an unaligned memory load.
22248       if (Lo && Subtarget->hasSSE3()) {
22249         Shuffle = X86ISD::MOVDDUP;
22250         ShuffleVT = MVT::v2f64;
22251       } else {
22252         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22253         // than the UNPCK variants.
22254         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22255         ShuffleVT = MVT::v4f32;
22256       }
22257       if (Depth == 1 && Root->getOpcode() == Shuffle)
22258         return false; // Nothing to do!
22259       Op = DAG.getBitcast(ShuffleVT, Input);
22260       DCI.AddToWorklist(Op.getNode());
22261       if (Shuffle == X86ISD::MOVDDUP)
22262         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22263       else
22264         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22265       DCI.AddToWorklist(Op.getNode());
22266       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22267                     /*AddTo*/ true);
22268       return true;
22269     }
22270     if (Subtarget->hasSSE3() &&
22271         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22272       bool Lo = Mask.equals({0, 0, 2, 2});
22273       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22274       MVT ShuffleVT = MVT::v4f32;
22275       if (Depth == 1 && Root->getOpcode() == Shuffle)
22276         return false; // Nothing to do!
22277       Op = DAG.getBitcast(ShuffleVT, Input);
22278       DCI.AddToWorklist(Op.getNode());
22279       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22280       DCI.AddToWorklist(Op.getNode());
22281       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22282                     /*AddTo*/ true);
22283       return true;
22284     }
22285     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22286       bool Lo = Mask.equals({0, 0, 1, 1});
22287       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22288       MVT ShuffleVT = MVT::v4f32;
22289       if (Depth == 1 && Root->getOpcode() == Shuffle)
22290         return false; // Nothing to do!
22291       Op = DAG.getBitcast(ShuffleVT, Input);
22292       DCI.AddToWorklist(Op.getNode());
22293       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22294       DCI.AddToWorklist(Op.getNode());
22295       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22296                     /*AddTo*/ true);
22297       return true;
22298     }
22299   }
22300
22301   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22302   // variants as none of these have single-instruction variants that are
22303   // superior to the UNPCK formulation.
22304   if (!FloatDomain && VT.getSizeInBits() == 128 &&
22305       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22306        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22307        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22308        Mask.equals(
22309            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22310     bool Lo = Mask[0] == 0;
22311     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22312     if (Depth == 1 && Root->getOpcode() == Shuffle)
22313       return false; // Nothing to do!
22314     MVT ShuffleVT;
22315     switch (Mask.size()) {
22316     case 8:
22317       ShuffleVT = MVT::v8i16;
22318       break;
22319     case 16:
22320       ShuffleVT = MVT::v16i8;
22321       break;
22322     default:
22323       llvm_unreachable("Impossible mask size!");
22324     };
22325     Op = DAG.getBitcast(ShuffleVT, Input);
22326     DCI.AddToWorklist(Op.getNode());
22327     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22328     DCI.AddToWorklist(Op.getNode());
22329     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22330                   /*AddTo*/ true);
22331     return true;
22332   }
22333
22334   // Don't try to re-form single instruction chains under any circumstances now
22335   // that we've done encoding canonicalization for them.
22336   if (Depth < 2)
22337     return false;
22338
22339   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22340   // can replace them with a single PSHUFB instruction profitably. Intel's
22341   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22342   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22343   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22344     SmallVector<SDValue, 16> PSHUFBMask;
22345     int NumBytes = VT.getSizeInBits() / 8;
22346     int Ratio = NumBytes / Mask.size();
22347     for (int i = 0; i < NumBytes; ++i) {
22348       if (Mask[i / Ratio] == SM_SentinelUndef) {
22349         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22350         continue;
22351       }
22352       int M = Mask[i / Ratio] != SM_SentinelZero
22353                   ? Ratio * Mask[i / Ratio] + i % Ratio
22354                   : 255;
22355       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22356     }
22357     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22358     Op = DAG.getBitcast(ByteVT, Input);
22359     DCI.AddToWorklist(Op.getNode());
22360     SDValue PSHUFBMaskOp =
22361         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22362     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22363     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22364     DCI.AddToWorklist(Op.getNode());
22365     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22366                   /*AddTo*/ true);
22367     return true;
22368   }
22369
22370   // Failed to find any combines.
22371   return false;
22372 }
22373
22374 /// \brief Fully generic combining of x86 shuffle instructions.
22375 ///
22376 /// This should be the last combine run over the x86 shuffle instructions. Once
22377 /// they have been fully optimized, this will recursively consider all chains
22378 /// of single-use shuffle instructions, build a generic model of the cumulative
22379 /// shuffle operation, and check for simpler instructions which implement this
22380 /// operation. We use this primarily for two purposes:
22381 ///
22382 /// 1) Collapse generic shuffles to specialized single instructions when
22383 ///    equivalent. In most cases, this is just an encoding size win, but
22384 ///    sometimes we will collapse multiple generic shuffles into a single
22385 ///    special-purpose shuffle.
22386 /// 2) Look for sequences of shuffle instructions with 3 or more total
22387 ///    instructions, and replace them with the slightly more expensive SSSE3
22388 ///    PSHUFB instruction if available. We do this as the last combining step
22389 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22390 ///    a suitable short sequence of other instructions. The PHUFB will either
22391 ///    use a register or have to read from memory and so is slightly (but only
22392 ///    slightly) more expensive than the other shuffle instructions.
22393 ///
22394 /// Because this is inherently a quadratic operation (for each shuffle in
22395 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22396 /// This should never be an issue in practice as the shuffle lowering doesn't
22397 /// produce sequences of more than 8 instructions.
22398 ///
22399 /// FIXME: We will currently miss some cases where the redundant shuffling
22400 /// would simplify under the threshold for PSHUFB formation because of
22401 /// combine-ordering. To fix this, we should do the redundant instruction
22402 /// combining in this recursive walk.
22403 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22404                                           ArrayRef<int> RootMask,
22405                                           int Depth, bool HasPSHUFB,
22406                                           SelectionDAG &DAG,
22407                                           TargetLowering::DAGCombinerInfo &DCI,
22408                                           const X86Subtarget *Subtarget) {
22409   // Bound the depth of our recursive combine because this is ultimately
22410   // quadratic in nature.
22411   if (Depth > 8)
22412     return false;
22413
22414   // Directly rip through bitcasts to find the underlying operand.
22415   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22416     Op = Op.getOperand(0);
22417
22418   MVT VT = Op.getSimpleValueType();
22419   if (!VT.isVector())
22420     return false; // Bail if we hit a non-vector.
22421
22422   assert(Root.getSimpleValueType().isVector() &&
22423          "Shuffles operate on vector types!");
22424   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22425          "Can only combine shuffles of the same vector register size.");
22426
22427   if (!isTargetShuffle(Op.getOpcode()))
22428     return false;
22429   SmallVector<int, 16> OpMask;
22430   bool IsUnary;
22431   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22432   // We only can combine unary shuffles which we can decode the mask for.
22433   if (!HaveMask || !IsUnary)
22434     return false;
22435
22436   assert(VT.getVectorNumElements() == OpMask.size() &&
22437          "Different mask size from vector size!");
22438   assert(((RootMask.size() > OpMask.size() &&
22439            RootMask.size() % OpMask.size() == 0) ||
22440           (OpMask.size() > RootMask.size() &&
22441            OpMask.size() % RootMask.size() == 0) ||
22442           OpMask.size() == RootMask.size()) &&
22443          "The smaller number of elements must divide the larger.");
22444   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22445   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22446   assert(((RootRatio == 1 && OpRatio == 1) ||
22447           (RootRatio == 1) != (OpRatio == 1)) &&
22448          "Must not have a ratio for both incoming and op masks!");
22449
22450   SmallVector<int, 16> Mask;
22451   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22452
22453   // Merge this shuffle operation's mask into our accumulated mask. Note that
22454   // this shuffle's mask will be the first applied to the input, followed by the
22455   // root mask to get us all the way to the root value arrangement. The reason
22456   // for this order is that we are recursing up the operation chain.
22457   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22458     int RootIdx = i / RootRatio;
22459     if (RootMask[RootIdx] < 0) {
22460       // This is a zero or undef lane, we're done.
22461       Mask.push_back(RootMask[RootIdx]);
22462       continue;
22463     }
22464
22465     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22466     int OpIdx = RootMaskedIdx / OpRatio;
22467     if (OpMask[OpIdx] < 0) {
22468       // The incoming lanes are zero or undef, it doesn't matter which ones we
22469       // are using.
22470       Mask.push_back(OpMask[OpIdx]);
22471       continue;
22472     }
22473
22474     // Ok, we have non-zero lanes, map them through.
22475     Mask.push_back(OpMask[OpIdx] * OpRatio +
22476                    RootMaskedIdx % OpRatio);
22477   }
22478
22479   // See if we can recurse into the operand to combine more things.
22480   switch (Op.getOpcode()) {
22481   case X86ISD::PSHUFB:
22482     HasPSHUFB = true;
22483   case X86ISD::PSHUFD:
22484   case X86ISD::PSHUFHW:
22485   case X86ISD::PSHUFLW:
22486     if (Op.getOperand(0).hasOneUse() &&
22487         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22488                                       HasPSHUFB, DAG, DCI, Subtarget))
22489       return true;
22490     break;
22491
22492   case X86ISD::UNPCKL:
22493   case X86ISD::UNPCKH:
22494     assert(Op.getOperand(0) == Op.getOperand(1) &&
22495            "We only combine unary shuffles!");
22496     // We can't check for single use, we have to check that this shuffle is the
22497     // only user.
22498     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22499         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22500                                       HasPSHUFB, DAG, DCI, Subtarget))
22501       return true;
22502     break;
22503   }
22504
22505   // Minor canonicalization of the accumulated shuffle mask to make it easier
22506   // to match below. All this does is detect masks with squential pairs of
22507   // elements, and shrink them to the half-width mask. It does this in a loop
22508   // so it will reduce the size of the mask to the minimal width mask which
22509   // performs an equivalent shuffle.
22510   SmallVector<int, 16> WidenedMask;
22511   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22512     Mask = std::move(WidenedMask);
22513     WidenedMask.clear();
22514   }
22515
22516   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22517                                 Subtarget);
22518 }
22519
22520 /// \brief Get the PSHUF-style mask from PSHUF node.
22521 ///
22522 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22523 /// PSHUF-style masks that can be reused with such instructions.
22524 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22525   MVT VT = N.getSimpleValueType();
22526   SmallVector<int, 4> Mask;
22527   bool IsUnary;
22528   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22529   (void)HaveMask;
22530   assert(HaveMask);
22531
22532   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22533   // matter. Check that the upper masks are repeats and remove them.
22534   if (VT.getSizeInBits() > 128) {
22535     int LaneElts = 128 / VT.getScalarSizeInBits();
22536 #ifndef NDEBUG
22537     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22538       for (int j = 0; j < LaneElts; ++j)
22539         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22540                "Mask doesn't repeat in high 128-bit lanes!");
22541 #endif
22542     Mask.resize(LaneElts);
22543   }
22544
22545   switch (N.getOpcode()) {
22546   case X86ISD::PSHUFD:
22547     return Mask;
22548   case X86ISD::PSHUFLW:
22549     Mask.resize(4);
22550     return Mask;
22551   case X86ISD::PSHUFHW:
22552     Mask.erase(Mask.begin(), Mask.begin() + 4);
22553     for (int &M : Mask)
22554       M -= 4;
22555     return Mask;
22556   default:
22557     llvm_unreachable("No valid shuffle instruction found!");
22558   }
22559 }
22560
22561 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22562 ///
22563 /// We walk up the chain and look for a combinable shuffle, skipping over
22564 /// shuffles that we could hoist this shuffle's transformation past without
22565 /// altering anything.
22566 static SDValue
22567 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22568                              SelectionDAG &DAG,
22569                              TargetLowering::DAGCombinerInfo &DCI) {
22570   assert(N.getOpcode() == X86ISD::PSHUFD &&
22571          "Called with something other than an x86 128-bit half shuffle!");
22572   SDLoc DL(N);
22573
22574   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22575   // of the shuffles in the chain so that we can form a fresh chain to replace
22576   // this one.
22577   SmallVector<SDValue, 8> Chain;
22578   SDValue V = N.getOperand(0);
22579   for (; V.hasOneUse(); V = V.getOperand(0)) {
22580     switch (V.getOpcode()) {
22581     default:
22582       return SDValue(); // Nothing combined!
22583
22584     case ISD::BITCAST:
22585       // Skip bitcasts as we always know the type for the target specific
22586       // instructions.
22587       continue;
22588
22589     case X86ISD::PSHUFD:
22590       // Found another dword shuffle.
22591       break;
22592
22593     case X86ISD::PSHUFLW:
22594       // Check that the low words (being shuffled) are the identity in the
22595       // dword shuffle, and the high words are self-contained.
22596       if (Mask[0] != 0 || Mask[1] != 1 ||
22597           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22598         return SDValue();
22599
22600       Chain.push_back(V);
22601       continue;
22602
22603     case X86ISD::PSHUFHW:
22604       // Check that the high words (being shuffled) are the identity in the
22605       // dword shuffle, and the low words are self-contained.
22606       if (Mask[2] != 2 || Mask[3] != 3 ||
22607           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22608         return SDValue();
22609
22610       Chain.push_back(V);
22611       continue;
22612
22613     case X86ISD::UNPCKL:
22614     case X86ISD::UNPCKH:
22615       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22616       // shuffle into a preceding word shuffle.
22617       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22618           V.getSimpleValueType().getScalarType() != MVT::i16)
22619         return SDValue();
22620
22621       // Search for a half-shuffle which we can combine with.
22622       unsigned CombineOp =
22623           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22624       if (V.getOperand(0) != V.getOperand(1) ||
22625           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22626         return SDValue();
22627       Chain.push_back(V);
22628       V = V.getOperand(0);
22629       do {
22630         switch (V.getOpcode()) {
22631         default:
22632           return SDValue(); // Nothing to combine.
22633
22634         case X86ISD::PSHUFLW:
22635         case X86ISD::PSHUFHW:
22636           if (V.getOpcode() == CombineOp)
22637             break;
22638
22639           Chain.push_back(V);
22640
22641           // Fallthrough!
22642         case ISD::BITCAST:
22643           V = V.getOperand(0);
22644           continue;
22645         }
22646         break;
22647       } while (V.hasOneUse());
22648       break;
22649     }
22650     // Break out of the loop if we break out of the switch.
22651     break;
22652   }
22653
22654   if (!V.hasOneUse())
22655     // We fell out of the loop without finding a viable combining instruction.
22656     return SDValue();
22657
22658   // Merge this node's mask and our incoming mask.
22659   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22660   for (int &M : Mask)
22661     M = VMask[M];
22662   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22663                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22664
22665   // Rebuild the chain around this new shuffle.
22666   while (!Chain.empty()) {
22667     SDValue W = Chain.pop_back_val();
22668
22669     if (V.getValueType() != W.getOperand(0).getValueType())
22670       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22671
22672     switch (W.getOpcode()) {
22673     default:
22674       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22675
22676     case X86ISD::UNPCKL:
22677     case X86ISD::UNPCKH:
22678       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22679       break;
22680
22681     case X86ISD::PSHUFD:
22682     case X86ISD::PSHUFLW:
22683     case X86ISD::PSHUFHW:
22684       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22685       break;
22686     }
22687   }
22688   if (V.getValueType() != N.getValueType())
22689     V = DAG.getBitcast(N.getValueType(), V);
22690
22691   // Return the new chain to replace N.
22692   return V;
22693 }
22694
22695 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22696 /// pshufhw.
22697 ///
22698 /// We walk up the chain, skipping shuffles of the other half and looking
22699 /// through shuffles which switch halves trying to find a shuffle of the same
22700 /// pair of dwords.
22701 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22702                                         SelectionDAG &DAG,
22703                                         TargetLowering::DAGCombinerInfo &DCI) {
22704   assert(
22705       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22706       "Called with something other than an x86 128-bit half shuffle!");
22707   SDLoc DL(N);
22708   unsigned CombineOpcode = N.getOpcode();
22709
22710   // Walk up a single-use chain looking for a combinable shuffle.
22711   SDValue V = N.getOperand(0);
22712   for (; V.hasOneUse(); V = V.getOperand(0)) {
22713     switch (V.getOpcode()) {
22714     default:
22715       return false; // Nothing combined!
22716
22717     case ISD::BITCAST:
22718       // Skip bitcasts as we always know the type for the target specific
22719       // instructions.
22720       continue;
22721
22722     case X86ISD::PSHUFLW:
22723     case X86ISD::PSHUFHW:
22724       if (V.getOpcode() == CombineOpcode)
22725         break;
22726
22727       // Other-half shuffles are no-ops.
22728       continue;
22729     }
22730     // Break out of the loop if we break out of the switch.
22731     break;
22732   }
22733
22734   if (!V.hasOneUse())
22735     // We fell out of the loop without finding a viable combining instruction.
22736     return false;
22737
22738   // Combine away the bottom node as its shuffle will be accumulated into
22739   // a preceding shuffle.
22740   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22741
22742   // Record the old value.
22743   SDValue Old = V;
22744
22745   // Merge this node's mask and our incoming mask (adjusted to account for all
22746   // the pshufd instructions encountered).
22747   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22748   for (int &M : Mask)
22749     M = VMask[M];
22750   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22751                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22752
22753   // Check that the shuffles didn't cancel each other out. If not, we need to
22754   // combine to the new one.
22755   if (Old != V)
22756     // Replace the combinable shuffle with the combined one, updating all users
22757     // so that we re-evaluate the chain here.
22758     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22759
22760   return true;
22761 }
22762
22763 /// \brief Try to combine x86 target specific shuffles.
22764 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22765                                            TargetLowering::DAGCombinerInfo &DCI,
22766                                            const X86Subtarget *Subtarget) {
22767   SDLoc DL(N);
22768   MVT VT = N.getSimpleValueType();
22769   SmallVector<int, 4> Mask;
22770
22771   switch (N.getOpcode()) {
22772   case X86ISD::PSHUFD:
22773   case X86ISD::PSHUFLW:
22774   case X86ISD::PSHUFHW:
22775     Mask = getPSHUFShuffleMask(N);
22776     assert(Mask.size() == 4);
22777     break;
22778   default:
22779     return SDValue();
22780   }
22781
22782   // Nuke no-op shuffles that show up after combining.
22783   if (isNoopShuffleMask(Mask))
22784     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22785
22786   // Look for simplifications involving one or two shuffle instructions.
22787   SDValue V = N.getOperand(0);
22788   switch (N.getOpcode()) {
22789   default:
22790     break;
22791   case X86ISD::PSHUFLW:
22792   case X86ISD::PSHUFHW:
22793     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22794
22795     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22796       return SDValue(); // We combined away this shuffle, so we're done.
22797
22798     // See if this reduces to a PSHUFD which is no more expensive and can
22799     // combine with more operations. Note that it has to at least flip the
22800     // dwords as otherwise it would have been removed as a no-op.
22801     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22802       int DMask[] = {0, 1, 2, 3};
22803       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22804       DMask[DOffset + 0] = DOffset + 1;
22805       DMask[DOffset + 1] = DOffset + 0;
22806       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22807       V = DAG.getBitcast(DVT, V);
22808       DCI.AddToWorklist(V.getNode());
22809       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22810                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22811       DCI.AddToWorklist(V.getNode());
22812       return DAG.getBitcast(VT, V);
22813     }
22814
22815     // Look for shuffle patterns which can be implemented as a single unpack.
22816     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22817     // only works when we have a PSHUFD followed by two half-shuffles.
22818     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22819         (V.getOpcode() == X86ISD::PSHUFLW ||
22820          V.getOpcode() == X86ISD::PSHUFHW) &&
22821         V.getOpcode() != N.getOpcode() &&
22822         V.hasOneUse()) {
22823       SDValue D = V.getOperand(0);
22824       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22825         D = D.getOperand(0);
22826       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22827         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22828         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22829         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22830         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22831         int WordMask[8];
22832         for (int i = 0; i < 4; ++i) {
22833           WordMask[i + NOffset] = Mask[i] + NOffset;
22834           WordMask[i + VOffset] = VMask[i] + VOffset;
22835         }
22836         // Map the word mask through the DWord mask.
22837         int MappedMask[8];
22838         for (int i = 0; i < 8; ++i)
22839           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22840         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22841             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22842           // We can replace all three shuffles with an unpack.
22843           V = DAG.getBitcast(VT, D.getOperand(0));
22844           DCI.AddToWorklist(V.getNode());
22845           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22846                                                 : X86ISD::UNPCKH,
22847                              DL, VT, V, V);
22848         }
22849       }
22850     }
22851
22852     break;
22853
22854   case X86ISD::PSHUFD:
22855     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22856       return NewN;
22857
22858     break;
22859   }
22860
22861   return SDValue();
22862 }
22863
22864 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22865 ///
22866 /// We combine this directly on the abstract vector shuffle nodes so it is
22867 /// easier to generically match. We also insert dummy vector shuffle nodes for
22868 /// the operands which explicitly discard the lanes which are unused by this
22869 /// operation to try to flow through the rest of the combiner the fact that
22870 /// they're unused.
22871 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22872   SDLoc DL(N);
22873   EVT VT = N->getValueType(0);
22874
22875   // We only handle target-independent shuffles.
22876   // FIXME: It would be easy and harmless to use the target shuffle mask
22877   // extraction tool to support more.
22878   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22879     return SDValue();
22880
22881   auto *SVN = cast<ShuffleVectorSDNode>(N);
22882   ArrayRef<int> Mask = SVN->getMask();
22883   SDValue V1 = N->getOperand(0);
22884   SDValue V2 = N->getOperand(1);
22885
22886   // We require the first shuffle operand to be the SUB node, and the second to
22887   // be the ADD node.
22888   // FIXME: We should support the commuted patterns.
22889   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22890     return SDValue();
22891
22892   // If there are other uses of these operations we can't fold them.
22893   if (!V1->hasOneUse() || !V2->hasOneUse())
22894     return SDValue();
22895
22896   // Ensure that both operations have the same operands. Note that we can
22897   // commute the FADD operands.
22898   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22899   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22900       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22901     return SDValue();
22902
22903   // We're looking for blends between FADD and FSUB nodes. We insist on these
22904   // nodes being lined up in a specific expected pattern.
22905   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22906         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22907         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22908     return SDValue();
22909
22910   // Only specific types are legal at this point, assert so we notice if and
22911   // when these change.
22912   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22913           VT == MVT::v4f64) &&
22914          "Unknown vector type encountered!");
22915
22916   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22917 }
22918
22919 /// PerformShuffleCombine - Performs several different shuffle combines.
22920 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22921                                      TargetLowering::DAGCombinerInfo &DCI,
22922                                      const X86Subtarget *Subtarget) {
22923   SDLoc dl(N);
22924   SDValue N0 = N->getOperand(0);
22925   SDValue N1 = N->getOperand(1);
22926   EVT VT = N->getValueType(0);
22927
22928   // Don't create instructions with illegal types after legalize types has run.
22929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22930   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22931     return SDValue();
22932
22933   // If we have legalized the vector types, look for blends of FADD and FSUB
22934   // nodes that we can fuse into an ADDSUB node.
22935   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22936     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22937       return AddSub;
22938
22939   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22940   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22941       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22942     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22943
22944   // During Type Legalization, when promoting illegal vector types,
22945   // the backend might introduce new shuffle dag nodes and bitcasts.
22946   //
22947   // This code performs the following transformation:
22948   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22949   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22950   //
22951   // We do this only if both the bitcast and the BINOP dag nodes have
22952   // one use. Also, perform this transformation only if the new binary
22953   // operation is legal. This is to avoid introducing dag nodes that
22954   // potentially need to be further expanded (or custom lowered) into a
22955   // less optimal sequence of dag nodes.
22956   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22957       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22958       N0.getOpcode() == ISD::BITCAST) {
22959     SDValue BC0 = N0.getOperand(0);
22960     EVT SVT = BC0.getValueType();
22961     unsigned Opcode = BC0.getOpcode();
22962     unsigned NumElts = VT.getVectorNumElements();
22963
22964     if (BC0.hasOneUse() && SVT.isVector() &&
22965         SVT.getVectorNumElements() * 2 == NumElts &&
22966         TLI.isOperationLegal(Opcode, VT)) {
22967       bool CanFold = false;
22968       switch (Opcode) {
22969       default : break;
22970       case ISD::ADD :
22971       case ISD::FADD :
22972       case ISD::SUB :
22973       case ISD::FSUB :
22974       case ISD::MUL :
22975       case ISD::FMUL :
22976         CanFold = true;
22977       }
22978
22979       unsigned SVTNumElts = SVT.getVectorNumElements();
22980       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22981       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22982         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22983       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22984         CanFold = SVOp->getMaskElt(i) < 0;
22985
22986       if (CanFold) {
22987         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22988         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22989         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22990         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22991       }
22992     }
22993   }
22994
22995   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22996   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22997   // consecutive, non-overlapping, and in the right order.
22998   SmallVector<SDValue, 16> Elts;
22999   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23000     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23001
23002   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23003     return LD;
23004
23005   if (isTargetShuffle(N->getOpcode())) {
23006     SDValue Shuffle =
23007         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23008     if (Shuffle.getNode())
23009       return Shuffle;
23010
23011     // Try recursively combining arbitrary sequences of x86 shuffle
23012     // instructions into higher-order shuffles. We do this after combining
23013     // specific PSHUF instruction sequences into their minimal form so that we
23014     // can evaluate how many specialized shuffle instructions are involved in
23015     // a particular chain.
23016     SmallVector<int, 1> NonceMask; // Just a placeholder.
23017     NonceMask.push_back(0);
23018     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23019                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23020                                       DCI, Subtarget))
23021       return SDValue(); // This routine will use CombineTo to replace N.
23022   }
23023
23024   return SDValue();
23025 }
23026
23027 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23028 /// specific shuffle of a load can be folded into a single element load.
23029 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23030 /// shuffles have been custom lowered so we need to handle those here.
23031 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23032                                          TargetLowering::DAGCombinerInfo &DCI) {
23033   if (DCI.isBeforeLegalizeOps())
23034     return SDValue();
23035
23036   SDValue InVec = N->getOperand(0);
23037   SDValue EltNo = N->getOperand(1);
23038
23039   if (!isa<ConstantSDNode>(EltNo))
23040     return SDValue();
23041
23042   EVT OriginalVT = InVec.getValueType();
23043
23044   if (InVec.getOpcode() == ISD::BITCAST) {
23045     // Don't duplicate a load with other uses.
23046     if (!InVec.hasOneUse())
23047       return SDValue();
23048     EVT BCVT = InVec.getOperand(0).getValueType();
23049     if (!BCVT.isVector() ||
23050         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23051       return SDValue();
23052     InVec = InVec.getOperand(0);
23053   }
23054
23055   EVT CurrentVT = InVec.getValueType();
23056
23057   if (!isTargetShuffle(InVec.getOpcode()))
23058     return SDValue();
23059
23060   // Don't duplicate a load with other uses.
23061   if (!InVec.hasOneUse())
23062     return SDValue();
23063
23064   SmallVector<int, 16> ShuffleMask;
23065   bool UnaryShuffle;
23066   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23067                             ShuffleMask, UnaryShuffle))
23068     return SDValue();
23069
23070   // Select the input vector, guarding against out of range extract vector.
23071   unsigned NumElems = CurrentVT.getVectorNumElements();
23072   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23073   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23074   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23075                                          : InVec.getOperand(1);
23076
23077   // If inputs to shuffle are the same for both ops, then allow 2 uses
23078   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23079                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23080
23081   if (LdNode.getOpcode() == ISD::BITCAST) {
23082     // Don't duplicate a load with other uses.
23083     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23084       return SDValue();
23085
23086     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23087     LdNode = LdNode.getOperand(0);
23088   }
23089
23090   if (!ISD::isNormalLoad(LdNode.getNode()))
23091     return SDValue();
23092
23093   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23094
23095   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23096     return SDValue();
23097
23098   EVT EltVT = N->getValueType(0);
23099   // If there's a bitcast before the shuffle, check if the load type and
23100   // alignment is valid.
23101   unsigned Align = LN0->getAlignment();
23102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23103   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23104       EltVT.getTypeForEVT(*DAG.getContext()));
23105
23106   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23107     return SDValue();
23108
23109   // All checks match so transform back to vector_shuffle so that DAG combiner
23110   // can finish the job
23111   SDLoc dl(N);
23112
23113   // Create shuffle node taking into account the case that its a unary shuffle
23114   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23115                                    : InVec.getOperand(1);
23116   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23117                                  InVec.getOperand(0), Shuffle,
23118                                  &ShuffleMask[0]);
23119   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23120   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23121                      EltNo);
23122 }
23123
23124 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23125                                      const X86Subtarget *Subtarget) {
23126   SDValue N0 = N->getOperand(0);
23127   EVT VT = N->getValueType(0);
23128
23129   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23130   // special and don't usually play with other vector types, it's better to
23131   // handle them early to be sure we emit efficient code by avoiding
23132   // store-load conversions.
23133   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23134       N0.getValueType() == MVT::v2i32 &&
23135       isa<ConstantSDNode>(N0.getOperand(1))) {
23136     SDValue N00 = N0->getOperand(0);
23137     if (N0.getConstantOperandVal(1) == 0 && N00.getValueType() == MVT::i32)
23138       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23139   }
23140
23141   // Convert a bitcasted integer logic operation that has one bitcasted
23142   // floating-point operand and one constant operand into a floating-point
23143   // logic operation. This may create a load of the constant, but that is
23144   // cheaper than materializing the constant in an integer register and
23145   // transferring it to an SSE register or transferring the SSE operand to
23146   // integer register and back.
23147   unsigned FPOpcode;
23148   switch (N0.getOpcode()) {
23149     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23150     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23151     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23152     default: return SDValue();
23153   }
23154   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23155        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23156       isa<ConstantSDNode>(N0.getOperand(1)) &&
23157       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23158       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23159     SDValue N000 = N0.getOperand(0).getOperand(0);
23160     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23161     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23162   }
23163
23164   return SDValue();
23165 }
23166
23167 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23168 /// generation and convert it from being a bunch of shuffles and extracts
23169 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23170 /// storing the value and loading scalars back, while for x64 we should
23171 /// use 64-bit extracts and shifts.
23172 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23173                                          TargetLowering::DAGCombinerInfo &DCI) {
23174   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23175     return NewOp;
23176
23177   SDValue InputVector = N->getOperand(0);
23178   SDLoc dl(InputVector);
23179   // Detect mmx to i32 conversion through a v2i32 elt extract.
23180   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23181       N->getValueType(0) == MVT::i32 &&
23182       InputVector.getValueType() == MVT::v2i32) {
23183
23184     // The bitcast source is a direct mmx result.
23185     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23186     if (MMXSrc.getValueType() == MVT::x86mmx)
23187       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23188                          N->getValueType(0),
23189                          InputVector.getNode()->getOperand(0));
23190
23191     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23192     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23193         MMXSrc.getValueType() == MVT::i64) {
23194       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23195       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23196           MMXSrcOp.getValueType() == MVT::v1i64 &&
23197           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23198         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23199                            N->getValueType(0), MMXSrcOp.getOperand(0));
23200     }
23201   }
23202
23203   EVT VT = N->getValueType(0);
23204
23205   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
23206       InputVector.getOpcode() == ISD::BITCAST &&
23207       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
23208     uint64_t ExtractedElt =
23209         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23210     uint64_t InputValue =
23211         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23212     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23213     return DAG.getConstant(Res, dl, MVT::i1);
23214   }
23215   // Only operate on vectors of 4 elements, where the alternative shuffling
23216   // gets to be more expensive.
23217   if (InputVector.getValueType() != MVT::v4i32)
23218     return SDValue();
23219
23220   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23221   // single use which is a sign-extend or zero-extend, and all elements are
23222   // used.
23223   SmallVector<SDNode *, 4> Uses;
23224   unsigned ExtractedElements = 0;
23225   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23226        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23227     if (UI.getUse().getResNo() != InputVector.getResNo())
23228       return SDValue();
23229
23230     SDNode *Extract = *UI;
23231     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23232       return SDValue();
23233
23234     if (Extract->getValueType(0) != MVT::i32)
23235       return SDValue();
23236     if (!Extract->hasOneUse())
23237       return SDValue();
23238     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23239         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23240       return SDValue();
23241     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23242       return SDValue();
23243
23244     // Record which element was extracted.
23245     ExtractedElements |=
23246       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23247
23248     Uses.push_back(Extract);
23249   }
23250
23251   // If not all the elements were used, this may not be worthwhile.
23252   if (ExtractedElements != 15)
23253     return SDValue();
23254
23255   // Ok, we've now decided to do the transformation.
23256   // If 64-bit shifts are legal, use the extract-shift sequence,
23257   // otherwise bounce the vector off the cache.
23258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23259   SDValue Vals[4];
23260
23261   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23262     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23263     auto &DL = DAG.getDataLayout();
23264     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23265     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23266       DAG.getConstant(0, dl, VecIdxTy));
23267     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23268       DAG.getConstant(1, dl, VecIdxTy));
23269
23270     SDValue ShAmt = DAG.getConstant(
23271         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23272     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23273     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23274       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23275     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23276     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23277       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23278   } else {
23279     // Store the value to a temporary stack slot.
23280     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23281     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23282       MachinePointerInfo(), false, false, 0);
23283
23284     EVT ElementType = InputVector.getValueType().getVectorElementType();
23285     unsigned EltSize = ElementType.getSizeInBits() / 8;
23286
23287     // Replace each use (extract) with a load of the appropriate element.
23288     for (unsigned i = 0; i < 4; ++i) {
23289       uint64_t Offset = EltSize * i;
23290       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23291       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23292
23293       SDValue ScalarAddr =
23294           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23295
23296       // Load the scalar.
23297       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23298                             ScalarAddr, MachinePointerInfo(),
23299                             false, false, false, 0);
23300
23301     }
23302   }
23303
23304   // Replace the extracts
23305   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23306     UE = Uses.end(); UI != UE; ++UI) {
23307     SDNode *Extract = *UI;
23308
23309     SDValue Idx = Extract->getOperand(1);
23310     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23311     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23312   }
23313
23314   // The replacement was made in place; don't return anything.
23315   return SDValue();
23316 }
23317
23318 static SDValue
23319 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23320                                       const X86Subtarget *Subtarget) {
23321   SDLoc dl(N);
23322   SDValue Cond = N->getOperand(0);
23323   SDValue LHS = N->getOperand(1);
23324   SDValue RHS = N->getOperand(2);
23325
23326   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23327     SDValue CondSrc = Cond->getOperand(0);
23328     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23329       Cond = CondSrc->getOperand(0);
23330   }
23331
23332   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23333     return SDValue();
23334
23335   // A vselect where all conditions and data are constants can be optimized into
23336   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23337   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23338       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23339     return SDValue();
23340
23341   unsigned MaskValue = 0;
23342   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23343     return SDValue();
23344
23345   MVT VT = N->getSimpleValueType(0);
23346   unsigned NumElems = VT.getVectorNumElements();
23347   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23348   for (unsigned i = 0; i < NumElems; ++i) {
23349     // Be sure we emit undef where we can.
23350     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23351       ShuffleMask[i] = -1;
23352     else
23353       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23354   }
23355
23356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23357   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23358     return SDValue();
23359   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23360 }
23361
23362 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23363 /// nodes.
23364 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23365                                     TargetLowering::DAGCombinerInfo &DCI,
23366                                     const X86Subtarget *Subtarget) {
23367   SDLoc DL(N);
23368   SDValue Cond = N->getOperand(0);
23369   // Get the LHS/RHS of the select.
23370   SDValue LHS = N->getOperand(1);
23371   SDValue RHS = N->getOperand(2);
23372   EVT VT = LHS.getValueType();
23373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23374
23375   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23376   // instructions match the semantics of the common C idiom x<y?x:y but not
23377   // x<=y?x:y, because of how they handle negative zero (which can be
23378   // ignored in unsafe-math mode).
23379   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23380   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23381       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23382       (Subtarget->hasSSE2() ||
23383        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23384     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23385
23386     unsigned Opcode = 0;
23387     // Check for x CC y ? x : y.
23388     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23389         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23390       switch (CC) {
23391       default: break;
23392       case ISD::SETULT:
23393         // Converting this to a min would handle NaNs incorrectly, and swapping
23394         // the operands would cause it to handle comparisons between positive
23395         // and negative zero incorrectly.
23396         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23397           if (!DAG.getTarget().Options.UnsafeFPMath &&
23398               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23399             break;
23400           std::swap(LHS, RHS);
23401         }
23402         Opcode = X86ISD::FMIN;
23403         break;
23404       case ISD::SETOLE:
23405         // Converting this to a min would handle comparisons between positive
23406         // and negative zero incorrectly.
23407         if (!DAG.getTarget().Options.UnsafeFPMath &&
23408             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23409           break;
23410         Opcode = X86ISD::FMIN;
23411         break;
23412       case ISD::SETULE:
23413         // Converting this to a min would handle both negative zeros and NaNs
23414         // incorrectly, but we can swap the operands to fix both.
23415         std::swap(LHS, RHS);
23416       case ISD::SETOLT:
23417       case ISD::SETLT:
23418       case ISD::SETLE:
23419         Opcode = X86ISD::FMIN;
23420         break;
23421
23422       case ISD::SETOGE:
23423         // Converting this to a max would handle comparisons between positive
23424         // and negative zero incorrectly.
23425         if (!DAG.getTarget().Options.UnsafeFPMath &&
23426             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23427           break;
23428         Opcode = X86ISD::FMAX;
23429         break;
23430       case ISD::SETUGT:
23431         // Converting this to a max would handle NaNs incorrectly, and swapping
23432         // the operands would cause it to handle comparisons between positive
23433         // and negative zero incorrectly.
23434         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23435           if (!DAG.getTarget().Options.UnsafeFPMath &&
23436               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23437             break;
23438           std::swap(LHS, RHS);
23439         }
23440         Opcode = X86ISD::FMAX;
23441         break;
23442       case ISD::SETUGE:
23443         // Converting this to a max would handle both negative zeros and NaNs
23444         // incorrectly, but we can swap the operands to fix both.
23445         std::swap(LHS, RHS);
23446       case ISD::SETOGT:
23447       case ISD::SETGT:
23448       case ISD::SETGE:
23449         Opcode = X86ISD::FMAX;
23450         break;
23451       }
23452     // Check for x CC y ? y : x -- a min/max with reversed arms.
23453     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23454                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23455       switch (CC) {
23456       default: break;
23457       case ISD::SETOGE:
23458         // Converting this to a min would handle comparisons between positive
23459         // and negative zero incorrectly, and swapping the operands would
23460         // cause it to handle NaNs incorrectly.
23461         if (!DAG.getTarget().Options.UnsafeFPMath &&
23462             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23463           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23464             break;
23465           std::swap(LHS, RHS);
23466         }
23467         Opcode = X86ISD::FMIN;
23468         break;
23469       case ISD::SETUGT:
23470         // Converting this to a min would handle NaNs incorrectly.
23471         if (!DAG.getTarget().Options.UnsafeFPMath &&
23472             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23473           break;
23474         Opcode = X86ISD::FMIN;
23475         break;
23476       case ISD::SETUGE:
23477         // Converting this to a min would handle both negative zeros and NaNs
23478         // incorrectly, but we can swap the operands to fix both.
23479         std::swap(LHS, RHS);
23480       case ISD::SETOGT:
23481       case ISD::SETGT:
23482       case ISD::SETGE:
23483         Opcode = X86ISD::FMIN;
23484         break;
23485
23486       case ISD::SETULT:
23487         // Converting this to a max would handle NaNs incorrectly.
23488         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23489           break;
23490         Opcode = X86ISD::FMAX;
23491         break;
23492       case ISD::SETOLE:
23493         // Converting this to a max would handle comparisons between positive
23494         // and negative zero incorrectly, and swapping the operands would
23495         // cause it to handle NaNs incorrectly.
23496         if (!DAG.getTarget().Options.UnsafeFPMath &&
23497             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23498           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23499             break;
23500           std::swap(LHS, RHS);
23501         }
23502         Opcode = X86ISD::FMAX;
23503         break;
23504       case ISD::SETULE:
23505         // Converting this to a max would handle both negative zeros and NaNs
23506         // incorrectly, but we can swap the operands to fix both.
23507         std::swap(LHS, RHS);
23508       case ISD::SETOLT:
23509       case ISD::SETLT:
23510       case ISD::SETLE:
23511         Opcode = X86ISD::FMAX;
23512         break;
23513       }
23514     }
23515
23516     if (Opcode)
23517       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23518   }
23519
23520   EVT CondVT = Cond.getValueType();
23521   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23522       CondVT.getVectorElementType() == MVT::i1) {
23523     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23524     // lowering on KNL. In this case we convert it to
23525     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23526     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23527     // Since SKX these selects have a proper lowering.
23528     EVT OpVT = LHS.getValueType();
23529     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23530         (OpVT.getVectorElementType() == MVT::i8 ||
23531          OpVT.getVectorElementType() == MVT::i16) &&
23532         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23533       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23534       DCI.AddToWorklist(Cond.getNode());
23535       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23536     }
23537   }
23538   // If this is a select between two integer constants, try to do some
23539   // optimizations.
23540   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23541     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23542       // Don't do this for crazy integer types.
23543       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23544         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23545         // so that TrueC (the true value) is larger than FalseC.
23546         bool NeedsCondInvert = false;
23547
23548         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23549             // Efficiently invertible.
23550             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23551              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23552               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23553           NeedsCondInvert = true;
23554           std::swap(TrueC, FalseC);
23555         }
23556
23557         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23558         if (FalseC->getAPIntValue() == 0 &&
23559             TrueC->getAPIntValue().isPowerOf2()) {
23560           if (NeedsCondInvert) // Invert the condition if needed.
23561             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23562                                DAG.getConstant(1, DL, Cond.getValueType()));
23563
23564           // Zero extend the condition if needed.
23565           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23566
23567           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23568           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23569                              DAG.getConstant(ShAmt, DL, MVT::i8));
23570         }
23571
23572         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23573         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23574           if (NeedsCondInvert) // Invert the condition if needed.
23575             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23576                                DAG.getConstant(1, DL, Cond.getValueType()));
23577
23578           // Zero extend the condition if needed.
23579           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23580                              FalseC->getValueType(0), Cond);
23581           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23582                              SDValue(FalseC, 0));
23583         }
23584
23585         // Optimize cases that will turn into an LEA instruction.  This requires
23586         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23587         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23588           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23589           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23590
23591           bool isFastMultiplier = false;
23592           if (Diff < 10) {
23593             switch ((unsigned char)Diff) {
23594               default: break;
23595               case 1:  // result = add base, cond
23596               case 2:  // result = lea base(    , cond*2)
23597               case 3:  // result = lea base(cond, cond*2)
23598               case 4:  // result = lea base(    , cond*4)
23599               case 5:  // result = lea base(cond, cond*4)
23600               case 8:  // result = lea base(    , cond*8)
23601               case 9:  // result = lea base(cond, cond*8)
23602                 isFastMultiplier = true;
23603                 break;
23604             }
23605           }
23606
23607           if (isFastMultiplier) {
23608             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23609             if (NeedsCondInvert) // Invert the condition if needed.
23610               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23611                                  DAG.getConstant(1, DL, Cond.getValueType()));
23612
23613             // Zero extend the condition if needed.
23614             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23615                                Cond);
23616             // Scale the condition by the difference.
23617             if (Diff != 1)
23618               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23619                                  DAG.getConstant(Diff, DL,
23620                                                  Cond.getValueType()));
23621
23622             // Add the base if non-zero.
23623             if (FalseC->getAPIntValue() != 0)
23624               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23625                                  SDValue(FalseC, 0));
23626             return Cond;
23627           }
23628         }
23629       }
23630   }
23631
23632   // Canonicalize max and min:
23633   // (x > y) ? x : y -> (x >= y) ? x : y
23634   // (x < y) ? x : y -> (x <= y) ? x : y
23635   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23636   // the need for an extra compare
23637   // against zero. e.g.
23638   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23639   // subl   %esi, %edi
23640   // testl  %edi, %edi
23641   // movl   $0, %eax
23642   // cmovgl %edi, %eax
23643   // =>
23644   // xorl   %eax, %eax
23645   // subl   %esi, $edi
23646   // cmovsl %eax, %edi
23647   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23648       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23649       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23650     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23651     switch (CC) {
23652     default: break;
23653     case ISD::SETLT:
23654     case ISD::SETGT: {
23655       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23656       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23657                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23658       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23659     }
23660     }
23661   }
23662
23663   // Early exit check
23664   if (!TLI.isTypeLegal(VT))
23665     return SDValue();
23666
23667   // Match VSELECTs into subs with unsigned saturation.
23668   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23669       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23670       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23671        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23672     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23673
23674     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23675     // left side invert the predicate to simplify logic below.
23676     SDValue Other;
23677     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23678       Other = RHS;
23679       CC = ISD::getSetCCInverse(CC, true);
23680     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23681       Other = LHS;
23682     }
23683
23684     if (Other.getNode() && Other->getNumOperands() == 2 &&
23685         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23686       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23687       SDValue CondRHS = Cond->getOperand(1);
23688
23689       // Look for a general sub with unsigned saturation first.
23690       // x >= y ? x-y : 0 --> subus x, y
23691       // x >  y ? x-y : 0 --> subus x, y
23692       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23693           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23694         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23695
23696       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23697         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23698           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23699             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23700               // If the RHS is a constant we have to reverse the const
23701               // canonicalization.
23702               // x > C-1 ? x+-C : 0 --> subus x, C
23703               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23704                   CondRHSConst->getAPIntValue() ==
23705                       (-OpRHSConst->getAPIntValue() - 1))
23706                 return DAG.getNode(
23707                     X86ISD::SUBUS, DL, VT, OpLHS,
23708                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23709
23710           // Another special case: If C was a sign bit, the sub has been
23711           // canonicalized into a xor.
23712           // FIXME: Would it be better to use computeKnownBits to determine
23713           //        whether it's safe to decanonicalize the xor?
23714           // x s< 0 ? x^C : 0 --> subus x, C
23715           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23716               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23717               OpRHSConst->getAPIntValue().isSignBit())
23718             // Note that we have to rebuild the RHS constant here to ensure we
23719             // don't rely on particular values of undef lanes.
23720             return DAG.getNode(
23721                 X86ISD::SUBUS, DL, VT, OpLHS,
23722                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23723         }
23724     }
23725   }
23726
23727   // Simplify vector selection if condition value type matches vselect
23728   // operand type
23729   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23730     assert(Cond.getValueType().isVector() &&
23731            "vector select expects a vector selector!");
23732
23733     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23734     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23735
23736     // Try invert the condition if true value is not all 1s and false value
23737     // is not all 0s.
23738     if (!TValIsAllOnes && !FValIsAllZeros &&
23739         // Check if the selector will be produced by CMPP*/PCMP*
23740         Cond.getOpcode() == ISD::SETCC &&
23741         // Check if SETCC has already been promoted
23742         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23743             CondVT) {
23744       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23745       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23746
23747       if (TValIsAllZeros || FValIsAllOnes) {
23748         SDValue CC = Cond.getOperand(2);
23749         ISD::CondCode NewCC =
23750           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23751                                Cond.getOperand(0).getValueType().isInteger());
23752         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23753         std::swap(LHS, RHS);
23754         TValIsAllOnes = FValIsAllOnes;
23755         FValIsAllZeros = TValIsAllZeros;
23756       }
23757     }
23758
23759     if (TValIsAllOnes || FValIsAllZeros) {
23760       SDValue Ret;
23761
23762       if (TValIsAllOnes && FValIsAllZeros)
23763         Ret = Cond;
23764       else if (TValIsAllOnes)
23765         Ret =
23766             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23767       else if (FValIsAllZeros)
23768         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23769                           DAG.getBitcast(CondVT, LHS));
23770
23771       return DAG.getBitcast(VT, Ret);
23772     }
23773   }
23774
23775   // We should generate an X86ISD::BLENDI from a vselect if its argument
23776   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23777   // constants. This specific pattern gets generated when we split a
23778   // selector for a 512 bit vector in a machine without AVX512 (but with
23779   // 256-bit vectors), during legalization:
23780   //
23781   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23782   //
23783   // Iff we find this pattern and the build_vectors are built from
23784   // constants, we translate the vselect into a shuffle_vector that we
23785   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23786   if ((N->getOpcode() == ISD::VSELECT ||
23787        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23788       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23789     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23790     if (Shuffle.getNode())
23791       return Shuffle;
23792   }
23793
23794   // If this is a *dynamic* select (non-constant condition) and we can match
23795   // this node with one of the variable blend instructions, restructure the
23796   // condition so that the blends can use the high bit of each element and use
23797   // SimplifyDemandedBits to simplify the condition operand.
23798   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23799       !DCI.isBeforeLegalize() &&
23800       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23801     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23802
23803     // Don't optimize vector selects that map to mask-registers.
23804     if (BitWidth == 1)
23805       return SDValue();
23806
23807     // We can only handle the cases where VSELECT is directly legal on the
23808     // subtarget. We custom lower VSELECT nodes with constant conditions and
23809     // this makes it hard to see whether a dynamic VSELECT will correctly
23810     // lower, so we both check the operation's status and explicitly handle the
23811     // cases where a *dynamic* blend will fail even though a constant-condition
23812     // blend could be custom lowered.
23813     // FIXME: We should find a better way to handle this class of problems.
23814     // Potentially, we should combine constant-condition vselect nodes
23815     // pre-legalization into shuffles and not mark as many types as custom
23816     // lowered.
23817     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23818       return SDValue();
23819     // FIXME: We don't support i16-element blends currently. We could and
23820     // should support them by making *all* the bits in the condition be set
23821     // rather than just the high bit and using an i8-element blend.
23822     if (VT.getScalarType() == MVT::i16)
23823       return SDValue();
23824     // Dynamic blending was only available from SSE4.1 onward.
23825     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23826       return SDValue();
23827     // Byte blends are only available in AVX2
23828     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23829         !Subtarget->hasAVX2())
23830       return SDValue();
23831
23832     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23833     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23834
23835     APInt KnownZero, KnownOne;
23836     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23837                                           DCI.isBeforeLegalizeOps());
23838     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23839         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23840                                  TLO)) {
23841       // If we changed the computation somewhere in the DAG, this change
23842       // will affect all users of Cond.
23843       // Make sure it is fine and update all the nodes so that we do not
23844       // use the generic VSELECT anymore. Otherwise, we may perform
23845       // wrong optimizations as we messed up with the actual expectation
23846       // for the vector boolean values.
23847       if (Cond != TLO.Old) {
23848         // Check all uses of that condition operand to check whether it will be
23849         // consumed by non-BLEND instructions, which may depend on all bits are
23850         // set properly.
23851         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23852              I != E; ++I)
23853           if (I->getOpcode() != ISD::VSELECT)
23854             // TODO: Add other opcodes eventually lowered into BLEND.
23855             return SDValue();
23856
23857         // Update all the users of the condition, before committing the change,
23858         // so that the VSELECT optimizations that expect the correct vector
23859         // boolean value will not be triggered.
23860         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23861              I != E; ++I)
23862           DAG.ReplaceAllUsesOfValueWith(
23863               SDValue(*I, 0),
23864               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23865                           Cond, I->getOperand(1), I->getOperand(2)));
23866         DCI.CommitTargetLoweringOpt(TLO);
23867         return SDValue();
23868       }
23869       // At this point, only Cond is changed. Change the condition
23870       // just for N to keep the opportunity to optimize all other
23871       // users their own way.
23872       DAG.ReplaceAllUsesOfValueWith(
23873           SDValue(N, 0),
23874           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23875                       TLO.New, N->getOperand(1), N->getOperand(2)));
23876       return SDValue();
23877     }
23878   }
23879
23880   return SDValue();
23881 }
23882
23883 // Check whether a boolean test is testing a boolean value generated by
23884 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23885 // code.
23886 //
23887 // Simplify the following patterns:
23888 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23889 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23890 // to (Op EFLAGS Cond)
23891 //
23892 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23893 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23894 // to (Op EFLAGS !Cond)
23895 //
23896 // where Op could be BRCOND or CMOV.
23897 //
23898 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23899   // Quit if not CMP and SUB with its value result used.
23900   if (Cmp.getOpcode() != X86ISD::CMP &&
23901       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23902       return SDValue();
23903
23904   // Quit if not used as a boolean value.
23905   if (CC != X86::COND_E && CC != X86::COND_NE)
23906     return SDValue();
23907
23908   // Check CMP operands. One of them should be 0 or 1 and the other should be
23909   // an SetCC or extended from it.
23910   SDValue Op1 = Cmp.getOperand(0);
23911   SDValue Op2 = Cmp.getOperand(1);
23912
23913   SDValue SetCC;
23914   const ConstantSDNode* C = nullptr;
23915   bool needOppositeCond = (CC == X86::COND_E);
23916   bool checkAgainstTrue = false; // Is it a comparison against 1?
23917
23918   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23919     SetCC = Op2;
23920   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23921     SetCC = Op1;
23922   else // Quit if all operands are not constants.
23923     return SDValue();
23924
23925   if (C->getZExtValue() == 1) {
23926     needOppositeCond = !needOppositeCond;
23927     checkAgainstTrue = true;
23928   } else if (C->getZExtValue() != 0)
23929     // Quit if the constant is neither 0 or 1.
23930     return SDValue();
23931
23932   bool truncatedToBoolWithAnd = false;
23933   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23934   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23935          SetCC.getOpcode() == ISD::TRUNCATE ||
23936          SetCC.getOpcode() == ISD::AND) {
23937     if (SetCC.getOpcode() == ISD::AND) {
23938       int OpIdx = -1;
23939       ConstantSDNode *CS;
23940       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23941           CS->getZExtValue() == 1)
23942         OpIdx = 1;
23943       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23944           CS->getZExtValue() == 1)
23945         OpIdx = 0;
23946       if (OpIdx == -1)
23947         break;
23948       SetCC = SetCC.getOperand(OpIdx);
23949       truncatedToBoolWithAnd = true;
23950     } else
23951       SetCC = SetCC.getOperand(0);
23952   }
23953
23954   switch (SetCC.getOpcode()) {
23955   case X86ISD::SETCC_CARRY:
23956     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23957     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23958     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23959     // truncated to i1 using 'and'.
23960     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23961       break;
23962     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23963            "Invalid use of SETCC_CARRY!");
23964     // FALL THROUGH
23965   case X86ISD::SETCC:
23966     // Set the condition code or opposite one if necessary.
23967     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23968     if (needOppositeCond)
23969       CC = X86::GetOppositeBranchCondition(CC);
23970     return SetCC.getOperand(1);
23971   case X86ISD::CMOV: {
23972     // Check whether false/true value has canonical one, i.e. 0 or 1.
23973     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23974     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23975     // Quit if true value is not a constant.
23976     if (!TVal)
23977       return SDValue();
23978     // Quit if false value is not a constant.
23979     if (!FVal) {
23980       SDValue Op = SetCC.getOperand(0);
23981       // Skip 'zext' or 'trunc' node.
23982       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23983           Op.getOpcode() == ISD::TRUNCATE)
23984         Op = Op.getOperand(0);
23985       // A special case for rdrand/rdseed, where 0 is set if false cond is
23986       // found.
23987       if ((Op.getOpcode() != X86ISD::RDRAND &&
23988            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23989         return SDValue();
23990     }
23991     // Quit if false value is not the constant 0 or 1.
23992     bool FValIsFalse = true;
23993     if (FVal && FVal->getZExtValue() != 0) {
23994       if (FVal->getZExtValue() != 1)
23995         return SDValue();
23996       // If FVal is 1, opposite cond is needed.
23997       needOppositeCond = !needOppositeCond;
23998       FValIsFalse = false;
23999     }
24000     // Quit if TVal is not the constant opposite of FVal.
24001     if (FValIsFalse && TVal->getZExtValue() != 1)
24002       return SDValue();
24003     if (!FValIsFalse && TVal->getZExtValue() != 0)
24004       return SDValue();
24005     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24006     if (needOppositeCond)
24007       CC = X86::GetOppositeBranchCondition(CC);
24008     return SetCC.getOperand(3);
24009   }
24010   }
24011
24012   return SDValue();
24013 }
24014
24015 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24016 /// Match:
24017 ///   (X86or (X86setcc) (X86setcc))
24018 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24019 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24020                                            X86::CondCode &CC1, SDValue &Flags,
24021                                            bool &isAnd) {
24022   if (Cond->getOpcode() == X86ISD::CMP) {
24023     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24024     if (!CondOp1C || !CondOp1C->isNullValue())
24025       return false;
24026
24027     Cond = Cond->getOperand(0);
24028   }
24029
24030   isAnd = false;
24031
24032   SDValue SetCC0, SetCC1;
24033   switch (Cond->getOpcode()) {
24034   default: return false;
24035   case ISD::AND:
24036   case X86ISD::AND:
24037     isAnd = true;
24038     // fallthru
24039   case ISD::OR:
24040   case X86ISD::OR:
24041     SetCC0 = Cond->getOperand(0);
24042     SetCC1 = Cond->getOperand(1);
24043     break;
24044   };
24045
24046   // Make sure we have SETCC nodes, using the same flags value.
24047   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24048       SetCC1.getOpcode() != X86ISD::SETCC ||
24049       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24050     return false;
24051
24052   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24053   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24054   Flags = SetCC0->getOperand(1);
24055   return true;
24056 }
24057
24058 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24059 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24060                                   TargetLowering::DAGCombinerInfo &DCI,
24061                                   const X86Subtarget *Subtarget) {
24062   SDLoc DL(N);
24063
24064   // If the flag operand isn't dead, don't touch this CMOV.
24065   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24066     return SDValue();
24067
24068   SDValue FalseOp = N->getOperand(0);
24069   SDValue TrueOp = N->getOperand(1);
24070   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24071   SDValue Cond = N->getOperand(3);
24072
24073   if (CC == X86::COND_E || CC == X86::COND_NE) {
24074     switch (Cond.getOpcode()) {
24075     default: break;
24076     case X86ISD::BSR:
24077     case X86ISD::BSF:
24078       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24079       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24080         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24081     }
24082   }
24083
24084   SDValue Flags;
24085
24086   Flags = checkBoolTestSetCCCombine(Cond, CC);
24087   if (Flags.getNode() &&
24088       // Extra check as FCMOV only supports a subset of X86 cond.
24089       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24090     SDValue Ops[] = { FalseOp, TrueOp,
24091                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24092     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24093   }
24094
24095   // If this is a select between two integer constants, try to do some
24096   // optimizations.  Note that the operands are ordered the opposite of SELECT
24097   // operands.
24098   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24099     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24100       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24101       // larger than FalseC (the false value).
24102       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24103         CC = X86::GetOppositeBranchCondition(CC);
24104         std::swap(TrueC, FalseC);
24105         std::swap(TrueOp, FalseOp);
24106       }
24107
24108       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24109       // This is efficient for any integer data type (including i8/i16) and
24110       // shift amount.
24111       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24112         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24113                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24114
24115         // Zero extend the condition if needed.
24116         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24117
24118         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24119         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24120                            DAG.getConstant(ShAmt, DL, MVT::i8));
24121         if (N->getNumValues() == 2)  // Dead flag value?
24122           return DCI.CombineTo(N, Cond, SDValue());
24123         return Cond;
24124       }
24125
24126       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24127       // for any integer data type, including i8/i16.
24128       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24129         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24130                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24131
24132         // Zero extend the condition if needed.
24133         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24134                            FalseC->getValueType(0), Cond);
24135         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24136                            SDValue(FalseC, 0));
24137
24138         if (N->getNumValues() == 2)  // Dead flag value?
24139           return DCI.CombineTo(N, Cond, SDValue());
24140         return Cond;
24141       }
24142
24143       // Optimize cases that will turn into an LEA instruction.  This requires
24144       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24145       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24146         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24147         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24148
24149         bool isFastMultiplier = false;
24150         if (Diff < 10) {
24151           switch ((unsigned char)Diff) {
24152           default: break;
24153           case 1:  // result = add base, cond
24154           case 2:  // result = lea base(    , cond*2)
24155           case 3:  // result = lea base(cond, cond*2)
24156           case 4:  // result = lea base(    , cond*4)
24157           case 5:  // result = lea base(cond, cond*4)
24158           case 8:  // result = lea base(    , cond*8)
24159           case 9:  // result = lea base(cond, cond*8)
24160             isFastMultiplier = true;
24161             break;
24162           }
24163         }
24164
24165         if (isFastMultiplier) {
24166           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24167           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24168                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24169           // Zero extend the condition if needed.
24170           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24171                              Cond);
24172           // Scale the condition by the difference.
24173           if (Diff != 1)
24174             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24175                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24176
24177           // Add the base if non-zero.
24178           if (FalseC->getAPIntValue() != 0)
24179             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24180                                SDValue(FalseC, 0));
24181           if (N->getNumValues() == 2)  // Dead flag value?
24182             return DCI.CombineTo(N, Cond, SDValue());
24183           return Cond;
24184         }
24185       }
24186     }
24187   }
24188
24189   // Handle these cases:
24190   //   (select (x != c), e, c) -> select (x != c), e, x),
24191   //   (select (x == c), c, e) -> select (x == c), x, e)
24192   // where the c is an integer constant, and the "select" is the combination
24193   // of CMOV and CMP.
24194   //
24195   // The rationale for this change is that the conditional-move from a constant
24196   // needs two instructions, however, conditional-move from a register needs
24197   // only one instruction.
24198   //
24199   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24200   //  some instruction-combining opportunities. This opt needs to be
24201   //  postponed as late as possible.
24202   //
24203   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24204     // the DCI.xxxx conditions are provided to postpone the optimization as
24205     // late as possible.
24206
24207     ConstantSDNode *CmpAgainst = nullptr;
24208     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24209         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24210         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24211
24212       if (CC == X86::COND_NE &&
24213           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24214         CC = X86::GetOppositeBranchCondition(CC);
24215         std::swap(TrueOp, FalseOp);
24216       }
24217
24218       if (CC == X86::COND_E &&
24219           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24220         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24221                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24222         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24223       }
24224     }
24225   }
24226
24227   // Fold and/or of setcc's to double CMOV:
24228   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24229   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24230   //
24231   // This combine lets us generate:
24232   //   cmovcc1 (jcc1 if we don't have CMOV)
24233   //   cmovcc2 (same)
24234   // instead of:
24235   //   setcc1
24236   //   setcc2
24237   //   and/or
24238   //   cmovne (jne if we don't have CMOV)
24239   // When we can't use the CMOV instruction, it might increase branch
24240   // mispredicts.
24241   // When we can use CMOV, or when there is no mispredict, this improves
24242   // throughput and reduces register pressure.
24243   //
24244   if (CC == X86::COND_NE) {
24245     SDValue Flags;
24246     X86::CondCode CC0, CC1;
24247     bool isAndSetCC;
24248     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24249       if (isAndSetCC) {
24250         std::swap(FalseOp, TrueOp);
24251         CC0 = X86::GetOppositeBranchCondition(CC0);
24252         CC1 = X86::GetOppositeBranchCondition(CC1);
24253       }
24254
24255       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24256         Flags};
24257       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24258       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24259       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24260       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24261       return CMOV;
24262     }
24263   }
24264
24265   return SDValue();
24266 }
24267
24268 /// PerformMulCombine - Optimize a single multiply with constant into two
24269 /// in order to implement it with two cheaper instructions, e.g.
24270 /// LEA + SHL, LEA + LEA.
24271 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24272                                  TargetLowering::DAGCombinerInfo &DCI) {
24273   // An imul is usually smaller than the alternative sequence.
24274   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24275     return SDValue();
24276
24277   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24278     return SDValue();
24279
24280   EVT VT = N->getValueType(0);
24281   if (VT != MVT::i64 && VT != MVT::i32)
24282     return SDValue();
24283
24284   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24285   if (!C)
24286     return SDValue();
24287   uint64_t MulAmt = C->getZExtValue();
24288   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24289     return SDValue();
24290
24291   uint64_t MulAmt1 = 0;
24292   uint64_t MulAmt2 = 0;
24293   if ((MulAmt % 9) == 0) {
24294     MulAmt1 = 9;
24295     MulAmt2 = MulAmt / 9;
24296   } else if ((MulAmt % 5) == 0) {
24297     MulAmt1 = 5;
24298     MulAmt2 = MulAmt / 5;
24299   } else if ((MulAmt % 3) == 0) {
24300     MulAmt1 = 3;
24301     MulAmt2 = MulAmt / 3;
24302   }
24303   if (MulAmt2 &&
24304       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24305     SDLoc DL(N);
24306
24307     if (isPowerOf2_64(MulAmt2) &&
24308         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24309       // If second multiplifer is pow2, issue it first. We want the multiply by
24310       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24311       // is an add.
24312       std::swap(MulAmt1, MulAmt2);
24313
24314     SDValue NewMul;
24315     if (isPowerOf2_64(MulAmt1))
24316       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24317                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24318     else
24319       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24320                            DAG.getConstant(MulAmt1, DL, VT));
24321
24322     if (isPowerOf2_64(MulAmt2))
24323       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24324                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24325     else
24326       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24327                            DAG.getConstant(MulAmt2, DL, VT));
24328
24329     // Do not add new nodes to DAG combiner worklist.
24330     DCI.CombineTo(N, NewMul, false);
24331   }
24332   return SDValue();
24333 }
24334
24335 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24336   SDValue N0 = N->getOperand(0);
24337   SDValue N1 = N->getOperand(1);
24338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24339   EVT VT = N0.getValueType();
24340
24341   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24342   // since the result of setcc_c is all zero's or all ones.
24343   if (VT.isInteger() && !VT.isVector() &&
24344       N1C && N0.getOpcode() == ISD::AND &&
24345       N0.getOperand(1).getOpcode() == ISD::Constant) {
24346     SDValue N00 = N0.getOperand(0);
24347     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24348     APInt ShAmt = N1C->getAPIntValue();
24349     Mask = Mask.shl(ShAmt);
24350     bool MaskOK = false;
24351     // We can handle cases concerning bit-widening nodes containing setcc_c if
24352     // we carefully interrogate the mask to make sure we are semantics
24353     // preserving.
24354     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24355     // of the underlying setcc_c operation if the setcc_c was zero extended.
24356     // Consider the following example:
24357     //   zext(setcc_c)                 -> i32 0x0000FFFF
24358     //   c1                            -> i32 0x0000FFFF
24359     //   c2                            -> i32 0x00000001
24360     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24361     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24362     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24363       MaskOK = true;
24364     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24365                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24366       MaskOK = true;
24367     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24368                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24369                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24370       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24371     }
24372     if (MaskOK && Mask != 0) {
24373       SDLoc DL(N);
24374       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24375     }
24376   }
24377
24378   // Hardware support for vector shifts is sparse which makes us scalarize the
24379   // vector operations in many cases. Also, on sandybridge ADD is faster than
24380   // shl.
24381   // (shl V, 1) -> add V,V
24382   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24383     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24384       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24385       // We shift all of the values by one. In many cases we do not have
24386       // hardware support for this operation. This is better expressed as an ADD
24387       // of two values.
24388       if (N1SplatC->getAPIntValue() == 1)
24389         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24390     }
24391
24392   return SDValue();
24393 }
24394
24395 /// \brief Returns a vector of 0s if the node in input is a vector logical
24396 /// shift by a constant amount which is known to be bigger than or equal
24397 /// to the vector element size in bits.
24398 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24399                                       const X86Subtarget *Subtarget) {
24400   EVT VT = N->getValueType(0);
24401
24402   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24403       (!Subtarget->hasInt256() ||
24404        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24405     return SDValue();
24406
24407   SDValue Amt = N->getOperand(1);
24408   SDLoc DL(N);
24409   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24410     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24411       APInt ShiftAmt = AmtSplat->getAPIntValue();
24412       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24413
24414       // SSE2/AVX2 logical shifts always return a vector of 0s
24415       // if the shift amount is bigger than or equal to
24416       // the element size. The constant shift amount will be
24417       // encoded as a 8-bit immediate.
24418       if (ShiftAmt.trunc(8).uge(MaxAmount))
24419         return getZeroVector(VT, Subtarget, DAG, DL);
24420     }
24421
24422   return SDValue();
24423 }
24424
24425 /// PerformShiftCombine - Combine shifts.
24426 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24427                                    TargetLowering::DAGCombinerInfo &DCI,
24428                                    const X86Subtarget *Subtarget) {
24429   if (N->getOpcode() == ISD::SHL)
24430     if (SDValue V = PerformSHLCombine(N, DAG))
24431       return V;
24432
24433   // Try to fold this logical shift into a zero vector.
24434   if (N->getOpcode() != ISD::SRA)
24435     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24436       return V;
24437
24438   return SDValue();
24439 }
24440
24441 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24442 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24443 // and friends.  Likewise for OR -> CMPNEQSS.
24444 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24445                             TargetLowering::DAGCombinerInfo &DCI,
24446                             const X86Subtarget *Subtarget) {
24447   unsigned opcode;
24448
24449   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24450   // we're requiring SSE2 for both.
24451   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24452     SDValue N0 = N->getOperand(0);
24453     SDValue N1 = N->getOperand(1);
24454     SDValue CMP0 = N0->getOperand(1);
24455     SDValue CMP1 = N1->getOperand(1);
24456     SDLoc DL(N);
24457
24458     // The SETCCs should both refer to the same CMP.
24459     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24460       return SDValue();
24461
24462     SDValue CMP00 = CMP0->getOperand(0);
24463     SDValue CMP01 = CMP0->getOperand(1);
24464     EVT     VT    = CMP00.getValueType();
24465
24466     if (VT == MVT::f32 || VT == MVT::f64) {
24467       bool ExpectingFlags = false;
24468       // Check for any users that want flags:
24469       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24470            !ExpectingFlags && UI != UE; ++UI)
24471         switch (UI->getOpcode()) {
24472         default:
24473         case ISD::BR_CC:
24474         case ISD::BRCOND:
24475         case ISD::SELECT:
24476           ExpectingFlags = true;
24477           break;
24478         case ISD::CopyToReg:
24479         case ISD::SIGN_EXTEND:
24480         case ISD::ZERO_EXTEND:
24481         case ISD::ANY_EXTEND:
24482           break;
24483         }
24484
24485       if (!ExpectingFlags) {
24486         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24487         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24488
24489         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24490           X86::CondCode tmp = cc0;
24491           cc0 = cc1;
24492           cc1 = tmp;
24493         }
24494
24495         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24496             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24497           // FIXME: need symbolic constants for these magic numbers.
24498           // See X86ATTInstPrinter.cpp:printSSECC().
24499           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24500           if (Subtarget->hasAVX512()) {
24501             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24502                                          CMP01,
24503                                          DAG.getConstant(x86cc, DL, MVT::i8));
24504             if (N->getValueType(0) != MVT::i1)
24505               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24506                                  FSetCC);
24507             return FSetCC;
24508           }
24509           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24510                                               CMP00.getValueType(), CMP00, CMP01,
24511                                               DAG.getConstant(x86cc, DL,
24512                                                               MVT::i8));
24513
24514           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24515           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24516
24517           if (is64BitFP && !Subtarget->is64Bit()) {
24518             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24519             // 64-bit integer, since that's not a legal type. Since
24520             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24521             // bits, but can do this little dance to extract the lowest 32 bits
24522             // and work with those going forward.
24523             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24524                                            OnesOrZeroesF);
24525             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24526             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24527                                         Vector32, DAG.getIntPtrConstant(0, DL));
24528             IntVT = MVT::i32;
24529           }
24530
24531           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24532           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24533                                       DAG.getConstant(1, DL, IntVT));
24534           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24535                                               ANDed);
24536           return OneBitOfTruth;
24537         }
24538       }
24539     }
24540   }
24541   return SDValue();
24542 }
24543
24544 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24545 /// so it can be folded inside ANDNP.
24546 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24547   EVT VT = N->getValueType(0);
24548
24549   // Match direct AllOnes for 128 and 256-bit vectors
24550   if (ISD::isBuildVectorAllOnes(N))
24551     return true;
24552
24553   // Look through a bit convert.
24554   if (N->getOpcode() == ISD::BITCAST)
24555     N = N->getOperand(0).getNode();
24556
24557   // Sometimes the operand may come from a insert_subvector building a 256-bit
24558   // allones vector
24559   if (VT.is256BitVector() &&
24560       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24561     SDValue V1 = N->getOperand(0);
24562     SDValue V2 = N->getOperand(1);
24563
24564     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24565         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24566         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24567         ISD::isBuildVectorAllOnes(V2.getNode()))
24568       return true;
24569   }
24570
24571   return false;
24572 }
24573
24574 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24575 // register. In most cases we actually compare or select YMM-sized registers
24576 // and mixing the two types creates horrible code. This method optimizes
24577 // some of the transition sequences.
24578 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24579                                  TargetLowering::DAGCombinerInfo &DCI,
24580                                  const X86Subtarget *Subtarget) {
24581   EVT VT = N->getValueType(0);
24582   if (!VT.is256BitVector())
24583     return SDValue();
24584
24585   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24586           N->getOpcode() == ISD::ZERO_EXTEND ||
24587           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24588
24589   SDValue Narrow = N->getOperand(0);
24590   EVT NarrowVT = Narrow->getValueType(0);
24591   if (!NarrowVT.is128BitVector())
24592     return SDValue();
24593
24594   if (Narrow->getOpcode() != ISD::XOR &&
24595       Narrow->getOpcode() != ISD::AND &&
24596       Narrow->getOpcode() != ISD::OR)
24597     return SDValue();
24598
24599   SDValue N0  = Narrow->getOperand(0);
24600   SDValue N1  = Narrow->getOperand(1);
24601   SDLoc DL(Narrow);
24602
24603   // The Left side has to be a trunc.
24604   if (N0.getOpcode() != ISD::TRUNCATE)
24605     return SDValue();
24606
24607   // The type of the truncated inputs.
24608   EVT WideVT = N0->getOperand(0)->getValueType(0);
24609   if (WideVT != VT)
24610     return SDValue();
24611
24612   // The right side has to be a 'trunc' or a constant vector.
24613   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24614   ConstantSDNode *RHSConstSplat = nullptr;
24615   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24616     RHSConstSplat = RHSBV->getConstantSplatNode();
24617   if (!RHSTrunc && !RHSConstSplat)
24618     return SDValue();
24619
24620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24621
24622   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24623     return SDValue();
24624
24625   // Set N0 and N1 to hold the inputs to the new wide operation.
24626   N0 = N0->getOperand(0);
24627   if (RHSConstSplat) {
24628     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24629                      SDValue(RHSConstSplat, 0));
24630     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24631     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24632   } else if (RHSTrunc) {
24633     N1 = N1->getOperand(0);
24634   }
24635
24636   // Generate the wide operation.
24637   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24638   unsigned Opcode = N->getOpcode();
24639   switch (Opcode) {
24640   case ISD::ANY_EXTEND:
24641     return Op;
24642   case ISD::ZERO_EXTEND: {
24643     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24644     APInt Mask = APInt::getAllOnesValue(InBits);
24645     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24646     return DAG.getNode(ISD::AND, DL, VT,
24647                        Op, DAG.getConstant(Mask, DL, VT));
24648   }
24649   case ISD::SIGN_EXTEND:
24650     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24651                        Op, DAG.getValueType(NarrowVT));
24652   default:
24653     llvm_unreachable("Unexpected opcode");
24654   }
24655 }
24656
24657 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24658                                  TargetLowering::DAGCombinerInfo &DCI,
24659                                  const X86Subtarget *Subtarget) {
24660   SDValue N0 = N->getOperand(0);
24661   SDValue N1 = N->getOperand(1);
24662   SDLoc DL(N);
24663
24664   // A vector zext_in_reg may be represented as a shuffle,
24665   // feeding into a bitcast (this represents anyext) feeding into
24666   // an and with a mask.
24667   // We'd like to try to combine that into a shuffle with zero
24668   // plus a bitcast, removing the and.
24669   if (N0.getOpcode() != ISD::BITCAST ||
24670       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24671     return SDValue();
24672
24673   // The other side of the AND should be a splat of 2^C, where C
24674   // is the number of bits in the source type.
24675   if (N1.getOpcode() == ISD::BITCAST)
24676     N1 = N1.getOperand(0);
24677   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24678     return SDValue();
24679   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24680
24681   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24682   EVT SrcType = Shuffle->getValueType(0);
24683
24684   // We expect a single-source shuffle
24685   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24686     return SDValue();
24687
24688   unsigned SrcSize = SrcType.getScalarSizeInBits();
24689
24690   APInt SplatValue, SplatUndef;
24691   unsigned SplatBitSize;
24692   bool HasAnyUndefs;
24693   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24694                                 SplatBitSize, HasAnyUndefs))
24695     return SDValue();
24696
24697   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24698   // Make sure the splat matches the mask we expect
24699   if (SplatBitSize > ResSize ||
24700       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24701     return SDValue();
24702
24703   // Make sure the input and output size make sense
24704   if (SrcSize >= ResSize || ResSize % SrcSize)
24705     return SDValue();
24706
24707   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24708   // The number of u's between each two values depends on the ratio between
24709   // the source and dest type.
24710   unsigned ZextRatio = ResSize / SrcSize;
24711   bool IsZext = true;
24712   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24713     if (i % ZextRatio) {
24714       if (Shuffle->getMaskElt(i) > 0) {
24715         // Expected undef
24716         IsZext = false;
24717         break;
24718       }
24719     } else {
24720       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24721         // Expected element number
24722         IsZext = false;
24723         break;
24724       }
24725     }
24726   }
24727
24728   if (!IsZext)
24729     return SDValue();
24730
24731   // Ok, perform the transformation - replace the shuffle with
24732   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24733   // (instead of undef) where the k elements come from the zero vector.
24734   SmallVector<int, 8> Mask;
24735   unsigned NumElems = SrcType.getVectorNumElements();
24736   for (unsigned i = 0; i < NumElems; ++i)
24737     if (i % ZextRatio)
24738       Mask.push_back(NumElems);
24739     else
24740       Mask.push_back(i / ZextRatio);
24741
24742   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24743     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24744   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24745 }
24746
24747 /// If both input operands of a logic op are being cast from floating point
24748 /// types, try to convert this into a floating point logic node to avoid
24749 /// unnecessary moves from SSE to integer registers.
24750 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24751                                         const X86Subtarget *Subtarget) {
24752   unsigned FPOpcode = ISD::DELETED_NODE;
24753   if (N->getOpcode() == ISD::AND)
24754     FPOpcode = X86ISD::FAND;
24755   else if (N->getOpcode() == ISD::OR)
24756     FPOpcode = X86ISD::FOR;
24757   else if (N->getOpcode() == ISD::XOR)
24758     FPOpcode = X86ISD::FXOR;
24759
24760   assert(FPOpcode != ISD::DELETED_NODE &&
24761          "Unexpected input node for FP logic conversion");
24762
24763   EVT VT = N->getValueType(0);
24764   SDValue N0 = N->getOperand(0);
24765   SDValue N1 = N->getOperand(1);
24766   SDLoc DL(N);
24767   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24768       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24769        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24770     SDValue N00 = N0.getOperand(0);
24771     SDValue N10 = N1.getOperand(0);
24772     EVT N00Type = N00.getValueType();
24773     EVT N10Type = N10.getValueType();
24774     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24775       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24776       return DAG.getBitcast(VT, FPLogic);
24777     }
24778   }
24779   return SDValue();
24780 }
24781
24782 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24783                                  TargetLowering::DAGCombinerInfo &DCI,
24784                                  const X86Subtarget *Subtarget) {
24785   if (DCI.isBeforeLegalizeOps())
24786     return SDValue();
24787
24788   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24789     return Zext;
24790
24791   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24792     return R;
24793
24794   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24795     return FPLogic;
24796
24797   EVT VT = N->getValueType(0);
24798   SDValue N0 = N->getOperand(0);
24799   SDValue N1 = N->getOperand(1);
24800   SDLoc DL(N);
24801
24802   // Create BEXTR instructions
24803   // BEXTR is ((X >> imm) & (2**size-1))
24804   if (VT == MVT::i32 || VT == MVT::i64) {
24805     // Check for BEXTR.
24806     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24807         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24808       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24809       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24810       if (MaskNode && ShiftNode) {
24811         uint64_t Mask = MaskNode->getZExtValue();
24812         uint64_t Shift = ShiftNode->getZExtValue();
24813         if (isMask_64(Mask)) {
24814           uint64_t MaskSize = countPopulation(Mask);
24815           if (Shift + MaskSize <= VT.getSizeInBits())
24816             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24817                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24818                                                VT));
24819         }
24820       }
24821     } // BEXTR
24822
24823     return SDValue();
24824   }
24825
24826   // Want to form ANDNP nodes:
24827   // 1) In the hopes of then easily combining them with OR and AND nodes
24828   //    to form PBLEND/PSIGN.
24829   // 2) To match ANDN packed intrinsics
24830   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24831     return SDValue();
24832
24833   // Check LHS for vnot
24834   if (N0.getOpcode() == ISD::XOR &&
24835       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24836       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24837     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24838
24839   // Check RHS for vnot
24840   if (N1.getOpcode() == ISD::XOR &&
24841       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24842       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24843     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24844
24845   return SDValue();
24846 }
24847
24848 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24849                                 TargetLowering::DAGCombinerInfo &DCI,
24850                                 const X86Subtarget *Subtarget) {
24851   if (DCI.isBeforeLegalizeOps())
24852     return SDValue();
24853
24854   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24855     return R;
24856
24857   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24858     return FPLogic;
24859
24860   SDValue N0 = N->getOperand(0);
24861   SDValue N1 = N->getOperand(1);
24862   EVT VT = N->getValueType(0);
24863
24864   // look for psign/blend
24865   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24866     if (!Subtarget->hasSSSE3() ||
24867         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24868       return SDValue();
24869
24870     // Canonicalize pandn to RHS
24871     if (N0.getOpcode() == X86ISD::ANDNP)
24872       std::swap(N0, N1);
24873     // or (and (m, y), (pandn m, x))
24874     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24875       SDValue Mask = N1.getOperand(0);
24876       SDValue X    = N1.getOperand(1);
24877       SDValue Y;
24878       if (N0.getOperand(0) == Mask)
24879         Y = N0.getOperand(1);
24880       if (N0.getOperand(1) == Mask)
24881         Y = N0.getOperand(0);
24882
24883       // Check to see if the mask appeared in both the AND and ANDNP and
24884       if (!Y.getNode())
24885         return SDValue();
24886
24887       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24888       // Look through mask bitcast.
24889       if (Mask.getOpcode() == ISD::BITCAST)
24890         Mask = Mask.getOperand(0);
24891       if (X.getOpcode() == ISD::BITCAST)
24892         X = X.getOperand(0);
24893       if (Y.getOpcode() == ISD::BITCAST)
24894         Y = Y.getOperand(0);
24895
24896       EVT MaskVT = Mask.getValueType();
24897
24898       // Validate that the Mask operand is a vector sra node.
24899       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24900       // there is no psrai.b
24901       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24902       unsigned SraAmt = ~0;
24903       if (Mask.getOpcode() == ISD::SRA) {
24904         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24905           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24906             SraAmt = AmtConst->getZExtValue();
24907       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24908         SDValue SraC = Mask.getOperand(1);
24909         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24910       }
24911       if ((SraAmt + 1) != EltBits)
24912         return SDValue();
24913
24914       SDLoc DL(N);
24915
24916       // Now we know we at least have a plendvb with the mask val.  See if
24917       // we can form a psignb/w/d.
24918       // psign = x.type == y.type == mask.type && y = sub(0, x);
24919       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24920           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24921           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24922         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24923                "Unsupported VT for PSIGN");
24924         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24925         return DAG.getBitcast(VT, Mask);
24926       }
24927       // PBLENDVB only available on SSE 4.1
24928       if (!Subtarget->hasSSE41())
24929         return SDValue();
24930
24931       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24932
24933       X = DAG.getBitcast(BlendVT, X);
24934       Y = DAG.getBitcast(BlendVT, Y);
24935       Mask = DAG.getBitcast(BlendVT, Mask);
24936       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24937       return DAG.getBitcast(VT, Mask);
24938     }
24939   }
24940
24941   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24942     return SDValue();
24943
24944   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24945   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24946
24947   // SHLD/SHRD instructions have lower register pressure, but on some
24948   // platforms they have higher latency than the equivalent
24949   // series of shifts/or that would otherwise be generated.
24950   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24951   // have higher latencies and we are not optimizing for size.
24952   if (!OptForSize && Subtarget->isSHLDSlow())
24953     return SDValue();
24954
24955   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24956     std::swap(N0, N1);
24957   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24958     return SDValue();
24959   if (!N0.hasOneUse() || !N1.hasOneUse())
24960     return SDValue();
24961
24962   SDValue ShAmt0 = N0.getOperand(1);
24963   if (ShAmt0.getValueType() != MVT::i8)
24964     return SDValue();
24965   SDValue ShAmt1 = N1.getOperand(1);
24966   if (ShAmt1.getValueType() != MVT::i8)
24967     return SDValue();
24968   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24969     ShAmt0 = ShAmt0.getOperand(0);
24970   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24971     ShAmt1 = ShAmt1.getOperand(0);
24972
24973   SDLoc DL(N);
24974   unsigned Opc = X86ISD::SHLD;
24975   SDValue Op0 = N0.getOperand(0);
24976   SDValue Op1 = N1.getOperand(0);
24977   if (ShAmt0.getOpcode() == ISD::SUB) {
24978     Opc = X86ISD::SHRD;
24979     std::swap(Op0, Op1);
24980     std::swap(ShAmt0, ShAmt1);
24981   }
24982
24983   unsigned Bits = VT.getSizeInBits();
24984   if (ShAmt1.getOpcode() == ISD::SUB) {
24985     SDValue Sum = ShAmt1.getOperand(0);
24986     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24987       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24988       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24989         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24990       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24991         return DAG.getNode(Opc, DL, VT,
24992                            Op0, Op1,
24993                            DAG.getNode(ISD::TRUNCATE, DL,
24994                                        MVT::i8, ShAmt0));
24995     }
24996   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24997     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24998     if (ShAmt0C &&
24999         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25000       return DAG.getNode(Opc, DL, VT,
25001                          N0.getOperand(0), N1.getOperand(0),
25002                          DAG.getNode(ISD::TRUNCATE, DL,
25003                                        MVT::i8, ShAmt0));
25004   }
25005
25006   return SDValue();
25007 }
25008
25009 // Generate NEG and CMOV for integer abs.
25010 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25011   EVT VT = N->getValueType(0);
25012
25013   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25014   // 8-bit integer abs to NEG and CMOV.
25015   if (VT.isInteger() && VT.getSizeInBits() == 8)
25016     return SDValue();
25017
25018   SDValue N0 = N->getOperand(0);
25019   SDValue N1 = N->getOperand(1);
25020   SDLoc DL(N);
25021
25022   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25023   // and change it to SUB and CMOV.
25024   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25025       N0.getOpcode() == ISD::ADD &&
25026       N0.getOperand(1) == N1 &&
25027       N1.getOpcode() == ISD::SRA &&
25028       N1.getOperand(0) == N0.getOperand(0))
25029     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25030       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25031         // Generate SUB & CMOV.
25032         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25033                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25034
25035         SDValue Ops[] = { N0.getOperand(0), Neg,
25036                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25037                           SDValue(Neg.getNode(), 1) };
25038         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25039       }
25040   return SDValue();
25041 }
25042
25043 // Try to turn tests against the signbit in the form of:
25044 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25045 // into:
25046 //   SETGT(X, -1)
25047 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25048   // This is only worth doing if the output type is i8.
25049   if (N->getValueType(0) != MVT::i8)
25050     return SDValue();
25051
25052   SDValue N0 = N->getOperand(0);
25053   SDValue N1 = N->getOperand(1);
25054
25055   // We should be performing an xor against a truncated shift.
25056   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25057     return SDValue();
25058
25059   // Make sure we are performing an xor against one.
25060   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25061     return SDValue();
25062
25063   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25064   SDValue Shift = N0.getOperand(0);
25065   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25066     return SDValue();
25067
25068   // Make sure we are truncating from one of i16, i32 or i64.
25069   EVT ShiftTy = Shift.getValueType();
25070   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25071     return SDValue();
25072
25073   // Make sure the shift amount extracts the sign bit.
25074   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25075       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25076     return SDValue();
25077
25078   // Create a greater-than comparison against -1.
25079   // N.B. Using SETGE against 0 works but we want a canonical looking
25080   // comparison, using SETGT matches up with what TranslateX86CC.
25081   SDLoc DL(N);
25082   SDValue ShiftOp = Shift.getOperand(0);
25083   EVT ShiftOpTy = ShiftOp.getValueType();
25084   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25085                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25086   return Cond;
25087 }
25088
25089 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25090                                  TargetLowering::DAGCombinerInfo &DCI,
25091                                  const X86Subtarget *Subtarget) {
25092   if (DCI.isBeforeLegalizeOps())
25093     return SDValue();
25094
25095   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25096     return RV;
25097
25098   if (Subtarget->hasCMov())
25099     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25100       return RV;
25101
25102   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25103     return FPLogic;
25104
25105   return SDValue();
25106 }
25107
25108 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25109 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25110                                   TargetLowering::DAGCombinerInfo &DCI,
25111                                   const X86Subtarget *Subtarget) {
25112   LoadSDNode *Ld = cast<LoadSDNode>(N);
25113   EVT RegVT = Ld->getValueType(0);
25114   EVT MemVT = Ld->getMemoryVT();
25115   SDLoc dl(Ld);
25116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25117
25118   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25119   // into two 16-byte operations.
25120   ISD::LoadExtType Ext = Ld->getExtensionType();
25121   bool Fast;
25122   unsigned AddressSpace = Ld->getAddressSpace();
25123   unsigned Alignment = Ld->getAlignment();
25124   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25125       Ext == ISD::NON_EXTLOAD &&
25126       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25127                              AddressSpace, Alignment, &Fast) && !Fast) {
25128     unsigned NumElems = RegVT.getVectorNumElements();
25129     if (NumElems < 2)
25130       return SDValue();
25131
25132     SDValue Ptr = Ld->getBasePtr();
25133     SDValue Increment =
25134         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25135
25136     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25137                                   NumElems/2);
25138     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25139                                 Ld->getPointerInfo(), Ld->isVolatile(),
25140                                 Ld->isNonTemporal(), Ld->isInvariant(),
25141                                 Alignment);
25142     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25143     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25144                                 Ld->getPointerInfo(), Ld->isVolatile(),
25145                                 Ld->isNonTemporal(), Ld->isInvariant(),
25146                                 std::min(16U, Alignment));
25147     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25148                              Load1.getValue(1),
25149                              Load2.getValue(1));
25150
25151     SDValue NewVec = DAG.getUNDEF(RegVT);
25152     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25153     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25154     return DCI.CombineTo(N, NewVec, TF, true);
25155   }
25156
25157   return SDValue();
25158 }
25159
25160 /// PerformMLOADCombine - Resolve extending loads
25161 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25162                                    TargetLowering::DAGCombinerInfo &DCI,
25163                                    const X86Subtarget *Subtarget) {
25164   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25165   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25166     return SDValue();
25167
25168   EVT VT = Mld->getValueType(0);
25169   unsigned NumElems = VT.getVectorNumElements();
25170   EVT LdVT = Mld->getMemoryVT();
25171   SDLoc dl(Mld);
25172
25173   assert(LdVT != VT && "Cannot extend to the same type");
25174   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25175   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25176   // From, To sizes and ElemCount must be pow of two
25177   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25178     "Unexpected size for extending masked load");
25179
25180   unsigned SizeRatio  = ToSz / FromSz;
25181   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25182
25183   // Create a type on which we perform the shuffle
25184   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25185           LdVT.getScalarType(), NumElems*SizeRatio);
25186   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25187
25188   // Convert Src0 value
25189   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25190   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25191     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25192     for (unsigned i = 0; i != NumElems; ++i)
25193       ShuffleVec[i] = i * SizeRatio;
25194
25195     // Can't shuffle using an illegal type.
25196     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25197            "WideVecVT should be legal");
25198     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25199                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25200   }
25201   // Prepare the new mask
25202   SDValue NewMask;
25203   SDValue Mask = Mld->getMask();
25204   if (Mask.getValueType() == VT) {
25205     // Mask and original value have the same type
25206     NewMask = DAG.getBitcast(WideVecVT, Mask);
25207     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25208     for (unsigned i = 0; i != NumElems; ++i)
25209       ShuffleVec[i] = i * SizeRatio;
25210     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25211       ShuffleVec[i] = NumElems*SizeRatio;
25212     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25213                                    DAG.getConstant(0, dl, WideVecVT),
25214                                    &ShuffleVec[0]);
25215   }
25216   else {
25217     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25218     unsigned WidenNumElts = NumElems*SizeRatio;
25219     unsigned MaskNumElts = VT.getVectorNumElements();
25220     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25221                                      WidenNumElts);
25222
25223     unsigned NumConcat = WidenNumElts / MaskNumElts;
25224     SmallVector<SDValue, 16> Ops(NumConcat);
25225     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25226     Ops[0] = Mask;
25227     for (unsigned i = 1; i != NumConcat; ++i)
25228       Ops[i] = ZeroVal;
25229
25230     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25231   }
25232
25233   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25234                                      Mld->getBasePtr(), NewMask, WideSrc0,
25235                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25236                                      ISD::NON_EXTLOAD);
25237   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25238   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25239 }
25240 /// PerformMSTORECombine - Resolve truncating stores
25241 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25242                                     const X86Subtarget *Subtarget) {
25243   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25244   if (!Mst->isTruncatingStore())
25245     return SDValue();
25246
25247   EVT VT = Mst->getValue().getValueType();
25248   unsigned NumElems = VT.getVectorNumElements();
25249   EVT StVT = Mst->getMemoryVT();
25250   SDLoc dl(Mst);
25251
25252   assert(StVT != VT && "Cannot truncate to the same type");
25253   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25254   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25255
25256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25257
25258   // The truncating store is legal in some cases. For example
25259   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25260   // are designated for truncate store.
25261   // In this case we don't need any further transformations.
25262   if (TLI.isTruncStoreLegal(VT, StVT))
25263     return SDValue();
25264
25265   // From, To sizes and ElemCount must be pow of two
25266   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25267     "Unexpected size for truncating masked store");
25268   // We are going to use the original vector elt for storing.
25269   // Accumulated smaller vector elements must be a multiple of the store size.
25270   assert (((NumElems * FromSz) % ToSz) == 0 &&
25271           "Unexpected ratio for truncating masked store");
25272
25273   unsigned SizeRatio  = FromSz / ToSz;
25274   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25275
25276   // Create a type on which we perform the shuffle
25277   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25278           StVT.getScalarType(), NumElems*SizeRatio);
25279
25280   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25281
25282   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25283   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25284   for (unsigned i = 0; i != NumElems; ++i)
25285     ShuffleVec[i] = i * SizeRatio;
25286
25287   // Can't shuffle using an illegal type.
25288   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25289          "WideVecVT should be legal");
25290
25291   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25292                                         DAG.getUNDEF(WideVecVT),
25293                                         &ShuffleVec[0]);
25294
25295   SDValue NewMask;
25296   SDValue Mask = Mst->getMask();
25297   if (Mask.getValueType() == VT) {
25298     // Mask and original value have the same type
25299     NewMask = DAG.getBitcast(WideVecVT, Mask);
25300     for (unsigned i = 0; i != NumElems; ++i)
25301       ShuffleVec[i] = i * SizeRatio;
25302     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25303       ShuffleVec[i] = NumElems*SizeRatio;
25304     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25305                                    DAG.getConstant(0, dl, WideVecVT),
25306                                    &ShuffleVec[0]);
25307   }
25308   else {
25309     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25310     unsigned WidenNumElts = NumElems*SizeRatio;
25311     unsigned MaskNumElts = VT.getVectorNumElements();
25312     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25313                                      WidenNumElts);
25314
25315     unsigned NumConcat = WidenNumElts / MaskNumElts;
25316     SmallVector<SDValue, 16> Ops(NumConcat);
25317     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25318     Ops[0] = Mask;
25319     for (unsigned i = 1; i != NumConcat; ++i)
25320       Ops[i] = ZeroVal;
25321
25322     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25323   }
25324
25325   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25326                             NewMask, StVT, Mst->getMemOperand(), false);
25327 }
25328 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25329 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25330                                    const X86Subtarget *Subtarget) {
25331   StoreSDNode *St = cast<StoreSDNode>(N);
25332   EVT VT = St->getValue().getValueType();
25333   EVT StVT = St->getMemoryVT();
25334   SDLoc dl(St);
25335   SDValue StoredVal = St->getOperand(1);
25336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25337
25338   // If we are saving a concatenation of two XMM registers and 32-byte stores
25339   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25340   bool Fast;
25341   unsigned AddressSpace = St->getAddressSpace();
25342   unsigned Alignment = St->getAlignment();
25343   if (VT.is256BitVector() && StVT == VT &&
25344       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25345                              AddressSpace, Alignment, &Fast) && !Fast) {
25346     unsigned NumElems = VT.getVectorNumElements();
25347     if (NumElems < 2)
25348       return SDValue();
25349
25350     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25351     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25352
25353     SDValue Stride =
25354         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25355     SDValue Ptr0 = St->getBasePtr();
25356     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25357
25358     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25359                                 St->getPointerInfo(), St->isVolatile(),
25360                                 St->isNonTemporal(), Alignment);
25361     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25362                                 St->getPointerInfo(), St->isVolatile(),
25363                                 St->isNonTemporal(),
25364                                 std::min(16U, Alignment));
25365     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25366   }
25367
25368   // Optimize trunc store (of multiple scalars) to shuffle and store.
25369   // First, pack all of the elements in one place. Next, store to memory
25370   // in fewer chunks.
25371   if (St->isTruncatingStore() && VT.isVector()) {
25372     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25373     unsigned NumElems = VT.getVectorNumElements();
25374     assert(StVT != VT && "Cannot truncate to the same type");
25375     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25376     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25377
25378     // The truncating store is legal in some cases. For example
25379     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25380     // are designated for truncate store.
25381     // In this case we don't need any further transformations.
25382     if (TLI.isTruncStoreLegal(VT, StVT))
25383       return SDValue();
25384
25385     // From, To sizes and ElemCount must be pow of two
25386     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25387     // We are going to use the original vector elt for storing.
25388     // Accumulated smaller vector elements must be a multiple of the store size.
25389     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25390
25391     unsigned SizeRatio  = FromSz / ToSz;
25392
25393     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25394
25395     // Create a type on which we perform the shuffle
25396     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25397             StVT.getScalarType(), NumElems*SizeRatio);
25398
25399     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25400
25401     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25402     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25403     for (unsigned i = 0; i != NumElems; ++i)
25404       ShuffleVec[i] = i * SizeRatio;
25405
25406     // Can't shuffle using an illegal type.
25407     if (!TLI.isTypeLegal(WideVecVT))
25408       return SDValue();
25409
25410     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25411                                          DAG.getUNDEF(WideVecVT),
25412                                          &ShuffleVec[0]);
25413     // At this point all of the data is stored at the bottom of the
25414     // register. We now need to save it to mem.
25415
25416     // Find the largest store unit
25417     MVT StoreType = MVT::i8;
25418     for (MVT Tp : MVT::integer_valuetypes()) {
25419       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25420         StoreType = Tp;
25421     }
25422
25423     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25424     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25425         (64 <= NumElems * ToSz))
25426       StoreType = MVT::f64;
25427
25428     // Bitcast the original vector into a vector of store-size units
25429     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25430             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25431     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25432     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25433     SmallVector<SDValue, 8> Chains;
25434     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25435                                         TLI.getPointerTy(DAG.getDataLayout()));
25436     SDValue Ptr = St->getBasePtr();
25437
25438     // Perform one or more big stores into memory.
25439     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25440       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25441                                    StoreType, ShuffWide,
25442                                    DAG.getIntPtrConstant(i, dl));
25443       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25444                                 St->getPointerInfo(), St->isVolatile(),
25445                                 St->isNonTemporal(), St->getAlignment());
25446       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25447       Chains.push_back(Ch);
25448     }
25449
25450     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25451   }
25452
25453   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25454   // the FP state in cases where an emms may be missing.
25455   // A preferable solution to the general problem is to figure out the right
25456   // places to insert EMMS.  This qualifies as a quick hack.
25457
25458   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25459   if (VT.getSizeInBits() != 64)
25460     return SDValue();
25461
25462   const Function *F = DAG.getMachineFunction().getFunction();
25463   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25464   bool F64IsLegal =
25465       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25466   if ((VT.isVector() ||
25467        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25468       isa<LoadSDNode>(St->getValue()) &&
25469       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25470       St->getChain().hasOneUse() && !St->isVolatile()) {
25471     SDNode* LdVal = St->getValue().getNode();
25472     LoadSDNode *Ld = nullptr;
25473     int TokenFactorIndex = -1;
25474     SmallVector<SDValue, 8> Ops;
25475     SDNode* ChainVal = St->getChain().getNode();
25476     // Must be a store of a load.  We currently handle two cases:  the load
25477     // is a direct child, and it's under an intervening TokenFactor.  It is
25478     // possible to dig deeper under nested TokenFactors.
25479     if (ChainVal == LdVal)
25480       Ld = cast<LoadSDNode>(St->getChain());
25481     else if (St->getValue().hasOneUse() &&
25482              ChainVal->getOpcode() == ISD::TokenFactor) {
25483       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25484         if (ChainVal->getOperand(i).getNode() == LdVal) {
25485           TokenFactorIndex = i;
25486           Ld = cast<LoadSDNode>(St->getValue());
25487         } else
25488           Ops.push_back(ChainVal->getOperand(i));
25489       }
25490     }
25491
25492     if (!Ld || !ISD::isNormalLoad(Ld))
25493       return SDValue();
25494
25495     // If this is not the MMX case, i.e. we are just turning i64 load/store
25496     // into f64 load/store, avoid the transformation if there are multiple
25497     // uses of the loaded value.
25498     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25499       return SDValue();
25500
25501     SDLoc LdDL(Ld);
25502     SDLoc StDL(N);
25503     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25504     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25505     // pair instead.
25506     if (Subtarget->is64Bit() || F64IsLegal) {
25507       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25508       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25509                                   Ld->getPointerInfo(), Ld->isVolatile(),
25510                                   Ld->isNonTemporal(), Ld->isInvariant(),
25511                                   Ld->getAlignment());
25512       SDValue NewChain = NewLd.getValue(1);
25513       if (TokenFactorIndex != -1) {
25514         Ops.push_back(NewChain);
25515         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25516       }
25517       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25518                           St->getPointerInfo(),
25519                           St->isVolatile(), St->isNonTemporal(),
25520                           St->getAlignment());
25521     }
25522
25523     // Otherwise, lower to two pairs of 32-bit loads / stores.
25524     SDValue LoAddr = Ld->getBasePtr();
25525     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25526                                  DAG.getConstant(4, LdDL, MVT::i32));
25527
25528     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25529                                Ld->getPointerInfo(),
25530                                Ld->isVolatile(), Ld->isNonTemporal(),
25531                                Ld->isInvariant(), Ld->getAlignment());
25532     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25533                                Ld->getPointerInfo().getWithOffset(4),
25534                                Ld->isVolatile(), Ld->isNonTemporal(),
25535                                Ld->isInvariant(),
25536                                MinAlign(Ld->getAlignment(), 4));
25537
25538     SDValue NewChain = LoLd.getValue(1);
25539     if (TokenFactorIndex != -1) {
25540       Ops.push_back(LoLd);
25541       Ops.push_back(HiLd);
25542       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25543     }
25544
25545     LoAddr = St->getBasePtr();
25546     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25547                          DAG.getConstant(4, StDL, MVT::i32));
25548
25549     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25550                                 St->getPointerInfo(),
25551                                 St->isVolatile(), St->isNonTemporal(),
25552                                 St->getAlignment());
25553     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25554                                 St->getPointerInfo().getWithOffset(4),
25555                                 St->isVolatile(),
25556                                 St->isNonTemporal(),
25557                                 MinAlign(St->getAlignment(), 4));
25558     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25559   }
25560
25561   // This is similar to the above case, but here we handle a scalar 64-bit
25562   // integer store that is extracted from a vector on a 32-bit target.
25563   // If we have SSE2, then we can treat it like a floating-point double
25564   // to get past legalization. The execution dependencies fixup pass will
25565   // choose the optimal machine instruction for the store if this really is
25566   // an integer or v2f32 rather than an f64.
25567   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25568       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25569     SDValue OldExtract = St->getOperand(1);
25570     SDValue ExtOp0 = OldExtract.getOperand(0);
25571     unsigned VecSize = ExtOp0.getValueSizeInBits();
25572     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25573     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25574     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25575                                      BitCast, OldExtract.getOperand(1));
25576     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25577                         St->getPointerInfo(), St->isVolatile(),
25578                         St->isNonTemporal(), St->getAlignment());
25579   }
25580
25581   return SDValue();
25582 }
25583
25584 /// Return 'true' if this vector operation is "horizontal"
25585 /// and return the operands for the horizontal operation in LHS and RHS.  A
25586 /// horizontal operation performs the binary operation on successive elements
25587 /// of its first operand, then on successive elements of its second operand,
25588 /// returning the resulting values in a vector.  For example, if
25589 ///   A = < float a0, float a1, float a2, float a3 >
25590 /// and
25591 ///   B = < float b0, float b1, float b2, float b3 >
25592 /// then the result of doing a horizontal operation on A and B is
25593 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25594 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25595 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25596 /// set to A, RHS to B, and the routine returns 'true'.
25597 /// Note that the binary operation should have the property that if one of the
25598 /// operands is UNDEF then the result is UNDEF.
25599 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25600   // Look for the following pattern: if
25601   //   A = < float a0, float a1, float a2, float a3 >
25602   //   B = < float b0, float b1, float b2, float b3 >
25603   // and
25604   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25605   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25606   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25607   // which is A horizontal-op B.
25608
25609   // At least one of the operands should be a vector shuffle.
25610   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25611       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25612     return false;
25613
25614   MVT VT = LHS.getSimpleValueType();
25615
25616   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25617          "Unsupported vector type for horizontal add/sub");
25618
25619   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25620   // operate independently on 128-bit lanes.
25621   unsigned NumElts = VT.getVectorNumElements();
25622   unsigned NumLanes = VT.getSizeInBits()/128;
25623   unsigned NumLaneElts = NumElts / NumLanes;
25624   assert((NumLaneElts % 2 == 0) &&
25625          "Vector type should have an even number of elements in each lane");
25626   unsigned HalfLaneElts = NumLaneElts/2;
25627
25628   // View LHS in the form
25629   //   LHS = VECTOR_SHUFFLE A, B, LMask
25630   // If LHS is not a shuffle then pretend it is the shuffle
25631   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25632   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25633   // type VT.
25634   SDValue A, B;
25635   SmallVector<int, 16> LMask(NumElts);
25636   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25637     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25638       A = LHS.getOperand(0);
25639     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25640       B = LHS.getOperand(1);
25641     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25642     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25643   } else {
25644     if (LHS.getOpcode() != ISD::UNDEF)
25645       A = LHS;
25646     for (unsigned i = 0; i != NumElts; ++i)
25647       LMask[i] = i;
25648   }
25649
25650   // Likewise, view RHS in the form
25651   //   RHS = VECTOR_SHUFFLE C, D, RMask
25652   SDValue C, D;
25653   SmallVector<int, 16> RMask(NumElts);
25654   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25655     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25656       C = RHS.getOperand(0);
25657     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25658       D = RHS.getOperand(1);
25659     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25660     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25661   } else {
25662     if (RHS.getOpcode() != ISD::UNDEF)
25663       C = RHS;
25664     for (unsigned i = 0; i != NumElts; ++i)
25665       RMask[i] = i;
25666   }
25667
25668   // Check that the shuffles are both shuffling the same vectors.
25669   if (!(A == C && B == D) && !(A == D && B == C))
25670     return false;
25671
25672   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25673   if (!A.getNode() && !B.getNode())
25674     return false;
25675
25676   // If A and B occur in reverse order in RHS, then "swap" them (which means
25677   // rewriting the mask).
25678   if (A != C)
25679     ShuffleVectorSDNode::commuteMask(RMask);
25680
25681   // At this point LHS and RHS are equivalent to
25682   //   LHS = VECTOR_SHUFFLE A, B, LMask
25683   //   RHS = VECTOR_SHUFFLE A, B, RMask
25684   // Check that the masks correspond to performing a horizontal operation.
25685   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25686     for (unsigned i = 0; i != NumLaneElts; ++i) {
25687       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25688
25689       // Ignore any UNDEF components.
25690       if (LIdx < 0 || RIdx < 0 ||
25691           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25692           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25693         continue;
25694
25695       // Check that successive elements are being operated on.  If not, this is
25696       // not a horizontal operation.
25697       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25698       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25699       if (!(LIdx == Index && RIdx == Index + 1) &&
25700           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25701         return false;
25702     }
25703   }
25704
25705   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25706   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25707   return true;
25708 }
25709
25710 /// Do target-specific dag combines on floating point adds.
25711 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25712                                   const X86Subtarget *Subtarget) {
25713   EVT VT = N->getValueType(0);
25714   SDValue LHS = N->getOperand(0);
25715   SDValue RHS = N->getOperand(1);
25716
25717   // Try to synthesize horizontal adds from adds of shuffles.
25718   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25719        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25720       isHorizontalBinOp(LHS, RHS, true))
25721     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25722   return SDValue();
25723 }
25724
25725 /// Do target-specific dag combines on floating point subs.
25726 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25727                                   const X86Subtarget *Subtarget) {
25728   EVT VT = N->getValueType(0);
25729   SDValue LHS = N->getOperand(0);
25730   SDValue RHS = N->getOperand(1);
25731
25732   // Try to synthesize horizontal subs from subs of shuffles.
25733   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25734        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25735       isHorizontalBinOp(LHS, RHS, false))
25736     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25737   return SDValue();
25738 }
25739
25740 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25741 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25742                                  const X86Subtarget *Subtarget) {
25743   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25744
25745   // F[X]OR(0.0, x) -> x
25746   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25747     if (C->getValueAPF().isPosZero())
25748       return N->getOperand(1);
25749
25750   // F[X]OR(x, 0.0) -> x
25751   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25752     if (C->getValueAPF().isPosZero())
25753       return N->getOperand(0);
25754
25755   EVT VT = N->getValueType(0);
25756   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25757     SDLoc dl(N);
25758     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25759     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25760
25761     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25762     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25763     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25764     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25765     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25766   }
25767   return SDValue();
25768 }
25769
25770 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25771 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25772   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25773
25774   // Only perform optimizations if UnsafeMath is used.
25775   if (!DAG.getTarget().Options.UnsafeFPMath)
25776     return SDValue();
25777
25778   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25779   // into FMINC and FMAXC, which are Commutative operations.
25780   unsigned NewOp = 0;
25781   switch (N->getOpcode()) {
25782     default: llvm_unreachable("unknown opcode");
25783     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25784     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25785   }
25786
25787   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25788                      N->getOperand(0), N->getOperand(1));
25789 }
25790
25791 /// Do target-specific dag combines on X86ISD::FAND nodes.
25792 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25793   // FAND(0.0, x) -> 0.0
25794   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25795     if (C->getValueAPF().isPosZero())
25796       return N->getOperand(0);
25797
25798   // FAND(x, 0.0) -> 0.0
25799   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25800     if (C->getValueAPF().isPosZero())
25801       return N->getOperand(1);
25802
25803   return SDValue();
25804 }
25805
25806 /// Do target-specific dag combines on X86ISD::FANDN nodes
25807 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25808   // FANDN(0.0, x) -> x
25809   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25810     if (C->getValueAPF().isPosZero())
25811       return N->getOperand(1);
25812
25813   // FANDN(x, 0.0) -> 0.0
25814   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25815     if (C->getValueAPF().isPosZero())
25816       return N->getOperand(1);
25817
25818   return SDValue();
25819 }
25820
25821 static SDValue PerformBTCombine(SDNode *N,
25822                                 SelectionDAG &DAG,
25823                                 TargetLowering::DAGCombinerInfo &DCI) {
25824   // BT ignores high bits in the bit index operand.
25825   SDValue Op1 = N->getOperand(1);
25826   if (Op1.hasOneUse()) {
25827     unsigned BitWidth = Op1.getValueSizeInBits();
25828     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25829     APInt KnownZero, KnownOne;
25830     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25831                                           !DCI.isBeforeLegalizeOps());
25832     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25833     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25834         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25835       DCI.CommitTargetLoweringOpt(TLO);
25836   }
25837   return SDValue();
25838 }
25839
25840 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25841   SDValue Op = N->getOperand(0);
25842   if (Op.getOpcode() == ISD::BITCAST)
25843     Op = Op.getOperand(0);
25844   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25845   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25846       VT.getVectorElementType().getSizeInBits() ==
25847       OpVT.getVectorElementType().getSizeInBits()) {
25848     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25849   }
25850   return SDValue();
25851 }
25852
25853 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25854                                                const X86Subtarget *Subtarget) {
25855   EVT VT = N->getValueType(0);
25856   if (!VT.isVector())
25857     return SDValue();
25858
25859   SDValue N0 = N->getOperand(0);
25860   SDValue N1 = N->getOperand(1);
25861   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25862   SDLoc dl(N);
25863
25864   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25865   // both SSE and AVX2 since there is no sign-extended shift right
25866   // operation on a vector with 64-bit elements.
25867   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25868   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25869   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25870       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25871     SDValue N00 = N0.getOperand(0);
25872
25873     // EXTLOAD has a better solution on AVX2,
25874     // it may be replaced with X86ISD::VSEXT node.
25875     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25876       if (!ISD::isNormalLoad(N00.getNode()))
25877         return SDValue();
25878
25879     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25880         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25881                                   N00, N1);
25882       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25883     }
25884   }
25885   return SDValue();
25886 }
25887
25888 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
25889 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
25890 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
25891 /// eliminate extend, add, and shift instructions.
25892 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
25893                                        const X86Subtarget *Subtarget) {
25894   // TODO: This should be valid for other integer types.
25895   EVT VT = Sext->getValueType(0);
25896   if (VT != MVT::i64)
25897     return SDValue();
25898
25899   // We need an 'add nsw' feeding into the 'sext'.
25900   SDValue Add = Sext->getOperand(0);
25901   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
25902     return SDValue();
25903
25904   // Having a constant operand to the 'add' ensures that we are not increasing
25905   // the instruction count because the constant is extended for free below.
25906   // A constant operand can also become the displacement field of an LEA.
25907   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
25908   if (!AddOp1)
25909     return SDValue();
25910
25911   // Don't make the 'add' bigger if there's no hope of combining it with some
25912   // other 'add' or 'shl' instruction.
25913   // TODO: It may be profitable to generate simpler LEA instructions in place
25914   // of single 'add' instructions, but the cost model for selecting an LEA
25915   // currently has a high threshold.
25916   bool HasLEAPotential = false;
25917   for (auto *User : Sext->uses()) {
25918     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
25919       HasLEAPotential = true;
25920       break;
25921     }
25922   }
25923   if (!HasLEAPotential)
25924     return SDValue();
25925
25926   // Everything looks good, so pull the 'sext' ahead of the 'add'.
25927   int64_t AddConstant = AddOp1->getSExtValue();
25928   SDValue AddOp0 = Add.getOperand(0);
25929   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
25930   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
25931
25932   // The wider add is guaranteed to not wrap because both operands are
25933   // sign-extended.
25934   SDNodeFlags Flags;
25935   Flags.setNoSignedWrap(true);
25936   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
25937 }
25938
25939 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25940                                   TargetLowering::DAGCombinerInfo &DCI,
25941                                   const X86Subtarget *Subtarget) {
25942   SDValue N0 = N->getOperand(0);
25943   EVT VT = N->getValueType(0);
25944   EVT SVT = VT.getScalarType();
25945   EVT InVT = N0.getValueType();
25946   EVT InSVT = InVT.getScalarType();
25947   SDLoc DL(N);
25948
25949   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25950   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25951   // This exposes the sext to the sdivrem lowering, so that it directly extends
25952   // from AH (which we otherwise need to do contortions to access).
25953   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25954       InVT == MVT::i8 && VT == MVT::i32) {
25955     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25956     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25957                             N0.getOperand(0), N0.getOperand(1));
25958     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25959     return R.getValue(1);
25960   }
25961
25962   if (!DCI.isBeforeLegalizeOps()) {
25963     if (InVT == MVT::i1) {
25964       SDValue Zero = DAG.getConstant(0, DL, VT);
25965       SDValue AllOnes =
25966         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25967       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25968     }
25969     return SDValue();
25970   }
25971
25972   if (VT.isVector() && Subtarget->hasSSE2()) {
25973     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25974       EVT InVT = N.getValueType();
25975       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25976                                    Size / InVT.getScalarSizeInBits());
25977       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25978                                     DAG.getUNDEF(InVT));
25979       Opnds[0] = N;
25980       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25981     };
25982
25983     // If target-size is less than 128-bits, extend to a type that would extend
25984     // to 128 bits, extend that and extract the original target vector.
25985     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25986         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25987         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25988       unsigned Scale = 128 / VT.getSizeInBits();
25989       EVT ExVT =
25990           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25991       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25992       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25993       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25994                          DAG.getIntPtrConstant(0, DL));
25995     }
25996
25997     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25998     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25999     if (VT.getSizeInBits() == 128 &&
26000         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26001         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26002       SDValue ExOp = ExtendVecSize(DL, N0, 128);
26003       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26004     }
26005
26006     // On pre-AVX2 targets, split into 128-bit nodes of
26007     // ISD::SIGN_EXTEND_VECTOR_INREG.
26008     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26009         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26010         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26011       unsigned NumVecs = VT.getSizeInBits() / 128;
26012       unsigned NumSubElts = 128 / SVT.getSizeInBits();
26013       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26014       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26015
26016       SmallVector<SDValue, 8> Opnds;
26017       for (unsigned i = 0, Offset = 0; i != NumVecs;
26018            ++i, Offset += NumSubElts) {
26019         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26020                                      DAG.getIntPtrConstant(Offset, DL));
26021         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26022         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26023         Opnds.push_back(SrcVec);
26024       }
26025       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26026     }
26027   }
26028
26029   if (Subtarget->hasAVX() && VT.isVector() && VT.getSizeInBits() == 256)
26030     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26031       return R;
26032
26033   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26034     return NewAdd;
26035
26036   return SDValue();
26037 }
26038
26039 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26040                                  const X86Subtarget* Subtarget) {
26041   SDLoc dl(N);
26042   EVT VT = N->getValueType(0);
26043
26044   // Let legalize expand this if it isn't a legal type yet.
26045   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26046     return SDValue();
26047
26048   EVT ScalarVT = VT.getScalarType();
26049   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26050       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26051        !Subtarget->hasAVX512()))
26052     return SDValue();
26053
26054   SDValue A = N->getOperand(0);
26055   SDValue B = N->getOperand(1);
26056   SDValue C = N->getOperand(2);
26057
26058   bool NegA = (A.getOpcode() == ISD::FNEG);
26059   bool NegB = (B.getOpcode() == ISD::FNEG);
26060   bool NegC = (C.getOpcode() == ISD::FNEG);
26061
26062   // Negative multiplication when NegA xor NegB
26063   bool NegMul = (NegA != NegB);
26064   if (NegA)
26065     A = A.getOperand(0);
26066   if (NegB)
26067     B = B.getOperand(0);
26068   if (NegC)
26069     C = C.getOperand(0);
26070
26071   unsigned Opcode;
26072   if (!NegMul)
26073     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26074   else
26075     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26076
26077   return DAG.getNode(Opcode, dl, VT, A, B, C);
26078 }
26079
26080 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26081                                   TargetLowering::DAGCombinerInfo &DCI,
26082                                   const X86Subtarget *Subtarget) {
26083   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26084   //           (and (i32 x86isd::setcc_carry), 1)
26085   // This eliminates the zext. This transformation is necessary because
26086   // ISD::SETCC is always legalized to i8.
26087   SDLoc dl(N);
26088   SDValue N0 = N->getOperand(0);
26089   EVT VT = N->getValueType(0);
26090
26091   if (N0.getOpcode() == ISD::AND &&
26092       N0.hasOneUse() &&
26093       N0.getOperand(0).hasOneUse()) {
26094     SDValue N00 = N0.getOperand(0);
26095     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26096       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26097       if (!C || C->getZExtValue() != 1)
26098         return SDValue();
26099       return DAG.getNode(ISD::AND, dl, VT,
26100                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26101                                      N00.getOperand(0), N00.getOperand(1)),
26102                          DAG.getConstant(1, dl, VT));
26103     }
26104   }
26105
26106   if (N0.getOpcode() == ISD::TRUNCATE &&
26107       N0.hasOneUse() &&
26108       N0.getOperand(0).hasOneUse()) {
26109     SDValue N00 = N0.getOperand(0);
26110     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26111       return DAG.getNode(ISD::AND, dl, VT,
26112                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26113                                      N00.getOperand(0), N00.getOperand(1)),
26114                          DAG.getConstant(1, dl, VT));
26115     }
26116   }
26117
26118   if (VT.is256BitVector())
26119     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26120       return R;
26121
26122   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26123   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26124   // This exposes the zext to the udivrem lowering, so that it directly extends
26125   // from AH (which we otherwise need to do contortions to access).
26126   if (N0.getOpcode() == ISD::UDIVREM &&
26127       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26128       (VT == MVT::i32 || VT == MVT::i64)) {
26129     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26130     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26131                             N0.getOperand(0), N0.getOperand(1));
26132     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26133     return R.getValue(1);
26134   }
26135
26136   return SDValue();
26137 }
26138
26139 // Optimize x == -y --> x+y == 0
26140 //          x != -y --> x+y != 0
26141 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26142                                       const X86Subtarget* Subtarget) {
26143   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26144   SDValue LHS = N->getOperand(0);
26145   SDValue RHS = N->getOperand(1);
26146   EVT VT = N->getValueType(0);
26147   SDLoc DL(N);
26148
26149   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26150     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26151       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26152         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26153                                    LHS.getOperand(1));
26154         return DAG.getSetCC(DL, N->getValueType(0), addV,
26155                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26156       }
26157   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26158     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26159       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26160         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26161                                    RHS.getOperand(1));
26162         return DAG.getSetCC(DL, N->getValueType(0), addV,
26163                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26164       }
26165
26166   if (VT.getScalarType() == MVT::i1 &&
26167       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26168     bool IsSEXT0 =
26169         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26170         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26171     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26172
26173     if (!IsSEXT0 || !IsVZero1) {
26174       // Swap the operands and update the condition code.
26175       std::swap(LHS, RHS);
26176       CC = ISD::getSetCCSwappedOperands(CC);
26177
26178       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26179                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26180       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26181     }
26182
26183     if (IsSEXT0 && IsVZero1) {
26184       assert(VT == LHS.getOperand(0).getValueType() &&
26185              "Uexpected operand type");
26186       if (CC == ISD::SETGT)
26187         return DAG.getConstant(0, DL, VT);
26188       if (CC == ISD::SETLE)
26189         return DAG.getConstant(1, DL, VT);
26190       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26191         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26192
26193       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26194              "Unexpected condition code!");
26195       return LHS.getOperand(0);
26196     }
26197   }
26198
26199   return SDValue();
26200 }
26201
26202 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
26203                                          SelectionDAG &DAG) {
26204   SDLoc dl(Load);
26205   MVT VT = Load->getSimpleValueType(0);
26206   MVT EVT = VT.getVectorElementType();
26207   SDValue Addr = Load->getOperand(1);
26208   SDValue NewAddr = DAG.getNode(
26209       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
26210       DAG.getConstant(Index * EVT.getStoreSize(), dl,
26211                       Addr.getSimpleValueType()));
26212
26213   SDValue NewLoad =
26214       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
26215                   DAG.getMachineFunction().getMachineMemOperand(
26216                       Load->getMemOperand(), 0, EVT.getStoreSize()));
26217   return NewLoad;
26218 }
26219
26220 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
26221                                       const X86Subtarget *Subtarget) {
26222   SDLoc dl(N);
26223   MVT VT = N->getOperand(1)->getSimpleValueType(0);
26224   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
26225          "X86insertps is only defined for v4x32");
26226
26227   SDValue Ld = N->getOperand(1);
26228   if (MayFoldLoad(Ld)) {
26229     // Extract the countS bits from the immediate so we can get the proper
26230     // address when narrowing the vector load to a specific element.
26231     // When the second source op is a memory address, insertps doesn't use
26232     // countS and just gets an f32 from that address.
26233     unsigned DestIndex =
26234         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
26235
26236     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
26237
26238     // Create this as a scalar to vector to match the instruction pattern.
26239     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
26240     // countS bits are ignored when loading from memory on insertps, which
26241     // means we don't need to explicitly set them to 0.
26242     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
26243                        LoadScalarToVector, N->getOperand(2));
26244   }
26245   return SDValue();
26246 }
26247
26248 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26249   SDValue V0 = N->getOperand(0);
26250   SDValue V1 = N->getOperand(1);
26251   SDLoc DL(N);
26252   EVT VT = N->getValueType(0);
26253
26254   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26255   // operands and changing the mask to 1. This saves us a bunch of
26256   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26257   // x86InstrInfo knows how to commute this back after instruction selection
26258   // if it would help register allocation.
26259
26260   // TODO: If optimizing for size or a processor that doesn't suffer from
26261   // partial register update stalls, this should be transformed into a MOVSD
26262   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26263
26264   if (VT == MVT::v2f64)
26265     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26266       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26267         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26268         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26269       }
26270
26271   return SDValue();
26272 }
26273
26274 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26275 // as "sbb reg,reg", since it can be extended without zext and produces
26276 // an all-ones bit which is more useful than 0/1 in some cases.
26277 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26278                                MVT VT) {
26279   if (VT == MVT::i8)
26280     return DAG.getNode(ISD::AND, DL, VT,
26281                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26282                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26283                                    EFLAGS),
26284                        DAG.getConstant(1, DL, VT));
26285   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26286   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26287                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26288                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26289                                  EFLAGS));
26290 }
26291
26292 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26293 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26294                                    TargetLowering::DAGCombinerInfo &DCI,
26295                                    const X86Subtarget *Subtarget) {
26296   SDLoc DL(N);
26297   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26298   SDValue EFLAGS = N->getOperand(1);
26299
26300   if (CC == X86::COND_A) {
26301     // Try to convert COND_A into COND_B in an attempt to facilitate
26302     // materializing "setb reg".
26303     //
26304     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26305     // cannot take an immediate as its first operand.
26306     //
26307     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26308         EFLAGS.getValueType().isInteger() &&
26309         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26310       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26311                                    EFLAGS.getNode()->getVTList(),
26312                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26313       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26314       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26315     }
26316   }
26317
26318   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26319   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26320   // cases.
26321   if (CC == X86::COND_B)
26322     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26323
26324   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26325     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26326     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26327   }
26328
26329   return SDValue();
26330 }
26331
26332 // Optimize branch condition evaluation.
26333 //
26334 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26335                                     TargetLowering::DAGCombinerInfo &DCI,
26336                                     const X86Subtarget *Subtarget) {
26337   SDLoc DL(N);
26338   SDValue Chain = N->getOperand(0);
26339   SDValue Dest = N->getOperand(1);
26340   SDValue EFLAGS = N->getOperand(3);
26341   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26342
26343   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26344     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26345     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26346                        Flags);
26347   }
26348
26349   return SDValue();
26350 }
26351
26352 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26353                                                          SelectionDAG &DAG) {
26354   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26355   // optimize away operation when it's from a constant.
26356   //
26357   // The general transformation is:
26358   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26359   //       AND(VECTOR_CMP(x,y), constant2)
26360   //    constant2 = UNARYOP(constant)
26361
26362   // Early exit if this isn't a vector operation, the operand of the
26363   // unary operation isn't a bitwise AND, or if the sizes of the operations
26364   // aren't the same.
26365   EVT VT = N->getValueType(0);
26366   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26367       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26368       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26369     return SDValue();
26370
26371   // Now check that the other operand of the AND is a constant. We could
26372   // make the transformation for non-constant splats as well, but it's unclear
26373   // that would be a benefit as it would not eliminate any operations, just
26374   // perform one more step in scalar code before moving to the vector unit.
26375   if (BuildVectorSDNode *BV =
26376           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26377     // Bail out if the vector isn't a constant.
26378     if (!BV->isConstant())
26379       return SDValue();
26380
26381     // Everything checks out. Build up the new and improved node.
26382     SDLoc DL(N);
26383     EVT IntVT = BV->getValueType(0);
26384     // Create a new constant of the appropriate type for the transformed
26385     // DAG.
26386     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26387     // The AND node needs bitcasts to/from an integer vector type around it.
26388     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26389     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26390                                  N->getOperand(0)->getOperand(0), MaskConst);
26391     SDValue Res = DAG.getBitcast(VT, NewAnd);
26392     return Res;
26393   }
26394
26395   return SDValue();
26396 }
26397
26398 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26399                                         const X86Subtarget *Subtarget) {
26400   SDValue Op0 = N->getOperand(0);
26401   EVT VT = N->getValueType(0);
26402   EVT InVT = Op0.getValueType();
26403   EVT InSVT = InVT.getScalarType();
26404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26405
26406   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26407   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26408   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26409     SDLoc dl(N);
26410     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26411                                  InVT.getVectorNumElements());
26412     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26413
26414     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26415       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26416
26417     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26418   }
26419
26420   return SDValue();
26421 }
26422
26423 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26424                                         const X86Subtarget *Subtarget) {
26425   // First try to optimize away the conversion entirely when it's
26426   // conditionally from a constant. Vectors only.
26427   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26428     return Res;
26429
26430   // Now move on to more general possibilities.
26431   SDValue Op0 = N->getOperand(0);
26432   EVT VT = N->getValueType(0);
26433   EVT InVT = Op0.getValueType();
26434   EVT InSVT = InVT.getScalarType();
26435
26436   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26437   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26438   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26439     SDLoc dl(N);
26440     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26441                                  InVT.getVectorNumElements());
26442     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26443     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26444   }
26445
26446   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26447   // a 32-bit target where SSE doesn't support i64->FP operations.
26448   if (Op0.getOpcode() == ISD::LOAD) {
26449     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26450     EVT LdVT = Ld->getValueType(0);
26451
26452     // This transformation is not supported if the result type is f16
26453     if (VT == MVT::f16)
26454       return SDValue();
26455
26456     if (!Ld->isVolatile() && !VT.isVector() &&
26457         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26458         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26459       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26460           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26461       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26462       return FILDChain;
26463     }
26464   }
26465   return SDValue();
26466 }
26467
26468 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26469 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26470                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26471   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26472   // the result is either zero or one (depending on the input carry bit).
26473   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26474   if (X86::isZeroNode(N->getOperand(0)) &&
26475       X86::isZeroNode(N->getOperand(1)) &&
26476       // We don't have a good way to replace an EFLAGS use, so only do this when
26477       // dead right now.
26478       SDValue(N, 1).use_empty()) {
26479     SDLoc DL(N);
26480     EVT VT = N->getValueType(0);
26481     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26482     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26483                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26484                                            DAG.getConstant(X86::COND_B, DL,
26485                                                            MVT::i8),
26486                                            N->getOperand(2)),
26487                                DAG.getConstant(1, DL, VT));
26488     return DCI.CombineTo(N, Res1, CarryOut);
26489   }
26490
26491   return SDValue();
26492 }
26493
26494 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26495 //      (add Y, (setne X, 0)) -> sbb -1, Y
26496 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26497 //      (sub (setne X, 0), Y) -> adc -1, Y
26498 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26499   SDLoc DL(N);
26500
26501   // Look through ZExts.
26502   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26503   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26504     return SDValue();
26505
26506   SDValue SetCC = Ext.getOperand(0);
26507   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26508     return SDValue();
26509
26510   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26511   if (CC != X86::COND_E && CC != X86::COND_NE)
26512     return SDValue();
26513
26514   SDValue Cmp = SetCC.getOperand(1);
26515   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26516       !X86::isZeroNode(Cmp.getOperand(1)) ||
26517       !Cmp.getOperand(0).getValueType().isInteger())
26518     return SDValue();
26519
26520   SDValue CmpOp0 = Cmp.getOperand(0);
26521   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26522                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26523
26524   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26525   if (CC == X86::COND_NE)
26526     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26527                        DL, OtherVal.getValueType(), OtherVal,
26528                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26529                        NewCmp);
26530   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26531                      DL, OtherVal.getValueType(), OtherVal,
26532                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26533 }
26534
26535 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26536 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26537                                  const X86Subtarget *Subtarget) {
26538   EVT VT = N->getValueType(0);
26539   SDValue Op0 = N->getOperand(0);
26540   SDValue Op1 = N->getOperand(1);
26541
26542   // Try to synthesize horizontal adds from adds of shuffles.
26543   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26544        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26545       isHorizontalBinOp(Op0, Op1, true))
26546     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26547
26548   return OptimizeConditionalInDecrement(N, DAG);
26549 }
26550
26551 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26552                                  const X86Subtarget *Subtarget) {
26553   SDValue Op0 = N->getOperand(0);
26554   SDValue Op1 = N->getOperand(1);
26555
26556   // X86 can't encode an immediate LHS of a sub. See if we can push the
26557   // negation into a preceding instruction.
26558   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26559     // If the RHS of the sub is a XOR with one use and a constant, invert the
26560     // immediate. Then add one to the LHS of the sub so we can turn
26561     // X-Y -> X+~Y+1, saving one register.
26562     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26563         isa<ConstantSDNode>(Op1.getOperand(1))) {
26564       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26565       EVT VT = Op0.getValueType();
26566       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26567                                    Op1.getOperand(0),
26568                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26569       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26570                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26571     }
26572   }
26573
26574   // Try to synthesize horizontal adds from adds of shuffles.
26575   EVT VT = N->getValueType(0);
26576   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26577        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26578       isHorizontalBinOp(Op0, Op1, true))
26579     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26580
26581   return OptimizeConditionalInDecrement(N, DAG);
26582 }
26583
26584 /// performVZEXTCombine - Performs build vector combines
26585 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26586                                    TargetLowering::DAGCombinerInfo &DCI,
26587                                    const X86Subtarget *Subtarget) {
26588   SDLoc DL(N);
26589   MVT VT = N->getSimpleValueType(0);
26590   SDValue Op = N->getOperand(0);
26591   MVT OpVT = Op.getSimpleValueType();
26592   MVT OpEltVT = OpVT.getVectorElementType();
26593   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26594
26595   // (vzext (bitcast (vzext (x)) -> (vzext x)
26596   SDValue V = Op;
26597   while (V.getOpcode() == ISD::BITCAST)
26598     V = V.getOperand(0);
26599
26600   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26601     MVT InnerVT = V.getSimpleValueType();
26602     MVT InnerEltVT = InnerVT.getVectorElementType();
26603
26604     // If the element sizes match exactly, we can just do one larger vzext. This
26605     // is always an exact type match as vzext operates on integer types.
26606     if (OpEltVT == InnerEltVT) {
26607       assert(OpVT == InnerVT && "Types must match for vzext!");
26608       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26609     }
26610
26611     // The only other way we can combine them is if only a single element of the
26612     // inner vzext is used in the input to the outer vzext.
26613     if (InnerEltVT.getSizeInBits() < InputBits)
26614       return SDValue();
26615
26616     // In this case, the inner vzext is completely dead because we're going to
26617     // only look at bits inside of the low element. Just do the outer vzext on
26618     // a bitcast of the input to the inner.
26619     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26620   }
26621
26622   // Check if we can bypass extracting and re-inserting an element of an input
26623   // vector. Essentially:
26624   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26625   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26626       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26627       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26628     SDValue ExtractedV = V.getOperand(0);
26629     SDValue OrigV = ExtractedV.getOperand(0);
26630     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26631       if (ExtractIdx->getZExtValue() == 0) {
26632         MVT OrigVT = OrigV.getSimpleValueType();
26633         // Extract a subvector if necessary...
26634         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26635           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26636           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26637                                     OrigVT.getVectorNumElements() / Ratio);
26638           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26639                               DAG.getIntPtrConstant(0, DL));
26640         }
26641         Op = DAG.getBitcast(OpVT, OrigV);
26642         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26643       }
26644   }
26645
26646   return SDValue();
26647 }
26648
26649 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26650                                              DAGCombinerInfo &DCI) const {
26651   SelectionDAG &DAG = DCI.DAG;
26652   switch (N->getOpcode()) {
26653   default: break;
26654   case ISD::EXTRACT_VECTOR_ELT:
26655     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26656   case ISD::VSELECT:
26657   case ISD::SELECT:
26658   case X86ISD::SHRUNKBLEND:
26659     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26660   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
26661   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26662   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26663   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26664   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26665   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26666   case ISD::SHL:
26667   case ISD::SRA:
26668   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26669   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26670   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26671   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26672   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26673   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26674   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26675   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26676   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26677   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26678   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26679   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26680   case X86ISD::FXOR:
26681   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26682   case X86ISD::FMIN:
26683   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26684   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26685   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26686   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26687   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26688   case ISD::ANY_EXTEND:
26689   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26690   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26691   case ISD::SIGN_EXTEND_INREG:
26692     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26693   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26694   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26695   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26696   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26697   case X86ISD::SHUFP:       // Handle all target specific shuffles
26698   case X86ISD::PALIGNR:
26699   case X86ISD::UNPCKH:
26700   case X86ISD::UNPCKL:
26701   case X86ISD::MOVHLPS:
26702   case X86ISD::MOVLHPS:
26703   case X86ISD::PSHUFB:
26704   case X86ISD::PSHUFD:
26705   case X86ISD::PSHUFHW:
26706   case X86ISD::PSHUFLW:
26707   case X86ISD::MOVSS:
26708   case X86ISD::MOVSD:
26709   case X86ISD::VPERMILPI:
26710   case X86ISD::VPERM2X128:
26711   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26712   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26713   case X86ISD::INSERTPS: {
26714     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26715       return PerformINSERTPSCombine(N, DAG, Subtarget);
26716     break;
26717   }
26718   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26719   }
26720
26721   return SDValue();
26722 }
26723
26724 /// isTypeDesirableForOp - Return true if the target has native support for
26725 /// the specified value type and it is 'desirable' to use the type for the
26726 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26727 /// instruction encodings are longer and some i16 instructions are slow.
26728 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26729   if (!isTypeLegal(VT))
26730     return false;
26731   if (VT != MVT::i16)
26732     return true;
26733
26734   switch (Opc) {
26735   default:
26736     return true;
26737   case ISD::LOAD:
26738   case ISD::SIGN_EXTEND:
26739   case ISD::ZERO_EXTEND:
26740   case ISD::ANY_EXTEND:
26741   case ISD::SHL:
26742   case ISD::SRL:
26743   case ISD::SUB:
26744   case ISD::ADD:
26745   case ISD::MUL:
26746   case ISD::AND:
26747   case ISD::OR:
26748   case ISD::XOR:
26749     return false;
26750   }
26751 }
26752
26753 /// IsDesirableToPromoteOp - This method query the target whether it is
26754 /// beneficial for dag combiner to promote the specified node. If true, it
26755 /// should return the desired promotion type by reference.
26756 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26757   EVT VT = Op.getValueType();
26758   if (VT != MVT::i16)
26759     return false;
26760
26761   bool Promote = false;
26762   bool Commute = false;
26763   switch (Op.getOpcode()) {
26764   default: break;
26765   case ISD::LOAD: {
26766     LoadSDNode *LD = cast<LoadSDNode>(Op);
26767     // If the non-extending load has a single use and it's not live out, then it
26768     // might be folded.
26769     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26770                                                      Op.hasOneUse()*/) {
26771       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26772              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26773         // The only case where we'd want to promote LOAD (rather then it being
26774         // promoted as an operand is when it's only use is liveout.
26775         if (UI->getOpcode() != ISD::CopyToReg)
26776           return false;
26777       }
26778     }
26779     Promote = true;
26780     break;
26781   }
26782   case ISD::SIGN_EXTEND:
26783   case ISD::ZERO_EXTEND:
26784   case ISD::ANY_EXTEND:
26785     Promote = true;
26786     break;
26787   case ISD::SHL:
26788   case ISD::SRL: {
26789     SDValue N0 = Op.getOperand(0);
26790     // Look out for (store (shl (load), x)).
26791     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26792       return false;
26793     Promote = true;
26794     break;
26795   }
26796   case ISD::ADD:
26797   case ISD::MUL:
26798   case ISD::AND:
26799   case ISD::OR:
26800   case ISD::XOR:
26801     Commute = true;
26802     // fallthrough
26803   case ISD::SUB: {
26804     SDValue N0 = Op.getOperand(0);
26805     SDValue N1 = Op.getOperand(1);
26806     if (!Commute && MayFoldLoad(N1))
26807       return false;
26808     // Avoid disabling potential load folding opportunities.
26809     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26810       return false;
26811     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26812       return false;
26813     Promote = true;
26814   }
26815   }
26816
26817   PVT = MVT::i32;
26818   return Promote;
26819 }
26820
26821 //===----------------------------------------------------------------------===//
26822 //                           X86 Inline Assembly Support
26823 //===----------------------------------------------------------------------===//
26824
26825 // Helper to match a string separated by whitespace.
26826 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26827   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26828
26829   for (StringRef Piece : Pieces) {
26830     if (!S.startswith(Piece)) // Check if the piece matches.
26831       return false;
26832
26833     S = S.substr(Piece.size());
26834     StringRef::size_type Pos = S.find_first_not_of(" \t");
26835     if (Pos == 0) // We matched a prefix.
26836       return false;
26837
26838     S = S.substr(Pos);
26839   }
26840
26841   return S.empty();
26842 }
26843
26844 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26845
26846   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26847     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26848         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26849         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26850
26851       if (AsmPieces.size() == 3)
26852         return true;
26853       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26854         return true;
26855     }
26856   }
26857   return false;
26858 }
26859
26860 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26861   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26862
26863   std::string AsmStr = IA->getAsmString();
26864
26865   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26866   if (!Ty || Ty->getBitWidth() % 16 != 0)
26867     return false;
26868
26869   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26870   SmallVector<StringRef, 4> AsmPieces;
26871   SplitString(AsmStr, AsmPieces, ";\n");
26872
26873   switch (AsmPieces.size()) {
26874   default: return false;
26875   case 1:
26876     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26877     // we will turn this bswap into something that will be lowered to logical
26878     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26879     // lower so don't worry about this.
26880     // bswap $0
26881     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26882         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26883         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26884         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26885         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26886         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26887       // No need to check constraints, nothing other than the equivalent of
26888       // "=r,0" would be valid here.
26889       return IntrinsicLowering::LowerToByteSwap(CI);
26890     }
26891
26892     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26893     if (CI->getType()->isIntegerTy(16) &&
26894         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26895         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26896          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26897       AsmPieces.clear();
26898       StringRef ConstraintsStr = IA->getConstraintString();
26899       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26900       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26901       if (clobbersFlagRegisters(AsmPieces))
26902         return IntrinsicLowering::LowerToByteSwap(CI);
26903     }
26904     break;
26905   case 3:
26906     if (CI->getType()->isIntegerTy(32) &&
26907         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26908         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26909         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26910         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26911       AsmPieces.clear();
26912       StringRef ConstraintsStr = IA->getConstraintString();
26913       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26914       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26915       if (clobbersFlagRegisters(AsmPieces))
26916         return IntrinsicLowering::LowerToByteSwap(CI);
26917     }
26918
26919     if (CI->getType()->isIntegerTy(64)) {
26920       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26921       if (Constraints.size() >= 2 &&
26922           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26923           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26924         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26925         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26926             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26927             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26928           return IntrinsicLowering::LowerToByteSwap(CI);
26929       }
26930     }
26931     break;
26932   }
26933   return false;
26934 }
26935
26936 /// getConstraintType - Given a constraint letter, return the type of
26937 /// constraint it is for this target.
26938 X86TargetLowering::ConstraintType
26939 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26940   if (Constraint.size() == 1) {
26941     switch (Constraint[0]) {
26942     case 'R':
26943     case 'q':
26944     case 'Q':
26945     case 'f':
26946     case 't':
26947     case 'u':
26948     case 'y':
26949     case 'x':
26950     case 'Y':
26951     case 'l':
26952       return C_RegisterClass;
26953     case 'a':
26954     case 'b':
26955     case 'c':
26956     case 'd':
26957     case 'S':
26958     case 'D':
26959     case 'A':
26960       return C_Register;
26961     case 'I':
26962     case 'J':
26963     case 'K':
26964     case 'L':
26965     case 'M':
26966     case 'N':
26967     case 'G':
26968     case 'C':
26969     case 'e':
26970     case 'Z':
26971       return C_Other;
26972     default:
26973       break;
26974     }
26975   }
26976   return TargetLowering::getConstraintType(Constraint);
26977 }
26978
26979 /// Examine constraint type and operand type and determine a weight value.
26980 /// This object must already have been set up with the operand type
26981 /// and the current alternative constraint selected.
26982 TargetLowering::ConstraintWeight
26983   X86TargetLowering::getSingleConstraintMatchWeight(
26984     AsmOperandInfo &info, const char *constraint) const {
26985   ConstraintWeight weight = CW_Invalid;
26986   Value *CallOperandVal = info.CallOperandVal;
26987     // If we don't have a value, we can't do a match,
26988     // but allow it at the lowest weight.
26989   if (!CallOperandVal)
26990     return CW_Default;
26991   Type *type = CallOperandVal->getType();
26992   // Look at the constraint type.
26993   switch (*constraint) {
26994   default:
26995     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26996   case 'R':
26997   case 'q':
26998   case 'Q':
26999   case 'a':
27000   case 'b':
27001   case 'c':
27002   case 'd':
27003   case 'S':
27004   case 'D':
27005   case 'A':
27006     if (CallOperandVal->getType()->isIntegerTy())
27007       weight = CW_SpecificReg;
27008     break;
27009   case 'f':
27010   case 't':
27011   case 'u':
27012     if (type->isFloatingPointTy())
27013       weight = CW_SpecificReg;
27014     break;
27015   case 'y':
27016     if (type->isX86_MMXTy() && Subtarget->hasMMX())
27017       weight = CW_SpecificReg;
27018     break;
27019   case 'x':
27020   case 'Y':
27021     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27022         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27023       weight = CW_Register;
27024     break;
27025   case 'I':
27026     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27027       if (C->getZExtValue() <= 31)
27028         weight = CW_Constant;
27029     }
27030     break;
27031   case 'J':
27032     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27033       if (C->getZExtValue() <= 63)
27034         weight = CW_Constant;
27035     }
27036     break;
27037   case 'K':
27038     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27039       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27040         weight = CW_Constant;
27041     }
27042     break;
27043   case 'L':
27044     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27045       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27046         weight = CW_Constant;
27047     }
27048     break;
27049   case 'M':
27050     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27051       if (C->getZExtValue() <= 3)
27052         weight = CW_Constant;
27053     }
27054     break;
27055   case 'N':
27056     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27057       if (C->getZExtValue() <= 0xff)
27058         weight = CW_Constant;
27059     }
27060     break;
27061   case 'G':
27062   case 'C':
27063     if (isa<ConstantFP>(CallOperandVal)) {
27064       weight = CW_Constant;
27065     }
27066     break;
27067   case 'e':
27068     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27069       if ((C->getSExtValue() >= -0x80000000LL) &&
27070           (C->getSExtValue() <= 0x7fffffffLL))
27071         weight = CW_Constant;
27072     }
27073     break;
27074   case 'Z':
27075     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27076       if (C->getZExtValue() <= 0xffffffff)
27077         weight = CW_Constant;
27078     }
27079     break;
27080   }
27081   return weight;
27082 }
27083
27084 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27085 /// with another that has more specific requirements based on the type of the
27086 /// corresponding operand.
27087 const char *X86TargetLowering::
27088 LowerXConstraint(EVT ConstraintVT) const {
27089   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27090   // 'f' like normal targets.
27091   if (ConstraintVT.isFloatingPoint()) {
27092     if (Subtarget->hasSSE2())
27093       return "Y";
27094     if (Subtarget->hasSSE1())
27095       return "x";
27096   }
27097
27098   return TargetLowering::LowerXConstraint(ConstraintVT);
27099 }
27100
27101 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27102 /// vector.  If it is invalid, don't add anything to Ops.
27103 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27104                                                      std::string &Constraint,
27105                                                      std::vector<SDValue>&Ops,
27106                                                      SelectionDAG &DAG) const {
27107   SDValue Result;
27108
27109   // Only support length 1 constraints for now.
27110   if (Constraint.length() > 1) return;
27111
27112   char ConstraintLetter = Constraint[0];
27113   switch (ConstraintLetter) {
27114   default: break;
27115   case 'I':
27116     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27117       if (C->getZExtValue() <= 31) {
27118         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27119                                        Op.getValueType());
27120         break;
27121       }
27122     }
27123     return;
27124   case 'J':
27125     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27126       if (C->getZExtValue() <= 63) {
27127         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27128                                        Op.getValueType());
27129         break;
27130       }
27131     }
27132     return;
27133   case 'K':
27134     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27135       if (isInt<8>(C->getSExtValue())) {
27136         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27137                                        Op.getValueType());
27138         break;
27139       }
27140     }
27141     return;
27142   case 'L':
27143     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27144       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27145           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27146         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27147                                        Op.getValueType());
27148         break;
27149       }
27150     }
27151     return;
27152   case 'M':
27153     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27154       if (C->getZExtValue() <= 3) {
27155         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27156                                        Op.getValueType());
27157         break;
27158       }
27159     }
27160     return;
27161   case 'N':
27162     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27163       if (C->getZExtValue() <= 255) {
27164         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27165                                        Op.getValueType());
27166         break;
27167       }
27168     }
27169     return;
27170   case 'O':
27171     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27172       if (C->getZExtValue() <= 127) {
27173         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27174                                        Op.getValueType());
27175         break;
27176       }
27177     }
27178     return;
27179   case 'e': {
27180     // 32-bit signed value
27181     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27182       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27183                                            C->getSExtValue())) {
27184         // Widen to 64 bits here to get it sign extended.
27185         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27186         break;
27187       }
27188     // FIXME gcc accepts some relocatable values here too, but only in certain
27189     // memory models; it's complicated.
27190     }
27191     return;
27192   }
27193   case 'Z': {
27194     // 32-bit unsigned value
27195     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27196       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27197                                            C->getZExtValue())) {
27198         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27199                                        Op.getValueType());
27200         break;
27201       }
27202     }
27203     // FIXME gcc accepts some relocatable values here too, but only in certain
27204     // memory models; it's complicated.
27205     return;
27206   }
27207   case 'i': {
27208     // Literal immediates are always ok.
27209     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27210       // Widen to 64 bits here to get it sign extended.
27211       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27212       break;
27213     }
27214
27215     // In any sort of PIC mode addresses need to be computed at runtime by
27216     // adding in a register or some sort of table lookup.  These can't
27217     // be used as immediates.
27218     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27219       return;
27220
27221     // If we are in non-pic codegen mode, we allow the address of a global (with
27222     // an optional displacement) to be used with 'i'.
27223     GlobalAddressSDNode *GA = nullptr;
27224     int64_t Offset = 0;
27225
27226     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27227     while (1) {
27228       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27229         Offset += GA->getOffset();
27230         break;
27231       } else if (Op.getOpcode() == ISD::ADD) {
27232         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27233           Offset += C->getZExtValue();
27234           Op = Op.getOperand(0);
27235           continue;
27236         }
27237       } else if (Op.getOpcode() == ISD::SUB) {
27238         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27239           Offset += -C->getZExtValue();
27240           Op = Op.getOperand(0);
27241           continue;
27242         }
27243       }
27244
27245       // Otherwise, this isn't something we can handle, reject it.
27246       return;
27247     }
27248
27249     const GlobalValue *GV = GA->getGlobal();
27250     // If we require an extra load to get this address, as in PIC mode, we
27251     // can't accept it.
27252     if (isGlobalStubReference(
27253             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27254       return;
27255
27256     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27257                                         GA->getValueType(0), Offset);
27258     break;
27259   }
27260   }
27261
27262   if (Result.getNode()) {
27263     Ops.push_back(Result);
27264     return;
27265   }
27266   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27267 }
27268
27269 std::pair<unsigned, const TargetRegisterClass *>
27270 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27271                                                 StringRef Constraint,
27272                                                 MVT VT) const {
27273   // First, see if this is a constraint that directly corresponds to an LLVM
27274   // register class.
27275   if (Constraint.size() == 1) {
27276     // GCC Constraint Letters
27277     switch (Constraint[0]) {
27278     default: break;
27279       // TODO: Slight differences here in allocation order and leaving
27280       // RIP in the class. Do they matter any more here than they do
27281       // in the normal allocation?
27282     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27283       if (Subtarget->is64Bit()) {
27284         if (VT == MVT::i32 || VT == MVT::f32)
27285           return std::make_pair(0U, &X86::GR32RegClass);
27286         if (VT == MVT::i16)
27287           return std::make_pair(0U, &X86::GR16RegClass);
27288         if (VT == MVT::i8 || VT == MVT::i1)
27289           return std::make_pair(0U, &X86::GR8RegClass);
27290         if (VT == MVT::i64 || VT == MVT::f64)
27291           return std::make_pair(0U, &X86::GR64RegClass);
27292         break;
27293       }
27294       // 32-bit fallthrough
27295     case 'Q':   // Q_REGS
27296       if (VT == MVT::i32 || VT == MVT::f32)
27297         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27298       if (VT == MVT::i16)
27299         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27300       if (VT == MVT::i8 || VT == MVT::i1)
27301         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27302       if (VT == MVT::i64)
27303         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27304       break;
27305     case 'r':   // GENERAL_REGS
27306     case 'l':   // INDEX_REGS
27307       if (VT == MVT::i8 || VT == MVT::i1)
27308         return std::make_pair(0U, &X86::GR8RegClass);
27309       if (VT == MVT::i16)
27310         return std::make_pair(0U, &X86::GR16RegClass);
27311       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27312         return std::make_pair(0U, &X86::GR32RegClass);
27313       return std::make_pair(0U, &X86::GR64RegClass);
27314     case 'R':   // LEGACY_REGS
27315       if (VT == MVT::i8 || VT == MVT::i1)
27316         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27317       if (VT == MVT::i16)
27318         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27319       if (VT == MVT::i32 || !Subtarget->is64Bit())
27320         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27321       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27322     case 'f':  // FP Stack registers.
27323       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27324       // value to the correct fpstack register class.
27325       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27326         return std::make_pair(0U, &X86::RFP32RegClass);
27327       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27328         return std::make_pair(0U, &X86::RFP64RegClass);
27329       return std::make_pair(0U, &X86::RFP80RegClass);
27330     case 'y':   // MMX_REGS if MMX allowed.
27331       if (!Subtarget->hasMMX()) break;
27332       return std::make_pair(0U, &X86::VR64RegClass);
27333     case 'Y':   // SSE_REGS if SSE2 allowed
27334       if (!Subtarget->hasSSE2()) break;
27335       // FALL THROUGH.
27336     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27337       if (!Subtarget->hasSSE1()) break;
27338
27339       switch (VT.SimpleTy) {
27340       default: break;
27341       // Scalar SSE types.
27342       case MVT::f32:
27343       case MVT::i32:
27344         return std::make_pair(0U, &X86::FR32RegClass);
27345       case MVT::f64:
27346       case MVT::i64:
27347         return std::make_pair(0U, &X86::FR64RegClass);
27348       // Vector types.
27349       case MVT::v16i8:
27350       case MVT::v8i16:
27351       case MVT::v4i32:
27352       case MVT::v2i64:
27353       case MVT::v4f32:
27354       case MVT::v2f64:
27355         return std::make_pair(0U, &X86::VR128RegClass);
27356       // AVX types.
27357       case MVT::v32i8:
27358       case MVT::v16i16:
27359       case MVT::v8i32:
27360       case MVT::v4i64:
27361       case MVT::v8f32:
27362       case MVT::v4f64:
27363         return std::make_pair(0U, &X86::VR256RegClass);
27364       case MVT::v8f64:
27365       case MVT::v16f32:
27366       case MVT::v16i32:
27367       case MVT::v8i64:
27368         return std::make_pair(0U, &X86::VR512RegClass);
27369       }
27370       break;
27371     }
27372   }
27373
27374   // Use the default implementation in TargetLowering to convert the register
27375   // constraint into a member of a register class.
27376   std::pair<unsigned, const TargetRegisterClass*> Res;
27377   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27378
27379   // Not found as a standard register?
27380   if (!Res.second) {
27381     // Map st(0) -> st(7) -> ST0
27382     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27383         tolower(Constraint[1]) == 's' &&
27384         tolower(Constraint[2]) == 't' &&
27385         Constraint[3] == '(' &&
27386         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27387         Constraint[5] == ')' &&
27388         Constraint[6] == '}') {
27389
27390       Res.first = X86::FP0+Constraint[4]-'0';
27391       Res.second = &X86::RFP80RegClass;
27392       return Res;
27393     }
27394
27395     // GCC allows "st(0)" to be called just plain "st".
27396     if (StringRef("{st}").equals_lower(Constraint)) {
27397       Res.first = X86::FP0;
27398       Res.second = &X86::RFP80RegClass;
27399       return Res;
27400     }
27401
27402     // flags -> EFLAGS
27403     if (StringRef("{flags}").equals_lower(Constraint)) {
27404       Res.first = X86::EFLAGS;
27405       Res.second = &X86::CCRRegClass;
27406       return Res;
27407     }
27408
27409     // 'A' means EAX + EDX.
27410     if (Constraint == "A") {
27411       Res.first = X86::EAX;
27412       Res.second = &X86::GR32_ADRegClass;
27413       return Res;
27414     }
27415     return Res;
27416   }
27417
27418   // Otherwise, check to see if this is a register class of the wrong value
27419   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27420   // turn into {ax},{dx}.
27421   // MVT::Other is used to specify clobber names.
27422   if (Res.second->hasType(VT) || VT == MVT::Other)
27423     return Res;   // Correct type already, nothing to do.
27424
27425   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27426   // return "eax". This should even work for things like getting 64bit integer
27427   // registers when given an f64 type.
27428   const TargetRegisterClass *Class = Res.second;
27429   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27430       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27431     unsigned Size = VT.getSizeInBits();
27432     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27433                                   : Size == 16 ? MVT::i16
27434                                   : Size == 32 ? MVT::i32
27435                                   : Size == 64 ? MVT::i64
27436                                   : MVT::Other;
27437     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27438     if (DestReg > 0) {
27439       Res.first = DestReg;
27440       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27441                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27442                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27443                  : &X86::GR64RegClass;
27444       assert(Res.second->contains(Res.first) && "Register in register class");
27445     } else {
27446       // No register found/type mismatch.
27447       Res.first = 0;
27448       Res.second = nullptr;
27449     }
27450   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27451              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27452              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27453              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27454              Class == &X86::VR512RegClass) {
27455     // Handle references to XMM physical registers that got mapped into the
27456     // wrong class.  This can happen with constraints like {xmm0} where the
27457     // target independent register mapper will just pick the first match it can
27458     // find, ignoring the required type.
27459
27460     if (VT == MVT::f32 || VT == MVT::i32)
27461       Res.second = &X86::FR32RegClass;
27462     else if (VT == MVT::f64 || VT == MVT::i64)
27463       Res.second = &X86::FR64RegClass;
27464     else if (X86::VR128RegClass.hasType(VT))
27465       Res.second = &X86::VR128RegClass;
27466     else if (X86::VR256RegClass.hasType(VT))
27467       Res.second = &X86::VR256RegClass;
27468     else if (X86::VR512RegClass.hasType(VT))
27469       Res.second = &X86::VR512RegClass;
27470     else {
27471       // Type mismatch and not a clobber: Return an error;
27472       Res.first = 0;
27473       Res.second = nullptr;
27474     }
27475   }
27476
27477   return Res;
27478 }
27479
27480 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27481                                             const AddrMode &AM, Type *Ty,
27482                                             unsigned AS) const {
27483   // Scaling factors are not free at all.
27484   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27485   // will take 2 allocations in the out of order engine instead of 1
27486   // for plain addressing mode, i.e. inst (reg1).
27487   // E.g.,
27488   // vaddps (%rsi,%drx), %ymm0, %ymm1
27489   // Requires two allocations (one for the load, one for the computation)
27490   // whereas:
27491   // vaddps (%rsi), %ymm0, %ymm1
27492   // Requires just 1 allocation, i.e., freeing allocations for other operations
27493   // and having less micro operations to execute.
27494   //
27495   // For some X86 architectures, this is even worse because for instance for
27496   // stores, the complex addressing mode forces the instruction to use the
27497   // "load" ports instead of the dedicated "store" port.
27498   // E.g., on Haswell:
27499   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27500   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27501   if (isLegalAddressingMode(DL, AM, Ty, AS))
27502     // Scale represents reg2 * scale, thus account for 1
27503     // as soon as we use a second register.
27504     return AM.Scale != 0;
27505   return -1;
27506 }
27507
27508 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27509   // Integer division on x86 is expensive. However, when aggressively optimizing
27510   // for code size, we prefer to use a div instruction, as it is usually smaller
27511   // than the alternative sequence.
27512   // The exception to this is vector division. Since x86 doesn't have vector
27513   // integer division, leaving the division as-is is a loss even in terms of
27514   // size, because it will have to be scalarized, while the alternative code
27515   // sequence can be performed in vector form.
27516   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27517                                    Attribute::MinSize);
27518   return OptSize && !VT.isVector();
27519 }
27520
27521 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27522        TargetLowering::ArgListTy& Args) const {
27523   // The MCU psABI requires some arguments to be passed in-register.
27524   // For regular calls, the inreg arguments are marked by the front-end.
27525   // However, for compiler generated library calls, we have to patch this
27526   // up here.
27527   if (!Subtarget->isTargetMCU() || !Args.size())
27528     return;
27529
27530   unsigned FreeRegs = 3;
27531   for (auto &Arg : Args) {
27532     // For library functions, we do not expect any fancy types.
27533     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27534     unsigned SizeInRegs = (Size + 31) / 32;
27535     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27536       continue;
27537
27538     Arg.isInReg = true;
27539     FreeRegs -= SizeInRegs;
27540     if (!FreeRegs)
27541       break;
27542   }
27543 }