[X86] Combine (cmov (and/or (setcc) (setcc))) into (cmov (cmov)).
[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/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<int> ReciprocalEstimateRefinementSteps(
70     "x86-recip-refinement-steps", cl::init(1),
71     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72              "result of the hardware reciprocal estimate instruction."),
73     cl::NotHidden);
74
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
77                        SDValue V2);
78
79 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
80                                 SelectionDAG &DAG, SDLoc dl,
81                                 unsigned vectorWidth) {
82   assert((vectorWidth == 128 || vectorWidth == 256) &&
83          "Unsupported vector width");
84   EVT VT = Vec.getValueType();
85   EVT ElVT = VT.getVectorElementType();
86   unsigned Factor = VT.getSizeInBits()/vectorWidth;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getUNDEF(ResultVT);
93
94   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
95   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
96
97   // This is the index of the first element of the vectorWidth-bit chunk
98   // we want.
99   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
100                                * ElemsPerChunk);
101
102   // If the input is a buildvector just emit a smaller one.
103   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
104     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
105                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
106                                     ElemsPerChunk));
107
108   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
109   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
110 }
111
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
154 }
155
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
163                                   SelectionDAG &DAG,SDLoc dl) {
164   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
165   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
166 }
167
168 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
169                                   SelectionDAG &DAG, SDLoc dl) {
170   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
171   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
172 }
173
174 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
175 /// instructions. This is used because creating CONCAT_VECTOR nodes of
176 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
177 /// large BUILD_VECTORS.
178 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
179                                    unsigned NumElems, SelectionDAG &DAG,
180                                    SDLoc dl) {
181   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
182   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
183 }
184
185 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
186                                    unsigned NumElems, SelectionDAG &DAG,
187                                    SDLoc dl) {
188   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
189   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
190 }
191
192 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
193                                      const X86Subtarget &STI)
194     : TargetLowering(TM), Subtarget(&STI) {
195   X86ScalarSSEf64 = Subtarget->hasSSE2();
196   X86ScalarSSEf32 = Subtarget->hasSSE1();
197   TD = getDataLayout();
198
199   // Set up the TargetLowering object.
200   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
201
202   // X86 is weird. It always uses i8 for shift amounts and setcc results.
203   setBooleanContents(ZeroOrOneBooleanContent);
204   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
205   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
206
207   // For 64-bit, since we have so many registers, use the ILP scheduler.
208   // For 32-bit, use the register pressure specific scheduling.
209   // For Atom, always use ILP scheduling.
210   if (Subtarget->isAtom())
211     setSchedulingPreference(Sched::ILP);
212   else if (Subtarget->is64Bit())
213     setSchedulingPreference(Sched::ILP);
214   else
215     setSchedulingPreference(Sched::RegPressure);
216   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
217   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
218
219   // Bypass expensive divides on Atom when compiling with O2.
220   if (TM.getOptLevel() >= CodeGenOpt::Default) {
221     if (Subtarget->hasSlowDivide32())
222       addBypassSlowDiv(32, 8);
223     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
224       addBypassSlowDiv(64, 16);
225   }
226
227   if (Subtarget->isTargetKnownWindowsMSVC()) {
228     // Setup Windows compiler runtime calls.
229     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231     setLibcallName(RTLIB::SREM_I64, "_allrem");
232     setLibcallName(RTLIB::UREM_I64, "_aullrem");
233     setLibcallName(RTLIB::MUL_I64, "_allmul");
234     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
235     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
237     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
238     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
239
240     // The _ftol2 runtime function has an unusual calling conv, which
241     // is modeled by a special pseudo-instruction.
242     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
243     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
244     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
245     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
246   }
247
248   if (Subtarget->isTargetDarwin()) {
249     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
250     setUseUnderscoreSetJmp(false);
251     setUseUnderscoreLongJmp(false);
252   } else if (Subtarget->isTargetWindowsGNU()) {
253     // MS runtime is weird: it exports _setjmp, but longjmp!
254     setUseUnderscoreSetJmp(true);
255     setUseUnderscoreLongJmp(false);
256   } else {
257     setUseUnderscoreSetJmp(true);
258     setUseUnderscoreLongJmp(true);
259   }
260
261   // Set up the register classes.
262   addRegisterClass(MVT::i8, &X86::GR8RegClass);
263   addRegisterClass(MVT::i16, &X86::GR16RegClass);
264   addRegisterClass(MVT::i32, &X86::GR32RegClass);
265   if (Subtarget->is64Bit())
266     addRegisterClass(MVT::i64, &X86::GR64RegClass);
267
268   for (MVT VT : MVT::integer_valuetypes())
269     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
270
271   // We don't accept any truncstore of integer registers.
272   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
273   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
274   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
275   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
276   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
277   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
278
279   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
280
281   // SETOEQ and SETUNE require checking two conditions.
282   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
283   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
284   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
285   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
286   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
287   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
288
289   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
290   // operation.
291   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
292   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
293   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
294
295   if (Subtarget->is64Bit()) {
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
297     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
298   } else if (!TM.Options.UseSoftFloat) {
299     // We have an algorithm for SSE2->double, and we turn this into a
300     // 64-bit FILD followed by conditional FADD for other targets.
301     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
302     // We have an algorithm for SSE2, and we turn this into a 64-bit
303     // FILD for other targets.
304     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
305   }
306
307   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
308   // this operation.
309   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
310   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
311
312   if (!TM.Options.UseSoftFloat) {
313     // SSE has no i16 to fp conversion, only i32
314     if (X86ScalarSSEf32) {
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
316       // f32 and f64 cases are Legal, f80 case is not
317       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
318     } else {
319       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
320       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
321     }
322   } else {
323     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
324     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
325   }
326
327   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
328   // are Legal, f80 is custom lowered.
329   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
330   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
331
332   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
333   // this operation.
334   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
335   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
336
337   if (X86ScalarSSEf32) {
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
339     // f32 and f64 cases are Legal, f80 case is not
340     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
341   } else {
342     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
343     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
344   }
345
346   // Handle FP_TO_UINT by promoting the destination to a larger signed
347   // conversion.
348   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
349   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
350   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
351
352   if (Subtarget->is64Bit()) {
353     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
354     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
355   } else if (!TM.Options.UseSoftFloat) {
356     // Since AVX is a superset of SSE3, only check for SSE here.
357     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
358       // Expand FP_TO_UINT into a select.
359       // FIXME: We would like to use a Custom expander here eventually to do
360       // the optimal thing for SSE vs. the default expansion in the legalizer.
361       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
362     else
363       // With SSE3 we can use fisttpll to convert to a signed i64; without
364       // SSE, we're stuck with a fistpll.
365       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
366   }
367
368   if (isTargetFTOL()) {
369     // Use the _ftol2 runtime function, which has a pseudo-instruction
370     // to handle its weird calling convention.
371     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
372   }
373
374   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
375   if (!X86ScalarSSEf64) {
376     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
377     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
378     if (Subtarget->is64Bit()) {
379       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
380       // Without SSE, i64->f64 goes through memory.
381       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
382     }
383   }
384
385   // Scalar integer divide and remainder are lowered to use operations that
386   // produce two results, to match the available instructions. This exposes
387   // the two-result form to trivial CSE, which is able to combine x/y and x%y
388   // into a single instruction.
389   //
390   // Scalar integer multiply-high is also lowered to use two-result
391   // operations, to match the available instructions. However, plain multiply
392   // (low) operations are left as Legal, as there are single-result
393   // instructions for this in x86. Using the two-result multiply instructions
394   // when both high and low results are needed must be arranged by dagcombine.
395   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
396     MVT VT = IntVTs[i];
397     setOperationAction(ISD::MULHS, VT, Expand);
398     setOperationAction(ISD::MULHU, VT, Expand);
399     setOperationAction(ISD::SDIV, VT, Expand);
400     setOperationAction(ISD::UDIV, VT, Expand);
401     setOperationAction(ISD::SREM, VT, Expand);
402     setOperationAction(ISD::UREM, VT, Expand);
403
404     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
405     setOperationAction(ISD::ADDC, VT, Custom);
406     setOperationAction(ISD::ADDE, VT, Custom);
407     setOperationAction(ISD::SUBC, VT, Custom);
408     setOperationAction(ISD::SUBE, VT, Custom);
409   }
410
411   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
412   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
413   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
414   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
415   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
416   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
417   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
418   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
419   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
420   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
421   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
422   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
423   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
424   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
425   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
426   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
427   if (Subtarget->is64Bit())
428     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
429   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
430   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
431   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
432   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
433   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
434   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
435   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
436   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
437
438   // Promote the i8 variants and force them on up to i32 which has a shorter
439   // encoding.
440   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
441   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
442   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
443   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
444   if (Subtarget->hasBMI()) {
445     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
446     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
447     if (Subtarget->is64Bit())
448       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
449   } else {
450     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
451     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
452     if (Subtarget->is64Bit())
453       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
454   }
455
456   if (Subtarget->hasLZCNT()) {
457     // When promoting the i8 variants, force them to i32 for a shorter
458     // encoding.
459     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
460     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
461     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
462     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
463     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
469     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
470     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
471     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
474     if (Subtarget->is64Bit()) {
475       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
476       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
477     }
478   }
479
480   // Special handling for half-precision floating point conversions.
481   // If we don't have F16C support, then lower half float conversions
482   // into library calls.
483   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
484     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
485     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
486   }
487
488   // There's never any support for operations beyond MVT::f32.
489   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
490   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
491   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
492   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
493
494   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
495   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
496   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
497   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
498   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
499   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
500
501   if (Subtarget->hasPOPCNT()) {
502     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
503   } else {
504     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
505     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
506     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
507     if (Subtarget->is64Bit())
508       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
509   }
510
511   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
512
513   if (!Subtarget->hasMOVBE())
514     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
515
516   // These should be promoted to a larger select which is supported.
517   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
518   // X86 wants to expand cmov itself.
519   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
520   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
524   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
530   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
531   if (Subtarget->is64Bit()) {
532     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
533     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
534   }
535   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
536   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
537   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
538   // support continuation, user-level threading, and etc.. As a result, no
539   // other SjLj exception interfaces are implemented and please don't build
540   // your own exception handling based on them.
541   // LLVM/Clang supports zero-cost DWARF exception handling.
542   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
543   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
544
545   // Darwin ABI issue.
546   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
547   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
548   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
549   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
550   if (Subtarget->is64Bit())
551     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
552   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
553   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
554   if (Subtarget->is64Bit()) {
555     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
556     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
557     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
558     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
559     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
560   }
561   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
562   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
563   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
564   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
567     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
568     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
569   }
570
571   if (Subtarget->hasSSE1())
572     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
573
574   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
575
576   // Expand certain atomics
577   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
578     MVT VT = IntVTs[i];
579     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
581     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
582   }
583
584   if (Subtarget->hasCmpxchg16b()) {
585     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
586   }
587
588   // FIXME - use subtarget debug flags
589   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
590       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
591     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
592   }
593
594   if (Subtarget->is64Bit()) {
595     setExceptionPointerRegister(X86::RAX);
596     setExceptionSelectorRegister(X86::RDX);
597   } else {
598     setExceptionPointerRegister(X86::EAX);
599     setExceptionSelectorRegister(X86::EDX);
600   }
601   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
602   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
603
604   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
605   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
606
607   setOperationAction(ISD::TRAP, MVT::Other, Legal);
608   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
609
610   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
611   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
612   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
613   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
614     // TargetInfo::X86_64ABIBuiltinVaList
615     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
616     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
617   } else {
618     // TargetInfo::CharPtrBuiltinVaList
619     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
620     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
621   }
622
623   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
624   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
625
626   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
627
628   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
629     // f32 and f64 use SSE.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f32, &X86::FR32RegClass);
632     addRegisterClass(MVT::f64, &X86::FR64RegClass);
633
634     // Use ANDPD to simulate FABS.
635     setOperationAction(ISD::FABS , MVT::f64, Custom);
636     setOperationAction(ISD::FABS , MVT::f32, Custom);
637
638     // Use XORP to simulate FNEG.
639     setOperationAction(ISD::FNEG , MVT::f64, Custom);
640     setOperationAction(ISD::FNEG , MVT::f32, Custom);
641
642     // Use ANDPD and ORPD to simulate FCOPYSIGN.
643     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
644     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
645
646     // Lower this to FGETSIGNx86 plus an AND.
647     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
648     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
649
650     // We don't support sin/cos/fmod
651     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
652     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
653     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
654     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
655     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
656     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
657
658     // Expand FP immediates into loads from the stack, except for the special
659     // cases we handle.
660     addLegalFPImmediate(APFloat(+0.0)); // xorpd
661     addLegalFPImmediate(APFloat(+0.0f)); // xorps
662   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
663     // Use SSE for f32, x87 for f64.
664     // Set up the FP register classes.
665     addRegisterClass(MVT::f32, &X86::FR32RegClass);
666     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
667
668     // Use ANDPS to simulate FABS.
669     setOperationAction(ISD::FABS , MVT::f32, Custom);
670
671     // Use XORP to simulate FNEG.
672     setOperationAction(ISD::FNEG , MVT::f32, Custom);
673
674     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
675
676     // Use ANDPS and ORPS to simulate FCOPYSIGN.
677     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
678     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
679
680     // We don't support sin/cos/fmod
681     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
682     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
683     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
684
685     // Special cases we handle for FP constants.
686     addLegalFPImmediate(APFloat(+0.0f)); // xorps
687     addLegalFPImmediate(APFloat(+0.0)); // FLD0
688     addLegalFPImmediate(APFloat(+1.0)); // FLD1
689     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
691
692     if (!TM.Options.UnsafeFPMath) {
693       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
694       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
695       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
696     }
697   } else if (!TM.Options.UseSoftFloat) {
698     // f32 and f64 in x87.
699     // Set up the FP register classes.
700     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
701     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
702
703     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
704     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
705     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
706     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
711       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
712       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
713       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
715     }
716     addLegalFPImmediate(APFloat(+0.0)); // FLD0
717     addLegalFPImmediate(APFloat(+1.0)); // FLD1
718     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
719     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
720     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
721     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
722     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
723     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
724   }
725
726   // We don't support FMA.
727   setOperationAction(ISD::FMA, MVT::f64, Expand);
728   setOperationAction(ISD::FMA, MVT::f32, Expand);
729
730   // Long double always uses X87.
731   if (!TM.Options.UseSoftFloat) {
732     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
733     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
734     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
735     {
736       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
737       addLegalFPImmediate(TmpFlt);  // FLD0
738       TmpFlt.changeSign();
739       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
740
741       bool ignored;
742       APFloat TmpFlt2(+1.0);
743       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
744                       &ignored);
745       addLegalFPImmediate(TmpFlt2);  // FLD1
746       TmpFlt2.changeSign();
747       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
748     }
749
750     if (!TM.Options.UnsafeFPMath) {
751       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
752       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
753       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
754     }
755
756     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
757     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
758     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
759     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
760     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
761     setOperationAction(ISD::FMA, MVT::f80, Expand);
762   }
763
764   // Always use a library call for pow.
765   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
766   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
767   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
768
769   setOperationAction(ISD::FLOG, MVT::f80, Expand);
770   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
771   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
772   setOperationAction(ISD::FEXP, MVT::f80, Expand);
773   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
774   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
775   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
776
777   // First set operation action for all vector types to either promote
778   // (for widening) or expand (for scalarization). Then we will selectively
779   // turn on ones that can be effectively codegen'd.
780   for (MVT VT : MVT::vector_valuetypes()) {
781     setOperationAction(ISD::ADD , VT, Expand);
782     setOperationAction(ISD::SUB , VT, Expand);
783     setOperationAction(ISD::FADD, VT, Expand);
784     setOperationAction(ISD::FNEG, VT, Expand);
785     setOperationAction(ISD::FSUB, VT, Expand);
786     setOperationAction(ISD::MUL , VT, Expand);
787     setOperationAction(ISD::FMUL, VT, Expand);
788     setOperationAction(ISD::SDIV, VT, Expand);
789     setOperationAction(ISD::UDIV, VT, Expand);
790     setOperationAction(ISD::FDIV, VT, Expand);
791     setOperationAction(ISD::SREM, VT, Expand);
792     setOperationAction(ISD::UREM, VT, Expand);
793     setOperationAction(ISD::LOAD, VT, Expand);
794     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
796     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
797     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
798     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
799     setOperationAction(ISD::FABS, VT, Expand);
800     setOperationAction(ISD::FSIN, VT, Expand);
801     setOperationAction(ISD::FSINCOS, VT, Expand);
802     setOperationAction(ISD::FCOS, VT, Expand);
803     setOperationAction(ISD::FSINCOS, VT, Expand);
804     setOperationAction(ISD::FREM, VT, Expand);
805     setOperationAction(ISD::FMA,  VT, Expand);
806     setOperationAction(ISD::FPOWI, VT, Expand);
807     setOperationAction(ISD::FSQRT, VT, Expand);
808     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
809     setOperationAction(ISD::FFLOOR, VT, Expand);
810     setOperationAction(ISD::FCEIL, VT, Expand);
811     setOperationAction(ISD::FTRUNC, VT, Expand);
812     setOperationAction(ISD::FRINT, VT, Expand);
813     setOperationAction(ISD::FNEARBYINT, VT, Expand);
814     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
815     setOperationAction(ISD::MULHS, VT, Expand);
816     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
817     setOperationAction(ISD::MULHU, VT, Expand);
818     setOperationAction(ISD::SDIVREM, VT, Expand);
819     setOperationAction(ISD::UDIVREM, VT, Expand);
820     setOperationAction(ISD::FPOW, VT, Expand);
821     setOperationAction(ISD::CTPOP, VT, Expand);
822     setOperationAction(ISD::CTTZ, VT, Expand);
823     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
824     setOperationAction(ISD::CTLZ, VT, Expand);
825     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
826     setOperationAction(ISD::SHL, VT, Expand);
827     setOperationAction(ISD::SRA, VT, Expand);
828     setOperationAction(ISD::SRL, VT, Expand);
829     setOperationAction(ISD::ROTL, VT, Expand);
830     setOperationAction(ISD::ROTR, VT, Expand);
831     setOperationAction(ISD::BSWAP, VT, Expand);
832     setOperationAction(ISD::SETCC, VT, Expand);
833     setOperationAction(ISD::FLOG, VT, Expand);
834     setOperationAction(ISD::FLOG2, VT, Expand);
835     setOperationAction(ISD::FLOG10, VT, Expand);
836     setOperationAction(ISD::FEXP, VT, Expand);
837     setOperationAction(ISD::FEXP2, VT, Expand);
838     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
839     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
840     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
841     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
842     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
843     setOperationAction(ISD::TRUNCATE, VT, Expand);
844     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
845     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
846     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
847     setOperationAction(ISD::VSELECT, VT, Expand);
848     setOperationAction(ISD::SELECT_CC, VT, Expand);
849     for (MVT InnerVT : MVT::vector_valuetypes()) {
850       setTruncStoreAction(InnerVT, VT, Expand);
851
852       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
853       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
854
855       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
856       // types, we have to deal with them whether we ask for Expansion or not.
857       // Setting Expand causes its own optimisation problems though, so leave
858       // them legal.
859       if (VT.getVectorElementType() == MVT::i1)
860         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
861     }
862   }
863
864   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
865   // with -msoft-float, disable use of MMX as well.
866   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
867     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
868     // No operations on x86mmx supported, everything uses intrinsics.
869   }
870
871   // MMX-sized vectors (other than x86mmx) are expected to be expanded
872   // into smaller operations.
873   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
874   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
875   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
876   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
877   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
878   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
879   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
880   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
881   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
882   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
883   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
884   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
885   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
886   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
887   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
888   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
889   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
890   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
891   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
892   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
893   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
894   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
895   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
896   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
897   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
898   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
899   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
900   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
901   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
902
903   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
904     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
905
906     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
907     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
908     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
909     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
910     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
911     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
912     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
913     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
916     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
917     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
919     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
920   }
921
922   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
923     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
924
925     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
926     // registers cannot be used even for integer operations.
927     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
928     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
929     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
930     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
931
932     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
933     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
934     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
935     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
936     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
937     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
938     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
939     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
940     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
941     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
942     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
943     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
944     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
945     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
946     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
947     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
952     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
953     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
954
955     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
959
960     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
965
966     // Only provide customized ctpop vector bit twiddling for vector types we
967     // know to perform better than using the popcnt instructions on each vector
968     // element. If popcnt isn't supported, always provide the custom version.
969     if (!Subtarget->hasPOPCNT()) {
970       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
971       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
972     }
973
974     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
975     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
976       MVT VT = (MVT::SimpleValueType)i;
977       // Do not attempt to custom lower non-power-of-2 vectors
978       if (!isPowerOf2_32(VT.getVectorNumElements()))
979         continue;
980       // Do not attempt to custom lower non-128-bit vectors
981       if (!VT.is128BitVector())
982         continue;
983       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
984       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
985       setOperationAction(ISD::VSELECT,            VT, Custom);
986       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
987     }
988
989     // We support custom legalizing of sext and anyext loads for specific
990     // memory vector types which we can load as a scalar (or sequence of
991     // scalars) and extend in-register to a legal 128-bit vector type. For sext
992     // loads these must work with a single scalar load.
993     for (MVT VT : MVT::integer_vector_valuetypes()) {
994       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
995       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
996       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
997       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
998       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
999       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1000       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1001       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1002       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1003     }
1004
1005     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1006     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1007     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1008     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1009     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1010     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1013
1014     if (Subtarget->is64Bit()) {
1015       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1016       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1017     }
1018
1019     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1020     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1021       MVT VT = (MVT::SimpleValueType)i;
1022
1023       // Do not attempt to promote non-128-bit vectors
1024       if (!VT.is128BitVector())
1025         continue;
1026
1027       setOperationAction(ISD::AND,    VT, Promote);
1028       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1029       setOperationAction(ISD::OR,     VT, Promote);
1030       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1031       setOperationAction(ISD::XOR,    VT, Promote);
1032       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1033       setOperationAction(ISD::LOAD,   VT, Promote);
1034       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1035       setOperationAction(ISD::SELECT, VT, Promote);
1036       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1037     }
1038
1039     // Custom lower v2i64 and v2f64 selects.
1040     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1042     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1043     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1044
1045     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1046     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1047
1048     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1049     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1050     // As there is no 64-bit GPR available, we need build a special custom
1051     // sequence to convert from v2i32 to v2f32.
1052     if (!Subtarget->is64Bit())
1053       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1054
1055     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1056     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1057
1058     for (MVT VT : MVT::fp_vector_valuetypes())
1059       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1060
1061     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1062     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1063     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1064   }
1065
1066   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1067     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1068     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1069     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1070     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1071     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1072     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1073     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1074     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1075     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1076     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1077
1078     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1088
1089     // FIXME: Do we need to handle scalar-to-vector here?
1090     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1091
1092     // We directly match byte blends in the backend as they match the VSELECT
1093     // condition form.
1094     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1095
1096     // SSE41 brings specific instructions for doing vector sign extend even in
1097     // cases where we don't have SRA.
1098     for (MVT VT : MVT::integer_vector_valuetypes()) {
1099       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1100       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1101       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1102     }
1103
1104     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1105     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1106     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1107     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1108     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1109     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1110     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1111
1112     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1113     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1114     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1115     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1116     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1117     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1118
1119     // i8 and i16 vectors are custom because the source register and source
1120     // source memory operand types are not the same width.  f32 vectors are
1121     // custom since the immediate controlling the insert encodes additional
1122     // information.
1123     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1124     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1125     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1126     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1127
1128     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1129     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1130     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1131     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1132
1133     // FIXME: these should be Legal, but that's only for the case where
1134     // the index is constant.  For now custom expand to deal with that.
1135     if (Subtarget->is64Bit()) {
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1138     }
1139   }
1140
1141   if (Subtarget->hasSSE2()) {
1142     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1143     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1144
1145     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1146     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1147
1148     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1149     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1150
1151     // In the customized shift lowering, the legal cases in AVX2 will be
1152     // recognized.
1153     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1160   }
1161
1162   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1163     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1164     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1165     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1166     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1167     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1168     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1169
1170     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1171     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1172     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1173
1174     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1175     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1176     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1177     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1178     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1179     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1180     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1181     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1182     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1183     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1184     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1185     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1186
1187     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1188     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1189     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1190     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1191     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1192     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1193     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1194     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1195     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1196     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1197     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1198     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1199
1200     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1201     // even though v8i16 is a legal type.
1202     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1203     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1204     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1205
1206     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1207     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1208     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1209
1210     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1211     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1212
1213     for (MVT VT : MVT::fp_vector_valuetypes())
1214       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1215
1216     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1217     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1218
1219     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1220     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1221
1222     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1223     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1224
1225     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1226     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1227     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1228     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1229
1230     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1231     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1232     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1233
1234     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1235     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1236     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1237     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1238     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1239     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1240     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1241     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1242     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1243     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1244     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1245     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1246
1247     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1248       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1249       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1250       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1251       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1252       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1253       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1254     }
1255
1256     if (Subtarget->hasInt256()) {
1257       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1258       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1259       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1260       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1261
1262       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1263       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1264       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1265       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1266
1267       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1268       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1269       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1270       // Don't lower v32i8 because there is no 128-bit byte mul
1271
1272       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1273       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1274       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1275       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1276
1277       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1278       // when we have a 256bit-wide blend with immediate.
1279       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1280
1281       // Only provide customized ctpop vector bit twiddling for vector types we
1282       // know to perform better than using the popcnt instructions on each
1283       // vector element. If popcnt isn't supported, always provide the custom
1284       // version.
1285       if (!Subtarget->hasPOPCNT())
1286         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1287
1288       // Custom CTPOP always performs better on natively supported v8i32
1289       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1290
1291       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1292       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1293       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1294       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1295       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1296       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1297       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1298
1299       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1300       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1301       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1302       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1303       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1304       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1305     } else {
1306       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1309       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1310
1311       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1312       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1313       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1314       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1315
1316       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1317       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1318       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1319       // Don't lower v32i8 because there is no 128-bit byte mul
1320     }
1321
1322     // In the customized shift lowering, the legal cases in AVX2 will be
1323     // recognized.
1324     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1325     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1326
1327     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1328     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1329
1330     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1331
1332     // Custom lower several nodes for 256-bit types.
1333     for (MVT VT : MVT::vector_valuetypes()) {
1334       if (VT.getScalarSizeInBits() >= 32) {
1335         setOperationAction(ISD::MLOAD,  VT, Legal);
1336         setOperationAction(ISD::MSTORE, VT, Legal);
1337       }
1338       // Extract subvector is special because the value type
1339       // (result) is 128-bit but the source is 256-bit wide.
1340       if (VT.is128BitVector()) {
1341         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1342       }
1343       // Do not attempt to custom lower other non-256-bit vectors
1344       if (!VT.is256BitVector())
1345         continue;
1346
1347       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1348       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1349       setOperationAction(ISD::VSELECT,            VT, Custom);
1350       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1351       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1352       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1353       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1354       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1355     }
1356
1357     if (Subtarget->hasInt256())
1358       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1359
1360
1361     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1362     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1363       MVT VT = (MVT::SimpleValueType)i;
1364
1365       // Do not attempt to promote non-256-bit vectors
1366       if (!VT.is256BitVector())
1367         continue;
1368
1369       setOperationAction(ISD::AND,    VT, Promote);
1370       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1371       setOperationAction(ISD::OR,     VT, Promote);
1372       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1373       setOperationAction(ISD::XOR,    VT, Promote);
1374       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1375       setOperationAction(ISD::LOAD,   VT, Promote);
1376       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1377       setOperationAction(ISD::SELECT, VT, Promote);
1378       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1379     }
1380   }
1381
1382   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1383     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1384     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1385     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1386     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1387
1388     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1389     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1390     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1391
1392     for (MVT VT : MVT::fp_vector_valuetypes())
1393       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1394
1395     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1396     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1397     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1398     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1399     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1400     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1401     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1402     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1403     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1404     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1405
1406     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1407     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1408     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1409     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1410     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1411     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1412
1413     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1414     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1415     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1416     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1417     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1418     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1419     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1420     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1421
1422     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1423     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1424     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1425     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1426     if (Subtarget->is64Bit()) {
1427       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1428       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1429       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1430       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1431     }
1432     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1433     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1434     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1435     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1436     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1437     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1438     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1439     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1440     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1441     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1442     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1443     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1444     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1445     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1446
1447     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1448     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1449     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1450     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1451     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1452     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1453     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1454     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1455     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1456     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1457     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1458     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1459     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1460
1461     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1462     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1463     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1464     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1465     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1466     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1467     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1468     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1469     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1470     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1471
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1474     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1475     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1476     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1477     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1478
1479     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1480     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1481
1482     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1483
1484     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1485     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1486     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1487     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1488     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1489     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1493
1494     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1496
1497     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1498     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1499
1500     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1501
1502     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1503     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1504
1505     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1506     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1507
1508     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1509     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1510
1511     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1512     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1513     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1514     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1515     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1516     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1517
1518     if (Subtarget->hasCDI()) {
1519       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1520       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1521     }
1522
1523     // Custom lower several nodes.
1524     for (MVT VT : MVT::vector_valuetypes()) {
1525       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1526       // Extract subvector is special because the value type
1527       // (result) is 256/128-bit but the source is 512-bit wide.
1528       if (VT.is128BitVector() || VT.is256BitVector()) {
1529         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1530       }
1531       if (VT.getVectorElementType() == MVT::i1)
1532         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1533
1534       // Do not attempt to custom lower other non-512-bit vectors
1535       if (!VT.is512BitVector())
1536         continue;
1537
1538       if ( EltSize >= 32) {
1539         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1540         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1541         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1542         setOperationAction(ISD::VSELECT,             VT, Legal);
1543         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1544         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1545         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1546         setOperationAction(ISD::MLOAD,               VT, Legal);
1547         setOperationAction(ISD::MSTORE,              VT, Legal);
1548       }
1549     }
1550     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1551       MVT VT = (MVT::SimpleValueType)i;
1552
1553       // Do not attempt to promote non-512-bit vectors.
1554       if (!VT.is512BitVector())
1555         continue;
1556
1557       setOperationAction(ISD::SELECT, VT, Promote);
1558       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1559     }
1560   }// has  AVX-512
1561
1562   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1563     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1564     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1565
1566     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1567     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1568
1569     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1570     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1571     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1572     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1573     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1574     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1575     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1576     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1577     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1578
1579     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1580       const MVT VT = (MVT::SimpleValueType)i;
1581
1582       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1583
1584       // Do not attempt to promote non-512-bit vectors.
1585       if (!VT.is512BitVector())
1586         continue;
1587
1588       if (EltSize < 32) {
1589         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1590         setOperationAction(ISD::VSELECT,             VT, Legal);
1591       }
1592     }
1593   }
1594
1595   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1596     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1597     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1598
1599     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1600     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1601     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1602
1603     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1604     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1605     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1606     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1607     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1608     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1609   }
1610
1611   // We want to custom lower some of our intrinsics.
1612   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1613   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1614   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1615   if (!Subtarget->is64Bit())
1616     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1617
1618   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1619   // handle type legalization for these operations here.
1620   //
1621   // FIXME: We really should do custom legalization for addition and
1622   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1623   // than generic legalization for 64-bit multiplication-with-overflow, though.
1624   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1625     // Add/Sub/Mul with overflow operations are custom lowered.
1626     MVT VT = IntVTs[i];
1627     setOperationAction(ISD::SADDO, VT, Custom);
1628     setOperationAction(ISD::UADDO, VT, Custom);
1629     setOperationAction(ISD::SSUBO, VT, Custom);
1630     setOperationAction(ISD::USUBO, VT, Custom);
1631     setOperationAction(ISD::SMULO, VT, Custom);
1632     setOperationAction(ISD::UMULO, VT, Custom);
1633   }
1634
1635
1636   if (!Subtarget->is64Bit()) {
1637     // These libcalls are not available in 32-bit.
1638     setLibcallName(RTLIB::SHL_I128, nullptr);
1639     setLibcallName(RTLIB::SRL_I128, nullptr);
1640     setLibcallName(RTLIB::SRA_I128, nullptr);
1641   }
1642
1643   // Combine sin / cos into one node or libcall if possible.
1644   if (Subtarget->hasSinCos()) {
1645     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1646     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1647     if (Subtarget->isTargetDarwin()) {
1648       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1649       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1650       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1651       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1652     }
1653   }
1654
1655   if (Subtarget->isTargetWin64()) {
1656     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1657     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1658     setOperationAction(ISD::SREM, MVT::i128, Custom);
1659     setOperationAction(ISD::UREM, MVT::i128, Custom);
1660     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1661     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1662   }
1663
1664   // We have target-specific dag combine patterns for the following nodes:
1665   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1666   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1667   setTargetDAGCombine(ISD::BITCAST);
1668   setTargetDAGCombine(ISD::VSELECT);
1669   setTargetDAGCombine(ISD::SELECT);
1670   setTargetDAGCombine(ISD::SHL);
1671   setTargetDAGCombine(ISD::SRA);
1672   setTargetDAGCombine(ISD::SRL);
1673   setTargetDAGCombine(ISD::OR);
1674   setTargetDAGCombine(ISD::AND);
1675   setTargetDAGCombine(ISD::ADD);
1676   setTargetDAGCombine(ISD::FADD);
1677   setTargetDAGCombine(ISD::FSUB);
1678   setTargetDAGCombine(ISD::FMA);
1679   setTargetDAGCombine(ISD::SUB);
1680   setTargetDAGCombine(ISD::LOAD);
1681   setTargetDAGCombine(ISD::MLOAD);
1682   setTargetDAGCombine(ISD::STORE);
1683   setTargetDAGCombine(ISD::MSTORE);
1684   setTargetDAGCombine(ISD::ZERO_EXTEND);
1685   setTargetDAGCombine(ISD::ANY_EXTEND);
1686   setTargetDAGCombine(ISD::SIGN_EXTEND);
1687   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1688   setTargetDAGCombine(ISD::TRUNCATE);
1689   setTargetDAGCombine(ISD::SINT_TO_FP);
1690   setTargetDAGCombine(ISD::SETCC);
1691   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1692   setTargetDAGCombine(ISD::BUILD_VECTOR);
1693   setTargetDAGCombine(ISD::MUL);
1694   setTargetDAGCombine(ISD::XOR);
1695
1696   computeRegisterProperties(Subtarget->getRegisterInfo());
1697
1698   // On Darwin, -Os means optimize for size without hurting performance,
1699   // do not reduce the limit.
1700   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1701   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1702   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1703   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1704   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1705   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1706   setPrefLoopAlignment(4); // 2^4 bytes.
1707
1708   // Predictable cmov don't hurt on atom because it's in-order.
1709   PredictableSelectIsExpensive = !Subtarget->isAtom();
1710   EnableExtLdPromotion = true;
1711   setPrefFunctionAlignment(4); // 2^4 bytes.
1712
1713   verifyIntrinsicTables();
1714 }
1715
1716 // This has so far only been implemented for 64-bit MachO.
1717 bool X86TargetLowering::useLoadStackGuardNode() const {
1718   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1719 }
1720
1721 TargetLoweringBase::LegalizeTypeAction
1722 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1723   if (ExperimentalVectorWideningLegalization &&
1724       VT.getVectorNumElements() != 1 &&
1725       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1726     return TypeWidenVector;
1727
1728   return TargetLoweringBase::getPreferredVectorAction(VT);
1729 }
1730
1731 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1732   if (!VT.isVector())
1733     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1734
1735   const unsigned NumElts = VT.getVectorNumElements();
1736   const EVT EltVT = VT.getVectorElementType();
1737   if (VT.is512BitVector()) {
1738     if (Subtarget->hasAVX512())
1739       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740           EltVT == MVT::f32 || EltVT == MVT::f64)
1741         switch(NumElts) {
1742         case  8: return MVT::v8i1;
1743         case 16: return MVT::v16i1;
1744       }
1745     if (Subtarget->hasBWI())
1746       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1747         switch(NumElts) {
1748         case 32: return MVT::v32i1;
1749         case 64: return MVT::v64i1;
1750       }
1751   }
1752
1753   if (VT.is256BitVector() || VT.is128BitVector()) {
1754     if (Subtarget->hasVLX())
1755       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1756           EltVT == MVT::f32 || EltVT == MVT::f64)
1757         switch(NumElts) {
1758         case 2: return MVT::v2i1;
1759         case 4: return MVT::v4i1;
1760         case 8: return MVT::v8i1;
1761       }
1762     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1763       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1764         switch(NumElts) {
1765         case  8: return MVT::v8i1;
1766         case 16: return MVT::v16i1;
1767         case 32: return MVT::v32i1;
1768       }
1769   }
1770
1771   return VT.changeVectorElementTypeToInteger();
1772 }
1773
1774 /// Helper for getByValTypeAlignment to determine
1775 /// the desired ByVal argument alignment.
1776 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1777   if (MaxAlign == 16)
1778     return;
1779   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1780     if (VTy->getBitWidth() == 128)
1781       MaxAlign = 16;
1782   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1783     unsigned EltAlign = 0;
1784     getMaxByValAlign(ATy->getElementType(), EltAlign);
1785     if (EltAlign > MaxAlign)
1786       MaxAlign = EltAlign;
1787   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1788     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1789       unsigned EltAlign = 0;
1790       getMaxByValAlign(STy->getElementType(i), EltAlign);
1791       if (EltAlign > MaxAlign)
1792         MaxAlign = EltAlign;
1793       if (MaxAlign == 16)
1794         break;
1795     }
1796   }
1797 }
1798
1799 /// Return the desired alignment for ByVal aggregate
1800 /// function arguments in the caller parameter area. For X86, aggregates
1801 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1802 /// are at 4-byte boundaries.
1803 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1804   if (Subtarget->is64Bit()) {
1805     // Max of 8 and alignment of type.
1806     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1807     if (TyAlign > 8)
1808       return TyAlign;
1809     return 8;
1810   }
1811
1812   unsigned Align = 4;
1813   if (Subtarget->hasSSE1())
1814     getMaxByValAlign(Ty, Align);
1815   return Align;
1816 }
1817
1818 /// Returns the target specific optimal type for load
1819 /// and store operations as a result of memset, memcpy, and memmove
1820 /// lowering. If DstAlign is zero that means it's safe to destination
1821 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1822 /// means there isn't a need to check it against alignment requirement,
1823 /// probably because the source does not need to be loaded. If 'IsMemset' is
1824 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1825 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1826 /// source is constant so it does not need to be loaded.
1827 /// It returns EVT::Other if the type should be determined using generic
1828 /// target-independent logic.
1829 EVT
1830 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1831                                        unsigned DstAlign, unsigned SrcAlign,
1832                                        bool IsMemset, bool ZeroMemset,
1833                                        bool MemcpyStrSrc,
1834                                        MachineFunction &MF) const {
1835   const Function *F = MF.getFunction();
1836   if ((!IsMemset || ZeroMemset) &&
1837       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1838     if (Size >= 16 &&
1839         (Subtarget->isUnalignedMemAccessFast() ||
1840          ((DstAlign == 0 || DstAlign >= 16) &&
1841           (SrcAlign == 0 || SrcAlign >= 16)))) {
1842       if (Size >= 32) {
1843         if (Subtarget->hasInt256())
1844           return MVT::v8i32;
1845         if (Subtarget->hasFp256())
1846           return MVT::v8f32;
1847       }
1848       if (Subtarget->hasSSE2())
1849         return MVT::v4i32;
1850       if (Subtarget->hasSSE1())
1851         return MVT::v4f32;
1852     } else if (!MemcpyStrSrc && Size >= 8 &&
1853                !Subtarget->is64Bit() &&
1854                Subtarget->hasSSE2()) {
1855       // Do not use f64 to lower memcpy if source is string constant. It's
1856       // better to use i32 to avoid the loads.
1857       return MVT::f64;
1858     }
1859   }
1860   if (Subtarget->is64Bit() && Size >= 8)
1861     return MVT::i64;
1862   return MVT::i32;
1863 }
1864
1865 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1866   if (VT == MVT::f32)
1867     return X86ScalarSSEf32;
1868   else if (VT == MVT::f64)
1869     return X86ScalarSSEf64;
1870   return true;
1871 }
1872
1873 bool
1874 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1875                                                   unsigned,
1876                                                   unsigned,
1877                                                   bool *Fast) const {
1878   if (Fast)
1879     *Fast = Subtarget->isUnalignedMemAccessFast();
1880   return true;
1881 }
1882
1883 /// Return the entry encoding for a jump table in the
1884 /// current function.  The returned value is a member of the
1885 /// MachineJumpTableInfo::JTEntryKind enum.
1886 unsigned X86TargetLowering::getJumpTableEncoding() const {
1887   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1888   // symbol.
1889   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1890       Subtarget->isPICStyleGOT())
1891     return MachineJumpTableInfo::EK_Custom32;
1892
1893   // Otherwise, use the normal jump table encoding heuristics.
1894   return TargetLowering::getJumpTableEncoding();
1895 }
1896
1897 const MCExpr *
1898 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1899                                              const MachineBasicBlock *MBB,
1900                                              unsigned uid,MCContext &Ctx) const{
1901   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1902          Subtarget->isPICStyleGOT());
1903   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1904   // entries.
1905   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1906                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1907 }
1908
1909 /// Returns relocation base for the given PIC jumptable.
1910 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1911                                                     SelectionDAG &DAG) const {
1912   if (!Subtarget->is64Bit())
1913     // This doesn't have SDLoc associated with it, but is not really the
1914     // same as a Register.
1915     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1916   return Table;
1917 }
1918
1919 /// This returns the relocation base for the given PIC jumptable,
1920 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1921 const MCExpr *X86TargetLowering::
1922 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1923                              MCContext &Ctx) const {
1924   // X86-64 uses RIP relative addressing based on the jump table label.
1925   if (Subtarget->isPICStyleRIPRel())
1926     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1927
1928   // Otherwise, the reference is relative to the PIC base.
1929   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1930 }
1931
1932 std::pair<const TargetRegisterClass *, uint8_t>
1933 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1934                                            MVT VT) const {
1935   const TargetRegisterClass *RRC = nullptr;
1936   uint8_t Cost = 1;
1937   switch (VT.SimpleTy) {
1938   default:
1939     return TargetLowering::findRepresentativeClass(TRI, VT);
1940   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1941     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1942     break;
1943   case MVT::x86mmx:
1944     RRC = &X86::VR64RegClass;
1945     break;
1946   case MVT::f32: case MVT::f64:
1947   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1948   case MVT::v4f32: case MVT::v2f64:
1949   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1950   case MVT::v4f64:
1951     RRC = &X86::VR128RegClass;
1952     break;
1953   }
1954   return std::make_pair(RRC, Cost);
1955 }
1956
1957 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1958                                                unsigned &Offset) const {
1959   if (!Subtarget->isTargetLinux())
1960     return false;
1961
1962   if (Subtarget->is64Bit()) {
1963     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1964     Offset = 0x28;
1965     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1966       AddressSpace = 256;
1967     else
1968       AddressSpace = 257;
1969   } else {
1970     // %gs:0x14 on i386
1971     Offset = 0x14;
1972     AddressSpace = 256;
1973   }
1974   return true;
1975 }
1976
1977 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1978                                             unsigned DestAS) const {
1979   assert(SrcAS != DestAS && "Expected different address spaces!");
1980
1981   return SrcAS < 256 && DestAS < 256;
1982 }
1983
1984 //===----------------------------------------------------------------------===//
1985 //               Return Value Calling Convention Implementation
1986 //===----------------------------------------------------------------------===//
1987
1988 #include "X86GenCallingConv.inc"
1989
1990 bool
1991 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1992                                   MachineFunction &MF, bool isVarArg,
1993                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1994                         LLVMContext &Context) const {
1995   SmallVector<CCValAssign, 16> RVLocs;
1996   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1997   return CCInfo.CheckReturn(Outs, RetCC_X86);
1998 }
1999
2000 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2001   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2002   return ScratchRegs;
2003 }
2004
2005 SDValue
2006 X86TargetLowering::LowerReturn(SDValue Chain,
2007                                CallingConv::ID CallConv, bool isVarArg,
2008                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2009                                const SmallVectorImpl<SDValue> &OutVals,
2010                                SDLoc dl, SelectionDAG &DAG) const {
2011   MachineFunction &MF = DAG.getMachineFunction();
2012   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2013
2014   SmallVector<CCValAssign, 16> RVLocs;
2015   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2016   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2017
2018   SDValue Flag;
2019   SmallVector<SDValue, 6> RetOps;
2020   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2021   // Operand #1 = Bytes To Pop
2022   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2023                    MVT::i16));
2024
2025   // Copy the result values into the output registers.
2026   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2027     CCValAssign &VA = RVLocs[i];
2028     assert(VA.isRegLoc() && "Can only return in registers!");
2029     SDValue ValToCopy = OutVals[i];
2030     EVT ValVT = ValToCopy.getValueType();
2031
2032     // Promote values to the appropriate types.
2033     if (VA.getLocInfo() == CCValAssign::SExt)
2034       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2035     else if (VA.getLocInfo() == CCValAssign::ZExt)
2036       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2037     else if (VA.getLocInfo() == CCValAssign::AExt)
2038       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2039     else if (VA.getLocInfo() == CCValAssign::BCvt)
2040       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2041
2042     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2043            "Unexpected FP-extend for return value.");
2044
2045     // If this is x86-64, and we disabled SSE, we can't return FP values,
2046     // or SSE or MMX vectors.
2047     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2048          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2049           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2050       report_fatal_error("SSE register return with SSE disabled");
2051     }
2052     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2053     // llvm-gcc has never done it right and no one has noticed, so this
2054     // should be OK for now.
2055     if (ValVT == MVT::f64 &&
2056         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2057       report_fatal_error("SSE2 register return with SSE2 disabled");
2058
2059     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2060     // the RET instruction and handled by the FP Stackifier.
2061     if (VA.getLocReg() == X86::FP0 ||
2062         VA.getLocReg() == X86::FP1) {
2063       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2064       // change the value to the FP stack register class.
2065       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2066         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2067       RetOps.push_back(ValToCopy);
2068       // Don't emit a copytoreg.
2069       continue;
2070     }
2071
2072     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2073     // which is returned in RAX / RDX.
2074     if (Subtarget->is64Bit()) {
2075       if (ValVT == MVT::x86mmx) {
2076         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2077           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2078           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2079                                   ValToCopy);
2080           // If we don't have SSE2 available, convert to v4f32 so the generated
2081           // register is legal.
2082           if (!Subtarget->hasSSE2())
2083             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2084         }
2085       }
2086     }
2087
2088     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2089     Flag = Chain.getValue(1);
2090     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2091   }
2092
2093   // The x86-64 ABIs require that for returning structs by value we copy
2094   // the sret argument into %rax/%eax (depending on ABI) for the return.
2095   // Win32 requires us to put the sret argument to %eax as well.
2096   // We saved the argument into a virtual register in the entry block,
2097   // so now we copy the value out and into %rax/%eax.
2098   //
2099   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2100   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2101   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2102   // either case FuncInfo->setSRetReturnReg() will have been called.
2103   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2104     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2105            "No need for an sret register");
2106     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2107
2108     unsigned RetValReg
2109         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2110           X86::RAX : X86::EAX;
2111     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2112     Flag = Chain.getValue(1);
2113
2114     // RAX/EAX now acts like a return value.
2115     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2116   }
2117
2118   RetOps[0] = Chain;  // Update chain.
2119
2120   // Add the flag if we have it.
2121   if (Flag.getNode())
2122     RetOps.push_back(Flag);
2123
2124   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2125 }
2126
2127 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2128   if (N->getNumValues() != 1)
2129     return false;
2130   if (!N->hasNUsesOfValue(1, 0))
2131     return false;
2132
2133   SDValue TCChain = Chain;
2134   SDNode *Copy = *N->use_begin();
2135   if (Copy->getOpcode() == ISD::CopyToReg) {
2136     // If the copy has a glue operand, we conservatively assume it isn't safe to
2137     // perform a tail call.
2138     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2139       return false;
2140     TCChain = Copy->getOperand(0);
2141   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2142     return false;
2143
2144   bool HasRet = false;
2145   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2146        UI != UE; ++UI) {
2147     if (UI->getOpcode() != X86ISD::RET_FLAG)
2148       return false;
2149     // If we are returning more than one value, we can definitely
2150     // not make a tail call see PR19530
2151     if (UI->getNumOperands() > 4)
2152       return false;
2153     if (UI->getNumOperands() == 4 &&
2154         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2155       return false;
2156     HasRet = true;
2157   }
2158
2159   if (!HasRet)
2160     return false;
2161
2162   Chain = TCChain;
2163   return true;
2164 }
2165
2166 EVT
2167 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2168                                             ISD::NodeType ExtendKind) const {
2169   MVT ReturnMVT;
2170   // TODO: Is this also valid on 32-bit?
2171   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2172     ReturnMVT = MVT::i8;
2173   else
2174     ReturnMVT = MVT::i32;
2175
2176   EVT MinVT = getRegisterType(Context, ReturnMVT);
2177   return VT.bitsLT(MinVT) ? MinVT : VT;
2178 }
2179
2180 /// Lower the result values of a call into the
2181 /// appropriate copies out of appropriate physical registers.
2182 ///
2183 SDValue
2184 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2185                                    CallingConv::ID CallConv, bool isVarArg,
2186                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2187                                    SDLoc dl, SelectionDAG &DAG,
2188                                    SmallVectorImpl<SDValue> &InVals) const {
2189
2190   // Assign locations to each value returned by this call.
2191   SmallVector<CCValAssign, 16> RVLocs;
2192   bool Is64Bit = Subtarget->is64Bit();
2193   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2194                  *DAG.getContext());
2195   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2196
2197   // Copy all of the result registers out of their specified physreg.
2198   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2199     CCValAssign &VA = RVLocs[i];
2200     EVT CopyVT = VA.getValVT();
2201
2202     // If this is x86-64, and we disabled SSE, we can't return FP values
2203     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2204         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2205       report_fatal_error("SSE register return with SSE disabled");
2206     }
2207
2208     // If we prefer to use the value in xmm registers, copy it out as f80 and
2209     // use a truncate to move it from fp stack reg to xmm reg.
2210     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2211         isScalarFPTypeInSSEReg(VA.getValVT()))
2212       CopyVT = MVT::f80;
2213
2214     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2215                                CopyVT, InFlag).getValue(1);
2216     SDValue Val = Chain.getValue(0);
2217
2218     if (CopyVT != VA.getValVT())
2219       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2220                         // This truncation won't change the value.
2221                         DAG.getIntPtrConstant(1));
2222
2223     InFlag = Chain.getValue(2);
2224     InVals.push_back(Val);
2225   }
2226
2227   return Chain;
2228 }
2229
2230 //===----------------------------------------------------------------------===//
2231 //                C & StdCall & Fast Calling Convention implementation
2232 //===----------------------------------------------------------------------===//
2233 //  StdCall calling convention seems to be standard for many Windows' API
2234 //  routines and around. It differs from C calling convention just a little:
2235 //  callee should clean up the stack, not caller. Symbols should be also
2236 //  decorated in some fancy way :) It doesn't support any vector arguments.
2237 //  For info on fast calling convention see Fast Calling Convention (tail call)
2238 //  implementation LowerX86_32FastCCCallTo.
2239
2240 /// CallIsStructReturn - Determines whether a call uses struct return
2241 /// semantics.
2242 enum StructReturnType {
2243   NotStructReturn,
2244   RegStructReturn,
2245   StackStructReturn
2246 };
2247 static StructReturnType
2248 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2249   if (Outs.empty())
2250     return NotStructReturn;
2251
2252   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2253   if (!Flags.isSRet())
2254     return NotStructReturn;
2255   if (Flags.isInReg())
2256     return RegStructReturn;
2257   return StackStructReturn;
2258 }
2259
2260 /// Determines whether a function uses struct return semantics.
2261 static StructReturnType
2262 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2263   if (Ins.empty())
2264     return NotStructReturn;
2265
2266   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2267   if (!Flags.isSRet())
2268     return NotStructReturn;
2269   if (Flags.isInReg())
2270     return RegStructReturn;
2271   return StackStructReturn;
2272 }
2273
2274 /// Make a copy of an aggregate at address specified by "Src" to address
2275 /// "Dst" with size and alignment information specified by the specific
2276 /// parameter attribute. The copy will be passed as a byval function parameter.
2277 static SDValue
2278 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2279                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2280                           SDLoc dl) {
2281   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2282
2283   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2284                        /*isVolatile*/false, /*AlwaysInline=*/true,
2285                        MachinePointerInfo(), MachinePointerInfo());
2286 }
2287
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292           CC == CallingConv::HiPE);
2293 }
2294
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298           CC == CallingConv::X86_64_SysV);
2299 }
2300
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2303     return false;
2304
2305   CallSite CS(CI);
2306   CallingConv::ID CalleeCC = CS.getCallingConv();
2307   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2308     return false;
2309
2310   return true;
2311 }
2312
2313 /// Return true if the function is being made into
2314 /// a tailcall target by changing its ABI.
2315 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2316                                    bool GuaranteedTailCallOpt) {
2317   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2318 }
2319
2320 SDValue
2321 X86TargetLowering::LowerMemArgument(SDValue Chain,
2322                                     CallingConv::ID CallConv,
2323                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2324                                     SDLoc dl, SelectionDAG &DAG,
2325                                     const CCValAssign &VA,
2326                                     MachineFrameInfo *MFI,
2327                                     unsigned i) const {
2328   // Create the nodes corresponding to a load from this parameter slot.
2329   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2330   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2331       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2332   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2333   EVT ValVT;
2334
2335   // If value is passed by pointer we have address passed instead of the value
2336   // itself.
2337   if (VA.getLocInfo() == CCValAssign::Indirect)
2338     ValVT = VA.getLocVT();
2339   else
2340     ValVT = VA.getValVT();
2341
2342   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343   // changed with more analysis.
2344   // In case of tail call optimization mark all arguments mutable. Since they
2345   // could be overwritten by lowering of arguments in case of a tail call.
2346   if (Flags.isByVal()) {
2347     unsigned Bytes = Flags.getByValSize();
2348     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350     return DAG.getFrameIndex(FI, getPointerTy());
2351   } else {
2352     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353                                     VA.getLocMemOffset(), isImmutable);
2354     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355     return DAG.getLoad(ValVT, dl, Chain, FIN,
2356                        MachinePointerInfo::getFixedStack(FI),
2357                        false, false, false, 0);
2358   }
2359 }
2360
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2363                                                 const X86Subtarget *Subtarget) {
2364   assert(Subtarget->is64Bit());
2365
2366   if (Subtarget->isCallingConvWin64(CallConv)) {
2367     static const MCPhysReg GPR64ArgRegsWin64[] = {
2368       X86::RCX, X86::RDX, X86::R8,  X86::R9
2369     };
2370     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2371   }
2372
2373   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2374     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2375   };
2376   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2377 }
2378
2379 // FIXME: Get this from tablegen.
2380 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2381                                                 CallingConv::ID CallConv,
2382                                                 const X86Subtarget *Subtarget) {
2383   assert(Subtarget->is64Bit());
2384   if (Subtarget->isCallingConvWin64(CallConv)) {
2385     // The XMM registers which might contain var arg parameters are shadowed
2386     // in their paired GPR.  So we only need to save the GPR to their home
2387     // slots.
2388     // TODO: __vectorcall will change this.
2389     return None;
2390   }
2391
2392   const Function *Fn = MF.getFunction();
2393   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2394   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2395          "SSE register cannot be used when SSE is disabled!");
2396   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397       !Subtarget->hasSSE1())
2398     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2399     // registers.
2400     return None;
2401
2402   static const MCPhysReg XMMArgRegs64Bit[] = {
2403     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2404     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2405   };
2406   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2407 }
2408
2409 SDValue
2410 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2411                                         CallingConv::ID CallConv,
2412                                         bool isVarArg,
2413                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2414                                         SDLoc dl,
2415                                         SelectionDAG &DAG,
2416                                         SmallVectorImpl<SDValue> &InVals)
2417                                           const {
2418   MachineFunction &MF = DAG.getMachineFunction();
2419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2420
2421   const Function* Fn = MF.getFunction();
2422   if (Fn->hasExternalLinkage() &&
2423       Subtarget->isTargetCygMing() &&
2424       Fn->getName() == "main")
2425     FuncInfo->setForceFramePointer(true);
2426
2427   MachineFrameInfo *MFI = MF.getFrameInfo();
2428   bool Is64Bit = Subtarget->is64Bit();
2429   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2430
2431   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2432          "Var args not supported with calling convention fastcc, ghc or hipe");
2433
2434   // Assign locations to all of the incoming arguments.
2435   SmallVector<CCValAssign, 16> ArgLocs;
2436   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2437
2438   // Allocate shadow area for Win64
2439   if (IsWin64)
2440     CCInfo.AllocateStack(32, 8);
2441
2442   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2443
2444   unsigned LastVal = ~0U;
2445   SDValue ArgValue;
2446   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447     CCValAssign &VA = ArgLocs[i];
2448     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2449     // places.
2450     assert(VA.getValNo() != LastVal &&
2451            "Don't support value assigned to multiple locs yet");
2452     (void)LastVal;
2453     LastVal = VA.getValNo();
2454
2455     if (VA.isRegLoc()) {
2456       EVT RegVT = VA.getLocVT();
2457       const TargetRegisterClass *RC;
2458       if (RegVT == MVT::i32)
2459         RC = &X86::GR32RegClass;
2460       else if (Is64Bit && RegVT == MVT::i64)
2461         RC = &X86::GR64RegClass;
2462       else if (RegVT == MVT::f32)
2463         RC = &X86::FR32RegClass;
2464       else if (RegVT == MVT::f64)
2465         RC = &X86::FR64RegClass;
2466       else if (RegVT.is512BitVector())
2467         RC = &X86::VR512RegClass;
2468       else if (RegVT.is256BitVector())
2469         RC = &X86::VR256RegClass;
2470       else if (RegVT.is128BitVector())
2471         RC = &X86::VR128RegClass;
2472       else if (RegVT == MVT::x86mmx)
2473         RC = &X86::VR64RegClass;
2474       else if (RegVT == MVT::i1)
2475         RC = &X86::VK1RegClass;
2476       else if (RegVT == MVT::v8i1)
2477         RC = &X86::VK8RegClass;
2478       else if (RegVT == MVT::v16i1)
2479         RC = &X86::VK16RegClass;
2480       else if (RegVT == MVT::v32i1)
2481         RC = &X86::VK32RegClass;
2482       else if (RegVT == MVT::v64i1)
2483         RC = &X86::VK64RegClass;
2484       else
2485         llvm_unreachable("Unknown argument type!");
2486
2487       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2488       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2489
2490       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2491       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2492       // right size.
2493       if (VA.getLocInfo() == CCValAssign::SExt)
2494         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2495                                DAG.getValueType(VA.getValVT()));
2496       else if (VA.getLocInfo() == CCValAssign::ZExt)
2497         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2498                                DAG.getValueType(VA.getValVT()));
2499       else if (VA.getLocInfo() == CCValAssign::BCvt)
2500         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2501
2502       if (VA.isExtInLoc()) {
2503         // Handle MMX values passed in XMM regs.
2504         if (RegVT.isVector())
2505           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2506         else
2507           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2508       }
2509     } else {
2510       assert(VA.isMemLoc());
2511       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2512     }
2513
2514     // If value is passed via pointer - do a load.
2515     if (VA.getLocInfo() == CCValAssign::Indirect)
2516       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2517                              MachinePointerInfo(), false, false, false, 0);
2518
2519     InVals.push_back(ArgValue);
2520   }
2521
2522   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2523     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524       // The x86-64 ABIs require that for returning structs by value we copy
2525       // the sret argument into %rax/%eax (depending on ABI) for the return.
2526       // Win32 requires us to put the sret argument to %eax as well.
2527       // Save the argument into a virtual register so that we can access it
2528       // from the return points.
2529       if (Ins[i].Flags.isSRet()) {
2530         unsigned Reg = FuncInfo->getSRetReturnReg();
2531         if (!Reg) {
2532           MVT PtrTy = getPointerTy();
2533           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2534           FuncInfo->setSRetReturnReg(Reg);
2535         }
2536         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2537         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2538         break;
2539       }
2540     }
2541   }
2542
2543   unsigned StackSize = CCInfo.getNextStackOffset();
2544   // Align stack specially for tail calls.
2545   if (FuncIsMadeTailCallSafe(CallConv,
2546                              MF.getTarget().Options.GuaranteedTailCallOpt))
2547     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2548
2549   // If the function takes variable number of arguments, make a frame index for
2550   // the start of the first vararg value... for expansion of llvm.va_start. We
2551   // can skip this if there are no va_start calls.
2552   if (MFI->hasVAStart() &&
2553       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554                    CallConv != CallingConv::X86_ThisCall))) {
2555     FuncInfo->setVarArgsFrameIndex(
2556         MFI->CreateFixedObject(1, StackSize, true));
2557   }
2558
2559   // Figure out if XMM registers are in use.
2560   assert(!(MF.getTarget().Options.UseSoftFloat &&
2561            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2562          "SSE register cannot be used when SSE is disabled!");
2563
2564   // 64-bit calling conventions support varargs and register parameters, so we
2565   // have to do extra work to spill them in the prologue.
2566   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2567     // Find the first unallocated argument registers.
2568     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2569     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2570     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2571     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2572     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2573            "SSE register cannot be used when SSE is disabled!");
2574
2575     // Gather all the live in physical registers.
2576     SmallVector<SDValue, 6> LiveGPRs;
2577     SmallVector<SDValue, 8> LiveXMMRegs;
2578     SDValue ALVal;
2579     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2580       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2581       LiveGPRs.push_back(
2582           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2583     }
2584     if (!ArgXMMs.empty()) {
2585       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2586       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2587       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2588         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2589         LiveXMMRegs.push_back(
2590             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2591       }
2592     }
2593
2594     if (IsWin64) {
2595       const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2596       // Get to the caller-allocated home save location.  Add 8 to account
2597       // for the return address.
2598       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2599       FuncInfo->setRegSaveFrameIndex(
2600           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2601       // Fixup to set vararg frame on shadow area (4 x i64).
2602       if (NumIntRegs < 4)
2603         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2604     } else {
2605       // For X86-64, if there are vararg parameters that are passed via
2606       // registers, then we must store them to their spots on the stack so
2607       // they may be loaded by deferencing the result of va_next.
2608       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2609       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2610       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2611           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2612     }
2613
2614     // Store the integer parameter registers.
2615     SmallVector<SDValue, 8> MemOps;
2616     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2617                                       getPointerTy());
2618     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2619     for (SDValue Val : LiveGPRs) {
2620       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2621                                 DAG.getIntPtrConstant(Offset));
2622       SDValue Store =
2623         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2624                      MachinePointerInfo::getFixedStack(
2625                        FuncInfo->getRegSaveFrameIndex(), Offset),
2626                      false, false, 0);
2627       MemOps.push_back(Store);
2628       Offset += 8;
2629     }
2630
2631     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2632       // Now store the XMM (fp + vector) parameter registers.
2633       SmallVector<SDValue, 12> SaveXMMOps;
2634       SaveXMMOps.push_back(Chain);
2635       SaveXMMOps.push_back(ALVal);
2636       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2637                              FuncInfo->getRegSaveFrameIndex()));
2638       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2639                              FuncInfo->getVarArgsFPOffset()));
2640       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2641                         LiveXMMRegs.end());
2642       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2643                                    MVT::Other, SaveXMMOps));
2644     }
2645
2646     if (!MemOps.empty())
2647       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2648   }
2649
2650   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2651     // Find the largest legal vector type.
2652     MVT VecVT = MVT::Other;
2653     // FIXME: Only some x86_32 calling conventions support AVX512.
2654     if (Subtarget->hasAVX512() &&
2655         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2656                      CallConv == CallingConv::Intel_OCL_BI)))
2657       VecVT = MVT::v16f32;
2658     else if (Subtarget->hasAVX())
2659       VecVT = MVT::v8f32;
2660     else if (Subtarget->hasSSE2())
2661       VecVT = MVT::v4f32;
2662
2663     // We forward some GPRs and some vector types.
2664     SmallVector<MVT, 2> RegParmTypes;
2665     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2666     RegParmTypes.push_back(IntVT);
2667     if (VecVT != MVT::Other)
2668       RegParmTypes.push_back(VecVT);
2669
2670     // Compute the set of forwarded registers. The rest are scratch.
2671     SmallVectorImpl<ForwardedRegister> &Forwards =
2672         FuncInfo->getForwardedMustTailRegParms();
2673     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2674
2675     // Conservatively forward AL on x86_64, since it might be used for varargs.
2676     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2677       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2678       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2679     }
2680
2681     // Copy all forwards from physical to virtual registers.
2682     for (ForwardedRegister &F : Forwards) {
2683       // FIXME: Can we use a less constrained schedule?
2684       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2685       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2686       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2687     }
2688   }
2689
2690   // Some CCs need callee pop.
2691   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2693     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2694   } else {
2695     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2696     // If this is an sret function, the return should pop the hidden pointer.
2697     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2698         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2699         argsAreStructReturn(Ins) == StackStructReturn)
2700       FuncInfo->setBytesToPopOnReturn(4);
2701   }
2702
2703   if (!Is64Bit) {
2704     // RegSaveFrameIndex is X86-64 only.
2705     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2706     if (CallConv == CallingConv::X86_FastCall ||
2707         CallConv == CallingConv::X86_ThisCall)
2708       // fastcc functions can't have varargs.
2709       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2710   }
2711
2712   FuncInfo->setArgumentStackSize(StackSize);
2713
2714   return Chain;
2715 }
2716
2717 SDValue
2718 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2719                                     SDValue StackPtr, SDValue Arg,
2720                                     SDLoc dl, SelectionDAG &DAG,
2721                                     const CCValAssign &VA,
2722                                     ISD::ArgFlagsTy Flags) const {
2723   unsigned LocMemOffset = VA.getLocMemOffset();
2724   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2725   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2726   if (Flags.isByVal())
2727     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2728
2729   return DAG.getStore(Chain, dl, Arg, PtrOff,
2730                       MachinePointerInfo::getStack(LocMemOffset),
2731                       false, false, 0);
2732 }
2733
2734 /// Emit a load of return address if tail call
2735 /// optimization is performed and it is required.
2736 SDValue
2737 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2738                                            SDValue &OutRetAddr, SDValue Chain,
2739                                            bool IsTailCall, bool Is64Bit,
2740                                            int FPDiff, SDLoc dl) const {
2741   // Adjust the Return address stack slot.
2742   EVT VT = getPointerTy();
2743   OutRetAddr = getReturnAddressFrameIndex(DAG);
2744
2745   // Load the "old" Return address.
2746   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2747                            false, false, false, 0);
2748   return SDValue(OutRetAddr.getNode(), 1);
2749 }
2750
2751 /// Emit a store of the return address if tail call
2752 /// optimization is performed and it is required (FPDiff!=0).
2753 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2754                                         SDValue Chain, SDValue RetAddrFrIdx,
2755                                         EVT PtrVT, unsigned SlotSize,
2756                                         int FPDiff, SDLoc dl) {
2757   // Store the return address to the appropriate stack slot.
2758   if (!FPDiff) return Chain;
2759   // Calculate the new stack slot for the return address.
2760   int NewReturnAddrFI =
2761     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2762                                          false);
2763   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2764   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2765                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2766                        false, false, 0);
2767   return Chain;
2768 }
2769
2770 SDValue
2771 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2772                              SmallVectorImpl<SDValue> &InVals) const {
2773   SelectionDAG &DAG                     = CLI.DAG;
2774   SDLoc &dl                             = CLI.DL;
2775   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2776   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2777   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2778   SDValue Chain                         = CLI.Chain;
2779   SDValue Callee                        = CLI.Callee;
2780   CallingConv::ID CallConv              = CLI.CallConv;
2781   bool &isTailCall                      = CLI.IsTailCall;
2782   bool isVarArg                         = CLI.IsVarArg;
2783
2784   MachineFunction &MF = DAG.getMachineFunction();
2785   bool Is64Bit        = Subtarget->is64Bit();
2786   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2787   StructReturnType SR = callIsStructReturn(Outs);
2788   bool IsSibcall      = false;
2789   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2790
2791   if (MF.getTarget().Options.DisableTailCalls)
2792     isTailCall = false;
2793
2794   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2795   if (IsMustTail) {
2796     // Force this to be a tail call.  The verifier rules are enough to ensure
2797     // that we can lower this successfully without moving the return address
2798     // around.
2799     isTailCall = true;
2800   } else if (isTailCall) {
2801     // Check if it's really possible to do a tail call.
2802     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2803                     isVarArg, SR != NotStructReturn,
2804                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2805                     Outs, OutVals, Ins, DAG);
2806
2807     // Sibcalls are automatically detected tailcalls which do not require
2808     // ABI changes.
2809     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2810       IsSibcall = true;
2811
2812     if (isTailCall)
2813       ++NumTailCalls;
2814   }
2815
2816   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2817          "Var args not supported with calling convention fastcc, ghc or hipe");
2818
2819   // Analyze operands of the call, assigning locations to each operand.
2820   SmallVector<CCValAssign, 16> ArgLocs;
2821   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2822
2823   // Allocate shadow area for Win64
2824   if (IsWin64)
2825     CCInfo.AllocateStack(32, 8);
2826
2827   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2828
2829   // Get a count of how many bytes are to be pushed on the stack.
2830   unsigned NumBytes = CCInfo.getNextStackOffset();
2831   if (IsSibcall)
2832     // This is a sibcall. The memory operands are available in caller's
2833     // own caller's stack.
2834     NumBytes = 0;
2835   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2836            IsTailCallConvention(CallConv))
2837     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2838
2839   int FPDiff = 0;
2840   if (isTailCall && !IsSibcall && !IsMustTail) {
2841     // Lower arguments at fp - stackoffset + fpdiff.
2842     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2843
2844     FPDiff = NumBytesCallerPushed - NumBytes;
2845
2846     // Set the delta of movement of the returnaddr stackslot.
2847     // But only set if delta is greater than previous delta.
2848     if (FPDiff < X86Info->getTCReturnAddrDelta())
2849       X86Info->setTCReturnAddrDelta(FPDiff);
2850   }
2851
2852   unsigned NumBytesToPush = NumBytes;
2853   unsigned NumBytesToPop = NumBytes;
2854
2855   // If we have an inalloca argument, all stack space has already been allocated
2856   // for us and be right at the top of the stack.  We don't support multiple
2857   // arguments passed in memory when using inalloca.
2858   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2859     NumBytesToPush = 0;
2860     if (!ArgLocs.back().isMemLoc())
2861       report_fatal_error("cannot use inalloca attribute on a register "
2862                          "parameter");
2863     if (ArgLocs.back().getLocMemOffset() != 0)
2864       report_fatal_error("any parameter with the inalloca attribute must be "
2865                          "the only memory argument");
2866   }
2867
2868   if (!IsSibcall)
2869     Chain = DAG.getCALLSEQ_START(
2870         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2871
2872   SDValue RetAddrFrIdx;
2873   // Load return address for tail calls.
2874   if (isTailCall && FPDiff)
2875     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2876                                     Is64Bit, FPDiff, dl);
2877
2878   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2879   SmallVector<SDValue, 8> MemOpChains;
2880   SDValue StackPtr;
2881
2882   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2883   // of tail call optimization arguments are handle later.
2884   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2885   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886     // Skip inalloca arguments, they have already been written.
2887     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888     if (Flags.isInAlloca())
2889       continue;
2890
2891     CCValAssign &VA = ArgLocs[i];
2892     EVT RegVT = VA.getLocVT();
2893     SDValue Arg = OutVals[i];
2894     bool isByVal = Flags.isByVal();
2895
2896     // Promote the value if needed.
2897     switch (VA.getLocInfo()) {
2898     default: llvm_unreachable("Unknown loc info!");
2899     case CCValAssign::Full: break;
2900     case CCValAssign::SExt:
2901       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2902       break;
2903     case CCValAssign::ZExt:
2904       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2905       break;
2906     case CCValAssign::AExt:
2907       if (RegVT.is128BitVector()) {
2908         // Special case: passing MMX values in XMM registers.
2909         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2910         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2911         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2912       } else
2913         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2914       break;
2915     case CCValAssign::BCvt:
2916       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2917       break;
2918     case CCValAssign::Indirect: {
2919       // Store the argument.
2920       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2921       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2922       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2923                            MachinePointerInfo::getFixedStack(FI),
2924                            false, false, 0);
2925       Arg = SpillSlot;
2926       break;
2927     }
2928     }
2929
2930     if (VA.isRegLoc()) {
2931       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2932       if (isVarArg && IsWin64) {
2933         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2934         // shadow reg if callee is a varargs function.
2935         unsigned ShadowReg = 0;
2936         switch (VA.getLocReg()) {
2937         case X86::XMM0: ShadowReg = X86::RCX; break;
2938         case X86::XMM1: ShadowReg = X86::RDX; break;
2939         case X86::XMM2: ShadowReg = X86::R8; break;
2940         case X86::XMM3: ShadowReg = X86::R9; break;
2941         }
2942         if (ShadowReg)
2943           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2944       }
2945     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2946       assert(VA.isMemLoc());
2947       if (!StackPtr.getNode())
2948         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2949                                       getPointerTy());
2950       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2951                                              dl, DAG, VA, Flags));
2952     }
2953   }
2954
2955   if (!MemOpChains.empty())
2956     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2957
2958   if (Subtarget->isPICStyleGOT()) {
2959     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2960     // GOT pointer.
2961     if (!isTailCall) {
2962       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2963                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2964     } else {
2965       // If we are tail calling and generating PIC/GOT style code load the
2966       // address of the callee into ECX. The value in ecx is used as target of
2967       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2968       // for tail calls on PIC/GOT architectures. Normally we would just put the
2969       // address of GOT into ebx and then call target@PLT. But for tail calls
2970       // ebx would be restored (since ebx is callee saved) before jumping to the
2971       // target@PLT.
2972
2973       // Note: The actual moving to ECX is done further down.
2974       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2975       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2976           !G->getGlobal()->hasProtectedVisibility())
2977         Callee = LowerGlobalAddress(Callee, DAG);
2978       else if (isa<ExternalSymbolSDNode>(Callee))
2979         Callee = LowerExternalSymbol(Callee, DAG);
2980     }
2981   }
2982
2983   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2984     // From AMD64 ABI document:
2985     // For calls that may call functions that use varargs or stdargs
2986     // (prototype-less calls or calls to functions containing ellipsis (...) in
2987     // the declaration) %al is used as hidden argument to specify the number
2988     // of SSE registers used. The contents of %al do not need to match exactly
2989     // the number of registers, but must be an ubound on the number of SSE
2990     // registers used and is in the range 0 - 8 inclusive.
2991
2992     // Count the number of XMM registers allocated.
2993     static const MCPhysReg XMMArgRegs[] = {
2994       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2995       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2996     };
2997     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2998     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2999            && "SSE registers cannot be used when SSE is disabled");
3000
3001     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3002                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
3003   }
3004
3005   if (isVarArg && IsMustTail) {
3006     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3007     for (const auto &F : Forwards) {
3008       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3009       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3010     }
3011   }
3012
3013   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3014   // don't need this because the eligibility check rejects calls that require
3015   // shuffling arguments passed in memory.
3016   if (!IsSibcall && isTailCall) {
3017     // Force all the incoming stack arguments to be loaded from the stack
3018     // before any new outgoing arguments are stored to the stack, because the
3019     // outgoing stack slots may alias the incoming argument stack slots, and
3020     // the alias isn't otherwise explicit. This is slightly more conservative
3021     // than necessary, because it means that each store effectively depends
3022     // on every argument instead of just those arguments it would clobber.
3023     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3024
3025     SmallVector<SDValue, 8> MemOpChains2;
3026     SDValue FIN;
3027     int FI = 0;
3028     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3029       CCValAssign &VA = ArgLocs[i];
3030       if (VA.isRegLoc())
3031         continue;
3032       assert(VA.isMemLoc());
3033       SDValue Arg = OutVals[i];
3034       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3035       // Skip inalloca arguments.  They don't require any work.
3036       if (Flags.isInAlloca())
3037         continue;
3038       // Create frame index.
3039       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3040       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3041       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3042       FIN = DAG.getFrameIndex(FI, getPointerTy());
3043
3044       if (Flags.isByVal()) {
3045         // Copy relative to framepointer.
3046         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3047         if (!StackPtr.getNode())
3048           StackPtr = DAG.getCopyFromReg(Chain, dl,
3049                                         RegInfo->getStackRegister(),
3050                                         getPointerTy());
3051         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3052
3053         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3054                                                          ArgChain,
3055                                                          Flags, DAG, dl));
3056       } else {
3057         // Store relative to framepointer.
3058         MemOpChains2.push_back(
3059           DAG.getStore(ArgChain, dl, Arg, FIN,
3060                        MachinePointerInfo::getFixedStack(FI),
3061                        false, false, 0));
3062       }
3063     }
3064
3065     if (!MemOpChains2.empty())
3066       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3067
3068     // Store the return address to the appropriate stack slot.
3069     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3070                                      getPointerTy(), RegInfo->getSlotSize(),
3071                                      FPDiff, dl);
3072   }
3073
3074   // Build a sequence of copy-to-reg nodes chained together with token chain
3075   // and flag operands which copy the outgoing args into registers.
3076   SDValue InFlag;
3077   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3078     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3079                              RegsToPass[i].second, InFlag);
3080     InFlag = Chain.getValue(1);
3081   }
3082
3083   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3084     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3085     // In the 64-bit large code model, we have to make all calls
3086     // through a register, since the call instruction's 32-bit
3087     // pc-relative offset may not be large enough to hold the whole
3088     // address.
3089   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3090     // If the callee is a GlobalAddress node (quite common, every direct call
3091     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3092     // it.
3093     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3094
3095     // We should use extra load for direct calls to dllimported functions in
3096     // non-JIT mode.
3097     const GlobalValue *GV = G->getGlobal();
3098     if (!GV->hasDLLImportStorageClass()) {
3099       unsigned char OpFlags = 0;
3100       bool ExtraLoad = false;
3101       unsigned WrapperKind = ISD::DELETED_NODE;
3102
3103       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3104       // external symbols most go through the PLT in PIC mode.  If the symbol
3105       // has hidden or protected visibility, or if it is static or local, then
3106       // we don't need to use the PLT - we can directly call it.
3107       if (Subtarget->isTargetELF() &&
3108           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3109           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3110         OpFlags = X86II::MO_PLT;
3111       } else if (Subtarget->isPICStyleStubAny() &&
3112                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3113                  (!Subtarget->getTargetTriple().isMacOSX() ||
3114                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115         // PC-relative references to external symbols should go through $stub,
3116         // unless we're building with the leopard linker or later, which
3117         // automatically synthesizes these stubs.
3118         OpFlags = X86II::MO_DARWIN_STUB;
3119       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3120                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3121         // If the function is marked as non-lazy, generate an indirect call
3122         // which loads from the GOT directly. This avoids runtime overhead
3123         // at the cost of eager binding (and one extra byte of encoding).
3124         OpFlags = X86II::MO_GOTPCREL;
3125         WrapperKind = X86ISD::WrapperRIP;
3126         ExtraLoad = true;
3127       }
3128
3129       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3130                                           G->getOffset(), OpFlags);
3131
3132       // Add a wrapper if needed.
3133       if (WrapperKind != ISD::DELETED_NODE)
3134         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3135       // Add extra indirection if needed.
3136       if (ExtraLoad)
3137         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3138                              MachinePointerInfo::getGOT(),
3139                              false, false, false, 0);
3140     }
3141   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3142     unsigned char OpFlags = 0;
3143
3144     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3145     // external symbols should go through the PLT.
3146     if (Subtarget->isTargetELF() &&
3147         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3148       OpFlags = X86II::MO_PLT;
3149     } else if (Subtarget->isPICStyleStubAny() &&
3150                (!Subtarget->getTargetTriple().isMacOSX() ||
3151                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3152       // PC-relative references to external symbols should go through $stub,
3153       // unless we're building with the leopard linker or later, which
3154       // automatically synthesizes these stubs.
3155       OpFlags = X86II::MO_DARWIN_STUB;
3156     }
3157
3158     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3159                                          OpFlags);
3160   } else if (Subtarget->isTarget64BitILP32() &&
3161              Callee->getValueType(0) == MVT::i32) {
3162     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3163     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3164   }
3165
3166   // Returns a chain & a flag for retval copy to use.
3167   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3168   SmallVector<SDValue, 8> Ops;
3169
3170   if (!IsSibcall && isTailCall) {
3171     Chain = DAG.getCALLSEQ_END(Chain,
3172                                DAG.getIntPtrConstant(NumBytesToPop, true),
3173                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3174     InFlag = Chain.getValue(1);
3175   }
3176
3177   Ops.push_back(Chain);
3178   Ops.push_back(Callee);
3179
3180   if (isTailCall)
3181     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3182
3183   // Add argument registers to the end of the list so that they are known live
3184   // into the call.
3185   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3186     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3187                                   RegsToPass[i].second.getValueType()));
3188
3189   // Add a register mask operand representing the call-preserved registers.
3190   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3191   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3192   assert(Mask && "Missing call preserved mask for calling convention");
3193   Ops.push_back(DAG.getRegisterMask(Mask));
3194
3195   if (InFlag.getNode())
3196     Ops.push_back(InFlag);
3197
3198   if (isTailCall) {
3199     // We used to do:
3200     //// If this is the first return lowered for this function, add the regs
3201     //// to the liveout set for the function.
3202     // This isn't right, although it's probably harmless on x86; liveouts
3203     // should be computed from returns not tail calls.  Consider a void
3204     // function making a tail call to a function returning int.
3205     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3206   }
3207
3208   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3209   InFlag = Chain.getValue(1);
3210
3211   // Create the CALLSEQ_END node.
3212   unsigned NumBytesForCalleeToPop;
3213   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3214                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3215     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3216   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3217            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3218            SR == StackStructReturn)
3219     // If this is a call to a struct-return function, the callee
3220     // pops the hidden struct pointer, so we have to push it back.
3221     // This is common for Darwin/X86, Linux & Mingw32 targets.
3222     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3223     NumBytesForCalleeToPop = 4;
3224   else
3225     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3226
3227   // Returns a flag for retval copy to use.
3228   if (!IsSibcall) {
3229     Chain = DAG.getCALLSEQ_END(Chain,
3230                                DAG.getIntPtrConstant(NumBytesToPop, true),
3231                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3232                                                      true),
3233                                InFlag, dl);
3234     InFlag = Chain.getValue(1);
3235   }
3236
3237   // Handle result values, copying them out of physregs into vregs that we
3238   // return.
3239   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3240                          Ins, dl, DAG, InVals);
3241 }
3242
3243 //===----------------------------------------------------------------------===//
3244 //                Fast Calling Convention (tail call) implementation
3245 //===----------------------------------------------------------------------===//
3246
3247 //  Like std call, callee cleans arguments, convention except that ECX is
3248 //  reserved for storing the tail called function address. Only 2 registers are
3249 //  free for argument passing (inreg). Tail call optimization is performed
3250 //  provided:
3251 //                * tailcallopt is enabled
3252 //                * caller/callee are fastcc
3253 //  On X86_64 architecture with GOT-style position independent code only local
3254 //  (within module) calls are supported at the moment.
3255 //  To keep the stack aligned according to platform abi the function
3256 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3257 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3258 //  If a tail called function callee has more arguments than the caller the
3259 //  caller needs to make sure that there is room to move the RETADDR to. This is
3260 //  achieved by reserving an area the size of the argument delta right after the
3261 //  original RETADDR, but before the saved framepointer or the spilled registers
3262 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3263 //  stack layout:
3264 //    arg1
3265 //    arg2
3266 //    RETADDR
3267 //    [ new RETADDR
3268 //      move area ]
3269 //    (possible EBP)
3270 //    ESI
3271 //    EDI
3272 //    local1 ..
3273
3274 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3275 /// for a 16 byte align requirement.
3276 unsigned
3277 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3278                                                SelectionDAG& DAG) const {
3279   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3280   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3281   unsigned StackAlignment = TFI.getStackAlignment();
3282   uint64_t AlignMask = StackAlignment - 1;
3283   int64_t Offset = StackSize;
3284   unsigned SlotSize = RegInfo->getSlotSize();
3285   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3286     // Number smaller than 12 so just add the difference.
3287     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3288   } else {
3289     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3290     Offset = ((~AlignMask) & Offset) + StackAlignment +
3291       (StackAlignment-SlotSize);
3292   }
3293   return Offset;
3294 }
3295
3296 /// MatchingStackOffset - Return true if the given stack call argument is
3297 /// already available in the same position (relatively) of the caller's
3298 /// incoming argument stack.
3299 static
3300 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3301                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3302                          const X86InstrInfo *TII) {
3303   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3304   int FI = INT_MAX;
3305   if (Arg.getOpcode() == ISD::CopyFromReg) {
3306     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3307     if (!TargetRegisterInfo::isVirtualRegister(VR))
3308       return false;
3309     MachineInstr *Def = MRI->getVRegDef(VR);
3310     if (!Def)
3311       return false;
3312     if (!Flags.isByVal()) {
3313       if (!TII->isLoadFromStackSlot(Def, FI))
3314         return false;
3315     } else {
3316       unsigned Opcode = Def->getOpcode();
3317       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3318            Opcode == X86::LEA64_32r) &&
3319           Def->getOperand(1).isFI()) {
3320         FI = Def->getOperand(1).getIndex();
3321         Bytes = Flags.getByValSize();
3322       } else
3323         return false;
3324     }
3325   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3326     if (Flags.isByVal())
3327       // ByVal argument is passed in as a pointer but it's now being
3328       // dereferenced. e.g.
3329       // define @foo(%struct.X* %A) {
3330       //   tail call @bar(%struct.X* byval %A)
3331       // }
3332       return false;
3333     SDValue Ptr = Ld->getBasePtr();
3334     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3335     if (!FINode)
3336       return false;
3337     FI = FINode->getIndex();
3338   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3339     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3340     FI = FINode->getIndex();
3341     Bytes = Flags.getByValSize();
3342   } else
3343     return false;
3344
3345   assert(FI != INT_MAX);
3346   if (!MFI->isFixedObjectIndex(FI))
3347     return false;
3348   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3349 }
3350
3351 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3352 /// for tail call optimization. Targets which want to do tail call
3353 /// optimization should implement this function.
3354 bool
3355 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3356                                                      CallingConv::ID CalleeCC,
3357                                                      bool isVarArg,
3358                                                      bool isCalleeStructRet,
3359                                                      bool isCallerStructRet,
3360                                                      Type *RetTy,
3361                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3362                                     const SmallVectorImpl<SDValue> &OutVals,
3363                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3364                                                      SelectionDAG &DAG) const {
3365   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3366     return false;
3367
3368   // If -tailcallopt is specified, make fastcc functions tail-callable.
3369   const MachineFunction &MF = DAG.getMachineFunction();
3370   const Function *CallerF = MF.getFunction();
3371
3372   // If the function return type is x86_fp80 and the callee return type is not,
3373   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3374   // perform a tailcall optimization here.
3375   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3376     return false;
3377
3378   CallingConv::ID CallerCC = CallerF->getCallingConv();
3379   bool CCMatch = CallerCC == CalleeCC;
3380   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3381   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3382
3383   // Win64 functions have extra shadow space for argument homing. Don't do the
3384   // sibcall if the caller and callee have mismatched expectations for this
3385   // space.
3386   if (IsCalleeWin64 != IsCallerWin64)
3387     return false;
3388
3389   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3390     if (IsTailCallConvention(CalleeCC) && CCMatch)
3391       return true;
3392     return false;
3393   }
3394
3395   // Look for obvious safe cases to perform tail call optimization that do not
3396   // require ABI changes. This is what gcc calls sibcall.
3397
3398   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3399   // emit a special epilogue.
3400   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3401   if (RegInfo->needsStackRealignment(MF))
3402     return false;
3403
3404   // Also avoid sibcall optimization if either caller or callee uses struct
3405   // return semantics.
3406   if (isCalleeStructRet || isCallerStructRet)
3407     return false;
3408
3409   // An stdcall/thiscall caller is expected to clean up its arguments; the
3410   // callee isn't going to do that.
3411   // FIXME: this is more restrictive than needed. We could produce a tailcall
3412   // when the stack adjustment matches. For example, with a thiscall that takes
3413   // only one argument.
3414   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3415                    CallerCC == CallingConv::X86_ThisCall))
3416     return false;
3417
3418   // Do not sibcall optimize vararg calls unless all arguments are passed via
3419   // registers.
3420   if (isVarArg && !Outs.empty()) {
3421
3422     // Optimizing for varargs on Win64 is unlikely to be safe without
3423     // additional testing.
3424     if (IsCalleeWin64 || IsCallerWin64)
3425       return false;
3426
3427     SmallVector<CCValAssign, 16> ArgLocs;
3428     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3429                    *DAG.getContext());
3430
3431     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3432     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3433       if (!ArgLocs[i].isRegLoc())
3434         return false;
3435   }
3436
3437   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3438   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3439   // this into a sibcall.
3440   bool Unused = false;
3441   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3442     if (!Ins[i].Used) {
3443       Unused = true;
3444       break;
3445     }
3446   }
3447   if (Unused) {
3448     SmallVector<CCValAssign, 16> RVLocs;
3449     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3450                    *DAG.getContext());
3451     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3452     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3453       CCValAssign &VA = RVLocs[i];
3454       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3455         return false;
3456     }
3457   }
3458
3459   // If the calling conventions do not match, then we'd better make sure the
3460   // results are returned in the same way as what the caller expects.
3461   if (!CCMatch) {
3462     SmallVector<CCValAssign, 16> RVLocs1;
3463     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3464                     *DAG.getContext());
3465     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3466
3467     SmallVector<CCValAssign, 16> RVLocs2;
3468     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3469                     *DAG.getContext());
3470     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3471
3472     if (RVLocs1.size() != RVLocs2.size())
3473       return false;
3474     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3475       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3476         return false;
3477       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3478         return false;
3479       if (RVLocs1[i].isRegLoc()) {
3480         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3481           return false;
3482       } else {
3483         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3484           return false;
3485       }
3486     }
3487   }
3488
3489   // If the callee takes no arguments then go on to check the results of the
3490   // call.
3491   if (!Outs.empty()) {
3492     // Check if stack adjustment is needed. For now, do not do this if any
3493     // argument is passed on the stack.
3494     SmallVector<CCValAssign, 16> ArgLocs;
3495     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3496                    *DAG.getContext());
3497
3498     // Allocate shadow area for Win64
3499     if (IsCalleeWin64)
3500       CCInfo.AllocateStack(32, 8);
3501
3502     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3503     if (CCInfo.getNextStackOffset()) {
3504       MachineFunction &MF = DAG.getMachineFunction();
3505       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3506         return false;
3507
3508       // Check if the arguments are already laid out in the right way as
3509       // the caller's fixed stack objects.
3510       MachineFrameInfo *MFI = MF.getFrameInfo();
3511       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3512       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3513       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3514         CCValAssign &VA = ArgLocs[i];
3515         SDValue Arg = OutVals[i];
3516         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3517         if (VA.getLocInfo() == CCValAssign::Indirect)
3518           return false;
3519         if (!VA.isRegLoc()) {
3520           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3521                                    MFI, MRI, TII))
3522             return false;
3523         }
3524       }
3525     }
3526
3527     // If the tailcall address may be in a register, then make sure it's
3528     // possible to register allocate for it. In 32-bit, the call address can
3529     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3530     // callee-saved registers are restored. These happen to be the same
3531     // registers used to pass 'inreg' arguments so watch out for those.
3532     if (!Subtarget->is64Bit() &&
3533         ((!isa<GlobalAddressSDNode>(Callee) &&
3534           !isa<ExternalSymbolSDNode>(Callee)) ||
3535          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3536       unsigned NumInRegs = 0;
3537       // In PIC we need an extra register to formulate the address computation
3538       // for the callee.
3539       unsigned MaxInRegs =
3540         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3541
3542       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3543         CCValAssign &VA = ArgLocs[i];
3544         if (!VA.isRegLoc())
3545           continue;
3546         unsigned Reg = VA.getLocReg();
3547         switch (Reg) {
3548         default: break;
3549         case X86::EAX: case X86::EDX: case X86::ECX:
3550           if (++NumInRegs == MaxInRegs)
3551             return false;
3552           break;
3553         }
3554       }
3555     }
3556   }
3557
3558   return true;
3559 }
3560
3561 FastISel *
3562 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3563                                   const TargetLibraryInfo *libInfo) const {
3564   return X86::createFastISel(funcInfo, libInfo);
3565 }
3566
3567 //===----------------------------------------------------------------------===//
3568 //                           Other Lowering Hooks
3569 //===----------------------------------------------------------------------===//
3570
3571 static bool MayFoldLoad(SDValue Op) {
3572   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3573 }
3574
3575 static bool MayFoldIntoStore(SDValue Op) {
3576   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3577 }
3578
3579 static bool isTargetShuffle(unsigned Opcode) {
3580   switch(Opcode) {
3581   default: return false;
3582   case X86ISD::BLENDI:
3583   case X86ISD::PSHUFB:
3584   case X86ISD::PSHUFD:
3585   case X86ISD::PSHUFHW:
3586   case X86ISD::PSHUFLW:
3587   case X86ISD::SHUFP:
3588   case X86ISD::PALIGNR:
3589   case X86ISD::MOVLHPS:
3590   case X86ISD::MOVLHPD:
3591   case X86ISD::MOVHLPS:
3592   case X86ISD::MOVLPS:
3593   case X86ISD::MOVLPD:
3594   case X86ISD::MOVSHDUP:
3595   case X86ISD::MOVSLDUP:
3596   case X86ISD::MOVDDUP:
3597   case X86ISD::MOVSS:
3598   case X86ISD::MOVSD:
3599   case X86ISD::UNPCKL:
3600   case X86ISD::UNPCKH:
3601   case X86ISD::VPERMILPI:
3602   case X86ISD::VPERM2X128:
3603   case X86ISD::VPERMI:
3604     return true;
3605   }
3606 }
3607
3608 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3609                                     SDValue V1, unsigned TargetMask,
3610                                     SelectionDAG &DAG) {
3611   switch(Opc) {
3612   default: llvm_unreachable("Unknown x86 shuffle node");
3613   case X86ISD::PSHUFD:
3614   case X86ISD::PSHUFHW:
3615   case X86ISD::PSHUFLW:
3616   case X86ISD::VPERMILPI:
3617   case X86ISD::VPERMI:
3618     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3619   }
3620 }
3621
3622 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3623                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3624   switch(Opc) {
3625   default: llvm_unreachable("Unknown x86 shuffle node");
3626   case X86ISD::MOVLHPS:
3627   case X86ISD::MOVLHPD:
3628   case X86ISD::MOVHLPS:
3629   case X86ISD::MOVLPS:
3630   case X86ISD::MOVLPD:
3631   case X86ISD::MOVSS:
3632   case X86ISD::MOVSD:
3633   case X86ISD::UNPCKL:
3634   case X86ISD::UNPCKH:
3635     return DAG.getNode(Opc, dl, VT, V1, V2);
3636   }
3637 }
3638
3639 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3640   MachineFunction &MF = DAG.getMachineFunction();
3641   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3642   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3643   int ReturnAddrIndex = FuncInfo->getRAIndex();
3644
3645   if (ReturnAddrIndex == 0) {
3646     // Set up a frame object for the return address.
3647     unsigned SlotSize = RegInfo->getSlotSize();
3648     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3649                                                            -(int64_t)SlotSize,
3650                                                            false);
3651     FuncInfo->setRAIndex(ReturnAddrIndex);
3652   }
3653
3654   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3655 }
3656
3657 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3658                                        bool hasSymbolicDisplacement) {
3659   // Offset should fit into 32 bit immediate field.
3660   if (!isInt<32>(Offset))
3661     return false;
3662
3663   // If we don't have a symbolic displacement - we don't have any extra
3664   // restrictions.
3665   if (!hasSymbolicDisplacement)
3666     return true;
3667
3668   // FIXME: Some tweaks might be needed for medium code model.
3669   if (M != CodeModel::Small && M != CodeModel::Kernel)
3670     return false;
3671
3672   // For small code model we assume that latest object is 16MB before end of 31
3673   // bits boundary. We may also accept pretty large negative constants knowing
3674   // that all objects are in the positive half of address space.
3675   if (M == CodeModel::Small && Offset < 16*1024*1024)
3676     return true;
3677
3678   // For kernel code model we know that all object resist in the negative half
3679   // of 32bits address space. We may not accept negative offsets, since they may
3680   // be just off and we may accept pretty large positive ones.
3681   if (M == CodeModel::Kernel && Offset >= 0)
3682     return true;
3683
3684   return false;
3685 }
3686
3687 /// isCalleePop - Determines whether the callee is required to pop its
3688 /// own arguments. Callee pop is necessary to support tail calls.
3689 bool X86::isCalleePop(CallingConv::ID CallingConv,
3690                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3691   switch (CallingConv) {
3692   default:
3693     return false;
3694   case CallingConv::X86_StdCall:
3695   case CallingConv::X86_FastCall:
3696   case CallingConv::X86_ThisCall:
3697     return !is64Bit;
3698   case CallingConv::Fast:
3699   case CallingConv::GHC:
3700   case CallingConv::HiPE:
3701     if (IsVarArg)
3702       return false;
3703     return TailCallOpt;
3704   }
3705 }
3706
3707 /// \brief Return true if the condition is an unsigned comparison operation.
3708 static bool isX86CCUnsigned(unsigned X86CC) {
3709   switch (X86CC) {
3710   default: llvm_unreachable("Invalid integer condition!");
3711   case X86::COND_E:     return true;
3712   case X86::COND_G:     return false;
3713   case X86::COND_GE:    return false;
3714   case X86::COND_L:     return false;
3715   case X86::COND_LE:    return false;
3716   case X86::COND_NE:    return true;
3717   case X86::COND_B:     return true;
3718   case X86::COND_A:     return true;
3719   case X86::COND_BE:    return true;
3720   case X86::COND_AE:    return true;
3721   }
3722   llvm_unreachable("covered switch fell through?!");
3723 }
3724
3725 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3726 /// specific condition code, returning the condition code and the LHS/RHS of the
3727 /// comparison to make.
3728 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3729                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3730   if (!isFP) {
3731     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3732       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3733         // X > -1   -> X == 0, jump !sign.
3734         RHS = DAG.getConstant(0, RHS.getValueType());
3735         return X86::COND_NS;
3736       }
3737       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3738         // X < 0   -> X == 0, jump on sign.
3739         return X86::COND_S;
3740       }
3741       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3742         // X < 1   -> X <= 0
3743         RHS = DAG.getConstant(0, RHS.getValueType());
3744         return X86::COND_LE;
3745       }
3746     }
3747
3748     switch (SetCCOpcode) {
3749     default: llvm_unreachable("Invalid integer condition!");
3750     case ISD::SETEQ:  return X86::COND_E;
3751     case ISD::SETGT:  return X86::COND_G;
3752     case ISD::SETGE:  return X86::COND_GE;
3753     case ISD::SETLT:  return X86::COND_L;
3754     case ISD::SETLE:  return X86::COND_LE;
3755     case ISD::SETNE:  return X86::COND_NE;
3756     case ISD::SETULT: return X86::COND_B;
3757     case ISD::SETUGT: return X86::COND_A;
3758     case ISD::SETULE: return X86::COND_BE;
3759     case ISD::SETUGE: return X86::COND_AE;
3760     }
3761   }
3762
3763   // First determine if it is required or is profitable to flip the operands.
3764
3765   // If LHS is a foldable load, but RHS is not, flip the condition.
3766   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3767       !ISD::isNON_EXTLoad(RHS.getNode())) {
3768     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3769     std::swap(LHS, RHS);
3770   }
3771
3772   switch (SetCCOpcode) {
3773   default: break;
3774   case ISD::SETOLT:
3775   case ISD::SETOLE:
3776   case ISD::SETUGT:
3777   case ISD::SETUGE:
3778     std::swap(LHS, RHS);
3779     break;
3780   }
3781
3782   // On a floating point condition, the flags are set as follows:
3783   // ZF  PF  CF   op
3784   //  0 | 0 | 0 | X > Y
3785   //  0 | 0 | 1 | X < Y
3786   //  1 | 0 | 0 | X == Y
3787   //  1 | 1 | 1 | unordered
3788   switch (SetCCOpcode) {
3789   default: llvm_unreachable("Condcode should be pre-legalized away");
3790   case ISD::SETUEQ:
3791   case ISD::SETEQ:   return X86::COND_E;
3792   case ISD::SETOLT:              // flipped
3793   case ISD::SETOGT:
3794   case ISD::SETGT:   return X86::COND_A;
3795   case ISD::SETOLE:              // flipped
3796   case ISD::SETOGE:
3797   case ISD::SETGE:   return X86::COND_AE;
3798   case ISD::SETUGT:              // flipped
3799   case ISD::SETULT:
3800   case ISD::SETLT:   return X86::COND_B;
3801   case ISD::SETUGE:              // flipped
3802   case ISD::SETULE:
3803   case ISD::SETLE:   return X86::COND_BE;
3804   case ISD::SETONE:
3805   case ISD::SETNE:   return X86::COND_NE;
3806   case ISD::SETUO:   return X86::COND_P;
3807   case ISD::SETO:    return X86::COND_NP;
3808   case ISD::SETOEQ:
3809   case ISD::SETUNE:  return X86::COND_INVALID;
3810   }
3811 }
3812
3813 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3814 /// code. Current x86 isa includes the following FP cmov instructions:
3815 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3816 static bool hasFPCMov(unsigned X86CC) {
3817   switch (X86CC) {
3818   default:
3819     return false;
3820   case X86::COND_B:
3821   case X86::COND_BE:
3822   case X86::COND_E:
3823   case X86::COND_P:
3824   case X86::COND_A:
3825   case X86::COND_AE:
3826   case X86::COND_NE:
3827   case X86::COND_NP:
3828     return true;
3829   }
3830 }
3831
3832 /// isFPImmLegal - Returns true if the target can instruction select the
3833 /// specified FP immediate natively. If false, the legalizer will
3834 /// materialize the FP immediate as a load from a constant pool.
3835 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3836   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3837     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3838       return true;
3839   }
3840   return false;
3841 }
3842
3843 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3844                                               ISD::LoadExtType ExtTy,
3845                                               EVT NewVT) const {
3846   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3847   // relocation target a movq or addq instruction: don't let the load shrink.
3848   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3849   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3850     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3851       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3852   return true;
3853 }
3854
3855 /// \brief Returns true if it is beneficial to convert a load of a constant
3856 /// to just the constant itself.
3857 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3858                                                           Type *Ty) const {
3859   assert(Ty->isIntegerTy());
3860
3861   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3862   if (BitSize == 0 || BitSize > 64)
3863     return false;
3864   return true;
3865 }
3866
3867 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3868                                                 unsigned Index) const {
3869   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3870     return false;
3871
3872   return (Index == 0 || Index == ResVT.getVectorNumElements());
3873 }
3874
3875 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3876   // Speculate cttz only if we can directly use TZCNT.
3877   return Subtarget->hasBMI();
3878 }
3879
3880 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3881   // Speculate ctlz only if we can directly use LZCNT.
3882   return Subtarget->hasLZCNT();
3883 }
3884
3885 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3886 /// the specified range (L, H].
3887 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3888   return (Val < 0) || (Val >= Low && Val < Hi);
3889 }
3890
3891 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3892 /// specified value.
3893 static bool isUndefOrEqual(int Val, int CmpVal) {
3894   return (Val < 0 || Val == CmpVal);
3895 }
3896
3897 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3898 /// from position Pos and ending in Pos+Size, falls within the specified
3899 /// sequential range (Low, Low+Size]. or is undef.
3900 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3901                                        unsigned Pos, unsigned Size, int Low) {
3902   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3903     if (!isUndefOrEqual(Mask[i], Low))
3904       return false;
3905   return true;
3906 }
3907
3908 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3909 /// the two vector operands have swapped position.
3910 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3911                                      unsigned NumElems) {
3912   for (unsigned i = 0; i != NumElems; ++i) {
3913     int idx = Mask[i];
3914     if (idx < 0)
3915       continue;
3916     else if (idx < (int)NumElems)
3917       Mask[i] = idx + NumElems;
3918     else
3919       Mask[i] = idx - NumElems;
3920   }
3921 }
3922
3923 /// isVEXTRACTIndex - Return true if the specified
3924 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3925 /// suitable for instruction that extract 128 or 256 bit vectors
3926 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3927   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3928   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929     return false;
3930
3931   // The index should be aligned on a vecWidth-bit boundary.
3932   uint64_t Index =
3933     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3934
3935   MVT VT = N->getSimpleValueType(0);
3936   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3937   bool Result = (Index * ElSize) % vecWidth == 0;
3938
3939   return Result;
3940 }
3941
3942 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3943 /// operand specifies a subvector insert that is suitable for input to
3944 /// insertion of 128 or 256-bit subvectors
3945 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3946   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3947   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3948     return false;
3949   // The index should be aligned on a vecWidth-bit boundary.
3950   uint64_t Index =
3951     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3952
3953   MVT VT = N->getSimpleValueType(0);
3954   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3955   bool Result = (Index * ElSize) % vecWidth == 0;
3956
3957   return Result;
3958 }
3959
3960 bool X86::isVINSERT128Index(SDNode *N) {
3961   return isVINSERTIndex(N, 128);
3962 }
3963
3964 bool X86::isVINSERT256Index(SDNode *N) {
3965   return isVINSERTIndex(N, 256);
3966 }
3967
3968 bool X86::isVEXTRACT128Index(SDNode *N) {
3969   return isVEXTRACTIndex(N, 128);
3970 }
3971
3972 bool X86::isVEXTRACT256Index(SDNode *N) {
3973   return isVEXTRACTIndex(N, 256);
3974 }
3975
3976 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3977   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3978   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3979     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3980
3981   uint64_t Index =
3982     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3983
3984   MVT VecVT = N->getOperand(0).getSimpleValueType();
3985   MVT ElVT = VecVT.getVectorElementType();
3986
3987   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3988   return Index / NumElemsPerChunk;
3989 }
3990
3991 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3992   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3993   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3994     llvm_unreachable("Illegal insert subvector for VINSERT");
3995
3996   uint64_t Index =
3997     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3998
3999   MVT VecVT = N->getSimpleValueType(0);
4000   MVT ElVT = VecVT.getVectorElementType();
4001
4002   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4003   return Index / NumElemsPerChunk;
4004 }
4005
4006 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// and VINSERTI128 instructions.
4009 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4010   return getExtractVEXTRACTImmediate(N, 128);
4011 }
4012
4013 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4014 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4015 /// and VINSERTI64x4 instructions.
4016 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4017   return getExtractVEXTRACTImmediate(N, 256);
4018 }
4019
4020 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4021 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4022 /// and VINSERTI128 instructions.
4023 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4024   return getInsertVINSERTImmediate(N, 128);
4025 }
4026
4027 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4028 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4029 /// and VINSERTI64x4 instructions.
4030 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4031   return getInsertVINSERTImmediate(N, 256);
4032 }
4033
4034 /// isZero - Returns true if Elt is a constant integer zero
4035 static bool isZero(SDValue V) {
4036   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4037   return C && C->isNullValue();
4038 }
4039
4040 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4041 /// constant +0.0.
4042 bool X86::isZeroNode(SDValue Elt) {
4043   if (isZero(Elt))
4044     return true;
4045   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4046     return CFP->getValueAPF().isPosZero();
4047   return false;
4048 }
4049
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4051 ///
4052 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4053                              SelectionDAG &DAG, SDLoc dl) {
4054   assert(VT.isVector() && "Expected a vector type");
4055
4056   // Always build SSE zero vectors as <4 x i32> bitcasted
4057   // to their dest type. This ensures they get CSE'd.
4058   SDValue Vec;
4059   if (VT.is128BitVector()) {  // SSE
4060     if (Subtarget->hasSSE2()) {  // SSE2
4061       SDValue Cst = DAG.getConstant(0, MVT::i32);
4062       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4063     } else { // SSE1
4064       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4065       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4066     }
4067   } else if (VT.is256BitVector()) { // AVX
4068     if (Subtarget->hasInt256()) { // AVX2
4069       SDValue Cst = DAG.getConstant(0, MVT::i32);
4070       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4071       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4072     } else {
4073       // 256-bit logic and arithmetic instructions in AVX are all
4074       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4075       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4076       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4077       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4078     }
4079   } else if (VT.is512BitVector()) { // AVX-512
4080       SDValue Cst = DAG.getConstant(0, MVT::i32);
4081       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4082                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4084   } else if (VT.getScalarType() == MVT::i1) {
4085     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4086     SDValue Cst = DAG.getConstant(0, MVT::i1);
4087     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4088     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4089   } else
4090     llvm_unreachable("Unexpected vector type");
4091
4092   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4093 }
4094
4095 /// getOnesVector - Returns a vector of specified type with all bits set.
4096 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4097 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4098 /// Then bitcast to their original type, ensuring they get CSE'd.
4099 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4100                              SDLoc dl) {
4101   assert(VT.isVector() && "Expected a vector type");
4102
4103   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4104   SDValue Vec;
4105   if (VT.is256BitVector()) {
4106     if (HasInt256) { // AVX2
4107       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4108       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4109     } else { // AVX
4110       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4111       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4112     }
4113   } else if (VT.is128BitVector()) {
4114     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4115   } else
4116     llvm_unreachable("Unexpected vector type");
4117
4118   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4119 }
4120
4121 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4122 /// operation of specified width.
4123 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4124                        SDValue V2) {
4125   unsigned NumElems = VT.getVectorNumElements();
4126   SmallVector<int, 8> Mask;
4127   Mask.push_back(NumElems);
4128   for (unsigned i = 1; i != NumElems; ++i)
4129     Mask.push_back(i);
4130   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4131 }
4132
4133 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4134 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4135                           SDValue V2) {
4136   unsigned NumElems = VT.getVectorNumElements();
4137   SmallVector<int, 8> Mask;
4138   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4139     Mask.push_back(i);
4140     Mask.push_back(i + NumElems);
4141   }
4142   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4143 }
4144
4145 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4146 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4147                           SDValue V2) {
4148   unsigned NumElems = VT.getVectorNumElements();
4149   SmallVector<int, 8> Mask;
4150   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4151     Mask.push_back(i + Half);
4152     Mask.push_back(i + NumElems + Half);
4153   }
4154   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4155 }
4156
4157 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4158 /// vector of zero or undef vector.  This produces a shuffle where the low
4159 /// element of V2 is swizzled into the zero/undef vector, landing at element
4160 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4161 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4162                                            bool IsZero,
4163                                            const X86Subtarget *Subtarget,
4164                                            SelectionDAG &DAG) {
4165   MVT VT = V2.getSimpleValueType();
4166   SDValue V1 = IsZero
4167     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4168   unsigned NumElems = VT.getVectorNumElements();
4169   SmallVector<int, 16> MaskVec;
4170   for (unsigned i = 0; i != NumElems; ++i)
4171     // If this is the insertion idx, put the low elt of V2 here.
4172     MaskVec.push_back(i == Idx ? NumElems : i);
4173   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4174 }
4175
4176 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4177 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4178 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4179 /// shuffles which use a single input multiple times, and in those cases it will
4180 /// adjust the mask to only have indices within that single input.
4181 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4182                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4183   unsigned NumElems = VT.getVectorNumElements();
4184   SDValue ImmN;
4185
4186   IsUnary = false;
4187   bool IsFakeUnary = false;
4188   switch(N->getOpcode()) {
4189   case X86ISD::BLENDI:
4190     ImmN = N->getOperand(N->getNumOperands()-1);
4191     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4192     break;
4193   case X86ISD::SHUFP:
4194     ImmN = N->getOperand(N->getNumOperands()-1);
4195     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4197     break;
4198   case X86ISD::UNPCKH:
4199     DecodeUNPCKHMask(VT, Mask);
4200     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4201     break;
4202   case X86ISD::UNPCKL:
4203     DecodeUNPCKLMask(VT, Mask);
4204     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4205     break;
4206   case X86ISD::MOVHLPS:
4207     DecodeMOVHLPSMask(NumElems, Mask);
4208     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4209     break;
4210   case X86ISD::MOVLHPS:
4211     DecodeMOVLHPSMask(NumElems, Mask);
4212     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4213     break;
4214   case X86ISD::PALIGNR:
4215     ImmN = N->getOperand(N->getNumOperands()-1);
4216     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4217     break;
4218   case X86ISD::PSHUFD:
4219   case X86ISD::VPERMILPI:
4220     ImmN = N->getOperand(N->getNumOperands()-1);
4221     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4222     IsUnary = true;
4223     break;
4224   case X86ISD::PSHUFHW:
4225     ImmN = N->getOperand(N->getNumOperands()-1);
4226     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4227     IsUnary = true;
4228     break;
4229   case X86ISD::PSHUFLW:
4230     ImmN = N->getOperand(N->getNumOperands()-1);
4231     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4232     IsUnary = true;
4233     break;
4234   case X86ISD::PSHUFB: {
4235     IsUnary = true;
4236     SDValue MaskNode = N->getOperand(1);
4237     while (MaskNode->getOpcode() == ISD::BITCAST)
4238       MaskNode = MaskNode->getOperand(0);
4239
4240     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4241       // If we have a build-vector, then things are easy.
4242       EVT VT = MaskNode.getValueType();
4243       assert(VT.isVector() &&
4244              "Can't produce a non-vector with a build_vector!");
4245       if (!VT.isInteger())
4246         return false;
4247
4248       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4249
4250       SmallVector<uint64_t, 32> RawMask;
4251       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4252         SDValue Op = MaskNode->getOperand(i);
4253         if (Op->getOpcode() == ISD::UNDEF) {
4254           RawMask.push_back((uint64_t)SM_SentinelUndef);
4255           continue;
4256         }
4257         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4258         if (!CN)
4259           return false;
4260         APInt MaskElement = CN->getAPIntValue();
4261
4262         // We now have to decode the element which could be any integer size and
4263         // extract each byte of it.
4264         for (int j = 0; j < NumBytesPerElement; ++j) {
4265           // Note that this is x86 and so always little endian: the low byte is
4266           // the first byte of the mask.
4267           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4268           MaskElement = MaskElement.lshr(8);
4269         }
4270       }
4271       DecodePSHUFBMask(RawMask, Mask);
4272       break;
4273     }
4274
4275     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4276     if (!MaskLoad)
4277       return false;
4278
4279     SDValue Ptr = MaskLoad->getBasePtr();
4280     if (Ptr->getOpcode() == X86ISD::Wrapper)
4281       Ptr = Ptr->getOperand(0);
4282
4283     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4284     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4285       return false;
4286
4287     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4288       DecodePSHUFBMask(C, Mask);
4289       if (Mask.empty())
4290         return false;
4291       break;
4292     }
4293
4294     return false;
4295   }
4296   case X86ISD::VPERMI:
4297     ImmN = N->getOperand(N->getNumOperands()-1);
4298     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4299     IsUnary = true;
4300     break;
4301   case X86ISD::MOVSS:
4302   case X86ISD::MOVSD:
4303     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4304     break;
4305   case X86ISD::VPERM2X128:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     if (Mask.empty()) return false;
4309     break;
4310   case X86ISD::MOVSLDUP:
4311     DecodeMOVSLDUPMask(VT, Mask);
4312     IsUnary = true;
4313     break;
4314   case X86ISD::MOVSHDUP:
4315     DecodeMOVSHDUPMask(VT, Mask);
4316     IsUnary = true;
4317     break;
4318   case X86ISD::MOVDDUP:
4319     DecodeMOVDDUPMask(VT, Mask);
4320     IsUnary = true;
4321     break;
4322   case X86ISD::MOVLHPD:
4323   case X86ISD::MOVLPD:
4324   case X86ISD::MOVLPS:
4325     // Not yet implemented
4326     return false;
4327   default: llvm_unreachable("unknown target shuffle node");
4328   }
4329
4330   // If we have a fake unary shuffle, the shuffle mask is spread across two
4331   // inputs that are actually the same node. Re-map the mask to always point
4332   // into the first input.
4333   if (IsFakeUnary)
4334     for (int &M : Mask)
4335       if (M >= (int)Mask.size())
4336         M -= Mask.size();
4337
4338   return true;
4339 }
4340
4341 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4342 /// element of the result of the vector shuffle.
4343 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4344                                    unsigned Depth) {
4345   if (Depth == 6)
4346     return SDValue();  // Limit search depth.
4347
4348   SDValue V = SDValue(N, 0);
4349   EVT VT = V.getValueType();
4350   unsigned Opcode = V.getOpcode();
4351
4352   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4353   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4354     int Elt = SV->getMaskElt(Index);
4355
4356     if (Elt < 0)
4357       return DAG.getUNDEF(VT.getVectorElementType());
4358
4359     unsigned NumElems = VT.getVectorNumElements();
4360     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4361                                          : SV->getOperand(1);
4362     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4363   }
4364
4365   // Recurse into target specific vector shuffles to find scalars.
4366   if (isTargetShuffle(Opcode)) {
4367     MVT ShufVT = V.getSimpleValueType();
4368     unsigned NumElems = ShufVT.getVectorNumElements();
4369     SmallVector<int, 16> ShuffleMask;
4370     bool IsUnary;
4371
4372     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4373       return SDValue();
4374
4375     int Elt = ShuffleMask[Index];
4376     if (Elt < 0)
4377       return DAG.getUNDEF(ShufVT.getVectorElementType());
4378
4379     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4380                                          : N->getOperand(1);
4381     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4382                                Depth+1);
4383   }
4384
4385   // Actual nodes that may contain scalar elements
4386   if (Opcode == ISD::BITCAST) {
4387     V = V.getOperand(0);
4388     EVT SrcVT = V.getValueType();
4389     unsigned NumElems = VT.getVectorNumElements();
4390
4391     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4392       return SDValue();
4393   }
4394
4395   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4396     return (Index == 0) ? V.getOperand(0)
4397                         : DAG.getUNDEF(VT.getVectorElementType());
4398
4399   if (V.getOpcode() == ISD::BUILD_VECTOR)
4400     return V.getOperand(Index);
4401
4402   return SDValue();
4403 }
4404
4405 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4406 ///
4407 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4408                                        unsigned NumNonZero, unsigned NumZero,
4409                                        SelectionDAG &DAG,
4410                                        const X86Subtarget* Subtarget,
4411                                        const TargetLowering &TLI) {
4412   if (NumNonZero > 8)
4413     return SDValue();
4414
4415   SDLoc dl(Op);
4416   SDValue V;
4417   bool First = true;
4418   for (unsigned i = 0; i < 16; ++i) {
4419     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4420     if (ThisIsNonZero && First) {
4421       if (NumZero)
4422         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4423       else
4424         V = DAG.getUNDEF(MVT::v8i16);
4425       First = false;
4426     }
4427
4428     if ((i & 1) != 0) {
4429       SDValue ThisElt, LastElt;
4430       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4431       if (LastIsNonZero) {
4432         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4433                               MVT::i16, Op.getOperand(i-1));
4434       }
4435       if (ThisIsNonZero) {
4436         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4437         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4438                               ThisElt, DAG.getConstant(8, MVT::i8));
4439         if (LastIsNonZero)
4440           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4441       } else
4442         ThisElt = LastElt;
4443
4444       if (ThisElt.getNode())
4445         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4446                         DAG.getIntPtrConstant(i/2));
4447     }
4448   }
4449
4450   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4451 }
4452
4453 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4454 ///
4455 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4456                                      unsigned NumNonZero, unsigned NumZero,
4457                                      SelectionDAG &DAG,
4458                                      const X86Subtarget* Subtarget,
4459                                      const TargetLowering &TLI) {
4460   if (NumNonZero > 4)
4461     return SDValue();
4462
4463   SDLoc dl(Op);
4464   SDValue V;
4465   bool First = true;
4466   for (unsigned i = 0; i < 8; ++i) {
4467     bool isNonZero = (NonZeros & (1 << i)) != 0;
4468     if (isNonZero) {
4469       if (First) {
4470         if (NumZero)
4471           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4472         else
4473           V = DAG.getUNDEF(MVT::v8i16);
4474         First = false;
4475       }
4476       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4477                       MVT::v8i16, V, Op.getOperand(i),
4478                       DAG.getIntPtrConstant(i));
4479     }
4480   }
4481
4482   return V;
4483 }
4484
4485 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4486 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4487                                      const X86Subtarget *Subtarget,
4488                                      const TargetLowering &TLI) {
4489   // Find all zeroable elements.
4490   std::bitset<4> Zeroable;
4491   for (int i=0; i < 4; ++i) {
4492     SDValue Elt = Op->getOperand(i);
4493     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4494   }
4495   assert(Zeroable.size() - Zeroable.count() > 1 &&
4496          "We expect at least two non-zero elements!");
4497
4498   // We only know how to deal with build_vector nodes where elements are either
4499   // zeroable or extract_vector_elt with constant index.
4500   SDValue FirstNonZero;
4501   unsigned FirstNonZeroIdx;
4502   for (unsigned i=0; i < 4; ++i) {
4503     if (Zeroable[i])
4504       continue;
4505     SDValue Elt = Op->getOperand(i);
4506     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4507         !isa<ConstantSDNode>(Elt.getOperand(1)))
4508       return SDValue();
4509     // Make sure that this node is extracting from a 128-bit vector.
4510     MVT VT = Elt.getOperand(0).getSimpleValueType();
4511     if (!VT.is128BitVector())
4512       return SDValue();
4513     if (!FirstNonZero.getNode()) {
4514       FirstNonZero = Elt;
4515       FirstNonZeroIdx = i;
4516     }
4517   }
4518
4519   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4520   SDValue V1 = FirstNonZero.getOperand(0);
4521   MVT VT = V1.getSimpleValueType();
4522
4523   // See if this build_vector can be lowered as a blend with zero.
4524   SDValue Elt;
4525   unsigned EltMaskIdx, EltIdx;
4526   int Mask[4];
4527   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4528     if (Zeroable[EltIdx]) {
4529       // The zero vector will be on the right hand side.
4530       Mask[EltIdx] = EltIdx+4;
4531       continue;
4532     }
4533
4534     Elt = Op->getOperand(EltIdx);
4535     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4536     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4537     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4538       break;
4539     Mask[EltIdx] = EltIdx;
4540   }
4541
4542   if (EltIdx == 4) {
4543     // Let the shuffle legalizer deal with blend operations.
4544     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4545     if (V1.getSimpleValueType() != VT)
4546       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4547     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4548   }
4549
4550   // See if we can lower this build_vector to a INSERTPS.
4551   if (!Subtarget->hasSSE41())
4552     return SDValue();
4553
4554   SDValue V2 = Elt.getOperand(0);
4555   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4556     V1 = SDValue();
4557
4558   bool CanFold = true;
4559   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4560     if (Zeroable[i])
4561       continue;
4562
4563     SDValue Current = Op->getOperand(i);
4564     SDValue SrcVector = Current->getOperand(0);
4565     if (!V1.getNode())
4566       V1 = SrcVector;
4567     CanFold = SrcVector == V1 &&
4568       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4569   }
4570
4571   if (!CanFold)
4572     return SDValue();
4573
4574   assert(V1.getNode() && "Expected at least two non-zero elements!");
4575   if (V1.getSimpleValueType() != MVT::v4f32)
4576     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4577   if (V2.getSimpleValueType() != MVT::v4f32)
4578     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4579
4580   // Ok, we can emit an INSERTPS instruction.
4581   unsigned ZMask = Zeroable.to_ulong();
4582
4583   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4584   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4585   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4586                                DAG.getIntPtrConstant(InsertPSMask));
4587   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4588 }
4589
4590 /// Return a vector logical shift node.
4591 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4592                          unsigned NumBits, SelectionDAG &DAG,
4593                          const TargetLowering &TLI, SDLoc dl) {
4594   assert(VT.is128BitVector() && "Unknown type for VShift");
4595   MVT ShVT = MVT::v2i64;
4596   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4597   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4598   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4599   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4600   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4601   return DAG.getNode(ISD::BITCAST, dl, VT,
4602                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4603 }
4604
4605 static SDValue
4606 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4607
4608   // Check if the scalar load can be widened into a vector load. And if
4609   // the address is "base + cst" see if the cst can be "absorbed" into
4610   // the shuffle mask.
4611   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4612     SDValue Ptr = LD->getBasePtr();
4613     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4614       return SDValue();
4615     EVT PVT = LD->getValueType(0);
4616     if (PVT != MVT::i32 && PVT != MVT::f32)
4617       return SDValue();
4618
4619     int FI = -1;
4620     int64_t Offset = 0;
4621     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4622       FI = FINode->getIndex();
4623       Offset = 0;
4624     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4625                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4626       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4627       Offset = Ptr.getConstantOperandVal(1);
4628       Ptr = Ptr.getOperand(0);
4629     } else {
4630       return SDValue();
4631     }
4632
4633     // FIXME: 256-bit vector instructions don't require a strict alignment,
4634     // improve this code to support it better.
4635     unsigned RequiredAlign = VT.getSizeInBits()/8;
4636     SDValue Chain = LD->getChain();
4637     // Make sure the stack object alignment is at least 16 or 32.
4638     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4639     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4640       if (MFI->isFixedObjectIndex(FI)) {
4641         // Can't change the alignment. FIXME: It's possible to compute
4642         // the exact stack offset and reference FI + adjust offset instead.
4643         // If someone *really* cares about this. That's the way to implement it.
4644         return SDValue();
4645       } else {
4646         MFI->setObjectAlignment(FI, RequiredAlign);
4647       }
4648     }
4649
4650     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4651     // Ptr + (Offset & ~15).
4652     if (Offset < 0)
4653       return SDValue();
4654     if ((Offset % RequiredAlign) & 3)
4655       return SDValue();
4656     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4657     if (StartOffset)
4658       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4659                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4660
4661     int EltNo = (Offset - StartOffset) >> 2;
4662     unsigned NumElems = VT.getVectorNumElements();
4663
4664     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4665     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4666                              LD->getPointerInfo().getWithOffset(StartOffset),
4667                              false, false, false, 0);
4668
4669     SmallVector<int, 8> Mask(NumElems, EltNo);
4670
4671     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4672   }
4673
4674   return SDValue();
4675 }
4676
4677 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4678 /// elements can be replaced by a single large load which has the same value as
4679 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4680 ///
4681 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4682 ///
4683 /// FIXME: we'd also like to handle the case where the last elements are zero
4684 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4685 /// There's even a handy isZeroNode for that purpose.
4686 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4687                                         SDLoc &DL, SelectionDAG &DAG,
4688                                         bool isAfterLegalize) {
4689   unsigned NumElems = Elts.size();
4690
4691   LoadSDNode *LDBase = nullptr;
4692   unsigned LastLoadedElt = -1U;
4693
4694   // For each element in the initializer, see if we've found a load or an undef.
4695   // If we don't find an initial load element, or later load elements are
4696   // non-consecutive, bail out.
4697   for (unsigned i = 0; i < NumElems; ++i) {
4698     SDValue Elt = Elts[i];
4699     // Look through a bitcast.
4700     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4701       Elt = Elt.getOperand(0);
4702     if (!Elt.getNode() ||
4703         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4704       return SDValue();
4705     if (!LDBase) {
4706       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4707         return SDValue();
4708       LDBase = cast<LoadSDNode>(Elt.getNode());
4709       LastLoadedElt = i;
4710       continue;
4711     }
4712     if (Elt.getOpcode() == ISD::UNDEF)
4713       continue;
4714
4715     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4716     EVT LdVT = Elt.getValueType();
4717     // Each loaded element must be the correct fractional portion of the
4718     // requested vector load.
4719     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4720       return SDValue();
4721     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4722       return SDValue();
4723     LastLoadedElt = i;
4724   }
4725
4726   // If we have found an entire vector of loads and undefs, then return a large
4727   // load of the entire vector width starting at the base pointer.  If we found
4728   // consecutive loads for the low half, generate a vzext_load node.
4729   if (LastLoadedElt == NumElems - 1) {
4730     assert(LDBase && "Did not find base load for merging consecutive loads");
4731     EVT EltVT = LDBase->getValueType(0);
4732     // Ensure that the input vector size for the merged loads matches the
4733     // cumulative size of the input elements.
4734     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4735       return SDValue();
4736
4737     if (isAfterLegalize &&
4738         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4739       return SDValue();
4740
4741     SDValue NewLd = SDValue();
4742
4743     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4744                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4745                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4746                         LDBase->getAlignment());
4747
4748     if (LDBase->hasAnyUseOfValue(1)) {
4749       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4750                                      SDValue(LDBase, 1),
4751                                      SDValue(NewLd.getNode(), 1));
4752       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4753       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4754                              SDValue(NewLd.getNode(), 1));
4755     }
4756
4757     return NewLd;
4758   }
4759
4760   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4761   //of a v4i32 / v4f32. It's probably worth generalizing.
4762   EVT EltVT = VT.getVectorElementType();
4763   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4764       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4765     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4766     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4767     SDValue ResNode =
4768         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4769                                 LDBase->getPointerInfo(),
4770                                 LDBase->getAlignment(),
4771                                 false/*isVolatile*/, true/*ReadMem*/,
4772                                 false/*WriteMem*/);
4773
4774     // Make sure the newly-created LOAD is in the same position as LDBase in
4775     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4776     // update uses of LDBase's output chain to use the TokenFactor.
4777     if (LDBase->hasAnyUseOfValue(1)) {
4778       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4779                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4780       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4781       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4782                              SDValue(ResNode.getNode(), 1));
4783     }
4784
4785     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4786   }
4787   return SDValue();
4788 }
4789
4790 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4791 /// to generate a splat value for the following cases:
4792 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4793 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4794 /// a scalar load, or a constant.
4795 /// The VBROADCAST node is returned when a pattern is found,
4796 /// or SDValue() otherwise.
4797 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4798                                     SelectionDAG &DAG) {
4799   // VBROADCAST requires AVX.
4800   // TODO: Splats could be generated for non-AVX CPUs using SSE
4801   // instructions, but there's less potential gain for only 128-bit vectors.
4802   if (!Subtarget->hasAVX())
4803     return SDValue();
4804
4805   MVT VT = Op.getSimpleValueType();
4806   SDLoc dl(Op);
4807
4808   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4809          "Unsupported vector type for broadcast.");
4810
4811   SDValue Ld;
4812   bool ConstSplatVal;
4813
4814   switch (Op.getOpcode()) {
4815     default:
4816       // Unknown pattern found.
4817       return SDValue();
4818
4819     case ISD::BUILD_VECTOR: {
4820       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4821       BitVector UndefElements;
4822       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4823
4824       // We need a splat of a single value to use broadcast, and it doesn't
4825       // make any sense if the value is only in one element of the vector.
4826       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4827         return SDValue();
4828
4829       Ld = Splat;
4830       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4831                        Ld.getOpcode() == ISD::ConstantFP);
4832
4833       // Make sure that all of the users of a non-constant load are from the
4834       // BUILD_VECTOR node.
4835       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4836         return SDValue();
4837       break;
4838     }
4839
4840     case ISD::VECTOR_SHUFFLE: {
4841       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4842
4843       // Shuffles must have a splat mask where the first element is
4844       // broadcasted.
4845       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4846         return SDValue();
4847
4848       SDValue Sc = Op.getOperand(0);
4849       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4850           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4851
4852         if (!Subtarget->hasInt256())
4853           return SDValue();
4854
4855         // Use the register form of the broadcast instruction available on AVX2.
4856         if (VT.getSizeInBits() >= 256)
4857           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4858         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4859       }
4860
4861       Ld = Sc.getOperand(0);
4862       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4863                        Ld.getOpcode() == ISD::ConstantFP);
4864
4865       // The scalar_to_vector node and the suspected
4866       // load node must have exactly one user.
4867       // Constants may have multiple users.
4868
4869       // AVX-512 has register version of the broadcast
4870       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4871         Ld.getValueType().getSizeInBits() >= 32;
4872       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4873           !hasRegVer))
4874         return SDValue();
4875       break;
4876     }
4877   }
4878
4879   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4880   bool IsGE256 = (VT.getSizeInBits() >= 256);
4881
4882   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4883   // instruction to save 8 or more bytes of constant pool data.
4884   // TODO: If multiple splats are generated to load the same constant,
4885   // it may be detrimental to overall size. There needs to be a way to detect
4886   // that condition to know if this is truly a size win.
4887   const Function *F = DAG.getMachineFunction().getFunction();
4888   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4889
4890   // Handle broadcasting a single constant scalar from the constant pool
4891   // into a vector.
4892   // On Sandybridge (no AVX2), it is still better to load a constant vector
4893   // from the constant pool and not to broadcast it from a scalar.
4894   // But override that restriction when optimizing for size.
4895   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4896   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4897     EVT CVT = Ld.getValueType();
4898     assert(!CVT.isVector() && "Must not broadcast a vector type");
4899
4900     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4901     // For size optimization, also splat v2f64 and v2i64, and for size opt
4902     // with AVX2, also splat i8 and i16.
4903     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4904     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4905         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4906       const Constant *C = nullptr;
4907       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4908         C = CI->getConstantIntValue();
4909       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4910         C = CF->getConstantFPValue();
4911
4912       assert(C && "Invalid constant type");
4913
4914       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4915       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4916       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4917       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4918                        MachinePointerInfo::getConstantPool(),
4919                        false, false, false, Alignment);
4920
4921       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4922     }
4923   }
4924
4925   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4926
4927   // Handle AVX2 in-register broadcasts.
4928   if (!IsLoad && Subtarget->hasInt256() &&
4929       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4930     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4931
4932   // The scalar source must be a normal load.
4933   if (!IsLoad)
4934     return SDValue();
4935
4936   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4937       (Subtarget->hasVLX() && ScalarSize == 64))
4938     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4939
4940   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4941   // double since there is no vbroadcastsd xmm
4942   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4943     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4944       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4945   }
4946
4947   // Unsupported broadcast.
4948   return SDValue();
4949 }
4950
4951 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4952 /// underlying vector and index.
4953 ///
4954 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4955 /// index.
4956 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4957                                          SDValue ExtIdx) {
4958   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4959   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4960     return Idx;
4961
4962   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4963   // lowered this:
4964   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4965   // to:
4966   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
4967   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
4968   //                           undef)
4969   //                       Constant<0>)
4970   // In this case the vector is the extract_subvector expression and the index
4971   // is 2, as specified by the shuffle.
4972   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4973   SDValue ShuffleVec = SVOp->getOperand(0);
4974   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4975   assert(ShuffleVecVT.getVectorElementType() ==
4976          ExtractedFromVec.getSimpleValueType().getVectorElementType());
4977
4978   int ShuffleIdx = SVOp->getMaskElt(Idx);
4979   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4980     ExtractedFromVec = ShuffleVec;
4981     return ShuffleIdx;
4982   }
4983   return Idx;
4984 }
4985
4986 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4987   MVT VT = Op.getSimpleValueType();
4988
4989   // Skip if insert_vec_elt is not supported.
4990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4991   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4992     return SDValue();
4993
4994   SDLoc DL(Op);
4995   unsigned NumElems = Op.getNumOperands();
4996
4997   SDValue VecIn1;
4998   SDValue VecIn2;
4999   SmallVector<unsigned, 4> InsertIndices;
5000   SmallVector<int, 8> Mask(NumElems, -1);
5001
5002   for (unsigned i = 0; i != NumElems; ++i) {
5003     unsigned Opc = Op.getOperand(i).getOpcode();
5004
5005     if (Opc == ISD::UNDEF)
5006       continue;
5007
5008     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5009       // Quit if more than 1 elements need inserting.
5010       if (InsertIndices.size() > 1)
5011         return SDValue();
5012
5013       InsertIndices.push_back(i);
5014       continue;
5015     }
5016
5017     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5018     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5019     // Quit if non-constant index.
5020     if (!isa<ConstantSDNode>(ExtIdx))
5021       return SDValue();
5022     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5023
5024     // Quit if extracted from vector of different type.
5025     if (ExtractedFromVec.getValueType() != VT)
5026       return SDValue();
5027
5028     if (!VecIn1.getNode())
5029       VecIn1 = ExtractedFromVec;
5030     else if (VecIn1 != ExtractedFromVec) {
5031       if (!VecIn2.getNode())
5032         VecIn2 = ExtractedFromVec;
5033       else if (VecIn2 != ExtractedFromVec)
5034         // Quit if more than 2 vectors to shuffle
5035         return SDValue();
5036     }
5037
5038     if (ExtractedFromVec == VecIn1)
5039       Mask[i] = Idx;
5040     else if (ExtractedFromVec == VecIn2)
5041       Mask[i] = Idx + NumElems;
5042   }
5043
5044   if (!VecIn1.getNode())
5045     return SDValue();
5046
5047   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5048   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5049   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5050     unsigned Idx = InsertIndices[i];
5051     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5052                      DAG.getIntPtrConstant(Idx));
5053   }
5054
5055   return NV;
5056 }
5057
5058 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5059 SDValue
5060 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5061
5062   MVT VT = Op.getSimpleValueType();
5063   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5064          "Unexpected type in LowerBUILD_VECTORvXi1!");
5065
5066   SDLoc dl(Op);
5067   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5068     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5069     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5070     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5071   }
5072
5073   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5074     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5075     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5076     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5077   }
5078
5079   bool AllContants = true;
5080   uint64_t Immediate = 0;
5081   int NonConstIdx = -1;
5082   bool IsSplat = true;
5083   unsigned NumNonConsts = 0;
5084   unsigned NumConsts = 0;
5085   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5086     SDValue In = Op.getOperand(idx);
5087     if (In.getOpcode() == ISD::UNDEF)
5088       continue;
5089     if (!isa<ConstantSDNode>(In)) {
5090       AllContants = false;
5091       NonConstIdx = idx;
5092       NumNonConsts++;
5093     } else {
5094       NumConsts++;
5095       if (cast<ConstantSDNode>(In)->getZExtValue())
5096       Immediate |= (1ULL << idx);
5097     }
5098     if (In != Op.getOperand(0))
5099       IsSplat = false;
5100   }
5101
5102   if (AllContants) {
5103     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5104       DAG.getConstant(Immediate, MVT::i16));
5105     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5106                        DAG.getIntPtrConstant(0));
5107   }
5108
5109   if (NumNonConsts == 1 && NonConstIdx != 0) {
5110     SDValue DstVec;
5111     if (NumConsts) {
5112       SDValue VecAsImm = DAG.getConstant(Immediate,
5113                                          MVT::getIntegerVT(VT.getSizeInBits()));
5114       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5115     }
5116     else
5117       DstVec = DAG.getUNDEF(VT);
5118     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5119                        Op.getOperand(NonConstIdx),
5120                        DAG.getIntPtrConstant(NonConstIdx));
5121   }
5122   if (!IsSplat && (NonConstIdx != 0))
5123     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5124   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5125   SDValue Select;
5126   if (IsSplat)
5127     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5128                           DAG.getConstant(-1, SelectVT),
5129                           DAG.getConstant(0, SelectVT));
5130   else
5131     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5132                          DAG.getConstant((Immediate | 1), SelectVT),
5133                          DAG.getConstant(Immediate, SelectVT));
5134   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5135 }
5136
5137 /// \brief Return true if \p N implements a horizontal binop and return the
5138 /// operands for the horizontal binop into V0 and V1.
5139 ///
5140 /// This is a helper function of PerformBUILD_VECTORCombine.
5141 /// This function checks that the build_vector \p N in input implements a
5142 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5143 /// operation to match.
5144 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5145 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5146 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5147 /// arithmetic sub.
5148 ///
5149 /// This function only analyzes elements of \p N whose indices are
5150 /// in range [BaseIdx, LastIdx).
5151 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5152                               SelectionDAG &DAG,
5153                               unsigned BaseIdx, unsigned LastIdx,
5154                               SDValue &V0, SDValue &V1) {
5155   EVT VT = N->getValueType(0);
5156
5157   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5158   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5159          "Invalid Vector in input!");
5160
5161   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5162   bool CanFold = true;
5163   unsigned ExpectedVExtractIdx = BaseIdx;
5164   unsigned NumElts = LastIdx - BaseIdx;
5165   V0 = DAG.getUNDEF(VT);
5166   V1 = DAG.getUNDEF(VT);
5167
5168   // Check if N implements a horizontal binop.
5169   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5170     SDValue Op = N->getOperand(i + BaseIdx);
5171
5172     // Skip UNDEFs.
5173     if (Op->getOpcode() == ISD::UNDEF) {
5174       // Update the expected vector extract index.
5175       if (i * 2 == NumElts)
5176         ExpectedVExtractIdx = BaseIdx;
5177       ExpectedVExtractIdx += 2;
5178       continue;
5179     }
5180
5181     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5182
5183     if (!CanFold)
5184       break;
5185
5186     SDValue Op0 = Op.getOperand(0);
5187     SDValue Op1 = Op.getOperand(1);
5188
5189     // Try to match the following pattern:
5190     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5191     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5192         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193         Op0.getOperand(0) == Op1.getOperand(0) &&
5194         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5195         isa<ConstantSDNode>(Op1.getOperand(1)));
5196     if (!CanFold)
5197       break;
5198
5199     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5200     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5201
5202     if (i * 2 < NumElts) {
5203       if (V0.getOpcode() == ISD::UNDEF)
5204         V0 = Op0.getOperand(0);
5205     } else {
5206       if (V1.getOpcode() == ISD::UNDEF)
5207         V1 = Op0.getOperand(0);
5208       if (i * 2 == NumElts)
5209         ExpectedVExtractIdx = BaseIdx;
5210     }
5211
5212     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5213     if (I0 == ExpectedVExtractIdx)
5214       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5215     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5216       // Try to match the following dag sequence:
5217       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5218       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5219     } else
5220       CanFold = false;
5221
5222     ExpectedVExtractIdx += 2;
5223   }
5224
5225   return CanFold;
5226 }
5227
5228 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5229 /// a concat_vector.
5230 ///
5231 /// This is a helper function of PerformBUILD_VECTORCombine.
5232 /// This function expects two 256-bit vectors called V0 and V1.
5233 /// At first, each vector is split into two separate 128-bit vectors.
5234 /// Then, the resulting 128-bit vectors are used to implement two
5235 /// horizontal binary operations.
5236 ///
5237 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5238 ///
5239 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5240 /// the two new horizontal binop.
5241 /// When Mode is set, the first horizontal binop dag node would take as input
5242 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5243 /// horizontal binop dag node would take as input the lower 128-bit of V1
5244 /// and the upper 128-bit of V1.
5245 ///   Example:
5246 ///     HADD V0_LO, V0_HI
5247 ///     HADD V1_LO, V1_HI
5248 ///
5249 /// Otherwise, the first horizontal binop dag node takes as input the lower
5250 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5251 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5252 ///   Example:
5253 ///     HADD V0_LO, V1_LO
5254 ///     HADD V0_HI, V1_HI
5255 ///
5256 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5257 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5258 /// the upper 128-bits of the result.
5259 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5260                                      SDLoc DL, SelectionDAG &DAG,
5261                                      unsigned X86Opcode, bool Mode,
5262                                      bool isUndefLO, bool isUndefHI) {
5263   EVT VT = V0.getValueType();
5264   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5265          "Invalid nodes in input!");
5266
5267   unsigned NumElts = VT.getVectorNumElements();
5268   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5269   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5270   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5271   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5272   EVT NewVT = V0_LO.getValueType();
5273
5274   SDValue LO = DAG.getUNDEF(NewVT);
5275   SDValue HI = DAG.getUNDEF(NewVT);
5276
5277   if (Mode) {
5278     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5279     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5280       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5281     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5282       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5283   } else {
5284     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5285     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5286                        V1_LO->getOpcode() != ISD::UNDEF))
5287       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5288
5289     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5290                        V1_HI->getOpcode() != ISD::UNDEF))
5291       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5292   }
5293
5294   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5295 }
5296
5297 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5298 /// sequence of 'vadd + vsub + blendi'.
5299 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5300                            const X86Subtarget *Subtarget) {
5301   SDLoc DL(BV);
5302   EVT VT = BV->getValueType(0);
5303   unsigned NumElts = VT.getVectorNumElements();
5304   SDValue InVec0 = DAG.getUNDEF(VT);
5305   SDValue InVec1 = DAG.getUNDEF(VT);
5306
5307   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5308           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5309
5310   // Odd-numbered elements in the input build vector are obtained from
5311   // adding two integer/float elements.
5312   // Even-numbered elements in the input build vector are obtained from
5313   // subtracting two integer/float elements.
5314   unsigned ExpectedOpcode = ISD::FSUB;
5315   unsigned NextExpectedOpcode = ISD::FADD;
5316   bool AddFound = false;
5317   bool SubFound = false;
5318
5319   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5320     SDValue Op = BV->getOperand(i);
5321
5322     // Skip 'undef' values.
5323     unsigned Opcode = Op.getOpcode();
5324     if (Opcode == ISD::UNDEF) {
5325       std::swap(ExpectedOpcode, NextExpectedOpcode);
5326       continue;
5327     }
5328
5329     // Early exit if we found an unexpected opcode.
5330     if (Opcode != ExpectedOpcode)
5331       return SDValue();
5332
5333     SDValue Op0 = Op.getOperand(0);
5334     SDValue Op1 = Op.getOperand(1);
5335
5336     // Try to match the following pattern:
5337     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5338     // Early exit if we cannot match that sequence.
5339     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5340         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5341         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5342         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5343         Op0.getOperand(1) != Op1.getOperand(1))
5344       return SDValue();
5345
5346     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5347     if (I0 != i)
5348       return SDValue();
5349
5350     // We found a valid add/sub node. Update the information accordingly.
5351     if (i & 1)
5352       AddFound = true;
5353     else
5354       SubFound = true;
5355
5356     // Update InVec0 and InVec1.
5357     if (InVec0.getOpcode() == ISD::UNDEF)
5358       InVec0 = Op0.getOperand(0);
5359     if (InVec1.getOpcode() == ISD::UNDEF)
5360       InVec1 = Op1.getOperand(0);
5361
5362     // Make sure that operands in input to each add/sub node always
5363     // come from a same pair of vectors.
5364     if (InVec0 != Op0.getOperand(0)) {
5365       if (ExpectedOpcode == ISD::FSUB)
5366         return SDValue();
5367
5368       // FADD is commutable. Try to commute the operands
5369       // and then test again.
5370       std::swap(Op0, Op1);
5371       if (InVec0 != Op0.getOperand(0))
5372         return SDValue();
5373     }
5374
5375     if (InVec1 != Op1.getOperand(0))
5376       return SDValue();
5377
5378     // Update the pair of expected opcodes.
5379     std::swap(ExpectedOpcode, NextExpectedOpcode);
5380   }
5381
5382   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5383   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5384       InVec1.getOpcode() != ISD::UNDEF)
5385     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5386
5387   return SDValue();
5388 }
5389
5390 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5391                                           const X86Subtarget *Subtarget) {
5392   SDLoc DL(N);
5393   EVT VT = N->getValueType(0);
5394   unsigned NumElts = VT.getVectorNumElements();
5395   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5396   SDValue InVec0, InVec1;
5397
5398   // Try to match an ADDSUB.
5399   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5400       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5401     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5402     if (Value.getNode())
5403       return Value;
5404   }
5405
5406   // Try to match horizontal ADD/SUB.
5407   unsigned NumUndefsLO = 0;
5408   unsigned NumUndefsHI = 0;
5409   unsigned Half = NumElts/2;
5410
5411   // Count the number of UNDEF operands in the build_vector in input.
5412   for (unsigned i = 0, e = Half; i != e; ++i)
5413     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5414       NumUndefsLO++;
5415
5416   for (unsigned i = Half, e = NumElts; i != e; ++i)
5417     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5418       NumUndefsHI++;
5419
5420   // Early exit if this is either a build_vector of all UNDEFs or all the
5421   // operands but one are UNDEF.
5422   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5423     return SDValue();
5424
5425   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5426     // Try to match an SSE3 float HADD/HSUB.
5427     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5428       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5429
5430     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5431       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5432   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5433     // Try to match an SSSE3 integer HADD/HSUB.
5434     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5435       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5436
5437     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5438       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5439   }
5440
5441   if (!Subtarget->hasAVX())
5442     return SDValue();
5443
5444   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5445     // Try to match an AVX horizontal add/sub of packed single/double
5446     // precision floating point values from 256-bit vectors.
5447     SDValue InVec2, InVec3;
5448     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5449         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5450         ((InVec0.getOpcode() == ISD::UNDEF ||
5451           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5452         ((InVec1.getOpcode() == ISD::UNDEF ||
5453           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5454       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5455
5456     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5457         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5458         ((InVec0.getOpcode() == ISD::UNDEF ||
5459           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5460         ((InVec1.getOpcode() == ISD::UNDEF ||
5461           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5462       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5463   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5464     // Try to match an AVX2 horizontal add/sub of signed integers.
5465     SDValue InVec2, InVec3;
5466     unsigned X86Opcode;
5467     bool CanFold = true;
5468
5469     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5470         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5471         ((InVec0.getOpcode() == ISD::UNDEF ||
5472           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5473         ((InVec1.getOpcode() == ISD::UNDEF ||
5474           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5475       X86Opcode = X86ISD::HADD;
5476     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5477         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5478         ((InVec0.getOpcode() == ISD::UNDEF ||
5479           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5480         ((InVec1.getOpcode() == ISD::UNDEF ||
5481           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5482       X86Opcode = X86ISD::HSUB;
5483     else
5484       CanFold = false;
5485
5486     if (CanFold) {
5487       // Fold this build_vector into a single horizontal add/sub.
5488       // Do this only if the target has AVX2.
5489       if (Subtarget->hasAVX2())
5490         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5491
5492       // Do not try to expand this build_vector into a pair of horizontal
5493       // add/sub if we can emit a pair of scalar add/sub.
5494       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5495         return SDValue();
5496
5497       // Convert this build_vector into a pair of horizontal binop followed by
5498       // a concat vector.
5499       bool isUndefLO = NumUndefsLO == Half;
5500       bool isUndefHI = NumUndefsHI == Half;
5501       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5502                                    isUndefLO, isUndefHI);
5503     }
5504   }
5505
5506   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5507        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5508     unsigned X86Opcode;
5509     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5510       X86Opcode = X86ISD::HADD;
5511     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5512       X86Opcode = X86ISD::HSUB;
5513     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5514       X86Opcode = X86ISD::FHADD;
5515     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5516       X86Opcode = X86ISD::FHSUB;
5517     else
5518       return SDValue();
5519
5520     // Don't try to expand this build_vector into a pair of horizontal add/sub
5521     // if we can simply emit a pair of scalar add/sub.
5522     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5523       return SDValue();
5524
5525     // Convert this build_vector into two horizontal add/sub followed by
5526     // a concat vector.
5527     bool isUndefLO = NumUndefsLO == Half;
5528     bool isUndefHI = NumUndefsHI == Half;
5529     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5530                                  isUndefLO, isUndefHI);
5531   }
5532
5533   return SDValue();
5534 }
5535
5536 SDValue
5537 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5538   SDLoc dl(Op);
5539
5540   MVT VT = Op.getSimpleValueType();
5541   MVT ExtVT = VT.getVectorElementType();
5542   unsigned NumElems = Op.getNumOperands();
5543
5544   // Generate vectors for predicate vectors.
5545   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5546     return LowerBUILD_VECTORvXi1(Op, DAG);
5547
5548   // Vectors containing all zeros can be matched by pxor and xorps later
5549   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5550     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5551     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5552     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5553       return Op;
5554
5555     return getZeroVector(VT, Subtarget, DAG, dl);
5556   }
5557
5558   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5559   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5560   // vpcmpeqd on 256-bit vectors.
5561   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5562     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5563       return Op;
5564
5565     if (!VT.is512BitVector())
5566       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5567   }
5568
5569   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5570   if (Broadcast.getNode())
5571     return Broadcast;
5572
5573   unsigned EVTBits = ExtVT.getSizeInBits();
5574
5575   unsigned NumZero  = 0;
5576   unsigned NumNonZero = 0;
5577   unsigned NonZeros = 0;
5578   bool IsAllConstants = true;
5579   SmallSet<SDValue, 8> Values;
5580   for (unsigned i = 0; i < NumElems; ++i) {
5581     SDValue Elt = Op.getOperand(i);
5582     if (Elt.getOpcode() == ISD::UNDEF)
5583       continue;
5584     Values.insert(Elt);
5585     if (Elt.getOpcode() != ISD::Constant &&
5586         Elt.getOpcode() != ISD::ConstantFP)
5587       IsAllConstants = false;
5588     if (X86::isZeroNode(Elt))
5589       NumZero++;
5590     else {
5591       NonZeros |= (1 << i);
5592       NumNonZero++;
5593     }
5594   }
5595
5596   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5597   if (NumNonZero == 0)
5598     return DAG.getUNDEF(VT);
5599
5600   // Special case for single non-zero, non-undef, element.
5601   if (NumNonZero == 1) {
5602     unsigned Idx = countTrailingZeros(NonZeros);
5603     SDValue Item = Op.getOperand(Idx);
5604
5605     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5606     // the value are obviously zero, truncate the value to i32 and do the
5607     // insertion that way.  Only do this if the value is non-constant or if the
5608     // value is a constant being inserted into element 0.  It is cheaper to do
5609     // a constant pool load than it is to do a movd + shuffle.
5610     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5611         (!IsAllConstants || Idx == 0)) {
5612       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5613         // Handle SSE only.
5614         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5615         EVT VecVT = MVT::v4i32;
5616
5617         // Truncate the value (which may itself be a constant) to i32, and
5618         // convert it to a vector with movd (S2V+shuffle to zero extend).
5619         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5620         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5621         return DAG.getNode(
5622             ISD::BITCAST, dl, VT,
5623             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5624       }
5625     }
5626
5627     // If we have a constant or non-constant insertion into the low element of
5628     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5629     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5630     // depending on what the source datatype is.
5631     if (Idx == 0) {
5632       if (NumZero == 0)
5633         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5634
5635       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5636           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5637         if (VT.is256BitVector() || VT.is512BitVector()) {
5638           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5639           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5640                              Item, DAG.getIntPtrConstant(0));
5641         }
5642         assert(VT.is128BitVector() && "Expected an SSE value type!");
5643         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5644         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5645         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5646       }
5647
5648       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5649         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5650         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5651         if (VT.is256BitVector()) {
5652           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5653           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5654         } else {
5655           assert(VT.is128BitVector() && "Expected an SSE value type!");
5656           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5657         }
5658         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5659       }
5660     }
5661
5662     // Is it a vector logical left shift?
5663     if (NumElems == 2 && Idx == 1 &&
5664         X86::isZeroNode(Op.getOperand(0)) &&
5665         !X86::isZeroNode(Op.getOperand(1))) {
5666       unsigned NumBits = VT.getSizeInBits();
5667       return getVShift(true, VT,
5668                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5669                                    VT, Op.getOperand(1)),
5670                        NumBits/2, DAG, *this, dl);
5671     }
5672
5673     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5674       return SDValue();
5675
5676     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5677     // is a non-constant being inserted into an element other than the low one,
5678     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5679     // movd/movss) to move this into the low element, then shuffle it into
5680     // place.
5681     if (EVTBits == 32) {
5682       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5683       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5684     }
5685   }
5686
5687   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5688   if (Values.size() == 1) {
5689     if (EVTBits == 32) {
5690       // Instead of a shuffle like this:
5691       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5692       // Check if it's possible to issue this instead.
5693       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5694       unsigned Idx = countTrailingZeros(NonZeros);
5695       SDValue Item = Op.getOperand(Idx);
5696       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5697         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5698     }
5699     return SDValue();
5700   }
5701
5702   // A vector full of immediates; various special cases are already
5703   // handled, so this is best done with a single constant-pool load.
5704   if (IsAllConstants)
5705     return SDValue();
5706
5707   // For AVX-length vectors, see if we can use a vector load to get all of the
5708   // elements, otherwise build the individual 128-bit pieces and use
5709   // shuffles to put them in place.
5710   if (VT.is256BitVector() || VT.is512BitVector()) {
5711     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5712
5713     // Check for a build vector of consecutive loads.
5714     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5715       return LD;
5716
5717     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5718
5719     // Build both the lower and upper subvector.
5720     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5721                                 makeArrayRef(&V[0], NumElems/2));
5722     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5723                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5724
5725     // Recreate the wider vector with the lower and upper part.
5726     if (VT.is256BitVector())
5727       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5728     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5729   }
5730
5731   // Let legalizer expand 2-wide build_vectors.
5732   if (EVTBits == 64) {
5733     if (NumNonZero == 1) {
5734       // One half is zero or undef.
5735       unsigned Idx = countTrailingZeros(NonZeros);
5736       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5737                                  Op.getOperand(Idx));
5738       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5739     }
5740     return SDValue();
5741   }
5742
5743   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5744   if (EVTBits == 8 && NumElems == 16) {
5745     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5746                                         Subtarget, *this);
5747     if (V.getNode()) return V;
5748   }
5749
5750   if (EVTBits == 16 && NumElems == 8) {
5751     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5752                                       Subtarget, *this);
5753     if (V.getNode()) return V;
5754   }
5755
5756   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5757   if (EVTBits == 32 && NumElems == 4) {
5758     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5759     if (V.getNode())
5760       return V;
5761   }
5762
5763   // If element VT is == 32 bits, turn it into a number of shuffles.
5764   SmallVector<SDValue, 8> V(NumElems);
5765   if (NumElems == 4 && NumZero > 0) {
5766     for (unsigned i = 0; i < 4; ++i) {
5767       bool isZero = !(NonZeros & (1 << i));
5768       if (isZero)
5769         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5770       else
5771         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5772     }
5773
5774     for (unsigned i = 0; i < 2; ++i) {
5775       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5776         default: break;
5777         case 0:
5778           V[i] = V[i*2];  // Must be a zero vector.
5779           break;
5780         case 1:
5781           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5782           break;
5783         case 2:
5784           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5785           break;
5786         case 3:
5787           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5788           break;
5789       }
5790     }
5791
5792     bool Reverse1 = (NonZeros & 0x3) == 2;
5793     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5794     int MaskVec[] = {
5795       Reverse1 ? 1 : 0,
5796       Reverse1 ? 0 : 1,
5797       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5798       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5799     };
5800     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5801   }
5802
5803   if (Values.size() > 1 && VT.is128BitVector()) {
5804     // Check for a build vector of consecutive loads.
5805     for (unsigned i = 0; i < NumElems; ++i)
5806       V[i] = Op.getOperand(i);
5807
5808     // Check for elements which are consecutive loads.
5809     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5810     if (LD.getNode())
5811       return LD;
5812
5813     // Check for a build vector from mostly shuffle plus few inserting.
5814     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5815     if (Sh.getNode())
5816       return Sh;
5817
5818     // For SSE 4.1, use insertps to put the high elements into the low element.
5819     if (Subtarget->hasSSE41()) {
5820       SDValue Result;
5821       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5822         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5823       else
5824         Result = DAG.getUNDEF(VT);
5825
5826       for (unsigned i = 1; i < NumElems; ++i) {
5827         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5828         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5829                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5830       }
5831       return Result;
5832     }
5833
5834     // Otherwise, expand into a number of unpckl*, start by extending each of
5835     // our (non-undef) elements to the full vector width with the element in the
5836     // bottom slot of the vector (which generates no code for SSE).
5837     for (unsigned i = 0; i < NumElems; ++i) {
5838       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5839         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5840       else
5841         V[i] = DAG.getUNDEF(VT);
5842     }
5843
5844     // Next, we iteratively mix elements, e.g. for v4f32:
5845     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5846     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5847     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5848     unsigned EltStride = NumElems >> 1;
5849     while (EltStride != 0) {
5850       for (unsigned i = 0; i < EltStride; ++i) {
5851         // If V[i+EltStride] is undef and this is the first round of mixing,
5852         // then it is safe to just drop this shuffle: V[i] is already in the
5853         // right place, the one element (since it's the first round) being
5854         // inserted as undef can be dropped.  This isn't safe for successive
5855         // rounds because they will permute elements within both vectors.
5856         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5857             EltStride == NumElems/2)
5858           continue;
5859
5860         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5861       }
5862       EltStride >>= 1;
5863     }
5864     return V[0];
5865   }
5866   return SDValue();
5867 }
5868
5869 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5870 // to create 256-bit vectors from two other 128-bit ones.
5871 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5872   SDLoc dl(Op);
5873   MVT ResVT = Op.getSimpleValueType();
5874
5875   assert((ResVT.is256BitVector() ||
5876           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5877
5878   SDValue V1 = Op.getOperand(0);
5879   SDValue V2 = Op.getOperand(1);
5880   unsigned NumElems = ResVT.getVectorNumElements();
5881   if(ResVT.is256BitVector())
5882     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5883
5884   if (Op.getNumOperands() == 4) {
5885     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5886                                 ResVT.getVectorNumElements()/2);
5887     SDValue V3 = Op.getOperand(2);
5888     SDValue V4 = Op.getOperand(3);
5889     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5890       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5891   }
5892   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5893 }
5894
5895 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5896   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
5897   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5898          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5899           Op.getNumOperands() == 4)));
5900
5901   // AVX can use the vinsertf128 instruction to create 256-bit vectors
5902   // from two other 128-bit ones.
5903
5904   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5905   return LowerAVXCONCAT_VECTORS(Op, DAG);
5906 }
5907
5908
5909 //===----------------------------------------------------------------------===//
5910 // Vector shuffle lowering
5911 //
5912 // This is an experimental code path for lowering vector shuffles on x86. It is
5913 // designed to handle arbitrary vector shuffles and blends, gracefully
5914 // degrading performance as necessary. It works hard to recognize idiomatic
5915 // shuffles and lower them to optimal instruction patterns without leaving
5916 // a framework that allows reasonably efficient handling of all vector shuffle
5917 // patterns.
5918 //===----------------------------------------------------------------------===//
5919
5920 /// \brief Tiny helper function to identify a no-op mask.
5921 ///
5922 /// This is a somewhat boring predicate function. It checks whether the mask
5923 /// array input, which is assumed to be a single-input shuffle mask of the kind
5924 /// used by the X86 shuffle instructions (not a fully general
5925 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5926 /// in-place shuffle are 'no-op's.
5927 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5928   for (int i = 0, Size = Mask.size(); i < Size; ++i)
5929     if (Mask[i] != -1 && Mask[i] != i)
5930       return false;
5931   return true;
5932 }
5933
5934 /// \brief Helper function to classify a mask as a single-input mask.
5935 ///
5936 /// This isn't a generic single-input test because in the vector shuffle
5937 /// lowering we canonicalize single inputs to be the first input operand. This
5938 /// means we can more quickly test for a single input by only checking whether
5939 /// an input from the second operand exists. We also assume that the size of
5940 /// mask corresponds to the size of the input vectors which isn't true in the
5941 /// fully general case.
5942 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5943   for (int M : Mask)
5944     if (M >= (int)Mask.size())
5945       return false;
5946   return true;
5947 }
5948
5949 /// \brief Test whether there are elements crossing 128-bit lanes in this
5950 /// shuffle mask.
5951 ///
5952 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5953 /// and we routinely test for these.
5954 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5955   int LaneSize = 128 / VT.getScalarSizeInBits();
5956   int Size = Mask.size();
5957   for (int i = 0; i < Size; ++i)
5958     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5959       return true;
5960   return false;
5961 }
5962
5963 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5964 ///
5965 /// This checks a shuffle mask to see if it is performing the same
5966 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5967 /// that it is also not lane-crossing. It may however involve a blend from the
5968 /// same lane of a second vector.
5969 ///
5970 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5971 /// non-trivial to compute in the face of undef lanes. The representation is
5972 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5973 /// entries from both V1 and V2 inputs to the wider mask.
5974 static bool
5975 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5976                                 SmallVectorImpl<int> &RepeatedMask) {
5977   int LaneSize = 128 / VT.getScalarSizeInBits();
5978   RepeatedMask.resize(LaneSize, -1);
5979   int Size = Mask.size();
5980   for (int i = 0; i < Size; ++i) {
5981     if (Mask[i] < 0)
5982       continue;
5983     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
5984       // This entry crosses lanes, so there is no way to model this shuffle.
5985       return false;
5986
5987     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
5988     if (RepeatedMask[i % LaneSize] == -1)
5989       // This is the first non-undef entry in this slot of a 128-bit lane.
5990       RepeatedMask[i % LaneSize] =
5991           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
5992     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
5993       // Found a mismatch with the repeated mask.
5994       return false;
5995   }
5996   return true;
5997 }
5998
5999 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6000 /// arguments.
6001 ///
6002 /// This is a fast way to test a shuffle mask against a fixed pattern:
6003 ///
6004 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6005 ///
6006 /// It returns true if the mask is exactly as wide as the argument list, and
6007 /// each element of the mask is either -1 (signifying undef) or the value given
6008 /// in the argument.
6009 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6010                                 ArrayRef<int> ExpectedMask) {
6011   if (Mask.size() != ExpectedMask.size())
6012     return false;
6013
6014   int Size = Mask.size();
6015
6016   // If the values are build vectors, we can look through them to find
6017   // equivalent inputs that make the shuffles equivalent.
6018   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6019   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6020
6021   for (int i = 0; i < Size; ++i)
6022     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6023       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6024       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6025       if (!MaskBV || !ExpectedBV ||
6026           MaskBV->getOperand(Mask[i] % Size) !=
6027               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6028         return false;
6029     }
6030
6031   return true;
6032 }
6033
6034 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6035 ///
6036 /// This helper function produces an 8-bit shuffle immediate corresponding to
6037 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6038 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6039 /// example.
6040 ///
6041 /// NB: We rely heavily on "undef" masks preserving the input lane.
6042 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6043                                           SelectionDAG &DAG) {
6044   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6045   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6046   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6047   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6048   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6049
6050   unsigned Imm = 0;
6051   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6052   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6053   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6054   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6055   return DAG.getConstant(Imm, MVT::i8);
6056 }
6057
6058 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6059 ///
6060 /// This is used as a fallback approach when first class blend instructions are
6061 /// unavailable. Currently it is only suitable for integer vectors, but could
6062 /// be generalized for floating point vectors if desirable.
6063 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6064                                             SDValue V2, ArrayRef<int> Mask,
6065                                             SelectionDAG &DAG) {
6066   assert(VT.isInteger() && "Only supports integer vector types!");
6067   MVT EltVT = VT.getScalarType();
6068   int NumEltBits = EltVT.getSizeInBits();
6069   SDValue Zero = DAG.getConstant(0, EltVT);
6070   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6071   SmallVector<SDValue, 16> MaskOps;
6072   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6073     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6074       return SDValue(); // Shuffled input!
6075     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6076   }
6077
6078   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6079   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6080   // We have to cast V2 around.
6081   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6082   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6083                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6084                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6085                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6086   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6087 }
6088
6089 /// \brief Try to emit a blend instruction for a shuffle.
6090 ///
6091 /// This doesn't do any checks for the availability of instructions for blending
6092 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6093 /// be matched in the backend with the type given. What it does check for is
6094 /// that the shuffle mask is in fact a blend.
6095 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6096                                          SDValue V2, ArrayRef<int> Mask,
6097                                          const X86Subtarget *Subtarget,
6098                                          SelectionDAG &DAG) {
6099   unsigned BlendMask = 0;
6100   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6101     if (Mask[i] >= Size) {
6102       if (Mask[i] != i + Size)
6103         return SDValue(); // Shuffled V2 input!
6104       BlendMask |= 1u << i;
6105       continue;
6106     }
6107     if (Mask[i] >= 0 && Mask[i] != i)
6108       return SDValue(); // Shuffled V1 input!
6109   }
6110   switch (VT.SimpleTy) {
6111   case MVT::v2f64:
6112   case MVT::v4f32:
6113   case MVT::v4f64:
6114   case MVT::v8f32:
6115     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6116                        DAG.getConstant(BlendMask, MVT::i8));
6117
6118   case MVT::v4i64:
6119   case MVT::v8i32:
6120     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6121     // FALLTHROUGH
6122   case MVT::v2i64:
6123   case MVT::v4i32:
6124     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6125     // that instruction.
6126     if (Subtarget->hasAVX2()) {
6127       // Scale the blend by the number of 32-bit dwords per element.
6128       int Scale =  VT.getScalarSizeInBits() / 32;
6129       BlendMask = 0;
6130       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6131         if (Mask[i] >= Size)
6132           for (int j = 0; j < Scale; ++j)
6133             BlendMask |= 1u << (i * Scale + j);
6134
6135       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6136       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6137       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6138       return DAG.getNode(ISD::BITCAST, DL, VT,
6139                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6140                                      DAG.getConstant(BlendMask, MVT::i8)));
6141     }
6142     // FALLTHROUGH
6143   case MVT::v8i16: {
6144     // For integer shuffles we need to expand the mask and cast the inputs to
6145     // v8i16s prior to blending.
6146     int Scale = 8 / VT.getVectorNumElements();
6147     BlendMask = 0;
6148     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6149       if (Mask[i] >= Size)
6150         for (int j = 0; j < Scale; ++j)
6151           BlendMask |= 1u << (i * Scale + j);
6152
6153     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6154     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6155     return DAG.getNode(ISD::BITCAST, DL, VT,
6156                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6157                                    DAG.getConstant(BlendMask, MVT::i8)));
6158   }
6159
6160   case MVT::v16i16: {
6161     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6162     SmallVector<int, 8> RepeatedMask;
6163     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6164       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6165       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6166       BlendMask = 0;
6167       for (int i = 0; i < 8; ++i)
6168         if (RepeatedMask[i] >= 16)
6169           BlendMask |= 1u << i;
6170       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6171                          DAG.getConstant(BlendMask, MVT::i8));
6172     }
6173   }
6174     // FALLTHROUGH
6175   case MVT::v16i8:
6176   case MVT::v32i8: {
6177     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6178            "256-bit byte-blends require AVX2 support!");
6179
6180     // Scale the blend by the number of bytes per element.
6181     int Scale = VT.getScalarSizeInBits() / 8;
6182
6183     // This form of blend is always done on bytes. Compute the byte vector
6184     // type.
6185     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6186
6187     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6188     // mix of LLVM's code generator and the x86 backend. We tell the code
6189     // generator that boolean values in the elements of an x86 vector register
6190     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6191     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6192     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6193     // of the element (the remaining are ignored) and 0 in that high bit would
6194     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6195     // the LLVM model for boolean values in vector elements gets the relevant
6196     // bit set, it is set backwards and over constrained relative to x86's
6197     // actual model.
6198     SmallVector<SDValue, 32> VSELECTMask;
6199     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6200       for (int j = 0; j < Scale; ++j)
6201         VSELECTMask.push_back(
6202             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6203                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6204
6205     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6206     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6207     return DAG.getNode(
6208         ISD::BITCAST, DL, VT,
6209         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6210                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6211                     V1, V2));
6212   }
6213
6214   default:
6215     llvm_unreachable("Not a supported integer vector type!");
6216   }
6217 }
6218
6219 /// \brief Try to lower as a blend of elements from two inputs followed by
6220 /// a single-input permutation.
6221 ///
6222 /// This matches the pattern where we can blend elements from two inputs and
6223 /// then reduce the shuffle to a single-input permutation.
6224 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6225                                                    SDValue V2,
6226                                                    ArrayRef<int> Mask,
6227                                                    SelectionDAG &DAG) {
6228   // We build up the blend mask while checking whether a blend is a viable way
6229   // to reduce the shuffle.
6230   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6231   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6232
6233   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6234     if (Mask[i] < 0)
6235       continue;
6236
6237     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6238
6239     if (BlendMask[Mask[i] % Size] == -1)
6240       BlendMask[Mask[i] % Size] = Mask[i];
6241     else if (BlendMask[Mask[i] % Size] != Mask[i])
6242       return SDValue(); // Can't blend in the needed input!
6243
6244     PermuteMask[i] = Mask[i] % Size;
6245   }
6246
6247   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6248   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6249 }
6250
6251 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6252 /// blends and permutes.
6253 ///
6254 /// This matches the extremely common pattern for handling combined
6255 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6256 /// operations. It will try to pick the best arrangement of shuffles and
6257 /// blends.
6258 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6259                                                           SDValue V1,
6260                                                           SDValue V2,
6261                                                           ArrayRef<int> Mask,
6262                                                           SelectionDAG &DAG) {
6263   // Shuffle the input elements into the desired positions in V1 and V2 and
6264   // blend them together.
6265   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6266   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6267   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6268   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6269     if (Mask[i] >= 0 && Mask[i] < Size) {
6270       V1Mask[i] = Mask[i];
6271       BlendMask[i] = i;
6272     } else if (Mask[i] >= Size) {
6273       V2Mask[i] = Mask[i] - Size;
6274       BlendMask[i] = i + Size;
6275     }
6276
6277   // Try to lower with the simpler initial blend strategy unless one of the
6278   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6279   // shuffle may be able to fold with a load or other benefit. However, when
6280   // we'll have to do 2x as many shuffles in order to achieve this, blending
6281   // first is a better strategy.
6282   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6283     if (SDValue BlendPerm =
6284             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6285       return BlendPerm;
6286
6287   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6288   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6289   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6290 }
6291
6292 /// \brief Try to lower a vector shuffle as a byte rotation.
6293 ///
6294 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6295 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6296 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6297 /// try to generically lower a vector shuffle through such an pattern. It
6298 /// does not check for the profitability of lowering either as PALIGNR or
6299 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6300 /// This matches shuffle vectors that look like:
6301 ///
6302 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6303 ///
6304 /// Essentially it concatenates V1 and V2, shifts right by some number of
6305 /// elements, and takes the low elements as the result. Note that while this is
6306 /// specified as a *right shift* because x86 is little-endian, it is a *left
6307 /// rotate* of the vector lanes.
6308 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6309                                               SDValue V2,
6310                                               ArrayRef<int> Mask,
6311                                               const X86Subtarget *Subtarget,
6312                                               SelectionDAG &DAG) {
6313   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6314
6315   int NumElts = Mask.size();
6316   int NumLanes = VT.getSizeInBits() / 128;
6317   int NumLaneElts = NumElts / NumLanes;
6318
6319   // We need to detect various ways of spelling a rotation:
6320   //   [11, 12, 13, 14, 15,  0,  1,  2]
6321   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6322   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6323   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6324   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6325   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6326   int Rotation = 0;
6327   SDValue Lo, Hi;
6328   for (int l = 0; l < NumElts; l += NumLaneElts) {
6329     for (int i = 0; i < NumLaneElts; ++i) {
6330       if (Mask[l + i] == -1)
6331         continue;
6332       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6333
6334       // Get the mod-Size index and lane correct it.
6335       int LaneIdx = (Mask[l + i] % NumElts) - l;
6336       // Make sure it was in this lane.
6337       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6338         return SDValue();
6339
6340       // Determine where a rotated vector would have started.
6341       int StartIdx = i - LaneIdx;
6342       if (StartIdx == 0)
6343         // The identity rotation isn't interesting, stop.
6344         return SDValue();
6345
6346       // If we found the tail of a vector the rotation must be the missing
6347       // front. If we found the head of a vector, it must be how much of the
6348       // head.
6349       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6350
6351       if (Rotation == 0)
6352         Rotation = CandidateRotation;
6353       else if (Rotation != CandidateRotation)
6354         // The rotations don't match, so we can't match this mask.
6355         return SDValue();
6356
6357       // Compute which value this mask is pointing at.
6358       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6359
6360       // Compute which of the two target values this index should be assigned
6361       // to. This reflects whether the high elements are remaining or the low
6362       // elements are remaining.
6363       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6364
6365       // Either set up this value if we've not encountered it before, or check
6366       // that it remains consistent.
6367       if (!TargetV)
6368         TargetV = MaskV;
6369       else if (TargetV != MaskV)
6370         // This may be a rotation, but it pulls from the inputs in some
6371         // unsupported interleaving.
6372         return SDValue();
6373     }
6374   }
6375
6376   // Check that we successfully analyzed the mask, and normalize the results.
6377   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6378   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6379   if (!Lo)
6380     Lo = Hi;
6381   else if (!Hi)
6382     Hi = Lo;
6383
6384   // The actual rotate instruction rotates bytes, so we need to scale the
6385   // rotation based on how many bytes are in the vector lane.
6386   int Scale = 16 / NumLaneElts;
6387
6388   // SSSE3 targets can use the palignr instruction.
6389   if (Subtarget->hasSSSE3()) {
6390     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6391     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6392     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6393     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6394
6395     return DAG.getNode(ISD::BITCAST, DL, VT,
6396                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6397                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6398   }
6399
6400   assert(VT.getSizeInBits() == 128 &&
6401          "Rotate-based lowering only supports 128-bit lowering!");
6402   assert(Mask.size() <= 16 &&
6403          "Can shuffle at most 16 bytes in a 128-bit vector!");
6404
6405   // Default SSE2 implementation
6406   int LoByteShift = 16 - Rotation * Scale;
6407   int HiByteShift = Rotation * Scale;
6408
6409   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6410   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6411   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6412
6413   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6414                                 DAG.getConstant(LoByteShift, MVT::i8));
6415   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6416                                 DAG.getConstant(HiByteShift, MVT::i8));
6417   return DAG.getNode(ISD::BITCAST, DL, VT,
6418                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6419 }
6420
6421 /// \brief Compute whether each element of a shuffle is zeroable.
6422 ///
6423 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6424 /// Either it is an undef element in the shuffle mask, the element of the input
6425 /// referenced is undef, or the element of the input referenced is known to be
6426 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6427 /// as many lanes with this technique as possible to simplify the remaining
6428 /// shuffle.
6429 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6430                                                      SDValue V1, SDValue V2) {
6431   SmallBitVector Zeroable(Mask.size(), false);
6432
6433   while (V1.getOpcode() == ISD::BITCAST)
6434     V1 = V1->getOperand(0);
6435   while (V2.getOpcode() == ISD::BITCAST)
6436     V2 = V2->getOperand(0);
6437
6438   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6439   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6440
6441   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6442     int M = Mask[i];
6443     // Handle the easy cases.
6444     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6445       Zeroable[i] = true;
6446       continue;
6447     }
6448
6449     // If this is an index into a build_vector node (which has the same number
6450     // of elements), dig out the input value and use it.
6451     SDValue V = M < Size ? V1 : V2;
6452     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6453       continue;
6454
6455     SDValue Input = V.getOperand(M % Size);
6456     // The UNDEF opcode check really should be dead code here, but not quite
6457     // worth asserting on (it isn't invalid, just unexpected).
6458     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6459       Zeroable[i] = true;
6460   }
6461
6462   return Zeroable;
6463 }
6464
6465 /// \brief Try to emit a bitmask instruction for a shuffle.
6466 ///
6467 /// This handles cases where we can model a blend exactly as a bitmask due to
6468 /// one of the inputs being zeroable.
6469 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6470                                            SDValue V2, ArrayRef<int> Mask,
6471                                            SelectionDAG &DAG) {
6472   MVT EltVT = VT.getScalarType();
6473   int NumEltBits = EltVT.getSizeInBits();
6474   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6475   SDValue Zero = DAG.getConstant(0, IntEltVT);
6476   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6477   if (EltVT.isFloatingPoint()) {
6478     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6479     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6480   }
6481   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6482   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6483   SDValue V;
6484   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6485     if (Zeroable[i])
6486       continue;
6487     if (Mask[i] % Size != i)
6488       return SDValue(); // Not a blend.
6489     if (!V)
6490       V = Mask[i] < Size ? V1 : V2;
6491     else if (V != (Mask[i] < Size ? V1 : V2))
6492       return SDValue(); // Can only let one input through the mask.
6493
6494     VMaskOps[i] = AllOnes;
6495   }
6496   if (!V)
6497     return SDValue(); // No non-zeroable elements!
6498
6499   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6500   V = DAG.getNode(VT.isFloatingPoint()
6501                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6502                   DL, VT, V, VMask);
6503   return V;
6504 }
6505
6506 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6507 ///
6508 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6509 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6510 /// matches elements from one of the input vectors shuffled to the left or
6511 /// right with zeroable elements 'shifted in'. It handles both the strictly
6512 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6513 /// quad word lane.
6514 ///
6515 /// PSHL : (little-endian) left bit shift.
6516 /// [ zz, 0, zz,  2 ]
6517 /// [ -1, 4, zz, -1 ]
6518 /// PSRL : (little-endian) right bit shift.
6519 /// [  1, zz,  3, zz]
6520 /// [ -1, -1,  7, zz]
6521 /// PSLLDQ : (little-endian) left byte shift
6522 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6523 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6524 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6525 /// PSRLDQ : (little-endian) right byte shift
6526 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6527 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6528 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6529 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6530                                          SDValue V2, ArrayRef<int> Mask,
6531                                          SelectionDAG &DAG) {
6532   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6533
6534   int Size = Mask.size();
6535   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6536
6537   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6538     for (int i = 0; i < Size; i += Scale)
6539       for (int j = 0; j < Shift; ++j)
6540         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6541           return false;
6542
6543     return true;
6544   };
6545
6546   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6547     for (int i = 0; i != Size; i += Scale) {
6548       unsigned Pos = Left ? i + Shift : i;
6549       unsigned Low = Left ? i : i + Shift;
6550       unsigned Len = Scale - Shift;
6551       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6552                                       Low + (V == V1 ? 0 : Size)))
6553         return SDValue();
6554     }
6555
6556     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6557     bool ByteShift = ShiftEltBits > 64;
6558     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6559                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6560     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6561
6562     // Normalize the scale for byte shifts to still produce an i64 element
6563     // type.
6564     Scale = ByteShift ? Scale / 2 : Scale;
6565
6566     // We need to round trip through the appropriate type for the shift.
6567     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6568     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6569     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6570            "Illegal integer vector type");
6571     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6572
6573     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6574     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6575   };
6576
6577   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6578   // keep doubling the size of the integer elements up to that. We can
6579   // then shift the elements of the integer vector by whole multiples of
6580   // their width within the elements of the larger integer vector. Test each
6581   // multiple to see if we can find a match with the moved element indices
6582   // and that the shifted in elements are all zeroable.
6583   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6584     for (int Shift = 1; Shift != Scale; ++Shift)
6585       for (bool Left : {true, false})
6586         if (CheckZeros(Shift, Scale, Left))
6587           for (SDValue V : {V1, V2})
6588             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6589               return Match;
6590
6591   // no match
6592   return SDValue();
6593 }
6594
6595 /// \brief Lower a vector shuffle as a zero or any extension.
6596 ///
6597 /// Given a specific number of elements, element bit width, and extension
6598 /// stride, produce either a zero or any extension based on the available
6599 /// features of the subtarget.
6600 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6601     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6602     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6603   assert(Scale > 1 && "Need a scale to extend.");
6604   int NumElements = VT.getVectorNumElements();
6605   int EltBits = VT.getScalarSizeInBits();
6606   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6607          "Only 8, 16, and 32 bit elements can be extended.");
6608   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6609
6610   // Found a valid zext mask! Try various lowering strategies based on the
6611   // input type and available ISA extensions.
6612   if (Subtarget->hasSSE41()) {
6613     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6614                                  NumElements / Scale);
6615     return DAG.getNode(ISD::BITCAST, DL, VT,
6616                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6617   }
6618
6619   // For any extends we can cheat for larger element sizes and use shuffle
6620   // instructions that can fold with a load and/or copy.
6621   if (AnyExt && EltBits == 32) {
6622     int PSHUFDMask[4] = {0, -1, 1, -1};
6623     return DAG.getNode(
6624         ISD::BITCAST, DL, VT,
6625         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6626                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6627                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6628   }
6629   if (AnyExt && EltBits == 16 && Scale > 2) {
6630     int PSHUFDMask[4] = {0, -1, 0, -1};
6631     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6632                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6633                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6634     int PSHUFHWMask[4] = {1, -1, -1, -1};
6635     return DAG.getNode(
6636         ISD::BITCAST, DL, VT,
6637         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6638                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6639                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6640   }
6641
6642   // If this would require more than 2 unpack instructions to expand, use
6643   // pshufb when available. We can only use more than 2 unpack instructions
6644   // when zero extending i8 elements which also makes it easier to use pshufb.
6645   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6646     assert(NumElements == 16 && "Unexpected byte vector width!");
6647     SDValue PSHUFBMask[16];
6648     for (int i = 0; i < 16; ++i)
6649       PSHUFBMask[i] =
6650           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6651     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6652     return DAG.getNode(ISD::BITCAST, DL, VT,
6653                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6654                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6655                                                MVT::v16i8, PSHUFBMask)));
6656   }
6657
6658   // Otherwise emit a sequence of unpacks.
6659   do {
6660     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6661     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6662                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6663     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6664     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6665     Scale /= 2;
6666     EltBits *= 2;
6667     NumElements /= 2;
6668   } while (Scale > 1);
6669   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6670 }
6671
6672 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6673 ///
6674 /// This routine will try to do everything in its power to cleverly lower
6675 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6676 /// check for the profitability of this lowering,  it tries to aggressively
6677 /// match this pattern. It will use all of the micro-architectural details it
6678 /// can to emit an efficient lowering. It handles both blends with all-zero
6679 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6680 /// masking out later).
6681 ///
6682 /// The reason we have dedicated lowering for zext-style shuffles is that they
6683 /// are both incredibly common and often quite performance sensitive.
6684 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6685     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6686     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6687   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6688
6689   int Bits = VT.getSizeInBits();
6690   int NumElements = VT.getVectorNumElements();
6691   assert(VT.getScalarSizeInBits() <= 32 &&
6692          "Exceeds 32-bit integer zero extension limit");
6693   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6694
6695   // Define a helper function to check a particular ext-scale and lower to it if
6696   // valid.
6697   auto Lower = [&](int Scale) -> SDValue {
6698     SDValue InputV;
6699     bool AnyExt = true;
6700     for (int i = 0; i < NumElements; ++i) {
6701       if (Mask[i] == -1)
6702         continue; // Valid anywhere but doesn't tell us anything.
6703       if (i % Scale != 0) {
6704         // Each of the extended elements need to be zeroable.
6705         if (!Zeroable[i])
6706           return SDValue();
6707
6708         // We no longer are in the anyext case.
6709         AnyExt = false;
6710         continue;
6711       }
6712
6713       // Each of the base elements needs to be consecutive indices into the
6714       // same input vector.
6715       SDValue V = Mask[i] < NumElements ? V1 : V2;
6716       if (!InputV)
6717         InputV = V;
6718       else if (InputV != V)
6719         return SDValue(); // Flip-flopping inputs.
6720
6721       if (Mask[i] % NumElements != i / Scale)
6722         return SDValue(); // Non-consecutive strided elements.
6723     }
6724
6725     // If we fail to find an input, we have a zero-shuffle which should always
6726     // have already been handled.
6727     // FIXME: Maybe handle this here in case during blending we end up with one?
6728     if (!InputV)
6729       return SDValue();
6730
6731     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6732         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6733   };
6734
6735   // The widest scale possible for extending is to a 64-bit integer.
6736   assert(Bits % 64 == 0 &&
6737          "The number of bits in a vector must be divisible by 64 on x86!");
6738   int NumExtElements = Bits / 64;
6739
6740   // Each iteration, try extending the elements half as much, but into twice as
6741   // many elements.
6742   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6743     assert(NumElements % NumExtElements == 0 &&
6744            "The input vector size must be divisible by the extended size.");
6745     if (SDValue V = Lower(NumElements / NumExtElements))
6746       return V;
6747   }
6748
6749   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6750   if (Bits != 128)
6751     return SDValue();
6752
6753   // Returns one of the source operands if the shuffle can be reduced to a
6754   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6755   auto CanZExtLowHalf = [&]() {
6756     for (int i = NumElements / 2; i != NumElements; ++i)
6757       if (!Zeroable[i])
6758         return SDValue();
6759     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6760       return V1;
6761     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6762       return V2;
6763     return SDValue();
6764   };
6765
6766   if (SDValue V = CanZExtLowHalf()) {
6767     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6768     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6769     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6770   }
6771
6772   // No viable ext lowering found.
6773   return SDValue();
6774 }
6775
6776 /// \brief Try to get a scalar value for a specific element of a vector.
6777 ///
6778 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6779 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6780                                               SelectionDAG &DAG) {
6781   MVT VT = V.getSimpleValueType();
6782   MVT EltVT = VT.getVectorElementType();
6783   while (V.getOpcode() == ISD::BITCAST)
6784     V = V.getOperand(0);
6785   // If the bitcasts shift the element size, we can't extract an equivalent
6786   // element from it.
6787   MVT NewVT = V.getSimpleValueType();
6788   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6789     return SDValue();
6790
6791   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6792       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6793     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6794
6795   return SDValue();
6796 }
6797
6798 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6799 ///
6800 /// This is particularly important because the set of instructions varies
6801 /// significantly based on whether the operand is a load or not.
6802 static bool isShuffleFoldableLoad(SDValue V) {
6803   while (V.getOpcode() == ISD::BITCAST)
6804     V = V.getOperand(0);
6805
6806   return ISD::isNON_EXTLoad(V.getNode());
6807 }
6808
6809 /// \brief Try to lower insertion of a single element into a zero vector.
6810 ///
6811 /// This is a common pattern that we have especially efficient patterns to lower
6812 /// across all subtarget feature sets.
6813 static SDValue lowerVectorShuffleAsElementInsertion(
6814     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6815     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6816   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6817   MVT ExtVT = VT;
6818   MVT EltVT = VT.getVectorElementType();
6819
6820   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6821                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6822                 Mask.begin();
6823   bool IsV1Zeroable = true;
6824   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6825     if (i != V2Index && !Zeroable[i]) {
6826       IsV1Zeroable = false;
6827       break;
6828     }
6829
6830   // Check for a single input from a SCALAR_TO_VECTOR node.
6831   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6832   // all the smarts here sunk into that routine. However, the current
6833   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6834   // vector shuffle lowering is dead.
6835   if (SDValue V2S = getScalarValueForVectorElement(
6836           V2, Mask[V2Index] - Mask.size(), DAG)) {
6837     // We need to zext the scalar if it is smaller than an i32.
6838     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6839     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6840       // Using zext to expand a narrow element won't work for non-zero
6841       // insertions.
6842       if (!IsV1Zeroable)
6843         return SDValue();
6844
6845       // Zero-extend directly to i32.
6846       ExtVT = MVT::v4i32;
6847       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6848     }
6849     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6850   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6851              EltVT == MVT::i16) {
6852     // Either not inserting from the low element of the input or the input
6853     // element size is too small to use VZEXT_MOVL to clear the high bits.
6854     return SDValue();
6855   }
6856
6857   if (!IsV1Zeroable) {
6858     // If V1 can't be treated as a zero vector we have fewer options to lower
6859     // this. We can't support integer vectors or non-zero targets cheaply, and
6860     // the V1 elements can't be permuted in any way.
6861     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6862     if (!VT.isFloatingPoint() || V2Index != 0)
6863       return SDValue();
6864     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6865     V1Mask[V2Index] = -1;
6866     if (!isNoopShuffleMask(V1Mask))
6867       return SDValue();
6868     // This is essentially a special case blend operation, but if we have
6869     // general purpose blend operations, they are always faster. Bail and let
6870     // the rest of the lowering handle these as blends.
6871     if (Subtarget->hasSSE41())
6872       return SDValue();
6873
6874     // Otherwise, use MOVSD or MOVSS.
6875     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6876            "Only two types of floating point element types to handle!");
6877     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6878                        ExtVT, V1, V2);
6879   }
6880
6881   // This lowering only works for the low element with floating point vectors.
6882   if (VT.isFloatingPoint() && V2Index != 0)
6883     return SDValue();
6884
6885   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6886   if (ExtVT != VT)
6887     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6888
6889   if (V2Index != 0) {
6890     // If we have 4 or fewer lanes we can cheaply shuffle the element into
6891     // the desired position. Otherwise it is more efficient to do a vector
6892     // shift left. We know that we can do a vector shift left because all
6893     // the inputs are zero.
6894     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6895       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6896       V2Shuffle[V2Index] = 0;
6897       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6898     } else {
6899       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6900       V2 = DAG.getNode(
6901           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6902           DAG.getConstant(
6903               V2Index * EltVT.getSizeInBits()/8,
6904               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6905       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6906     }
6907   }
6908   return V2;
6909 }
6910
6911 /// \brief Try to lower broadcast of a single element.
6912 ///
6913 /// For convenience, this code also bundles all of the subtarget feature set
6914 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6915 /// a convenient way to factor it out.
6916 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6917                                              ArrayRef<int> Mask,
6918                                              const X86Subtarget *Subtarget,
6919                                              SelectionDAG &DAG) {
6920   if (!Subtarget->hasAVX())
6921     return SDValue();
6922   if (VT.isInteger() && !Subtarget->hasAVX2())
6923     return SDValue();
6924
6925   // Check that the mask is a broadcast.
6926   int BroadcastIdx = -1;
6927   for (int M : Mask)
6928     if (M >= 0 && BroadcastIdx == -1)
6929       BroadcastIdx = M;
6930     else if (M >= 0 && M != BroadcastIdx)
6931       return SDValue();
6932
6933   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6934                                             "a sorted mask where the broadcast "
6935                                             "comes from V1.");
6936
6937   // Go up the chain of (vector) values to try and find a scalar load that
6938   // we can combine with the broadcast.
6939   for (;;) {
6940     switch (V.getOpcode()) {
6941     case ISD::CONCAT_VECTORS: {
6942       int OperandSize = Mask.size() / V.getNumOperands();
6943       V = V.getOperand(BroadcastIdx / OperandSize);
6944       BroadcastIdx %= OperandSize;
6945       continue;
6946     }
6947
6948     case ISD::INSERT_SUBVECTOR: {
6949       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6950       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6951       if (!ConstantIdx)
6952         break;
6953
6954       int BeginIdx = (int)ConstantIdx->getZExtValue();
6955       int EndIdx =
6956           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6957       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6958         BroadcastIdx -= BeginIdx;
6959         V = VInner;
6960       } else {
6961         V = VOuter;
6962       }
6963       continue;
6964     }
6965     }
6966     break;
6967   }
6968
6969   // Check if this is a broadcast of a scalar. We special case lowering
6970   // for scalars so that we can more effectively fold with loads.
6971   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6972       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6973     V = V.getOperand(BroadcastIdx);
6974
6975     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6976     // AVX2.
6977     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6978       return SDValue();
6979   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6980     // We can't broadcast from a vector register w/o AVX2, and we can only
6981     // broadcast from the zero-element of a vector register.
6982     return SDValue();
6983   }
6984
6985   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
6986 }
6987
6988 // Check for whether we can use INSERTPS to perform the shuffle. We only use
6989 // INSERTPS when the V1 elements are already in the correct locations
6990 // because otherwise we can just always use two SHUFPS instructions which
6991 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
6992 // perform INSERTPS if a single V1 element is out of place and all V2
6993 // elements are zeroable.
6994 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
6995                                             ArrayRef<int> Mask,
6996                                             SelectionDAG &DAG) {
6997   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
6998   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6999   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7000   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7001
7002   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7003
7004   unsigned ZMask = 0;
7005   int V1DstIndex = -1;
7006   int V2DstIndex = -1;
7007   bool V1UsedInPlace = false;
7008
7009   for (int i = 0; i < 4; ++i) {
7010     // Synthesize a zero mask from the zeroable elements (includes undefs).
7011     if (Zeroable[i]) {
7012       ZMask |= 1 << i;
7013       continue;
7014     }
7015
7016     // Flag if we use any V1 inputs in place.
7017     if (i == Mask[i]) {
7018       V1UsedInPlace = true;
7019       continue;
7020     }
7021
7022     // We can only insert a single non-zeroable element.
7023     if (V1DstIndex != -1 || V2DstIndex != -1)
7024       return SDValue();
7025
7026     if (Mask[i] < 4) {
7027       // V1 input out of place for insertion.
7028       V1DstIndex = i;
7029     } else {
7030       // V2 input for insertion.
7031       V2DstIndex = i;
7032     }
7033   }
7034
7035   // Don't bother if we have no (non-zeroable) element for insertion.
7036   if (V1DstIndex == -1 && V2DstIndex == -1)
7037     return SDValue();
7038
7039   // Determine element insertion src/dst indices. The src index is from the
7040   // start of the inserted vector, not the start of the concatenated vector.
7041   unsigned V2SrcIndex = 0;
7042   if (V1DstIndex != -1) {
7043     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7044     // and don't use the original V2 at all.
7045     V2SrcIndex = Mask[V1DstIndex];
7046     V2DstIndex = V1DstIndex;
7047     V2 = V1;
7048   } else {
7049     V2SrcIndex = Mask[V2DstIndex] - 4;
7050   }
7051
7052   // If no V1 inputs are used in place, then the result is created only from
7053   // the zero mask and the V2 insertion - so remove V1 dependency.
7054   if (!V1UsedInPlace)
7055     V1 = DAG.getUNDEF(MVT::v4f32);
7056
7057   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7058   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7059
7060   // Insert the V2 element into the desired position.
7061   SDLoc DL(Op);
7062   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7063                      DAG.getConstant(InsertPSMask, MVT::i8));
7064 }
7065
7066 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7067 /// UNPCK instruction.
7068 ///
7069 /// This specifically targets cases where we end up with alternating between
7070 /// the two inputs, and so can permute them into something that feeds a single
7071 /// UNPCK instruction. Note that this routine only targets integer vectors
7072 /// because for floating point vectors we have a generalized SHUFPS lowering
7073 /// strategy that handles everything that doesn't *exactly* match an unpack,
7074 /// making this clever lowering unnecessary.
7075 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7076                                           SDValue V2, ArrayRef<int> Mask,
7077                                           SelectionDAG &DAG) {
7078   assert(!VT.isFloatingPoint() &&
7079          "This routine only supports integer vectors.");
7080   assert(!isSingleInputShuffleMask(Mask) &&
7081          "This routine should only be used when blending two inputs.");
7082   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7083
7084   int Size = Mask.size();
7085
7086   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7087     return M >= 0 && M % Size < Size / 2;
7088   });
7089   int NumHiInputs = std::count_if(
7090       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7091
7092   bool UnpackLo = NumLoInputs >= NumHiInputs;
7093
7094   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7095     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7096     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7097
7098     for (int i = 0; i < Size; ++i) {
7099       if (Mask[i] < 0)
7100         continue;
7101
7102       // Each element of the unpack contains Scale elements from this mask.
7103       int UnpackIdx = i / Scale;
7104
7105       // We only handle the case where V1 feeds the first slots of the unpack.
7106       // We rely on canonicalization to ensure this is the case.
7107       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7108         return SDValue();
7109
7110       // Setup the mask for this input. The indexing is tricky as we have to
7111       // handle the unpack stride.
7112       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7113       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7114           Mask[i] % Size;
7115     }
7116
7117     // If we will have to shuffle both inputs to use the unpack, check whether
7118     // we can just unpack first and shuffle the result. If so, skip this unpack.
7119     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7120         !isNoopShuffleMask(V2Mask))
7121       return SDValue();
7122
7123     // Shuffle the inputs into place.
7124     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7125     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7126
7127     // Cast the inputs to the type we will use to unpack them.
7128     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7129     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7130
7131     // Unpack the inputs and cast the result back to the desired type.
7132     return DAG.getNode(ISD::BITCAST, DL, VT,
7133                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7134                                    DL, UnpackVT, V1, V2));
7135   };
7136
7137   // We try each unpack from the largest to the smallest to try and find one
7138   // that fits this mask.
7139   int OrigNumElements = VT.getVectorNumElements();
7140   int OrigScalarSize = VT.getScalarSizeInBits();
7141   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7142     int Scale = ScalarSize / OrigScalarSize;
7143     int NumElements = OrigNumElements / Scale;
7144     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7145     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7146       return Unpack;
7147   }
7148
7149   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7150   // initial unpack.
7151   if (NumLoInputs == 0 || NumHiInputs == 0) {
7152     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7153            "We have to have *some* inputs!");
7154     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7155
7156     // FIXME: We could consider the total complexity of the permute of each
7157     // possible unpacking. Or at the least we should consider how many
7158     // half-crossings are created.
7159     // FIXME: We could consider commuting the unpacks.
7160
7161     SmallVector<int, 32> PermMask;
7162     PermMask.assign(Size, -1);
7163     for (int i = 0; i < Size; ++i) {
7164       if (Mask[i] < 0)
7165         continue;
7166
7167       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7168
7169       PermMask[i] =
7170           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7171     }
7172     return DAG.getVectorShuffle(
7173         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7174                             DL, VT, V1, V2),
7175         DAG.getUNDEF(VT), PermMask);
7176   }
7177
7178   return SDValue();
7179 }
7180
7181 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7182 ///
7183 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7184 /// support for floating point shuffles but not integer shuffles. These
7185 /// instructions will incur a domain crossing penalty on some chips though so
7186 /// it is better to avoid lowering through this for integer vectors where
7187 /// possible.
7188 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7189                                        const X86Subtarget *Subtarget,
7190                                        SelectionDAG &DAG) {
7191   SDLoc DL(Op);
7192   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7193   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7194   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7196   ArrayRef<int> Mask = SVOp->getMask();
7197   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7198
7199   if (isSingleInputShuffleMask(Mask)) {
7200     // Use low duplicate instructions for masks that match their pattern.
7201     if (Subtarget->hasSSE3())
7202       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7203         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7204
7205     // Straight shuffle of a single input vector. Simulate this by using the
7206     // single input as both of the "inputs" to this instruction..
7207     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7208
7209     if (Subtarget->hasAVX()) {
7210       // If we have AVX, we can use VPERMILPS which will allow folding a load
7211       // into the shuffle.
7212       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7213                          DAG.getConstant(SHUFPDMask, MVT::i8));
7214     }
7215
7216     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7217                        DAG.getConstant(SHUFPDMask, MVT::i8));
7218   }
7219   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7220   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7221
7222   // If we have a single input, insert that into V1 if we can do so cheaply.
7223   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7224     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7225             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7226       return Insertion;
7227     // Try inverting the insertion since for v2 masks it is easy to do and we
7228     // can't reliably sort the mask one way or the other.
7229     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7230                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7231     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7232             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7233       return Insertion;
7234   }
7235
7236   // Try to use one of the special instruction patterns to handle two common
7237   // blend patterns if a zero-blend above didn't work.
7238   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7239       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7240     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7241       // We can either use a special instruction to load over the low double or
7242       // to move just the low double.
7243       return DAG.getNode(
7244           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7245           DL, MVT::v2f64, V2,
7246           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7247
7248   if (Subtarget->hasSSE41())
7249     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7250                                                   Subtarget, DAG))
7251       return Blend;
7252
7253   // Use dedicated unpack instructions for masks that match their pattern.
7254   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7255     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7256   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7257     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7258
7259   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7260   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7261                      DAG.getConstant(SHUFPDMask, MVT::i8));
7262 }
7263
7264 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7265 ///
7266 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7267 /// the integer unit to minimize domain crossing penalties. However, for blends
7268 /// it falls back to the floating point shuffle operation with appropriate bit
7269 /// casting.
7270 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7271                                        const X86Subtarget *Subtarget,
7272                                        SelectionDAG &DAG) {
7273   SDLoc DL(Op);
7274   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7275   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7276   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7277   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7278   ArrayRef<int> Mask = SVOp->getMask();
7279   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7280
7281   if (isSingleInputShuffleMask(Mask)) {
7282     // Check for being able to broadcast a single element.
7283     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7284                                                           Mask, Subtarget, DAG))
7285       return Broadcast;
7286
7287     // Straight shuffle of a single input vector. For everything from SSE2
7288     // onward this has a single fast instruction with no scary immediates.
7289     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7290     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7291     int WidenedMask[4] = {
7292         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7293         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7294     return DAG.getNode(
7295         ISD::BITCAST, DL, MVT::v2i64,
7296         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7297                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7298   }
7299   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7300   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7301   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7302   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7303
7304   // If we have a blend of two PACKUS operations an the blend aligns with the
7305   // low and half halves, we can just merge the PACKUS operations. This is
7306   // particularly important as it lets us merge shuffles that this routine itself
7307   // creates.
7308   auto GetPackNode = [](SDValue V) {
7309     while (V.getOpcode() == ISD::BITCAST)
7310       V = V.getOperand(0);
7311
7312     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7313   };
7314   if (SDValue V1Pack = GetPackNode(V1))
7315     if (SDValue V2Pack = GetPackNode(V2))
7316       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7317                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7318                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7319                                                   : V1Pack.getOperand(1),
7320                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7321                                                   : V2Pack.getOperand(1)));
7322
7323   // Try to use shift instructions.
7324   if (SDValue Shift =
7325           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7326     return Shift;
7327
7328   // When loading a scalar and then shuffling it into a vector we can often do
7329   // the insertion cheaply.
7330   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7331           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7332     return Insertion;
7333   // Try inverting the insertion since for v2 masks it is easy to do and we
7334   // can't reliably sort the mask one way or the other.
7335   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7336   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7337           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7338     return Insertion;
7339
7340   // We have different paths for blend lowering, but they all must use the
7341   // *exact* same predicate.
7342   bool IsBlendSupported = Subtarget->hasSSE41();
7343   if (IsBlendSupported)
7344     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7345                                                   Subtarget, DAG))
7346       return Blend;
7347
7348   // Use dedicated unpack instructions for masks that match their pattern.
7349   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7350     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7351   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7352     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7353
7354   // Try to use byte rotation instructions.
7355   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7356   if (Subtarget->hasSSSE3())
7357     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7358             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7359       return Rotate;
7360
7361   // If we have direct support for blends, we should lower by decomposing into
7362   // a permute. That will be faster than the domain cross.
7363   if (IsBlendSupported)
7364     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7365                                                       Mask, DAG);
7366
7367   // We implement this with SHUFPD which is pretty lame because it will likely
7368   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7369   // However, all the alternatives are still more cycles and newer chips don't
7370   // have this problem. It would be really nice if x86 had better shuffles here.
7371   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7372   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7373   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7374                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7375 }
7376
7377 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7378 ///
7379 /// This is used to disable more specialized lowerings when the shufps lowering
7380 /// will happen to be efficient.
7381 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7382   // This routine only handles 128-bit shufps.
7383   assert(Mask.size() == 4 && "Unsupported mask size!");
7384
7385   // To lower with a single SHUFPS we need to have the low half and high half
7386   // each requiring a single input.
7387   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7388     return false;
7389   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7390     return false;
7391
7392   return true;
7393 }
7394
7395 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7396 ///
7397 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7398 /// It makes no assumptions about whether this is the *best* lowering, it simply
7399 /// uses it.
7400 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7401                                             ArrayRef<int> Mask, SDValue V1,
7402                                             SDValue V2, SelectionDAG &DAG) {
7403   SDValue LowV = V1, HighV = V2;
7404   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7405
7406   int NumV2Elements =
7407       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7408
7409   if (NumV2Elements == 1) {
7410     int V2Index =
7411         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7412         Mask.begin();
7413
7414     // Compute the index adjacent to V2Index and in the same half by toggling
7415     // the low bit.
7416     int V2AdjIndex = V2Index ^ 1;
7417
7418     if (Mask[V2AdjIndex] == -1) {
7419       // Handles all the cases where we have a single V2 element and an undef.
7420       // This will only ever happen in the high lanes because we commute the
7421       // vector otherwise.
7422       if (V2Index < 2)
7423         std::swap(LowV, HighV);
7424       NewMask[V2Index] -= 4;
7425     } else {
7426       // Handle the case where the V2 element ends up adjacent to a V1 element.
7427       // To make this work, blend them together as the first step.
7428       int V1Index = V2AdjIndex;
7429       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7430       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7431                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7432
7433       // Now proceed to reconstruct the final blend as we have the necessary
7434       // high or low half formed.
7435       if (V2Index < 2) {
7436         LowV = V2;
7437         HighV = V1;
7438       } else {
7439         HighV = V2;
7440       }
7441       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7442       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7443     }
7444   } else if (NumV2Elements == 2) {
7445     if (Mask[0] < 4 && Mask[1] < 4) {
7446       // Handle the easy case where we have V1 in the low lanes and V2 in the
7447       // high lanes.
7448       NewMask[2] -= 4;
7449       NewMask[3] -= 4;
7450     } else if (Mask[2] < 4 && Mask[3] < 4) {
7451       // We also handle the reversed case because this utility may get called
7452       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7453       // arrange things in the right direction.
7454       NewMask[0] -= 4;
7455       NewMask[1] -= 4;
7456       HighV = V1;
7457       LowV = V2;
7458     } else {
7459       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7460       // trying to place elements directly, just blend them and set up the final
7461       // shuffle to place them.
7462
7463       // The first two blend mask elements are for V1, the second two are for
7464       // V2.
7465       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7466                           Mask[2] < 4 ? Mask[2] : Mask[3],
7467                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7468                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7469       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7470                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7471
7472       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7473       // a blend.
7474       LowV = HighV = V1;
7475       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7476       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7477       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7478       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7479     }
7480   }
7481   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7482                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7483 }
7484
7485 /// \brief Lower 4-lane 32-bit floating point shuffles.
7486 ///
7487 /// Uses instructions exclusively from the floating point unit to minimize
7488 /// domain crossing penalties, as these are sufficient to implement all v4f32
7489 /// shuffles.
7490 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7491                                        const X86Subtarget *Subtarget,
7492                                        SelectionDAG &DAG) {
7493   SDLoc DL(Op);
7494   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7495   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7496   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7497   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7498   ArrayRef<int> Mask = SVOp->getMask();
7499   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7500
7501   int NumV2Elements =
7502       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7503
7504   if (NumV2Elements == 0) {
7505     // Check for being able to broadcast a single element.
7506     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7507                                                           Mask, Subtarget, DAG))
7508       return Broadcast;
7509
7510     // Use even/odd duplicate instructions for masks that match their pattern.
7511     if (Subtarget->hasSSE3()) {
7512       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7513         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7514       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7515         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7516     }
7517
7518     if (Subtarget->hasAVX()) {
7519       // If we have AVX, we can use VPERMILPS which will allow folding a load
7520       // into the shuffle.
7521       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7522                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7523     }
7524
7525     // Otherwise, use a straight shuffle of a single input vector. We pass the
7526     // input vector to both operands to simulate this with a SHUFPS.
7527     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7528                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7529   }
7530
7531   // There are special ways we can lower some single-element blends. However, we
7532   // have custom ways we can lower more complex single-element blends below that
7533   // we defer to if both this and BLENDPS fail to match, so restrict this to
7534   // when the V2 input is targeting element 0 of the mask -- that is the fast
7535   // case here.
7536   if (NumV2Elements == 1 && Mask[0] >= 4)
7537     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7538                                                          Mask, Subtarget, DAG))
7539       return V;
7540
7541   if (Subtarget->hasSSE41()) {
7542     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7543                                                   Subtarget, DAG))
7544       return Blend;
7545
7546     // Use INSERTPS if we can complete the shuffle efficiently.
7547     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7548       return V;
7549
7550     if (!isSingleSHUFPSMask(Mask))
7551       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7552               DL, MVT::v4f32, V1, V2, Mask, DAG))
7553         return BlendPerm;
7554   }
7555
7556   // Use dedicated unpack instructions for masks that match their pattern.
7557   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7558     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7559   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7560     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7561   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7562     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7563   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7564     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7565
7566   // Otherwise fall back to a SHUFPS lowering strategy.
7567   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7568 }
7569
7570 /// \brief Lower 4-lane i32 vector shuffles.
7571 ///
7572 /// We try to handle these with integer-domain shuffles where we can, but for
7573 /// blends we use the floating point domain blend instructions.
7574 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7575                                        const X86Subtarget *Subtarget,
7576                                        SelectionDAG &DAG) {
7577   SDLoc DL(Op);
7578   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7579   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7580   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7581   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7582   ArrayRef<int> Mask = SVOp->getMask();
7583   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7584
7585   // Whenever we can lower this as a zext, that instruction is strictly faster
7586   // than any alternative. It also allows us to fold memory operands into the
7587   // shuffle in many cases.
7588   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7589                                                          Mask, Subtarget, DAG))
7590     return ZExt;
7591
7592   int NumV2Elements =
7593       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7594
7595   if (NumV2Elements == 0) {
7596     // Check for being able to broadcast a single element.
7597     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7598                                                           Mask, Subtarget, DAG))
7599       return Broadcast;
7600
7601     // Straight shuffle of a single input vector. For everything from SSE2
7602     // onward this has a single fast instruction with no scary immediates.
7603     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7604     // but we aren't actually going to use the UNPCK instruction because doing
7605     // so prevents folding a load into this instruction or making a copy.
7606     const int UnpackLoMask[] = {0, 0, 1, 1};
7607     const int UnpackHiMask[] = {2, 2, 3, 3};
7608     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7609       Mask = UnpackLoMask;
7610     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7611       Mask = UnpackHiMask;
7612
7613     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7614                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7615   }
7616
7617   // Try to use shift instructions.
7618   if (SDValue Shift =
7619           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7620     return Shift;
7621
7622   // There are special ways we can lower some single-element blends.
7623   if (NumV2Elements == 1)
7624     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7625                                                          Mask, Subtarget, DAG))
7626       return V;
7627
7628   // We have different paths for blend lowering, but they all must use the
7629   // *exact* same predicate.
7630   bool IsBlendSupported = Subtarget->hasSSE41();
7631   if (IsBlendSupported)
7632     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7633                                                   Subtarget, DAG))
7634       return Blend;
7635
7636   if (SDValue Masked =
7637           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7638     return Masked;
7639
7640   // Use dedicated unpack instructions for masks that match their pattern.
7641   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7642     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7643   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7644     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7645   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7646     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7647   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7648     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7649
7650   // Try to use byte rotation instructions.
7651   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7652   if (Subtarget->hasSSSE3())
7653     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7654             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7655       return Rotate;
7656
7657   // If we have direct support for blends, we should lower by decomposing into
7658   // a permute. That will be faster than the domain cross.
7659   if (IsBlendSupported)
7660     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7661                                                       Mask, DAG);
7662
7663   // Try to lower by permuting the inputs into an unpack instruction.
7664   if (SDValue Unpack =
7665           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7666     return Unpack;
7667
7668   // We implement this with SHUFPS because it can blend from two vectors.
7669   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7670   // up the inputs, bypassing domain shift penalties that we would encur if we
7671   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7672   // relevant.
7673   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7674                      DAG.getVectorShuffle(
7675                          MVT::v4f32, DL,
7676                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7677                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7678 }
7679
7680 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7681 /// shuffle lowering, and the most complex part.
7682 ///
7683 /// The lowering strategy is to try to form pairs of input lanes which are
7684 /// targeted at the same half of the final vector, and then use a dword shuffle
7685 /// to place them onto the right half, and finally unpack the paired lanes into
7686 /// their final position.
7687 ///
7688 /// The exact breakdown of how to form these dword pairs and align them on the
7689 /// correct sides is really tricky. See the comments within the function for
7690 /// more of the details.
7691 ///
7692 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7693 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7694 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7695 /// vector, form the analogous 128-bit 8-element Mask.
7696 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7697     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7698     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7699   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7700   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7701
7702   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7703   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7704   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7705
7706   SmallVector<int, 4> LoInputs;
7707   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7708                [](int M) { return M >= 0; });
7709   std::sort(LoInputs.begin(), LoInputs.end());
7710   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7711   SmallVector<int, 4> HiInputs;
7712   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7713                [](int M) { return M >= 0; });
7714   std::sort(HiInputs.begin(), HiInputs.end());
7715   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7716   int NumLToL =
7717       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7718   int NumHToL = LoInputs.size() - NumLToL;
7719   int NumLToH =
7720       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7721   int NumHToH = HiInputs.size() - NumLToH;
7722   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7723   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7724   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7725   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7726
7727   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7728   // such inputs we can swap two of the dwords across the half mark and end up
7729   // with <=2 inputs to each half in each half. Once there, we can fall through
7730   // to the generic code below. For example:
7731   //
7732   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7733   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7734   //
7735   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7736   // and an existing 2-into-2 on the other half. In this case we may have to
7737   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7738   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7739   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7740   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7741   // half than the one we target for fixing) will be fixed when we re-enter this
7742   // path. We will also combine away any sequence of PSHUFD instructions that
7743   // result into a single instruction. Here is an example of the tricky case:
7744   //
7745   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7746   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7747   //
7748   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7749   //
7750   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7751   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7752   //
7753   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7754   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7755   //
7756   // The result is fine to be handled by the generic logic.
7757   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7758                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7759                           int AOffset, int BOffset) {
7760     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7761            "Must call this with A having 3 or 1 inputs from the A half.");
7762     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7763            "Must call this with B having 1 or 3 inputs from the B half.");
7764     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7765            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7766
7767     // Compute the index of dword with only one word among the three inputs in
7768     // a half by taking the sum of the half with three inputs and subtracting
7769     // the sum of the actual three inputs. The difference is the remaining
7770     // slot.
7771     int ADWord, BDWord;
7772     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7773     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7774     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7775     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7776     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7777     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7778     int TripleNonInputIdx =
7779         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7780     TripleDWord = TripleNonInputIdx / 2;
7781
7782     // We use xor with one to compute the adjacent DWord to whichever one the
7783     // OneInput is in.
7784     OneInputDWord = (OneInput / 2) ^ 1;
7785
7786     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7787     // and BToA inputs. If there is also such a problem with the BToB and AToB
7788     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7789     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7790     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7791     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7792       // Compute how many inputs will be flipped by swapping these DWords. We
7793       // need
7794       // to balance this to ensure we don't form a 3-1 shuffle in the other
7795       // half.
7796       int NumFlippedAToBInputs =
7797           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7798           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7799       int NumFlippedBToBInputs =
7800           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7801           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7802       if ((NumFlippedAToBInputs == 1 &&
7803            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7804           (NumFlippedBToBInputs == 1 &&
7805            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7806         // We choose whether to fix the A half or B half based on whether that
7807         // half has zero flipped inputs. At zero, we may not be able to fix it
7808         // with that half. We also bias towards fixing the B half because that
7809         // will more commonly be the high half, and we have to bias one way.
7810         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7811                                                        ArrayRef<int> Inputs) {
7812           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7813           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7814                                          PinnedIdx ^ 1) != Inputs.end();
7815           // Determine whether the free index is in the flipped dword or the
7816           // unflipped dword based on where the pinned index is. We use this bit
7817           // in an xor to conditionally select the adjacent dword.
7818           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7819           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7820                                              FixFreeIdx) != Inputs.end();
7821           if (IsFixIdxInput == IsFixFreeIdxInput)
7822             FixFreeIdx += 1;
7823           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7824                                         FixFreeIdx) != Inputs.end();
7825           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7826                  "We need to be changing the number of flipped inputs!");
7827           int PSHUFHalfMask[] = {0, 1, 2, 3};
7828           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7829           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7830                           MVT::v8i16, V,
7831                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7832
7833           for (int &M : Mask)
7834             if (M != -1 && M == FixIdx)
7835               M = FixFreeIdx;
7836             else if (M != -1 && M == FixFreeIdx)
7837               M = FixIdx;
7838         };
7839         if (NumFlippedBToBInputs != 0) {
7840           int BPinnedIdx =
7841               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7842           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7843         } else {
7844           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7845           int APinnedIdx =
7846               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7847           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7848         }
7849       }
7850     }
7851
7852     int PSHUFDMask[] = {0, 1, 2, 3};
7853     PSHUFDMask[ADWord] = BDWord;
7854     PSHUFDMask[BDWord] = ADWord;
7855     V = DAG.getNode(ISD::BITCAST, DL, VT,
7856                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7857                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7858                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7859
7860     // Adjust the mask to match the new locations of A and B.
7861     for (int &M : Mask)
7862       if (M != -1 && M/2 == ADWord)
7863         M = 2 * BDWord + M % 2;
7864       else if (M != -1 && M/2 == BDWord)
7865         M = 2 * ADWord + M % 2;
7866
7867     // Recurse back into this routine to re-compute state now that this isn't
7868     // a 3 and 1 problem.
7869     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7870                                                      DAG);
7871   };
7872   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7873     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7874   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7875     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7876
7877   // At this point there are at most two inputs to the low and high halves from
7878   // each half. That means the inputs can always be grouped into dwords and
7879   // those dwords can then be moved to the correct half with a dword shuffle.
7880   // We use at most one low and one high word shuffle to collect these paired
7881   // inputs into dwords, and finally a dword shuffle to place them.
7882   int PSHUFLMask[4] = {-1, -1, -1, -1};
7883   int PSHUFHMask[4] = {-1, -1, -1, -1};
7884   int PSHUFDMask[4] = {-1, -1, -1, -1};
7885
7886   // First fix the masks for all the inputs that are staying in their
7887   // original halves. This will then dictate the targets of the cross-half
7888   // shuffles.
7889   auto fixInPlaceInputs =
7890       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7891                     MutableArrayRef<int> SourceHalfMask,
7892                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7893     if (InPlaceInputs.empty())
7894       return;
7895     if (InPlaceInputs.size() == 1) {
7896       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7897           InPlaceInputs[0] - HalfOffset;
7898       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7899       return;
7900     }
7901     if (IncomingInputs.empty()) {
7902       // Just fix all of the in place inputs.
7903       for (int Input : InPlaceInputs) {
7904         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7905         PSHUFDMask[Input / 2] = Input / 2;
7906       }
7907       return;
7908     }
7909
7910     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7911     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7912         InPlaceInputs[0] - HalfOffset;
7913     // Put the second input next to the first so that they are packed into
7914     // a dword. We find the adjacent index by toggling the low bit.
7915     int AdjIndex = InPlaceInputs[0] ^ 1;
7916     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7917     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7918     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7919   };
7920   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7921   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7922
7923   // Now gather the cross-half inputs and place them into a free dword of
7924   // their target half.
7925   // FIXME: This operation could almost certainly be simplified dramatically to
7926   // look more like the 3-1 fixing operation.
7927   auto moveInputsToRightHalf = [&PSHUFDMask](
7928       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7929       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7930       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7931       int DestOffset) {
7932     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7933       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7934     };
7935     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7936                                                int Word) {
7937       int LowWord = Word & ~1;
7938       int HighWord = Word | 1;
7939       return isWordClobbered(SourceHalfMask, LowWord) ||
7940              isWordClobbered(SourceHalfMask, HighWord);
7941     };
7942
7943     if (IncomingInputs.empty())
7944       return;
7945
7946     if (ExistingInputs.empty()) {
7947       // Map any dwords with inputs from them into the right half.
7948       for (int Input : IncomingInputs) {
7949         // If the source half mask maps over the inputs, turn those into
7950         // swaps and use the swapped lane.
7951         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7952           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7953             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7954                 Input - SourceOffset;
7955             // We have to swap the uses in our half mask in one sweep.
7956             for (int &M : HalfMask)
7957               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7958                 M = Input;
7959               else if (M == Input)
7960                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7961           } else {
7962             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7963                        Input - SourceOffset &&
7964                    "Previous placement doesn't match!");
7965           }
7966           // Note that this correctly re-maps both when we do a swap and when
7967           // we observe the other side of the swap above. We rely on that to
7968           // avoid swapping the members of the input list directly.
7969           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7970         }
7971
7972         // Map the input's dword into the correct half.
7973         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7974           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7975         else
7976           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7977                      Input / 2 &&
7978                  "Previous placement doesn't match!");
7979       }
7980
7981       // And just directly shift any other-half mask elements to be same-half
7982       // as we will have mirrored the dword containing the element into the
7983       // same position within that half.
7984       for (int &M : HalfMask)
7985         if (M >= SourceOffset && M < SourceOffset + 4) {
7986           M = M - SourceOffset + DestOffset;
7987           assert(M >= 0 && "This should never wrap below zero!");
7988         }
7989       return;
7990     }
7991
7992     // Ensure we have the input in a viable dword of its current half. This
7993     // is particularly tricky because the original position may be clobbered
7994     // by inputs being moved and *staying* in that half.
7995     if (IncomingInputs.size() == 1) {
7996       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7997         int InputFixed = std::find(std::begin(SourceHalfMask),
7998                                    std::end(SourceHalfMask), -1) -
7999                          std::begin(SourceHalfMask) + SourceOffset;
8000         SourceHalfMask[InputFixed - SourceOffset] =
8001             IncomingInputs[0] - SourceOffset;
8002         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8003                      InputFixed);
8004         IncomingInputs[0] = InputFixed;
8005       }
8006     } else if (IncomingInputs.size() == 2) {
8007       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8008           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8009         // We have two non-adjacent or clobbered inputs we need to extract from
8010         // the source half. To do this, we need to map them into some adjacent
8011         // dword slot in the source mask.
8012         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8013                               IncomingInputs[1] - SourceOffset};
8014
8015         // If there is a free slot in the source half mask adjacent to one of
8016         // the inputs, place the other input in it. We use (Index XOR 1) to
8017         // compute an adjacent index.
8018         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8019             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8020           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8021           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8022           InputsFixed[1] = InputsFixed[0] ^ 1;
8023         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8024                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8025           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8026           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8027           InputsFixed[0] = InputsFixed[1] ^ 1;
8028         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8029                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8030           // The two inputs are in the same DWord but it is clobbered and the
8031           // adjacent DWord isn't used at all. Move both inputs to the free
8032           // slot.
8033           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8034           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8035           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8036           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8037         } else {
8038           // The only way we hit this point is if there is no clobbering
8039           // (because there are no off-half inputs to this half) and there is no
8040           // free slot adjacent to one of the inputs. In this case, we have to
8041           // swap an input with a non-input.
8042           for (int i = 0; i < 4; ++i)
8043             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8044                    "We can't handle any clobbers here!");
8045           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8046                  "Cannot have adjacent inputs here!");
8047
8048           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8049           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8050
8051           // We also have to update the final source mask in this case because
8052           // it may need to undo the above swap.
8053           for (int &M : FinalSourceHalfMask)
8054             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8055               M = InputsFixed[1] + SourceOffset;
8056             else if (M == InputsFixed[1] + SourceOffset)
8057               M = (InputsFixed[0] ^ 1) + SourceOffset;
8058
8059           InputsFixed[1] = InputsFixed[0] ^ 1;
8060         }
8061
8062         // Point everything at the fixed inputs.
8063         for (int &M : HalfMask)
8064           if (M == IncomingInputs[0])
8065             M = InputsFixed[0] + SourceOffset;
8066           else if (M == IncomingInputs[1])
8067             M = InputsFixed[1] + SourceOffset;
8068
8069         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8070         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8071       }
8072     } else {
8073       llvm_unreachable("Unhandled input size!");
8074     }
8075
8076     // Now hoist the DWord down to the right half.
8077     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8078     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8079     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8080     for (int &M : HalfMask)
8081       for (int Input : IncomingInputs)
8082         if (M == Input)
8083           M = FreeDWord * 2 + Input % 2;
8084   };
8085   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8086                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8087   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8088                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8089
8090   // Now enact all the shuffles we've computed to move the inputs into their
8091   // target half.
8092   if (!isNoopShuffleMask(PSHUFLMask))
8093     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8094                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8095   if (!isNoopShuffleMask(PSHUFHMask))
8096     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8097                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8098   if (!isNoopShuffleMask(PSHUFDMask))
8099     V = DAG.getNode(ISD::BITCAST, DL, VT,
8100                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8101                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8102                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8103
8104   // At this point, each half should contain all its inputs, and we can then
8105   // just shuffle them into their final position.
8106   assert(std::count_if(LoMask.begin(), LoMask.end(),
8107                        [](int M) { return M >= 4; }) == 0 &&
8108          "Failed to lift all the high half inputs to the low mask!");
8109   assert(std::count_if(HiMask.begin(), HiMask.end(),
8110                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8111          "Failed to lift all the low half inputs to the high mask!");
8112
8113   // Do a half shuffle for the low mask.
8114   if (!isNoopShuffleMask(LoMask))
8115     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8116                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8117
8118   // Do a half shuffle with the high mask after shifting its values down.
8119   for (int &M : HiMask)
8120     if (M >= 0)
8121       M -= 4;
8122   if (!isNoopShuffleMask(HiMask))
8123     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8124                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8125
8126   return V;
8127 }
8128
8129 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8130 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8131                                           SDValue V2, ArrayRef<int> Mask,
8132                                           SelectionDAG &DAG, bool &V1InUse,
8133                                           bool &V2InUse) {
8134   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8135   SDValue V1Mask[16];
8136   SDValue V2Mask[16];
8137   V1InUse = false;
8138   V2InUse = false;
8139
8140   int Size = Mask.size();
8141   int Scale = 16 / Size;
8142   for (int i = 0; i < 16; ++i) {
8143     if (Mask[i / Scale] == -1) {
8144       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8145     } else {
8146       const int ZeroMask = 0x80;
8147       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8148                                           : ZeroMask;
8149       int V2Idx = Mask[i / Scale] < Size
8150                       ? ZeroMask
8151                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8152       if (Zeroable[i / Scale])
8153         V1Idx = V2Idx = ZeroMask;
8154       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8155       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8156       V1InUse |= (ZeroMask != V1Idx);
8157       V2InUse |= (ZeroMask != V2Idx);
8158     }
8159   }
8160
8161   if (V1InUse)
8162     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8163                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8164                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8165   if (V2InUse)
8166     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8167                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8168                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8169
8170   // If we need shuffled inputs from both, blend the two.
8171   SDValue V;
8172   if (V1InUse && V2InUse)
8173     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8174   else
8175     V = V1InUse ? V1 : V2;
8176
8177   // Cast the result back to the correct type.
8178   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8179 }
8180
8181 /// \brief Generic lowering of 8-lane i16 shuffles.
8182 ///
8183 /// This handles both single-input shuffles and combined shuffle/blends with
8184 /// two inputs. The single input shuffles are immediately delegated to
8185 /// a dedicated lowering routine.
8186 ///
8187 /// The blends are lowered in one of three fundamental ways. If there are few
8188 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8189 /// of the input is significantly cheaper when lowered as an interleaving of
8190 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8191 /// halves of the inputs separately (making them have relatively few inputs)
8192 /// and then concatenate them.
8193 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8194                                        const X86Subtarget *Subtarget,
8195                                        SelectionDAG &DAG) {
8196   SDLoc DL(Op);
8197   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8198   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8199   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8200   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8201   ArrayRef<int> OrigMask = SVOp->getMask();
8202   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8203                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8204   MutableArrayRef<int> Mask(MaskStorage);
8205
8206   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8207
8208   // Whenever we can lower this as a zext, that instruction is strictly faster
8209   // than any alternative.
8210   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8211           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8212     return ZExt;
8213
8214   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8215   (void)isV1;
8216   auto isV2 = [](int M) { return M >= 8; };
8217
8218   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8219
8220   if (NumV2Inputs == 0) {
8221     // Check for being able to broadcast a single element.
8222     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8223                                                           Mask, Subtarget, DAG))
8224       return Broadcast;
8225
8226     // Try to use shift instructions.
8227     if (SDValue Shift =
8228             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8229       return Shift;
8230
8231     // Use dedicated unpack instructions for masks that match their pattern.
8232     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8233       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8234     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8235       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8236
8237     // Try to use byte rotation instructions.
8238     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8239                                                         Mask, Subtarget, DAG))
8240       return Rotate;
8241
8242     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8243                                                      Subtarget, DAG);
8244   }
8245
8246   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8247          "All single-input shuffles should be canonicalized to be V1-input "
8248          "shuffles.");
8249
8250   // Try to use shift instructions.
8251   if (SDValue Shift =
8252           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8253     return Shift;
8254
8255   // There are special ways we can lower some single-element blends.
8256   if (NumV2Inputs == 1)
8257     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8258                                                          Mask, Subtarget, DAG))
8259       return V;
8260
8261   // We have different paths for blend lowering, but they all must use the
8262   // *exact* same predicate.
8263   bool IsBlendSupported = Subtarget->hasSSE41();
8264   if (IsBlendSupported)
8265     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8266                                                   Subtarget, DAG))
8267       return Blend;
8268
8269   if (SDValue Masked =
8270           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8271     return Masked;
8272
8273   // Use dedicated unpack instructions for masks that match their pattern.
8274   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8275     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8276   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8277     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8278
8279   // Try to use byte rotation instructions.
8280   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8281           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8282     return Rotate;
8283
8284   if (SDValue BitBlend =
8285           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8286     return BitBlend;
8287
8288   if (SDValue Unpack =
8289           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8290     return Unpack;
8291
8292   // If we can't directly blend but can use PSHUFB, that will be better as it
8293   // can both shuffle and set up the inefficient blend.
8294   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8295     bool V1InUse, V2InUse;
8296     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8297                                       V1InUse, V2InUse);
8298   }
8299
8300   // We can always bit-blend if we have to so the fallback strategy is to
8301   // decompose into single-input permutes and blends.
8302   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8303                                                       Mask, DAG);
8304 }
8305
8306 /// \brief Check whether a compaction lowering can be done by dropping even
8307 /// elements and compute how many times even elements must be dropped.
8308 ///
8309 /// This handles shuffles which take every Nth element where N is a power of
8310 /// two. Example shuffle masks:
8311 ///
8312 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8313 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8314 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8315 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8316 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8317 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8318 ///
8319 /// Any of these lanes can of course be undef.
8320 ///
8321 /// This routine only supports N <= 3.
8322 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8323 /// for larger N.
8324 ///
8325 /// \returns N above, or the number of times even elements must be dropped if
8326 /// there is such a number. Otherwise returns zero.
8327 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8328   // Figure out whether we're looping over two inputs or just one.
8329   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8330
8331   // The modulus for the shuffle vector entries is based on whether this is
8332   // a single input or not.
8333   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8334   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8335          "We should only be called with masks with a power-of-2 size!");
8336
8337   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8338
8339   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8340   // and 2^3 simultaneously. This is because we may have ambiguity with
8341   // partially undef inputs.
8342   bool ViableForN[3] = {true, true, true};
8343
8344   for (int i = 0, e = Mask.size(); i < e; ++i) {
8345     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8346     // want.
8347     if (Mask[i] == -1)
8348       continue;
8349
8350     bool IsAnyViable = false;
8351     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8352       if (ViableForN[j]) {
8353         uint64_t N = j + 1;
8354
8355         // The shuffle mask must be equal to (i * 2^N) % M.
8356         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8357           IsAnyViable = true;
8358         else
8359           ViableForN[j] = false;
8360       }
8361     // Early exit if we exhaust the possible powers of two.
8362     if (!IsAnyViable)
8363       break;
8364   }
8365
8366   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8367     if (ViableForN[j])
8368       return j + 1;
8369
8370   // Return 0 as there is no viable power of two.
8371   return 0;
8372 }
8373
8374 /// \brief Generic lowering of v16i8 shuffles.
8375 ///
8376 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8377 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8378 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8379 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8380 /// back together.
8381 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8382                                        const X86Subtarget *Subtarget,
8383                                        SelectionDAG &DAG) {
8384   SDLoc DL(Op);
8385   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8386   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8387   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8389   ArrayRef<int> Mask = SVOp->getMask();
8390   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8391
8392   // Try to use shift instructions.
8393   if (SDValue Shift =
8394           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8395     return Shift;
8396
8397   // Try to use byte rotation instructions.
8398   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8399           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8400     return Rotate;
8401
8402   // Try to use a zext lowering.
8403   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8404           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8405     return ZExt;
8406
8407   int NumV2Elements =
8408       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8409
8410   // For single-input shuffles, there are some nicer lowering tricks we can use.
8411   if (NumV2Elements == 0) {
8412     // Check for being able to broadcast a single element.
8413     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8414                                                           Mask, Subtarget, DAG))
8415       return Broadcast;
8416
8417     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8418     // Notably, this handles splat and partial-splat shuffles more efficiently.
8419     // However, it only makes sense if the pre-duplication shuffle simplifies
8420     // things significantly. Currently, this means we need to be able to
8421     // express the pre-duplication shuffle as an i16 shuffle.
8422     //
8423     // FIXME: We should check for other patterns which can be widened into an
8424     // i16 shuffle as well.
8425     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8426       for (int i = 0; i < 16; i += 2)
8427         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8428           return false;
8429
8430       return true;
8431     };
8432     auto tryToWidenViaDuplication = [&]() -> SDValue {
8433       if (!canWidenViaDuplication(Mask))
8434         return SDValue();
8435       SmallVector<int, 4> LoInputs;
8436       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8437                    [](int M) { return M >= 0 && M < 8; });
8438       std::sort(LoInputs.begin(), LoInputs.end());
8439       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8440                      LoInputs.end());
8441       SmallVector<int, 4> HiInputs;
8442       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8443                    [](int M) { return M >= 8; });
8444       std::sort(HiInputs.begin(), HiInputs.end());
8445       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8446                      HiInputs.end());
8447
8448       bool TargetLo = LoInputs.size() >= HiInputs.size();
8449       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8450       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8451
8452       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8453       SmallDenseMap<int, int, 8> LaneMap;
8454       for (int I : InPlaceInputs) {
8455         PreDupI16Shuffle[I/2] = I/2;
8456         LaneMap[I] = I;
8457       }
8458       int j = TargetLo ? 0 : 4, je = j + 4;
8459       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8460         // Check if j is already a shuffle of this input. This happens when
8461         // there are two adjacent bytes after we move the low one.
8462         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8463           // If we haven't yet mapped the input, search for a slot into which
8464           // we can map it.
8465           while (j < je && PreDupI16Shuffle[j] != -1)
8466             ++j;
8467
8468           if (j == je)
8469             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8470             return SDValue();
8471
8472           // Map this input with the i16 shuffle.
8473           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8474         }
8475
8476         // Update the lane map based on the mapping we ended up with.
8477         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8478       }
8479       V1 = DAG.getNode(
8480           ISD::BITCAST, DL, MVT::v16i8,
8481           DAG.getVectorShuffle(MVT::v8i16, DL,
8482                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8483                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8484
8485       // Unpack the bytes to form the i16s that will be shuffled into place.
8486       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8487                        MVT::v16i8, V1, V1);
8488
8489       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8490       for (int i = 0; i < 16; ++i)
8491         if (Mask[i] != -1) {
8492           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8493           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8494           if (PostDupI16Shuffle[i / 2] == -1)
8495             PostDupI16Shuffle[i / 2] = MappedMask;
8496           else
8497             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8498                    "Conflicting entrties in the original shuffle!");
8499         }
8500       return DAG.getNode(
8501           ISD::BITCAST, DL, MVT::v16i8,
8502           DAG.getVectorShuffle(MVT::v8i16, DL,
8503                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8504                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8505     };
8506     if (SDValue V = tryToWidenViaDuplication())
8507       return V;
8508   }
8509
8510   // Use dedicated unpack instructions for masks that match their pattern.
8511   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8512                                          0, 16, 1, 17, 2, 18, 3, 19,
8513                                          // High half.
8514                                          4, 20, 5, 21, 6, 22, 7, 23}))
8515     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8516   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8517                                          8, 24, 9, 25, 10, 26, 11, 27,
8518                                          // High half.
8519                                          12, 28, 13, 29, 14, 30, 15, 31}))
8520     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8521
8522   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8523   // with PSHUFB. It is important to do this before we attempt to generate any
8524   // blends but after all of the single-input lowerings. If the single input
8525   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8526   // want to preserve that and we can DAG combine any longer sequences into
8527   // a PSHUFB in the end. But once we start blending from multiple inputs,
8528   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8529   // and there are *very* few patterns that would actually be faster than the
8530   // PSHUFB approach because of its ability to zero lanes.
8531   //
8532   // FIXME: The only exceptions to the above are blends which are exact
8533   // interleavings with direct instructions supporting them. We currently don't
8534   // handle those well here.
8535   if (Subtarget->hasSSSE3()) {
8536     bool V1InUse = false;
8537     bool V2InUse = false;
8538
8539     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8540                                                 DAG, V1InUse, V2InUse);
8541
8542     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8543     // do so. This avoids using them to handle blends-with-zero which is
8544     // important as a single pshufb is significantly faster for that.
8545     if (V1InUse && V2InUse) {
8546       if (Subtarget->hasSSE41())
8547         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8548                                                       Mask, Subtarget, DAG))
8549           return Blend;
8550
8551       // We can use an unpack to do the blending rather than an or in some
8552       // cases. Even though the or may be (very minorly) more efficient, we
8553       // preference this lowering because there are common cases where part of
8554       // the complexity of the shuffles goes away when we do the final blend as
8555       // an unpack.
8556       // FIXME: It might be worth trying to detect if the unpack-feeding
8557       // shuffles will both be pshufb, in which case we shouldn't bother with
8558       // this.
8559       if (SDValue Unpack =
8560               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8561         return Unpack;
8562     }
8563
8564     return PSHUFB;
8565   }
8566
8567   // There are special ways we can lower some single-element blends.
8568   if (NumV2Elements == 1)
8569     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8570                                                          Mask, Subtarget, DAG))
8571       return V;
8572
8573   if (SDValue BitBlend =
8574           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8575     return BitBlend;
8576
8577   // Check whether a compaction lowering can be done. This handles shuffles
8578   // which take every Nth element for some even N. See the helper function for
8579   // details.
8580   //
8581   // We special case these as they can be particularly efficiently handled with
8582   // the PACKUSB instruction on x86 and they show up in common patterns of
8583   // rearranging bytes to truncate wide elements.
8584   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8585     // NumEvenDrops is the power of two stride of the elements. Another way of
8586     // thinking about it is that we need to drop the even elements this many
8587     // times to get the original input.
8588     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8589
8590     // First we need to zero all the dropped bytes.
8591     assert(NumEvenDrops <= 3 &&
8592            "No support for dropping even elements more than 3 times.");
8593     // We use the mask type to pick which bytes are preserved based on how many
8594     // elements are dropped.
8595     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8596     SDValue ByteClearMask =
8597         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8598                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8599     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8600     if (!IsSingleInput)
8601       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8602
8603     // Now pack things back together.
8604     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8605     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8606     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8607     for (int i = 1; i < NumEvenDrops; ++i) {
8608       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8609       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8610     }
8611
8612     return Result;
8613   }
8614
8615   // Handle multi-input cases by blending single-input shuffles.
8616   if (NumV2Elements > 0)
8617     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8618                                                       Mask, DAG);
8619
8620   // The fallback path for single-input shuffles widens this into two v8i16
8621   // vectors with unpacks, shuffles those, and then pulls them back together
8622   // with a pack.
8623   SDValue V = V1;
8624
8625   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8626   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8627   for (int i = 0; i < 16; ++i)
8628     if (Mask[i] >= 0)
8629       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8630
8631   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8632
8633   SDValue VLoHalf, VHiHalf;
8634   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8635   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8636   // i16s.
8637   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8638                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8639       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8640                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8641     // Use a mask to drop the high bytes.
8642     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8643     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8644                      DAG.getConstant(0x00FF, MVT::v8i16));
8645
8646     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8647     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8648
8649     // Squash the masks to point directly into VLoHalf.
8650     for (int &M : LoBlendMask)
8651       if (M >= 0)
8652         M /= 2;
8653     for (int &M : HiBlendMask)
8654       if (M >= 0)
8655         M /= 2;
8656   } else {
8657     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8658     // VHiHalf so that we can blend them as i16s.
8659     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8660                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8661     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8662                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8663   }
8664
8665   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8666   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8667
8668   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8669 }
8670
8671 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8672 ///
8673 /// This routine breaks down the specific type of 128-bit shuffle and
8674 /// dispatches to the lowering routines accordingly.
8675 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8676                                         MVT VT, const X86Subtarget *Subtarget,
8677                                         SelectionDAG &DAG) {
8678   switch (VT.SimpleTy) {
8679   case MVT::v2i64:
8680     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8681   case MVT::v2f64:
8682     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8683   case MVT::v4i32:
8684     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8685   case MVT::v4f32:
8686     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8687   case MVT::v8i16:
8688     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8689   case MVT::v16i8:
8690     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8691
8692   default:
8693     llvm_unreachable("Unimplemented!");
8694   }
8695 }
8696
8697 /// \brief Helper function to test whether a shuffle mask could be
8698 /// simplified by widening the elements being shuffled.
8699 ///
8700 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8701 /// leaves it in an unspecified state.
8702 ///
8703 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8704 /// shuffle masks. The latter have the special property of a '-2' representing
8705 /// a zero-ed lane of a vector.
8706 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8707                                     SmallVectorImpl<int> &WidenedMask) {
8708   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8709     // If both elements are undef, its trivial.
8710     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8711       WidenedMask.push_back(SM_SentinelUndef);
8712       continue;
8713     }
8714
8715     // Check for an undef mask and a mask value properly aligned to fit with
8716     // a pair of values. If we find such a case, use the non-undef mask's value.
8717     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8718       WidenedMask.push_back(Mask[i + 1] / 2);
8719       continue;
8720     }
8721     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8722       WidenedMask.push_back(Mask[i] / 2);
8723       continue;
8724     }
8725
8726     // When zeroing, we need to spread the zeroing across both lanes to widen.
8727     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8728       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8729           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8730         WidenedMask.push_back(SM_SentinelZero);
8731         continue;
8732       }
8733       return false;
8734     }
8735
8736     // Finally check if the two mask values are adjacent and aligned with
8737     // a pair.
8738     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8739       WidenedMask.push_back(Mask[i] / 2);
8740       continue;
8741     }
8742
8743     // Otherwise we can't safely widen the elements used in this shuffle.
8744     return false;
8745   }
8746   assert(WidenedMask.size() == Mask.size() / 2 &&
8747          "Incorrect size of mask after widening the elements!");
8748
8749   return true;
8750 }
8751
8752 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8753 ///
8754 /// This routine just extracts two subvectors, shuffles them independently, and
8755 /// then concatenates them back together. This should work effectively with all
8756 /// AVX vector shuffle types.
8757 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8758                                           SDValue V2, ArrayRef<int> Mask,
8759                                           SelectionDAG &DAG) {
8760   assert(VT.getSizeInBits() >= 256 &&
8761          "Only for 256-bit or wider vector shuffles!");
8762   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8763   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8764
8765   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8766   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8767
8768   int NumElements = VT.getVectorNumElements();
8769   int SplitNumElements = NumElements / 2;
8770   MVT ScalarVT = VT.getScalarType();
8771   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8772
8773   // Rather than splitting build-vectors, just build two narrower build
8774   // vectors. This helps shuffling with splats and zeros.
8775   auto SplitVector = [&](SDValue V) {
8776     while (V.getOpcode() == ISD::BITCAST)
8777       V = V->getOperand(0);
8778
8779     MVT OrigVT = V.getSimpleValueType();
8780     int OrigNumElements = OrigVT.getVectorNumElements();
8781     int OrigSplitNumElements = OrigNumElements / 2;
8782     MVT OrigScalarVT = OrigVT.getScalarType();
8783     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8784
8785     SDValue LoV, HiV;
8786
8787     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8788     if (!BV) {
8789       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8790                         DAG.getIntPtrConstant(0));
8791       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8792                         DAG.getIntPtrConstant(OrigSplitNumElements));
8793     } else {
8794
8795       SmallVector<SDValue, 16> LoOps, HiOps;
8796       for (int i = 0; i < OrigSplitNumElements; ++i) {
8797         LoOps.push_back(BV->getOperand(i));
8798         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8799       }
8800       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8801       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8802     }
8803     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8804                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8805   };
8806
8807   SDValue LoV1, HiV1, LoV2, HiV2;
8808   std::tie(LoV1, HiV1) = SplitVector(V1);
8809   std::tie(LoV2, HiV2) = SplitVector(V2);
8810
8811   // Now create two 4-way blends of these half-width vectors.
8812   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8813     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8814     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8815     for (int i = 0; i < SplitNumElements; ++i) {
8816       int M = HalfMask[i];
8817       if (M >= NumElements) {
8818         if (M >= NumElements + SplitNumElements)
8819           UseHiV2 = true;
8820         else
8821           UseLoV2 = true;
8822         V2BlendMask.push_back(M - NumElements);
8823         V1BlendMask.push_back(-1);
8824         BlendMask.push_back(SplitNumElements + i);
8825       } else if (M >= 0) {
8826         if (M >= SplitNumElements)
8827           UseHiV1 = true;
8828         else
8829           UseLoV1 = true;
8830         V2BlendMask.push_back(-1);
8831         V1BlendMask.push_back(M);
8832         BlendMask.push_back(i);
8833       } else {
8834         V2BlendMask.push_back(-1);
8835         V1BlendMask.push_back(-1);
8836         BlendMask.push_back(-1);
8837       }
8838     }
8839
8840     // Because the lowering happens after all combining takes place, we need to
8841     // manually combine these blend masks as much as possible so that we create
8842     // a minimal number of high-level vector shuffle nodes.
8843
8844     // First try just blending the halves of V1 or V2.
8845     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8846       return DAG.getUNDEF(SplitVT);
8847     if (!UseLoV2 && !UseHiV2)
8848       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8849     if (!UseLoV1 && !UseHiV1)
8850       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8851
8852     SDValue V1Blend, V2Blend;
8853     if (UseLoV1 && UseHiV1) {
8854       V1Blend =
8855         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8856     } else {
8857       // We only use half of V1 so map the usage down into the final blend mask.
8858       V1Blend = UseLoV1 ? LoV1 : HiV1;
8859       for (int i = 0; i < SplitNumElements; ++i)
8860         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8861           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8862     }
8863     if (UseLoV2 && UseHiV2) {
8864       V2Blend =
8865         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8866     } else {
8867       // We only use half of V2 so map the usage down into the final blend mask.
8868       V2Blend = UseLoV2 ? LoV2 : HiV2;
8869       for (int i = 0; i < SplitNumElements; ++i)
8870         if (BlendMask[i] >= SplitNumElements)
8871           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8872     }
8873     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8874   };
8875   SDValue Lo = HalfBlend(LoMask);
8876   SDValue Hi = HalfBlend(HiMask);
8877   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8878 }
8879
8880 /// \brief Either split a vector in halves or decompose the shuffles and the
8881 /// blend.
8882 ///
8883 /// This is provided as a good fallback for many lowerings of non-single-input
8884 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8885 /// between splitting the shuffle into 128-bit components and stitching those
8886 /// back together vs. extracting the single-input shuffles and blending those
8887 /// results.
8888 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8889                                                 SDValue V2, ArrayRef<int> Mask,
8890                                                 SelectionDAG &DAG) {
8891   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8892                                             "lower single-input shuffles as it "
8893                                             "could then recurse on itself.");
8894   int Size = Mask.size();
8895
8896   // If this can be modeled as a broadcast of two elements followed by a blend,
8897   // prefer that lowering. This is especially important because broadcasts can
8898   // often fold with memory operands.
8899   auto DoBothBroadcast = [&] {
8900     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8901     for (int M : Mask)
8902       if (M >= Size) {
8903         if (V2BroadcastIdx == -1)
8904           V2BroadcastIdx = M - Size;
8905         else if (M - Size != V2BroadcastIdx)
8906           return false;
8907       } else if (M >= 0) {
8908         if (V1BroadcastIdx == -1)
8909           V1BroadcastIdx = M;
8910         else if (M != V1BroadcastIdx)
8911           return false;
8912       }
8913     return true;
8914   };
8915   if (DoBothBroadcast())
8916     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8917                                                       DAG);
8918
8919   // If the inputs all stem from a single 128-bit lane of each input, then we
8920   // split them rather than blending because the split will decompose to
8921   // unusually few instructions.
8922   int LaneCount = VT.getSizeInBits() / 128;
8923   int LaneSize = Size / LaneCount;
8924   SmallBitVector LaneInputs[2];
8925   LaneInputs[0].resize(LaneCount, false);
8926   LaneInputs[1].resize(LaneCount, false);
8927   for (int i = 0; i < Size; ++i)
8928     if (Mask[i] >= 0)
8929       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8930   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8931     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8932
8933   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8934   // that the decomposed single-input shuffles don't end up here.
8935   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8936 }
8937
8938 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8939 /// a permutation and blend of those lanes.
8940 ///
8941 /// This essentially blends the out-of-lane inputs to each lane into the lane
8942 /// from a permuted copy of the vector. This lowering strategy results in four
8943 /// instructions in the worst case for a single-input cross lane shuffle which
8944 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8945 /// of. Special cases for each particular shuffle pattern should be handled
8946 /// prior to trying this lowering.
8947 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8948                                                        SDValue V1, SDValue V2,
8949                                                        ArrayRef<int> Mask,
8950                                                        SelectionDAG &DAG) {
8951   // FIXME: This should probably be generalized for 512-bit vectors as well.
8952   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8953   int LaneSize = Mask.size() / 2;
8954
8955   // If there are only inputs from one 128-bit lane, splitting will in fact be
8956   // less expensive. The flags track wether the given lane contains an element
8957   // that crosses to another lane.
8958   bool LaneCrossing[2] = {false, false};
8959   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8960     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8961       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8962   if (!LaneCrossing[0] || !LaneCrossing[1])
8963     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8964
8965   if (isSingleInputShuffleMask(Mask)) {
8966     SmallVector<int, 32> FlippedBlendMask;
8967     for (int i = 0, Size = Mask.size(); i < Size; ++i)
8968       FlippedBlendMask.push_back(
8969           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8970                                   ? Mask[i]
8971                                   : Mask[i] % LaneSize +
8972                                         (i / LaneSize) * LaneSize + Size));
8973
8974     // Flip the vector, and blend the results which should now be in-lane. The
8975     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8976     // 5 for the high source. The value 3 selects the high half of source 2 and
8977     // the value 2 selects the low half of source 2. We only use source 2 to
8978     // allow folding it into a memory operand.
8979     unsigned PERMMask = 3 | 2 << 4;
8980     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
8981                                   V1, DAG.getConstant(PERMMask, MVT::i8));
8982     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
8983   }
8984
8985   // This now reduces to two single-input shuffles of V1 and V2 which at worst
8986   // will be handled by the above logic and a blend of the results, much like
8987   // other patterns in AVX.
8988   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8989 }
8990
8991 /// \brief Handle lowering 2-lane 128-bit shuffles.
8992 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8993                                         SDValue V2, ArrayRef<int> Mask,
8994                                         const X86Subtarget *Subtarget,
8995                                         SelectionDAG &DAG) {
8996   // Blends are faster and handle all the non-lane-crossing cases.
8997   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
8998                                                 Subtarget, DAG))
8999     return Blend;
9000
9001   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9002                                VT.getVectorNumElements() / 2);
9003   // Check for patterns which can be matched with a single insert of a 128-bit
9004   // subvector.
9005   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
9006       isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9007     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9008                               DAG.getIntPtrConstant(0));
9009     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9010                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9011     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9012   }
9013   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9014     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9015                               DAG.getIntPtrConstant(0));
9016     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9017                               DAG.getIntPtrConstant(2));
9018     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9019   }
9020
9021   // Otherwise form a 128-bit permutation.
9022   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9023   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9024   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9025                      DAG.getConstant(PermMask, MVT::i8));
9026 }
9027
9028 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9029 /// shuffling each lane.
9030 ///
9031 /// This will only succeed when the result of fixing the 128-bit lanes results
9032 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9033 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9034 /// the lane crosses early and then use simpler shuffles within each lane.
9035 ///
9036 /// FIXME: It might be worthwhile at some point to support this without
9037 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9038 /// in x86 only floating point has interesting non-repeating shuffles, and even
9039 /// those are still *marginally* more expensive.
9040 static SDValue lowerVectorShuffleByMerging128BitLanes(
9041     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9042     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9043   assert(!isSingleInputShuffleMask(Mask) &&
9044          "This is only useful with multiple inputs.");
9045
9046   int Size = Mask.size();
9047   int LaneSize = 128 / VT.getScalarSizeInBits();
9048   int NumLanes = Size / LaneSize;
9049   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9050
9051   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9052   // check whether the in-128-bit lane shuffles share a repeating pattern.
9053   SmallVector<int, 4> Lanes;
9054   Lanes.resize(NumLanes, -1);
9055   SmallVector<int, 4> InLaneMask;
9056   InLaneMask.resize(LaneSize, -1);
9057   for (int i = 0; i < Size; ++i) {
9058     if (Mask[i] < 0)
9059       continue;
9060
9061     int j = i / LaneSize;
9062
9063     if (Lanes[j] < 0) {
9064       // First entry we've seen for this lane.
9065       Lanes[j] = Mask[i] / LaneSize;
9066     } else if (Lanes[j] != Mask[i] / LaneSize) {
9067       // This doesn't match the lane selected previously!
9068       return SDValue();
9069     }
9070
9071     // Check that within each lane we have a consistent shuffle mask.
9072     int k = i % LaneSize;
9073     if (InLaneMask[k] < 0) {
9074       InLaneMask[k] = Mask[i] % LaneSize;
9075     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9076       // This doesn't fit a repeating in-lane mask.
9077       return SDValue();
9078     }
9079   }
9080
9081   // First shuffle the lanes into place.
9082   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9083                                 VT.getSizeInBits() / 64);
9084   SmallVector<int, 8> LaneMask;
9085   LaneMask.resize(NumLanes * 2, -1);
9086   for (int i = 0; i < NumLanes; ++i)
9087     if (Lanes[i] >= 0) {
9088       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9089       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9090     }
9091
9092   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9093   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9094   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9095
9096   // Cast it back to the type we actually want.
9097   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9098
9099   // Now do a simple shuffle that isn't lane crossing.
9100   SmallVector<int, 8> NewMask;
9101   NewMask.resize(Size, -1);
9102   for (int i = 0; i < Size; ++i)
9103     if (Mask[i] >= 0)
9104       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9105   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9106          "Must not introduce lane crosses at this point!");
9107
9108   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9109 }
9110
9111 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9112 /// given mask.
9113 ///
9114 /// This returns true if the elements from a particular input are already in the
9115 /// slot required by the given mask and require no permutation.
9116 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9117   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9118   int Size = Mask.size();
9119   for (int i = 0; i < Size; ++i)
9120     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9121       return false;
9122
9123   return true;
9124 }
9125
9126 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9127 ///
9128 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9129 /// isn't available.
9130 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9131                                        const X86Subtarget *Subtarget,
9132                                        SelectionDAG &DAG) {
9133   SDLoc DL(Op);
9134   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9135   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9136   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9137   ArrayRef<int> Mask = SVOp->getMask();
9138   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9139
9140   SmallVector<int, 4> WidenedMask;
9141   if (canWidenShuffleElements(Mask, WidenedMask))
9142     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9143                                     DAG);
9144
9145   if (isSingleInputShuffleMask(Mask)) {
9146     // Check for being able to broadcast a single element.
9147     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9148                                                           Mask, Subtarget, DAG))
9149       return Broadcast;
9150
9151     // Use low duplicate instructions for masks that match their pattern.
9152     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9153       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9154
9155     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9156       // Non-half-crossing single input shuffles can be lowerid with an
9157       // interleaved permutation.
9158       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9159                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9160       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9161                          DAG.getConstant(VPERMILPMask, MVT::i8));
9162     }
9163
9164     // With AVX2 we have direct support for this permutation.
9165     if (Subtarget->hasAVX2())
9166       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9167                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9168
9169     // Otherwise, fall back.
9170     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9171                                                    DAG);
9172   }
9173
9174   // X86 has dedicated unpack instructions that can handle specific blend
9175   // operations: UNPCKH and UNPCKL.
9176   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9177     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9178   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9179     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9180   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9181     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9182   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9183     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9184
9185   // If we have a single input to the zero element, insert that into V1 if we
9186   // can do so cheaply.
9187   int NumV2Elements =
9188       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9189   if (NumV2Elements == 1 && Mask[0] >= 4)
9190     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9191             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9192       return Insertion;
9193
9194   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9195                                                 Subtarget, DAG))
9196     return Blend;
9197
9198   // Check if the blend happens to exactly fit that of SHUFPD.
9199   if ((Mask[0] == -1 || Mask[0] < 2) &&
9200       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9201       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9202       (Mask[3] == -1 || Mask[3] >= 6)) {
9203     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9204                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9205     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9206                        DAG.getConstant(SHUFPDMask, MVT::i8));
9207   }
9208   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9209       (Mask[1] == -1 || Mask[1] < 2) &&
9210       (Mask[2] == -1 || Mask[2] >= 6) &&
9211       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9212     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9213                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9214     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9215                        DAG.getConstant(SHUFPDMask, MVT::i8));
9216   }
9217
9218   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9219   // shuffle. However, if we have AVX2 and either inputs are already in place,
9220   // we will be able to shuffle even across lanes the other input in a single
9221   // instruction so skip this pattern.
9222   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9223                                  isShuffleMaskInputInPlace(1, Mask))))
9224     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9225             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9226       return Result;
9227
9228   // If we have AVX2 then we always want to lower with a blend because an v4 we
9229   // can fully permute the elements.
9230   if (Subtarget->hasAVX2())
9231     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9232                                                       Mask, DAG);
9233
9234   // Otherwise fall back on generic lowering.
9235   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9236 }
9237
9238 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9239 ///
9240 /// This routine is only called when we have AVX2 and thus a reasonable
9241 /// instruction set for v4i64 shuffling..
9242 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9243                                        const X86Subtarget *Subtarget,
9244                                        SelectionDAG &DAG) {
9245   SDLoc DL(Op);
9246   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9247   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9248   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9249   ArrayRef<int> Mask = SVOp->getMask();
9250   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9251   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9252
9253   SmallVector<int, 4> WidenedMask;
9254   if (canWidenShuffleElements(Mask, WidenedMask))
9255     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9256                                     DAG);
9257
9258   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9259                                                 Subtarget, DAG))
9260     return Blend;
9261
9262   // Check for being able to broadcast a single element.
9263   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9264                                                         Mask, Subtarget, DAG))
9265     return Broadcast;
9266
9267   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9268   // use lower latency instructions that will operate on both 128-bit lanes.
9269   SmallVector<int, 2> RepeatedMask;
9270   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9271     if (isSingleInputShuffleMask(Mask)) {
9272       int PSHUFDMask[] = {-1, -1, -1, -1};
9273       for (int i = 0; i < 2; ++i)
9274         if (RepeatedMask[i] >= 0) {
9275           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9276           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9277         }
9278       return DAG.getNode(
9279           ISD::BITCAST, DL, MVT::v4i64,
9280           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9281                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9282                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9283     }
9284   }
9285
9286   // AVX2 provides a direct instruction for permuting a single input across
9287   // lanes.
9288   if (isSingleInputShuffleMask(Mask))
9289     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9290                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9291
9292   // Try to use shift instructions.
9293   if (SDValue Shift =
9294           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9295     return Shift;
9296
9297   // Use dedicated unpack instructions for masks that match their pattern.
9298   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9299     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9300   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9301     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9302   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9303     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9304   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9305     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9306
9307   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9308   // shuffle. However, if we have AVX2 and either inputs are already in place,
9309   // we will be able to shuffle even across lanes the other input in a single
9310   // instruction so skip this pattern.
9311   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9312                                  isShuffleMaskInputInPlace(1, Mask))))
9313     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9314             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9315       return Result;
9316
9317   // Otherwise fall back on generic blend lowering.
9318   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9319                                                     Mask, DAG);
9320 }
9321
9322 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9323 ///
9324 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9325 /// isn't available.
9326 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9327                                        const X86Subtarget *Subtarget,
9328                                        SelectionDAG &DAG) {
9329   SDLoc DL(Op);
9330   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9331   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9332   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9333   ArrayRef<int> Mask = SVOp->getMask();
9334   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9335
9336   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9337                                                 Subtarget, DAG))
9338     return Blend;
9339
9340   // Check for being able to broadcast a single element.
9341   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9342                                                         Mask, Subtarget, DAG))
9343     return Broadcast;
9344
9345   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9346   // options to efficiently lower the shuffle.
9347   SmallVector<int, 4> RepeatedMask;
9348   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9349     assert(RepeatedMask.size() == 4 &&
9350            "Repeated masks must be half the mask width!");
9351
9352     // Use even/odd duplicate instructions for masks that match their pattern.
9353     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9354       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9355     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9356       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9357
9358     if (isSingleInputShuffleMask(Mask))
9359       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9360                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9361
9362     // Use dedicated unpack instructions for masks that match their pattern.
9363     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9364       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9365     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9366       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9367     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9368       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9369     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9370       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9371
9372     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9373     // have already handled any direct blends. We also need to squash the
9374     // repeated mask into a simulated v4f32 mask.
9375     for (int i = 0; i < 4; ++i)
9376       if (RepeatedMask[i] >= 8)
9377         RepeatedMask[i] -= 4;
9378     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9379   }
9380
9381   // If we have a single input shuffle with different shuffle patterns in the
9382   // two 128-bit lanes use the variable mask to VPERMILPS.
9383   if (isSingleInputShuffleMask(Mask)) {
9384     SDValue VPermMask[8];
9385     for (int i = 0; i < 8; ++i)
9386       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9387                                  : DAG.getConstant(Mask[i], MVT::i32);
9388     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9389       return DAG.getNode(
9390           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9391           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9392
9393     if (Subtarget->hasAVX2())
9394       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9395                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9396                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9397                                                  MVT::v8i32, VPermMask)),
9398                          V1);
9399
9400     // Otherwise, fall back.
9401     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9402                                                    DAG);
9403   }
9404
9405   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9406   // shuffle.
9407   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9408           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9409     return Result;
9410
9411   // If we have AVX2 then we always want to lower with a blend because at v8 we
9412   // can fully permute the elements.
9413   if (Subtarget->hasAVX2())
9414     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9415                                                       Mask, DAG);
9416
9417   // Otherwise fall back on generic lowering.
9418   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9419 }
9420
9421 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9422 ///
9423 /// This routine is only called when we have AVX2 and thus a reasonable
9424 /// instruction set for v8i32 shuffling..
9425 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9426                                        const X86Subtarget *Subtarget,
9427                                        SelectionDAG &DAG) {
9428   SDLoc DL(Op);
9429   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9430   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9432   ArrayRef<int> Mask = SVOp->getMask();
9433   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9434   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9435
9436   // Whenever we can lower this as a zext, that instruction is strictly faster
9437   // than any alternative. It also allows us to fold memory operands into the
9438   // shuffle in many cases.
9439   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9440                                                          Mask, Subtarget, DAG))
9441     return ZExt;
9442
9443   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9444                                                 Subtarget, DAG))
9445     return Blend;
9446
9447   // Check for being able to broadcast a single element.
9448   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9449                                                         Mask, Subtarget, DAG))
9450     return Broadcast;
9451
9452   // If the shuffle mask is repeated in each 128-bit lane we can use more
9453   // efficient instructions that mirror the shuffles across the two 128-bit
9454   // lanes.
9455   SmallVector<int, 4> RepeatedMask;
9456   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9457     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9458     if (isSingleInputShuffleMask(Mask))
9459       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9460                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9461
9462     // Use dedicated unpack instructions for masks that match their pattern.
9463     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9464       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9465     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9466       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9467     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9468       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9469     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9470       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9471   }
9472
9473   // Try to use shift instructions.
9474   if (SDValue Shift =
9475           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9476     return Shift;
9477
9478   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9479           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9480     return Rotate;
9481
9482   // If the shuffle patterns aren't repeated but it is a single input, directly
9483   // generate a cross-lane VPERMD instruction.
9484   if (isSingleInputShuffleMask(Mask)) {
9485     SDValue VPermMask[8];
9486     for (int i = 0; i < 8; ++i)
9487       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9488                                  : DAG.getConstant(Mask[i], MVT::i32);
9489     return DAG.getNode(
9490         X86ISD::VPERMV, DL, MVT::v8i32,
9491         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9492   }
9493
9494   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9495   // shuffle.
9496   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9497           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9498     return Result;
9499
9500   // Otherwise fall back on generic blend lowering.
9501   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9502                                                     Mask, DAG);
9503 }
9504
9505 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9506 ///
9507 /// This routine is only called when we have AVX2 and thus a reasonable
9508 /// instruction set for v16i16 shuffling..
9509 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9510                                         const X86Subtarget *Subtarget,
9511                                         SelectionDAG &DAG) {
9512   SDLoc DL(Op);
9513   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9514   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9515   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9516   ArrayRef<int> Mask = SVOp->getMask();
9517   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9518   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9519
9520   // Whenever we can lower this as a zext, that instruction is strictly faster
9521   // than any alternative. It also allows us to fold memory operands into the
9522   // shuffle in many cases.
9523   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9524                                                          Mask, Subtarget, DAG))
9525     return ZExt;
9526
9527   // Check for being able to broadcast a single element.
9528   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9529                                                         Mask, Subtarget, DAG))
9530     return Broadcast;
9531
9532   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9533                                                 Subtarget, DAG))
9534     return Blend;
9535
9536   // Use dedicated unpack instructions for masks that match their pattern.
9537   if (isShuffleEquivalent(V1, V2, Mask,
9538                           {// First 128-bit lane:
9539                            0, 16, 1, 17, 2, 18, 3, 19,
9540                            // Second 128-bit lane:
9541                            8, 24, 9, 25, 10, 26, 11, 27}))
9542     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9543   if (isShuffleEquivalent(V1, V2, Mask,
9544                           {// First 128-bit lane:
9545                            4, 20, 5, 21, 6, 22, 7, 23,
9546                            // Second 128-bit lane:
9547                            12, 28, 13, 29, 14, 30, 15, 31}))
9548     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9549
9550   // Try to use shift instructions.
9551   if (SDValue Shift =
9552           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9553     return Shift;
9554
9555   // Try to use byte rotation instructions.
9556   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9557           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9558     return Rotate;
9559
9560   if (isSingleInputShuffleMask(Mask)) {
9561     // There are no generalized cross-lane shuffle operations available on i16
9562     // element types.
9563     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9564       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9565                                                      Mask, DAG);
9566
9567     SmallVector<int, 8> RepeatedMask;
9568     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9569       // As this is a single-input shuffle, the repeated mask should be
9570       // a strictly valid v8i16 mask that we can pass through to the v8i16
9571       // lowering to handle even the v16 case.
9572       return lowerV8I16GeneralSingleInputVectorShuffle(
9573           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9574     }
9575
9576     SDValue PSHUFBMask[32];
9577     for (int i = 0; i < 16; ++i) {
9578       if (Mask[i] == -1) {
9579         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9580         continue;
9581       }
9582
9583       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9584       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9585       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9586       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9587     }
9588     return DAG.getNode(
9589         ISD::BITCAST, DL, MVT::v16i16,
9590         DAG.getNode(
9591             X86ISD::PSHUFB, DL, MVT::v32i8,
9592             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9593             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9594   }
9595
9596   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9597   // shuffle.
9598   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9599           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9600     return Result;
9601
9602   // Otherwise fall back on generic lowering.
9603   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9604 }
9605
9606 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9607 ///
9608 /// This routine is only called when we have AVX2 and thus a reasonable
9609 /// instruction set for v32i8 shuffling..
9610 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9611                                        const X86Subtarget *Subtarget,
9612                                        SelectionDAG &DAG) {
9613   SDLoc DL(Op);
9614   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9615   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9616   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9617   ArrayRef<int> Mask = SVOp->getMask();
9618   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9619   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9620
9621   // Whenever we can lower this as a zext, that instruction is strictly faster
9622   // than any alternative. It also allows us to fold memory operands into the
9623   // shuffle in many cases.
9624   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9625                                                          Mask, Subtarget, DAG))
9626     return ZExt;
9627
9628   // Check for being able to broadcast a single element.
9629   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9630                                                         Mask, Subtarget, DAG))
9631     return Broadcast;
9632
9633   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9634                                                 Subtarget, DAG))
9635     return Blend;
9636
9637   // Use dedicated unpack instructions for masks that match their pattern.
9638   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9639   // 256-bit lanes.
9640   if (isShuffleEquivalent(
9641           V1, V2, Mask,
9642           {// First 128-bit lane:
9643            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9644            // Second 128-bit lane:
9645            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9646     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9647   if (isShuffleEquivalent(
9648           V1, V2, Mask,
9649           {// First 128-bit lane:
9650            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9651            // Second 128-bit lane:
9652            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9653     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9654
9655   // Try to use shift instructions.
9656   if (SDValue Shift =
9657           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9658     return Shift;
9659
9660   // Try to use byte rotation instructions.
9661   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9662           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9663     return Rotate;
9664
9665   if (isSingleInputShuffleMask(Mask)) {
9666     // There are no generalized cross-lane shuffle operations available on i8
9667     // element types.
9668     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9669       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9670                                                      Mask, DAG);
9671
9672     SDValue PSHUFBMask[32];
9673     for (int i = 0; i < 32; ++i)
9674       PSHUFBMask[i] =
9675           Mask[i] < 0
9676               ? DAG.getUNDEF(MVT::i8)
9677               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9678
9679     return DAG.getNode(
9680         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9681         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9682   }
9683
9684   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9685   // shuffle.
9686   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9687           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9688     return Result;
9689
9690   // Otherwise fall back on generic lowering.
9691   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9692 }
9693
9694 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9695 ///
9696 /// This routine either breaks down the specific type of a 256-bit x86 vector
9697 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9698 /// together based on the available instructions.
9699 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9700                                         MVT VT, const X86Subtarget *Subtarget,
9701                                         SelectionDAG &DAG) {
9702   SDLoc DL(Op);
9703   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9704   ArrayRef<int> Mask = SVOp->getMask();
9705
9706   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9707   // check for those subtargets here and avoid much of the subtarget querying in
9708   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9709   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9710   // floating point types there eventually, just immediately cast everything to
9711   // a float and operate entirely in that domain.
9712   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9713     int ElementBits = VT.getScalarSizeInBits();
9714     if (ElementBits < 32)
9715       // No floating point type available, decompose into 128-bit vectors.
9716       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9717
9718     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9719                                 VT.getVectorNumElements());
9720     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9721     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9722     return DAG.getNode(ISD::BITCAST, DL, VT,
9723                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9724   }
9725
9726   switch (VT.SimpleTy) {
9727   case MVT::v4f64:
9728     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9729   case MVT::v4i64:
9730     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9731   case MVT::v8f32:
9732     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9733   case MVT::v8i32:
9734     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9735   case MVT::v16i16:
9736     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9737   case MVT::v32i8:
9738     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9739
9740   default:
9741     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9742   }
9743 }
9744
9745 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9746 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9747                                        const X86Subtarget *Subtarget,
9748                                        SelectionDAG &DAG) {
9749   SDLoc DL(Op);
9750   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9751   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9752   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9753   ArrayRef<int> Mask = SVOp->getMask();
9754   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9755
9756   // X86 has dedicated unpack instructions that can handle specific blend
9757   // operations: UNPCKH and UNPCKL.
9758   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9759     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9760   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9761     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9762
9763   // FIXME: Implement direct support for this type!
9764   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9765 }
9766
9767 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9768 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9769                                        const X86Subtarget *Subtarget,
9770                                        SelectionDAG &DAG) {
9771   SDLoc DL(Op);
9772   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9773   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9775   ArrayRef<int> Mask = SVOp->getMask();
9776   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9777
9778   // Use dedicated unpack instructions for masks that match their pattern.
9779   if (isShuffleEquivalent(V1, V2, Mask,
9780                           {// First 128-bit lane.
9781                            0, 16, 1, 17, 4, 20, 5, 21,
9782                            // Second 128-bit lane.
9783                            8, 24, 9, 25, 12, 28, 13, 29}))
9784     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9785   if (isShuffleEquivalent(V1, V2, Mask,
9786                           {// First 128-bit lane.
9787                            2, 18, 3, 19, 6, 22, 7, 23,
9788                            // Second 128-bit lane.
9789                            10, 26, 11, 27, 14, 30, 15, 31}))
9790     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9791
9792   // FIXME: Implement direct support for this type!
9793   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9794 }
9795
9796 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9797 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9798                                        const X86Subtarget *Subtarget,
9799                                        SelectionDAG &DAG) {
9800   SDLoc DL(Op);
9801   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9802   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9804   ArrayRef<int> Mask = SVOp->getMask();
9805   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9806
9807   // X86 has dedicated unpack instructions that can handle specific blend
9808   // operations: UNPCKH and UNPCKL.
9809   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9810     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9811   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9812     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9813
9814   // FIXME: Implement direct support for this type!
9815   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9816 }
9817
9818 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9819 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9820                                        const X86Subtarget *Subtarget,
9821                                        SelectionDAG &DAG) {
9822   SDLoc DL(Op);
9823   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9824   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9825   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9826   ArrayRef<int> Mask = SVOp->getMask();
9827   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9828
9829   // Use dedicated unpack instructions for masks that match their pattern.
9830   if (isShuffleEquivalent(V1, V2, Mask,
9831                           {// First 128-bit lane.
9832                            0, 16, 1, 17, 4, 20, 5, 21,
9833                            // Second 128-bit lane.
9834                            8, 24, 9, 25, 12, 28, 13, 29}))
9835     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9836   if (isShuffleEquivalent(V1, V2, Mask,
9837                           {// First 128-bit lane.
9838                            2, 18, 3, 19, 6, 22, 7, 23,
9839                            // Second 128-bit lane.
9840                            10, 26, 11, 27, 14, 30, 15, 31}))
9841     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9842
9843   // FIXME: Implement direct support for this type!
9844   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9845 }
9846
9847 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9848 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9849                                         const X86Subtarget *Subtarget,
9850                                         SelectionDAG &DAG) {
9851   SDLoc DL(Op);
9852   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9853   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9854   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855   ArrayRef<int> Mask = SVOp->getMask();
9856   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9857   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9858
9859   // FIXME: Implement direct support for this type!
9860   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9861 }
9862
9863 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9864 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9865                                        const X86Subtarget *Subtarget,
9866                                        SelectionDAG &DAG) {
9867   SDLoc DL(Op);
9868   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9869   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9871   ArrayRef<int> Mask = SVOp->getMask();
9872   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9873   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9874
9875   // FIXME: Implement direct support for this type!
9876   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9877 }
9878
9879 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9880 ///
9881 /// This routine either breaks down the specific type of a 512-bit x86 vector
9882 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9883 /// together based on the available instructions.
9884 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885                                         MVT VT, const X86Subtarget *Subtarget,
9886                                         SelectionDAG &DAG) {
9887   SDLoc DL(Op);
9888   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9889   ArrayRef<int> Mask = SVOp->getMask();
9890   assert(Subtarget->hasAVX512() &&
9891          "Cannot lower 512-bit vectors w/ basic ISA!");
9892
9893   // Check for being able to broadcast a single element.
9894   if (SDValue Broadcast =
9895           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9896     return Broadcast;
9897
9898   // Dispatch to each element type for lowering. If we don't have supprot for
9899   // specific element type shuffles at 512 bits, immediately split them and
9900   // lower them. Each lowering routine of a given type is allowed to assume that
9901   // the requisite ISA extensions for that element type are available.
9902   switch (VT.SimpleTy) {
9903   case MVT::v8f64:
9904     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9905   case MVT::v16f32:
9906     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9907   case MVT::v8i64:
9908     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9909   case MVT::v16i32:
9910     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9911   case MVT::v32i16:
9912     if (Subtarget->hasBWI())
9913       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9914     break;
9915   case MVT::v64i8:
9916     if (Subtarget->hasBWI())
9917       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9918     break;
9919
9920   default:
9921     llvm_unreachable("Not a valid 512-bit x86 vector type!");
9922   }
9923
9924   // Otherwise fall back on splitting.
9925   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9926 }
9927
9928 /// \brief Top-level lowering for x86 vector shuffles.
9929 ///
9930 /// This handles decomposition, canonicalization, and lowering of all x86
9931 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9932 /// above in helper routines. The canonicalization attempts to widen shuffles
9933 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9934 /// s.t. only one of the two inputs needs to be tested, etc.
9935 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9936                                   SelectionDAG &DAG) {
9937   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9938   ArrayRef<int> Mask = SVOp->getMask();
9939   SDValue V1 = Op.getOperand(0);
9940   SDValue V2 = Op.getOperand(1);
9941   MVT VT = Op.getSimpleValueType();
9942   int NumElements = VT.getVectorNumElements();
9943   SDLoc dl(Op);
9944
9945   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9946
9947   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9948   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9949   if (V1IsUndef && V2IsUndef)
9950     return DAG.getUNDEF(VT);
9951
9952   // When we create a shuffle node we put the UNDEF node to second operand,
9953   // but in some cases the first operand may be transformed to UNDEF.
9954   // In this case we should just commute the node.
9955   if (V1IsUndef)
9956     return DAG.getCommutedVectorShuffle(*SVOp);
9957
9958   // Check for non-undef masks pointing at an undef vector and make the masks
9959   // undef as well. This makes it easier to match the shuffle based solely on
9960   // the mask.
9961   if (V2IsUndef)
9962     for (int M : Mask)
9963       if (M >= NumElements) {
9964         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9965         for (int &M : NewMask)
9966           if (M >= NumElements)
9967             M = -1;
9968         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9969       }
9970
9971   // We actually see shuffles that are entirely re-arrangements of a set of
9972   // zero inputs. This mostly happens while decomposing complex shuffles into
9973   // simple ones. Directly lower these as a buildvector of zeros.
9974   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9975   if (Zeroable.all())
9976     return getZeroVector(VT, Subtarget, DAG, dl);
9977
9978   // Try to collapse shuffles into using a vector type with fewer elements but
9979   // wider element types. We cap this to not form integers or floating point
9980   // elements wider than 64 bits, but it might be interesting to form i128
9981   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
9982   SmallVector<int, 16> WidenedMask;
9983   if (VT.getScalarSizeInBits() < 64 &&
9984       canWidenShuffleElements(Mask, WidenedMask)) {
9985     MVT NewEltVT = VT.isFloatingPoint()
9986                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
9987                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
9988     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9989     // Make sure that the new vector type is legal. For example, v2f64 isn't
9990     // legal on SSE1.
9991     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9992       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9993       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9994       return DAG.getNode(ISD::BITCAST, dl, VT,
9995                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
9996     }
9997   }
9998
9999   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10000   for (int M : SVOp->getMask())
10001     if (M < 0)
10002       ++NumUndefElements;
10003     else if (M < NumElements)
10004       ++NumV1Elements;
10005     else
10006       ++NumV2Elements;
10007
10008   // Commute the shuffle as needed such that more elements come from V1 than
10009   // V2. This allows us to match the shuffle pattern strictly on how many
10010   // elements come from V1 without handling the symmetric cases.
10011   if (NumV2Elements > NumV1Elements)
10012     return DAG.getCommutedVectorShuffle(*SVOp);
10013
10014   // When the number of V1 and V2 elements are the same, try to minimize the
10015   // number of uses of V2 in the low half of the vector. When that is tied,
10016   // ensure that the sum of indices for V1 is equal to or lower than the sum
10017   // indices for V2. When those are equal, try to ensure that the number of odd
10018   // indices for V1 is lower than the number of odd indices for V2.
10019   if (NumV1Elements == NumV2Elements) {
10020     int LowV1Elements = 0, LowV2Elements = 0;
10021     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10022       if (M >= NumElements)
10023         ++LowV2Elements;
10024       else if (M >= 0)
10025         ++LowV1Elements;
10026     if (LowV2Elements > LowV1Elements) {
10027       return DAG.getCommutedVectorShuffle(*SVOp);
10028     } else if (LowV2Elements == LowV1Elements) {
10029       int SumV1Indices = 0, SumV2Indices = 0;
10030       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10031         if (SVOp->getMask()[i] >= NumElements)
10032           SumV2Indices += i;
10033         else if (SVOp->getMask()[i] >= 0)
10034           SumV1Indices += i;
10035       if (SumV2Indices < SumV1Indices) {
10036         return DAG.getCommutedVectorShuffle(*SVOp);
10037       } else if (SumV2Indices == SumV1Indices) {
10038         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10039         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10040           if (SVOp->getMask()[i] >= NumElements)
10041             NumV2OddIndices += i % 2;
10042           else if (SVOp->getMask()[i] >= 0)
10043             NumV1OddIndices += i % 2;
10044         if (NumV2OddIndices < NumV1OddIndices)
10045           return DAG.getCommutedVectorShuffle(*SVOp);
10046       }
10047     }
10048   }
10049
10050   // For each vector width, delegate to a specialized lowering routine.
10051   if (VT.getSizeInBits() == 128)
10052     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10053
10054   if (VT.getSizeInBits() == 256)
10055     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10056
10057   // Force AVX-512 vectors to be scalarized for now.
10058   // FIXME: Implement AVX-512 support!
10059   if (VT.getSizeInBits() == 512)
10060     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10061
10062   llvm_unreachable("Unimplemented!");
10063 }
10064
10065 // This function assumes its argument is a BUILD_VECTOR of constants or
10066 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10067 // true.
10068 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10069                                     unsigned &MaskValue) {
10070   MaskValue = 0;
10071   unsigned NumElems = BuildVector->getNumOperands();
10072   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10073   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10074   unsigned NumElemsInLane = NumElems / NumLanes;
10075
10076   // Blend for v16i16 should be symetric for the both lanes.
10077   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10078     SDValue EltCond = BuildVector->getOperand(i);
10079     SDValue SndLaneEltCond =
10080         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10081
10082     int Lane1Cond = -1, Lane2Cond = -1;
10083     if (isa<ConstantSDNode>(EltCond))
10084       Lane1Cond = !isZero(EltCond);
10085     if (isa<ConstantSDNode>(SndLaneEltCond))
10086       Lane2Cond = !isZero(SndLaneEltCond);
10087
10088     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10089       // Lane1Cond != 0, means we want the first argument.
10090       // Lane1Cond == 0, means we want the second argument.
10091       // The encoding of this argument is 0 for the first argument, 1
10092       // for the second. Therefore, invert the condition.
10093       MaskValue |= !Lane1Cond << i;
10094     else if (Lane1Cond < 0)
10095       MaskValue |= !Lane2Cond << i;
10096     else
10097       return false;
10098   }
10099   return true;
10100 }
10101
10102 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10103 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10104                                            const X86Subtarget *Subtarget,
10105                                            SelectionDAG &DAG) {
10106   SDValue Cond = Op.getOperand(0);
10107   SDValue LHS = Op.getOperand(1);
10108   SDValue RHS = Op.getOperand(2);
10109   SDLoc dl(Op);
10110   MVT VT = Op.getSimpleValueType();
10111
10112   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10113     return SDValue();
10114   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10115
10116   // Only non-legal VSELECTs reach this lowering, convert those into generic
10117   // shuffles and re-use the shuffle lowering path for blends.
10118   SmallVector<int, 32> Mask;
10119   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10120     SDValue CondElt = CondBV->getOperand(i);
10121     Mask.push_back(
10122         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10123   }
10124   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10125 }
10126
10127 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10128   // A vselect where all conditions and data are constants can be optimized into
10129   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10130   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10131       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10132       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10133     return SDValue();
10134
10135   // Try to lower this to a blend-style vector shuffle. This can handle all
10136   // constant condition cases.
10137   SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG);
10138   if (BlendOp.getNode())
10139     return BlendOp;
10140
10141   // Variable blends are only legal from SSE4.1 onward.
10142   if (!Subtarget->hasSSE41())
10143     return SDValue();
10144
10145   // Only some types will be legal on some subtargets. If we can emit a legal
10146   // VSELECT-matching blend, return Op, and but if we need to expand, return
10147   // a null value.
10148   switch (Op.getSimpleValueType().SimpleTy) {
10149   default:
10150     // Most of the vector types have blends past SSE4.1.
10151     return Op;
10152
10153   case MVT::v32i8:
10154     // The byte blends for AVX vectors were introduced only in AVX2.
10155     if (Subtarget->hasAVX2())
10156       return Op;
10157
10158     return SDValue();
10159
10160   case MVT::v8i16:
10161   case MVT::v16i16:
10162     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10163     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10164       return Op;
10165
10166     // FIXME: We should custom lower this by fixing the condition and using i8
10167     // blends.
10168     return SDValue();
10169   }
10170 }
10171
10172 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10173   MVT VT = Op.getSimpleValueType();
10174   SDLoc dl(Op);
10175
10176   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10177     return SDValue();
10178
10179   if (VT.getSizeInBits() == 8) {
10180     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10181                                   Op.getOperand(0), Op.getOperand(1));
10182     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10183                                   DAG.getValueType(VT));
10184     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10185   }
10186
10187   if (VT.getSizeInBits() == 16) {
10188     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10189     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10190     if (Idx == 0)
10191       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10192                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10193                                      DAG.getNode(ISD::BITCAST, dl,
10194                                                  MVT::v4i32,
10195                                                  Op.getOperand(0)),
10196                                      Op.getOperand(1)));
10197     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10198                                   Op.getOperand(0), Op.getOperand(1));
10199     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10200                                   DAG.getValueType(VT));
10201     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10202   }
10203
10204   if (VT == MVT::f32) {
10205     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10206     // the result back to FR32 register. It's only worth matching if the
10207     // result has a single use which is a store or a bitcast to i32.  And in
10208     // the case of a store, it's not worth it if the index is a constant 0,
10209     // because a MOVSSmr can be used instead, which is smaller and faster.
10210     if (!Op.hasOneUse())
10211       return SDValue();
10212     SDNode *User = *Op.getNode()->use_begin();
10213     if ((User->getOpcode() != ISD::STORE ||
10214          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10215           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10216         (User->getOpcode() != ISD::BITCAST ||
10217          User->getValueType(0) != MVT::i32))
10218       return SDValue();
10219     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10220                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10221                                               Op.getOperand(0)),
10222                                               Op.getOperand(1));
10223     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10224   }
10225
10226   if (VT == MVT::i32 || VT == MVT::i64) {
10227     // ExtractPS/pextrq works with constant index.
10228     if (isa<ConstantSDNode>(Op.getOperand(1)))
10229       return Op;
10230   }
10231   return SDValue();
10232 }
10233
10234 /// Extract one bit from mask vector, like v16i1 or v8i1.
10235 /// AVX-512 feature.
10236 SDValue
10237 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10238   SDValue Vec = Op.getOperand(0);
10239   SDLoc dl(Vec);
10240   MVT VecVT = Vec.getSimpleValueType();
10241   SDValue Idx = Op.getOperand(1);
10242   MVT EltVT = Op.getSimpleValueType();
10243
10244   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10245   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10246          "Unexpected vector type in ExtractBitFromMaskVector");
10247
10248   // variable index can't be handled in mask registers,
10249   // extend vector to VR512
10250   if (!isa<ConstantSDNode>(Idx)) {
10251     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10252     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10253     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10254                               ExtVT.getVectorElementType(), Ext, Idx);
10255     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10256   }
10257
10258   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10259   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10260   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10261     rc = getRegClassFor(MVT::v16i1);
10262   unsigned MaxSift = rc->getSize()*8 - 1;
10263   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10264                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10265   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10266                     DAG.getConstant(MaxSift, MVT::i8));
10267   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10268                        DAG.getIntPtrConstant(0));
10269 }
10270
10271 SDValue
10272 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10273                                            SelectionDAG &DAG) const {
10274   SDLoc dl(Op);
10275   SDValue Vec = Op.getOperand(0);
10276   MVT VecVT = Vec.getSimpleValueType();
10277   SDValue Idx = Op.getOperand(1);
10278
10279   if (Op.getSimpleValueType() == MVT::i1)
10280     return ExtractBitFromMaskVector(Op, DAG);
10281
10282   if (!isa<ConstantSDNode>(Idx)) {
10283     if (VecVT.is512BitVector() ||
10284         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10285          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10286
10287       MVT MaskEltVT =
10288         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10289       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10290                                     MaskEltVT.getSizeInBits());
10291
10292       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10293       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10294                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10295                                 Idx, DAG.getConstant(0, getPointerTy()));
10296       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10297       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10298                         Perm, DAG.getConstant(0, getPointerTy()));
10299     }
10300     return SDValue();
10301   }
10302
10303   // If this is a 256-bit vector result, first extract the 128-bit vector and
10304   // then extract the element from the 128-bit vector.
10305   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10306
10307     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10308     // Get the 128-bit vector.
10309     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10310     MVT EltVT = VecVT.getVectorElementType();
10311
10312     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10313
10314     //if (IdxVal >= NumElems/2)
10315     //  IdxVal -= NumElems/2;
10316     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10317     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10318                        DAG.getConstant(IdxVal, MVT::i32));
10319   }
10320
10321   assert(VecVT.is128BitVector() && "Unexpected vector length");
10322
10323   if (Subtarget->hasSSE41()) {
10324     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10325     if (Res.getNode())
10326       return Res;
10327   }
10328
10329   MVT VT = Op.getSimpleValueType();
10330   // TODO: handle v16i8.
10331   if (VT.getSizeInBits() == 16) {
10332     SDValue Vec = Op.getOperand(0);
10333     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10334     if (Idx == 0)
10335       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10336                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10337                                      DAG.getNode(ISD::BITCAST, dl,
10338                                                  MVT::v4i32, Vec),
10339                                      Op.getOperand(1)));
10340     // Transform it so it match pextrw which produces a 32-bit result.
10341     MVT EltVT = MVT::i32;
10342     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10343                                   Op.getOperand(0), Op.getOperand(1));
10344     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10345                                   DAG.getValueType(VT));
10346     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10347   }
10348
10349   if (VT.getSizeInBits() == 32) {
10350     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10351     if (Idx == 0)
10352       return Op;
10353
10354     // SHUFPS the element to the lowest double word, then movss.
10355     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10356     MVT VVT = Op.getOperand(0).getSimpleValueType();
10357     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10358                                        DAG.getUNDEF(VVT), Mask);
10359     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10360                        DAG.getIntPtrConstant(0));
10361   }
10362
10363   if (VT.getSizeInBits() == 64) {
10364     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10365     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10366     //        to match extract_elt for f64.
10367     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10368     if (Idx == 0)
10369       return Op;
10370
10371     // UNPCKHPD the element to the lowest double word, then movsd.
10372     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10373     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10374     int Mask[2] = { 1, -1 };
10375     MVT VVT = Op.getOperand(0).getSimpleValueType();
10376     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10377                                        DAG.getUNDEF(VVT), Mask);
10378     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10379                        DAG.getIntPtrConstant(0));
10380   }
10381
10382   return SDValue();
10383 }
10384
10385 /// Insert one bit to mask vector, like v16i1 or v8i1.
10386 /// AVX-512 feature.
10387 SDValue
10388 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10389   SDLoc dl(Op);
10390   SDValue Vec = Op.getOperand(0);
10391   SDValue Elt = Op.getOperand(1);
10392   SDValue Idx = Op.getOperand(2);
10393   MVT VecVT = Vec.getSimpleValueType();
10394
10395   if (!isa<ConstantSDNode>(Idx)) {
10396     // Non constant index. Extend source and destination,
10397     // insert element and then truncate the result.
10398     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10399     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10400     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10401       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10402       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10403     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10404   }
10405
10406   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10407   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10408   if (Vec.getOpcode() == ISD::UNDEF)
10409     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10410                        DAG.getConstant(IdxVal, MVT::i8));
10411   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10412   unsigned MaxSift = rc->getSize()*8 - 1;
10413   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10414                     DAG.getConstant(MaxSift, MVT::i8));
10415   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10416                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10417   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10418 }
10419
10420 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10421                                                   SelectionDAG &DAG) const {
10422   MVT VT = Op.getSimpleValueType();
10423   MVT EltVT = VT.getVectorElementType();
10424
10425   if (EltVT == MVT::i1)
10426     return InsertBitToMaskVector(Op, DAG);
10427
10428   SDLoc dl(Op);
10429   SDValue N0 = Op.getOperand(0);
10430   SDValue N1 = Op.getOperand(1);
10431   SDValue N2 = Op.getOperand(2);
10432   if (!isa<ConstantSDNode>(N2))
10433     return SDValue();
10434   auto *N2C = cast<ConstantSDNode>(N2);
10435   unsigned IdxVal = N2C->getZExtValue();
10436
10437   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10438   // into that, and then insert the subvector back into the result.
10439   if (VT.is256BitVector() || VT.is512BitVector()) {
10440     // Get the desired 128-bit vector half.
10441     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10442
10443     // Insert the element into the desired half.
10444     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10445     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10446
10447     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10448                     DAG.getConstant(IdxIn128, MVT::i32));
10449
10450     // Insert the changed part back to the 256-bit vector
10451     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10452   }
10453   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10454
10455   if (Subtarget->hasSSE41()) {
10456     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10457       unsigned Opc;
10458       if (VT == MVT::v8i16) {
10459         Opc = X86ISD::PINSRW;
10460       } else {
10461         assert(VT == MVT::v16i8);
10462         Opc = X86ISD::PINSRB;
10463       }
10464
10465       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10466       // argument.
10467       if (N1.getValueType() != MVT::i32)
10468         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10469       if (N2.getValueType() != MVT::i32)
10470         N2 = DAG.getIntPtrConstant(IdxVal);
10471       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10472     }
10473
10474     if (EltVT == MVT::f32) {
10475       // Bits [7:6] of the constant are the source select.  This will always be
10476       //  zero here.  The DAG Combiner may combine an extract_elt index into
10477       //  these
10478       //  bits.  For example (insert (extract, 3), 2) could be matched by
10479       //  putting
10480       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10481       // Bits [5:4] of the constant are the destination select.  This is the
10482       //  value of the incoming immediate.
10483       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10484       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10485       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10486       // Create this as a scalar to vector..
10487       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10488       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10489     }
10490
10491     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10492       // PINSR* works with constant index.
10493       return Op;
10494     }
10495   }
10496
10497   if (EltVT == MVT::i8)
10498     return SDValue();
10499
10500   if (EltVT.getSizeInBits() == 16) {
10501     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10502     // as its second argument.
10503     if (N1.getValueType() != MVT::i32)
10504       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10505     if (N2.getValueType() != MVT::i32)
10506       N2 = DAG.getIntPtrConstant(IdxVal);
10507     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10508   }
10509   return SDValue();
10510 }
10511
10512 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10513   SDLoc dl(Op);
10514   MVT OpVT = Op.getSimpleValueType();
10515
10516   // If this is a 256-bit vector result, first insert into a 128-bit
10517   // vector and then insert into the 256-bit vector.
10518   if (!OpVT.is128BitVector()) {
10519     // Insert into a 128-bit vector.
10520     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10521     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10522                                  OpVT.getVectorNumElements() / SizeFactor);
10523
10524     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10525
10526     // Insert the 128-bit vector.
10527     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10528   }
10529
10530   if (OpVT == MVT::v1i64 &&
10531       Op.getOperand(0).getValueType() == MVT::i64)
10532     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10533
10534   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10535   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10536   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10537                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10538 }
10539
10540 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10541 // a simple subregister reference or explicit instructions to grab
10542 // upper bits of a vector.
10543 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10544                                       SelectionDAG &DAG) {
10545   SDLoc dl(Op);
10546   SDValue In =  Op.getOperand(0);
10547   SDValue Idx = Op.getOperand(1);
10548   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10549   MVT ResVT   = Op.getSimpleValueType();
10550   MVT InVT    = In.getSimpleValueType();
10551
10552   if (Subtarget->hasFp256()) {
10553     if (ResVT.is128BitVector() &&
10554         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10555         isa<ConstantSDNode>(Idx)) {
10556       return Extract128BitVector(In, IdxVal, DAG, dl);
10557     }
10558     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10559         isa<ConstantSDNode>(Idx)) {
10560       return Extract256BitVector(In, IdxVal, DAG, dl);
10561     }
10562   }
10563   return SDValue();
10564 }
10565
10566 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10567 // simple superregister reference or explicit instructions to insert
10568 // the upper bits of a vector.
10569 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10570                                      SelectionDAG &DAG) {
10571   if (!Subtarget->hasAVX())
10572     return SDValue();
10573
10574   SDLoc dl(Op);
10575   SDValue Vec = Op.getOperand(0);
10576   SDValue SubVec = Op.getOperand(1);
10577   SDValue Idx = Op.getOperand(2);
10578
10579   if (!isa<ConstantSDNode>(Idx))
10580     return SDValue();
10581
10582   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10583   MVT OpVT = Op.getSimpleValueType();
10584   MVT SubVecVT = SubVec.getSimpleValueType();
10585
10586   // Fold two 16-byte subvector loads into one 32-byte load:
10587   // (insert_subvector (insert_subvector undef, (load addr), 0),
10588   //                   (load addr + 16), Elts/2)
10589   // --> load32 addr
10590   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10591       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10592       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10593       !Subtarget->isUnalignedMem32Slow()) {
10594     SDValue SubVec2 = Vec.getOperand(1);
10595     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10596       if (Idx2->getZExtValue() == 0) {
10597         SDValue Ops[] = { SubVec2, SubVec };
10598         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10599         if (LD.getNode())
10600           return LD;
10601       }
10602     }
10603   }
10604
10605   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10606       SubVecVT.is128BitVector())
10607     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10608
10609   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10610     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10611
10612   return SDValue();
10613 }
10614
10615 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10616 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10617 // one of the above mentioned nodes. It has to be wrapped because otherwise
10618 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10619 // be used to form addressing mode. These wrapped nodes will be selected
10620 // into MOV32ri.
10621 SDValue
10622 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10623   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10624
10625   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10626   // global base reg.
10627   unsigned char OpFlag = 0;
10628   unsigned WrapperKind = X86ISD::Wrapper;
10629   CodeModel::Model M = DAG.getTarget().getCodeModel();
10630
10631   if (Subtarget->isPICStyleRIPRel() &&
10632       (M == CodeModel::Small || M == CodeModel::Kernel))
10633     WrapperKind = X86ISD::WrapperRIP;
10634   else if (Subtarget->isPICStyleGOT())
10635     OpFlag = X86II::MO_GOTOFF;
10636   else if (Subtarget->isPICStyleStubPIC())
10637     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10638
10639   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10640                                              CP->getAlignment(),
10641                                              CP->getOffset(), OpFlag);
10642   SDLoc DL(CP);
10643   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10644   // With PIC, the address is actually $g + Offset.
10645   if (OpFlag) {
10646     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10647                          DAG.getNode(X86ISD::GlobalBaseReg,
10648                                      SDLoc(), getPointerTy()),
10649                          Result);
10650   }
10651
10652   return Result;
10653 }
10654
10655 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10656   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10657
10658   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10659   // global base reg.
10660   unsigned char OpFlag = 0;
10661   unsigned WrapperKind = X86ISD::Wrapper;
10662   CodeModel::Model M = DAG.getTarget().getCodeModel();
10663
10664   if (Subtarget->isPICStyleRIPRel() &&
10665       (M == CodeModel::Small || M == CodeModel::Kernel))
10666     WrapperKind = X86ISD::WrapperRIP;
10667   else if (Subtarget->isPICStyleGOT())
10668     OpFlag = X86II::MO_GOTOFF;
10669   else if (Subtarget->isPICStyleStubPIC())
10670     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10671
10672   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10673                                           OpFlag);
10674   SDLoc DL(JT);
10675   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10676
10677   // With PIC, the address is actually $g + Offset.
10678   if (OpFlag)
10679     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10680                          DAG.getNode(X86ISD::GlobalBaseReg,
10681                                      SDLoc(), getPointerTy()),
10682                          Result);
10683
10684   return Result;
10685 }
10686
10687 SDValue
10688 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10689   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10690
10691   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10692   // global base reg.
10693   unsigned char OpFlag = 0;
10694   unsigned WrapperKind = X86ISD::Wrapper;
10695   CodeModel::Model M = DAG.getTarget().getCodeModel();
10696
10697   if (Subtarget->isPICStyleRIPRel() &&
10698       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10699     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10700       OpFlag = X86II::MO_GOTPCREL;
10701     WrapperKind = X86ISD::WrapperRIP;
10702   } else if (Subtarget->isPICStyleGOT()) {
10703     OpFlag = X86II::MO_GOT;
10704   } else if (Subtarget->isPICStyleStubPIC()) {
10705     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10706   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10707     OpFlag = X86II::MO_DARWIN_NONLAZY;
10708   }
10709
10710   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10711
10712   SDLoc DL(Op);
10713   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10714
10715   // With PIC, the address is actually $g + Offset.
10716   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10717       !Subtarget->is64Bit()) {
10718     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10719                          DAG.getNode(X86ISD::GlobalBaseReg,
10720                                      SDLoc(), getPointerTy()),
10721                          Result);
10722   }
10723
10724   // For symbols that require a load from a stub to get the address, emit the
10725   // load.
10726   if (isGlobalStubReference(OpFlag))
10727     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10728                          MachinePointerInfo::getGOT(), false, false, false, 0);
10729
10730   return Result;
10731 }
10732
10733 SDValue
10734 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10735   // Create the TargetBlockAddressAddress node.
10736   unsigned char OpFlags =
10737     Subtarget->ClassifyBlockAddressReference();
10738   CodeModel::Model M = DAG.getTarget().getCodeModel();
10739   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10740   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10741   SDLoc dl(Op);
10742   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10743                                              OpFlags);
10744
10745   if (Subtarget->isPICStyleRIPRel() &&
10746       (M == CodeModel::Small || M == CodeModel::Kernel))
10747     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10748   else
10749     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10750
10751   // With PIC, the address is actually $g + Offset.
10752   if (isGlobalRelativeToPICBase(OpFlags)) {
10753     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10754                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10755                          Result);
10756   }
10757
10758   return Result;
10759 }
10760
10761 SDValue
10762 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10763                                       int64_t Offset, SelectionDAG &DAG) const {
10764   // Create the TargetGlobalAddress node, folding in the constant
10765   // offset if it is legal.
10766   unsigned char OpFlags =
10767       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10768   CodeModel::Model M = DAG.getTarget().getCodeModel();
10769   SDValue Result;
10770   if (OpFlags == X86II::MO_NO_FLAG &&
10771       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10772     // A direct static reference to a global.
10773     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10774     Offset = 0;
10775   } else {
10776     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10777   }
10778
10779   if (Subtarget->isPICStyleRIPRel() &&
10780       (M == CodeModel::Small || M == CodeModel::Kernel))
10781     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10782   else
10783     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10784
10785   // With PIC, the address is actually $g + Offset.
10786   if (isGlobalRelativeToPICBase(OpFlags)) {
10787     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10788                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10789                          Result);
10790   }
10791
10792   // For globals that require a load from a stub to get the address, emit the
10793   // load.
10794   if (isGlobalStubReference(OpFlags))
10795     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10796                          MachinePointerInfo::getGOT(), false, false, false, 0);
10797
10798   // If there was a non-zero offset that we didn't fold, create an explicit
10799   // addition for it.
10800   if (Offset != 0)
10801     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10802                          DAG.getConstant(Offset, getPointerTy()));
10803
10804   return Result;
10805 }
10806
10807 SDValue
10808 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10809   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10810   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10811   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10812 }
10813
10814 static SDValue
10815 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10816            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10817            unsigned char OperandFlags, bool LocalDynamic = false) {
10818   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10819   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10820   SDLoc dl(GA);
10821   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10822                                            GA->getValueType(0),
10823                                            GA->getOffset(),
10824                                            OperandFlags);
10825
10826   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10827                                            : X86ISD::TLSADDR;
10828
10829   if (InFlag) {
10830     SDValue Ops[] = { Chain,  TGA, *InFlag };
10831     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10832   } else {
10833     SDValue Ops[]  = { Chain, TGA };
10834     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10835   }
10836
10837   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10838   MFI->setAdjustsStack(true);
10839   MFI->setHasCalls(true);
10840
10841   SDValue Flag = Chain.getValue(1);
10842   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10843 }
10844
10845 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10846 static SDValue
10847 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10848                                 const EVT PtrVT) {
10849   SDValue InFlag;
10850   SDLoc dl(GA);  // ? function entry point might be better
10851   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10852                                    DAG.getNode(X86ISD::GlobalBaseReg,
10853                                                SDLoc(), PtrVT), InFlag);
10854   InFlag = Chain.getValue(1);
10855
10856   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10857 }
10858
10859 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10860 static SDValue
10861 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10862                                 const EVT PtrVT) {
10863   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10864                     X86::RAX, X86II::MO_TLSGD);
10865 }
10866
10867 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10868                                            SelectionDAG &DAG,
10869                                            const EVT PtrVT,
10870                                            bool is64Bit) {
10871   SDLoc dl(GA);
10872
10873   // Get the start address of the TLS block for this module.
10874   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10875       .getInfo<X86MachineFunctionInfo>();
10876   MFI->incNumLocalDynamicTLSAccesses();
10877
10878   SDValue Base;
10879   if (is64Bit) {
10880     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10881                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10882   } else {
10883     SDValue InFlag;
10884     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10885         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10886     InFlag = Chain.getValue(1);
10887     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10888                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10889   }
10890
10891   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10892   // of Base.
10893
10894   // Build x@dtpoff.
10895   unsigned char OperandFlags = X86II::MO_DTPOFF;
10896   unsigned WrapperKind = X86ISD::Wrapper;
10897   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10898                                            GA->getValueType(0),
10899                                            GA->getOffset(), OperandFlags);
10900   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10901
10902   // Add x@dtpoff with the base.
10903   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10904 }
10905
10906 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10907 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10908                                    const EVT PtrVT, TLSModel::Model model,
10909                                    bool is64Bit, bool isPIC) {
10910   SDLoc dl(GA);
10911
10912   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10913   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10914                                                          is64Bit ? 257 : 256));
10915
10916   SDValue ThreadPointer =
10917       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10918                   MachinePointerInfo(Ptr), false, false, false, 0);
10919
10920   unsigned char OperandFlags = 0;
10921   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10922   // initialexec.
10923   unsigned WrapperKind = X86ISD::Wrapper;
10924   if (model == TLSModel::LocalExec) {
10925     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10926   } else if (model == TLSModel::InitialExec) {
10927     if (is64Bit) {
10928       OperandFlags = X86II::MO_GOTTPOFF;
10929       WrapperKind = X86ISD::WrapperRIP;
10930     } else {
10931       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10932     }
10933   } else {
10934     llvm_unreachable("Unexpected model");
10935   }
10936
10937   // emit "addl x@ntpoff,%eax" (local exec)
10938   // or "addl x@indntpoff,%eax" (initial exec)
10939   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10940   SDValue TGA =
10941       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10942                                  GA->getOffset(), OperandFlags);
10943   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10944
10945   if (model == TLSModel::InitialExec) {
10946     if (isPIC && !is64Bit) {
10947       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10948                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10949                            Offset);
10950     }
10951
10952     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10953                          MachinePointerInfo::getGOT(), false, false, false, 0);
10954   }
10955
10956   // The address of the thread local variable is the add of the thread
10957   // pointer with the offset of the variable.
10958   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10959 }
10960
10961 SDValue
10962 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10963
10964   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10965   const GlobalValue *GV = GA->getGlobal();
10966
10967   if (Subtarget->isTargetELF()) {
10968     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10969
10970     switch (model) {
10971       case TLSModel::GeneralDynamic:
10972         if (Subtarget->is64Bit())
10973           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10974         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10975       case TLSModel::LocalDynamic:
10976         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10977                                            Subtarget->is64Bit());
10978       case TLSModel::InitialExec:
10979       case TLSModel::LocalExec:
10980         return LowerToTLSExecModel(
10981             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10982             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10983     }
10984     llvm_unreachable("Unknown TLS model.");
10985   }
10986
10987   if (Subtarget->isTargetDarwin()) {
10988     // Darwin only has one model of TLS.  Lower to that.
10989     unsigned char OpFlag = 0;
10990     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10991                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10992
10993     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10994     // global base reg.
10995     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10996                  !Subtarget->is64Bit();
10997     if (PIC32)
10998       OpFlag = X86II::MO_TLVP_PIC_BASE;
10999     else
11000       OpFlag = X86II::MO_TLVP;
11001     SDLoc DL(Op);
11002     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11003                                                 GA->getValueType(0),
11004                                                 GA->getOffset(), OpFlag);
11005     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11006
11007     // With PIC32, the address is actually $g + Offset.
11008     if (PIC32)
11009       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11010                            DAG.getNode(X86ISD::GlobalBaseReg,
11011                                        SDLoc(), getPointerTy()),
11012                            Offset);
11013
11014     // Lowering the machine isd will make sure everything is in the right
11015     // location.
11016     SDValue Chain = DAG.getEntryNode();
11017     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11018     SDValue Args[] = { Chain, Offset };
11019     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11020
11021     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11022     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11023     MFI->setAdjustsStack(true);
11024
11025     // And our return value (tls address) is in the standard call return value
11026     // location.
11027     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11028     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11029                               Chain.getValue(1));
11030   }
11031
11032   if (Subtarget->isTargetKnownWindowsMSVC() ||
11033       Subtarget->isTargetWindowsGNU()) {
11034     // Just use the implicit TLS architecture
11035     // Need to generate someting similar to:
11036     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11037     //                                  ; from TEB
11038     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11039     //   mov     rcx, qword [rdx+rcx*8]
11040     //   mov     eax, .tls$:tlsvar
11041     //   [rax+rcx] contains the address
11042     // Windows 64bit: gs:0x58
11043     // Windows 32bit: fs:__tls_array
11044
11045     SDLoc dl(GA);
11046     SDValue Chain = DAG.getEntryNode();
11047
11048     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11049     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11050     // use its literal value of 0x2C.
11051     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11052                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11053                                                              256)
11054                                         : Type::getInt32PtrTy(*DAG.getContext(),
11055                                                               257));
11056
11057     SDValue TlsArray =
11058         Subtarget->is64Bit()
11059             ? DAG.getIntPtrConstant(0x58)
11060             : (Subtarget->isTargetWindowsGNU()
11061                    ? DAG.getIntPtrConstant(0x2C)
11062                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11063
11064     SDValue ThreadPointer =
11065         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11066                     MachinePointerInfo(Ptr), false, false, false, 0);
11067
11068     // Load the _tls_index variable
11069     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11070     if (Subtarget->is64Bit())
11071       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11072                            IDX, MachinePointerInfo(), MVT::i32,
11073                            false, false, false, 0);
11074     else
11075       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11076                         false, false, false, 0);
11077
11078     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11079                                     getPointerTy());
11080     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11081
11082     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11083     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11084                       false, false, false, 0);
11085
11086     // Get the offset of start of .tls section
11087     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11088                                              GA->getValueType(0),
11089                                              GA->getOffset(), X86II::MO_SECREL);
11090     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11091
11092     // The address of the thread local variable is the add of the thread
11093     // pointer with the offset of the variable.
11094     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11095   }
11096
11097   llvm_unreachable("TLS not implemented for this target.");
11098 }
11099
11100 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11101 /// and take a 2 x i32 value to shift plus a shift amount.
11102 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11103   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11104   MVT VT = Op.getSimpleValueType();
11105   unsigned VTBits = VT.getSizeInBits();
11106   SDLoc dl(Op);
11107   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11108   SDValue ShOpLo = Op.getOperand(0);
11109   SDValue ShOpHi = Op.getOperand(1);
11110   SDValue ShAmt  = Op.getOperand(2);
11111   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11112   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11113   // during isel.
11114   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11115                                   DAG.getConstant(VTBits - 1, MVT::i8));
11116   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11117                                      DAG.getConstant(VTBits - 1, MVT::i8))
11118                        : DAG.getConstant(0, VT);
11119
11120   SDValue Tmp2, Tmp3;
11121   if (Op.getOpcode() == ISD::SHL_PARTS) {
11122     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11123     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11124   } else {
11125     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11126     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11127   }
11128
11129   // If the shift amount is larger or equal than the width of a part we can't
11130   // rely on the results of shld/shrd. Insert a test and select the appropriate
11131   // values for large shift amounts.
11132   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11133                                 DAG.getConstant(VTBits, MVT::i8));
11134   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11135                              AndNode, DAG.getConstant(0, MVT::i8));
11136
11137   SDValue Hi, Lo;
11138   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11139   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11140   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11141
11142   if (Op.getOpcode() == ISD::SHL_PARTS) {
11143     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11144     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11145   } else {
11146     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11147     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11148   }
11149
11150   SDValue Ops[2] = { Lo, Hi };
11151   return DAG.getMergeValues(Ops, dl);
11152 }
11153
11154 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11155                                            SelectionDAG &DAG) const {
11156   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11157   SDLoc dl(Op);
11158
11159   if (SrcVT.isVector()) {
11160     if (SrcVT.getVectorElementType() == MVT::i1) {
11161       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11162       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11163                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11164                                      Op.getOperand(0)));
11165     }
11166     return SDValue();
11167   }
11168
11169   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11170          "Unknown SINT_TO_FP to lower!");
11171
11172   // These are really Legal; return the operand so the caller accepts it as
11173   // Legal.
11174   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11175     return Op;
11176   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11177       Subtarget->is64Bit()) {
11178     return Op;
11179   }
11180
11181   unsigned Size = SrcVT.getSizeInBits()/8;
11182   MachineFunction &MF = DAG.getMachineFunction();
11183   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11184   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11185   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11186                                StackSlot,
11187                                MachinePointerInfo::getFixedStack(SSFI),
11188                                false, false, 0);
11189   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11190 }
11191
11192 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11193                                      SDValue StackSlot,
11194                                      SelectionDAG &DAG) const {
11195   // Build the FILD
11196   SDLoc DL(Op);
11197   SDVTList Tys;
11198   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11199   if (useSSE)
11200     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11201   else
11202     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11203
11204   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11205
11206   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11207   MachineMemOperand *MMO;
11208   if (FI) {
11209     int SSFI = FI->getIndex();
11210     MMO =
11211       DAG.getMachineFunction()
11212       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11213                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11214   } else {
11215     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11216     StackSlot = StackSlot.getOperand(1);
11217   }
11218   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11219   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11220                                            X86ISD::FILD, DL,
11221                                            Tys, Ops, SrcVT, MMO);
11222
11223   if (useSSE) {
11224     Chain = Result.getValue(1);
11225     SDValue InFlag = Result.getValue(2);
11226
11227     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11228     // shouldn't be necessary except that RFP cannot be live across
11229     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11230     MachineFunction &MF = DAG.getMachineFunction();
11231     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11232     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11233     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11234     Tys = DAG.getVTList(MVT::Other);
11235     SDValue Ops[] = {
11236       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11237     };
11238     MachineMemOperand *MMO =
11239       DAG.getMachineFunction()
11240       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11241                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11242
11243     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11244                                     Ops, Op.getValueType(), MMO);
11245     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11246                          MachinePointerInfo::getFixedStack(SSFI),
11247                          false, false, false, 0);
11248   }
11249
11250   return Result;
11251 }
11252
11253 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11254 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11255                                                SelectionDAG &DAG) const {
11256   // This algorithm is not obvious. Here it is what we're trying to output:
11257   /*
11258      movq       %rax,  %xmm0
11259      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11260      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11261      #ifdef __SSE3__
11262        haddpd   %xmm0, %xmm0
11263      #else
11264        pshufd   $0x4e, %xmm0, %xmm1
11265        addpd    %xmm1, %xmm0
11266      #endif
11267   */
11268
11269   SDLoc dl(Op);
11270   LLVMContext *Context = DAG.getContext();
11271
11272   // Build some magic constants.
11273   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11274   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11275   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11276
11277   SmallVector<Constant*,2> CV1;
11278   CV1.push_back(
11279     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11280                                       APInt(64, 0x4330000000000000ULL))));
11281   CV1.push_back(
11282     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11283                                       APInt(64, 0x4530000000000000ULL))));
11284   Constant *C1 = ConstantVector::get(CV1);
11285   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11286
11287   // Load the 64-bit value into an XMM register.
11288   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11289                             Op.getOperand(0));
11290   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11291                               MachinePointerInfo::getConstantPool(),
11292                               false, false, false, 16);
11293   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11294                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11295                               CLod0);
11296
11297   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11298                               MachinePointerInfo::getConstantPool(),
11299                               false, false, false, 16);
11300   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11301   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11302   SDValue Result;
11303
11304   if (Subtarget->hasSSE3()) {
11305     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11306     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11307   } else {
11308     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11309     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11310                                            S2F, 0x4E, DAG);
11311     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11312                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11313                          Sub);
11314   }
11315
11316   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11317                      DAG.getIntPtrConstant(0));
11318 }
11319
11320 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11321 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11322                                                SelectionDAG &DAG) const {
11323   SDLoc dl(Op);
11324   // FP constant to bias correct the final result.
11325   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11326                                    MVT::f64);
11327
11328   // Load the 32-bit value into an XMM register.
11329   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11330                              Op.getOperand(0));
11331
11332   // Zero out the upper parts of the register.
11333   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11334
11335   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11336                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11337                      DAG.getIntPtrConstant(0));
11338
11339   // Or the load with the bias.
11340   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11341                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11342                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11343                                                    MVT::v2f64, Load)),
11344                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11345                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11346                                                    MVT::v2f64, Bias)));
11347   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11348                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11349                    DAG.getIntPtrConstant(0));
11350
11351   // Subtract the bias.
11352   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11353
11354   // Handle final rounding.
11355   EVT DestVT = Op.getValueType();
11356
11357   if (DestVT.bitsLT(MVT::f64))
11358     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11359                        DAG.getIntPtrConstant(0));
11360   if (DestVT.bitsGT(MVT::f64))
11361     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11362
11363   // Handle final rounding.
11364   return Sub;
11365 }
11366
11367 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11368                                      const X86Subtarget &Subtarget) {
11369   // The algorithm is the following:
11370   // #ifdef __SSE4_1__
11371   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11372   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11373   //                                 (uint4) 0x53000000, 0xaa);
11374   // #else
11375   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11376   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11377   // #endif
11378   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11379   //     return (float4) lo + fhi;
11380
11381   SDLoc DL(Op);
11382   SDValue V = Op->getOperand(0);
11383   EVT VecIntVT = V.getValueType();
11384   bool Is128 = VecIntVT == MVT::v4i32;
11385   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11386   // If we convert to something else than the supported type, e.g., to v4f64,
11387   // abort early.
11388   if (VecFloatVT != Op->getValueType(0))
11389     return SDValue();
11390
11391   unsigned NumElts = VecIntVT.getVectorNumElements();
11392   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11393          "Unsupported custom type");
11394   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11395
11396   // In the #idef/#else code, we have in common:
11397   // - The vector of constants:
11398   // -- 0x4b000000
11399   // -- 0x53000000
11400   // - A shift:
11401   // -- v >> 16
11402
11403   // Create the splat vector for 0x4b000000.
11404   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11405   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11406                            CstLow, CstLow, CstLow, CstLow};
11407   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11408                                   makeArrayRef(&CstLowArray[0], NumElts));
11409   // Create the splat vector for 0x53000000.
11410   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11411   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11412                             CstHigh, CstHigh, CstHigh, CstHigh};
11413   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11414                                    makeArrayRef(&CstHighArray[0], NumElts));
11415
11416   // Create the right shift.
11417   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11418   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11419                              CstShift, CstShift, CstShift, CstShift};
11420   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11421                                     makeArrayRef(&CstShiftArray[0], NumElts));
11422   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11423
11424   SDValue Low, High;
11425   if (Subtarget.hasSSE41()) {
11426     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11427     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11428     SDValue VecCstLowBitcast =
11429         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11430     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11431     // Low will be bitcasted right away, so do not bother bitcasting back to its
11432     // original type.
11433     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11434                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11435     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11436     //                                 (uint4) 0x53000000, 0xaa);
11437     SDValue VecCstHighBitcast =
11438         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11439     SDValue VecShiftBitcast =
11440         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11441     // High will be bitcasted right away, so do not bother bitcasting back to
11442     // its original type.
11443     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11444                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11445   } else {
11446     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11447     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11448                                      CstMask, CstMask, CstMask);
11449     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11450     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11451     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11452
11453     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11454     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11455   }
11456
11457   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11458   SDValue CstFAdd = DAG.getConstantFP(
11459       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11460   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11461                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11462   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11463                                    makeArrayRef(&CstFAddArray[0], NumElts));
11464
11465   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11466   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11467   SDValue FHigh =
11468       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11469   //     return (float4) lo + fhi;
11470   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11471   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11472 }
11473
11474 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11475                                                SelectionDAG &DAG) const {
11476   SDValue N0 = Op.getOperand(0);
11477   MVT SVT = N0.getSimpleValueType();
11478   SDLoc dl(Op);
11479
11480   switch (SVT.SimpleTy) {
11481   default:
11482     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11483   case MVT::v4i8:
11484   case MVT::v4i16:
11485   case MVT::v8i8:
11486   case MVT::v8i16: {
11487     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11488     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11489                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11490   }
11491   case MVT::v4i32:
11492   case MVT::v8i32:
11493     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11494   }
11495   llvm_unreachable(nullptr);
11496 }
11497
11498 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11499                                            SelectionDAG &DAG) const {
11500   SDValue N0 = Op.getOperand(0);
11501   SDLoc dl(Op);
11502
11503   if (Op.getValueType().isVector())
11504     return lowerUINT_TO_FP_vec(Op, DAG);
11505
11506   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11507   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11508   // the optimization here.
11509   if (DAG.SignBitIsZero(N0))
11510     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11511
11512   MVT SrcVT = N0.getSimpleValueType();
11513   MVT DstVT = Op.getSimpleValueType();
11514   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11515     return LowerUINT_TO_FP_i64(Op, DAG);
11516   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11517     return LowerUINT_TO_FP_i32(Op, DAG);
11518   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11519     return SDValue();
11520
11521   // Make a 64-bit buffer, and use it to build an FILD.
11522   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11523   if (SrcVT == MVT::i32) {
11524     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11525     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11526                                      getPointerTy(), StackSlot, WordOff);
11527     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11528                                   StackSlot, MachinePointerInfo(),
11529                                   false, false, 0);
11530     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11531                                   OffsetSlot, MachinePointerInfo(),
11532                                   false, false, 0);
11533     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11534     return Fild;
11535   }
11536
11537   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11538   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11539                                StackSlot, MachinePointerInfo(),
11540                                false, false, 0);
11541   // For i64 source, we need to add the appropriate power of 2 if the input
11542   // was negative.  This is the same as the optimization in
11543   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11544   // we must be careful to do the computation in x87 extended precision, not
11545   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11546   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11547   MachineMemOperand *MMO =
11548     DAG.getMachineFunction()
11549     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11550                           MachineMemOperand::MOLoad, 8, 8);
11551
11552   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11553   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11554   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11555                                          MVT::i64, MMO);
11556
11557   APInt FF(32, 0x5F800000ULL);
11558
11559   // Check whether the sign bit is set.
11560   SDValue SignSet = DAG.getSetCC(dl,
11561                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11562                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11563                                  ISD::SETLT);
11564
11565   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11566   SDValue FudgePtr = DAG.getConstantPool(
11567                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11568                                          getPointerTy());
11569
11570   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11571   SDValue Zero = DAG.getIntPtrConstant(0);
11572   SDValue Four = DAG.getIntPtrConstant(4);
11573   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11574                                Zero, Four);
11575   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11576
11577   // Load the value out, extending it from f32 to f80.
11578   // FIXME: Avoid the extend by constructing the right constant pool?
11579   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11580                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11581                                  MVT::f32, false, false, false, 4);
11582   // Extend everything to 80 bits to force it to be done on x87.
11583   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11584   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11585 }
11586
11587 std::pair<SDValue,SDValue>
11588 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11589                                     bool IsSigned, bool IsReplace) const {
11590   SDLoc DL(Op);
11591
11592   EVT DstTy = Op.getValueType();
11593
11594   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11595     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11596     DstTy = MVT::i64;
11597   }
11598
11599   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11600          DstTy.getSimpleVT() >= MVT::i16 &&
11601          "Unknown FP_TO_INT to lower!");
11602
11603   // These are really Legal.
11604   if (DstTy == MVT::i32 &&
11605       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11606     return std::make_pair(SDValue(), SDValue());
11607   if (Subtarget->is64Bit() &&
11608       DstTy == MVT::i64 &&
11609       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11610     return std::make_pair(SDValue(), SDValue());
11611
11612   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11613   // stack slot, or into the FTOL runtime function.
11614   MachineFunction &MF = DAG.getMachineFunction();
11615   unsigned MemSize = DstTy.getSizeInBits()/8;
11616   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11617   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11618
11619   unsigned Opc;
11620   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11621     Opc = X86ISD::WIN_FTOL;
11622   else
11623     switch (DstTy.getSimpleVT().SimpleTy) {
11624     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11625     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11626     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11627     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11628     }
11629
11630   SDValue Chain = DAG.getEntryNode();
11631   SDValue Value = Op.getOperand(0);
11632   EVT TheVT = Op.getOperand(0).getValueType();
11633   // FIXME This causes a redundant load/store if the SSE-class value is already
11634   // in memory, such as if it is on the callstack.
11635   if (isScalarFPTypeInSSEReg(TheVT)) {
11636     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11637     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11638                          MachinePointerInfo::getFixedStack(SSFI),
11639                          false, false, 0);
11640     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11641     SDValue Ops[] = {
11642       Chain, StackSlot, DAG.getValueType(TheVT)
11643     };
11644
11645     MachineMemOperand *MMO =
11646       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11647                               MachineMemOperand::MOLoad, MemSize, MemSize);
11648     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11649     Chain = Value.getValue(1);
11650     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11651     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11652   }
11653
11654   MachineMemOperand *MMO =
11655     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11656                             MachineMemOperand::MOStore, MemSize, MemSize);
11657
11658   if (Opc != X86ISD::WIN_FTOL) {
11659     // Build the FP_TO_INT*_IN_MEM
11660     SDValue Ops[] = { Chain, Value, StackSlot };
11661     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11662                                            Ops, DstTy, MMO);
11663     return std::make_pair(FIST, StackSlot);
11664   } else {
11665     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11666       DAG.getVTList(MVT::Other, MVT::Glue),
11667       Chain, Value);
11668     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11669       MVT::i32, ftol.getValue(1));
11670     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11671       MVT::i32, eax.getValue(2));
11672     SDValue Ops[] = { eax, edx };
11673     SDValue pair = IsReplace
11674       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11675       : DAG.getMergeValues(Ops, DL);
11676     return std::make_pair(pair, SDValue());
11677   }
11678 }
11679
11680 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11681                               const X86Subtarget *Subtarget) {
11682   MVT VT = Op->getSimpleValueType(0);
11683   SDValue In = Op->getOperand(0);
11684   MVT InVT = In.getSimpleValueType();
11685   SDLoc dl(Op);
11686
11687   // Optimize vectors in AVX mode:
11688   //
11689   //   v8i16 -> v8i32
11690   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11691   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11692   //   Concat upper and lower parts.
11693   //
11694   //   v4i32 -> v4i64
11695   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11696   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11697   //   Concat upper and lower parts.
11698   //
11699
11700   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11701       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11702       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11703     return SDValue();
11704
11705   if (Subtarget->hasInt256())
11706     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11707
11708   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11709   SDValue Undef = DAG.getUNDEF(InVT);
11710   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11711   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11712   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11713
11714   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11715                              VT.getVectorNumElements()/2);
11716
11717   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11718   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11719
11720   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11721 }
11722
11723 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11724                                         SelectionDAG &DAG) {
11725   MVT VT = Op->getSimpleValueType(0);
11726   SDValue In = Op->getOperand(0);
11727   MVT InVT = In.getSimpleValueType();
11728   SDLoc DL(Op);
11729   unsigned int NumElts = VT.getVectorNumElements();
11730   if (NumElts != 8 && NumElts != 16)
11731     return SDValue();
11732
11733   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11734     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11735
11736   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11738   // Now we have only mask extension
11739   assert(InVT.getVectorElementType() == MVT::i1);
11740   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11741   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11742   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11743   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11744   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11745                            MachinePointerInfo::getConstantPool(),
11746                            false, false, false, Alignment);
11747
11748   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11749   if (VT.is512BitVector())
11750     return Brcst;
11751   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11752 }
11753
11754 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11755                                SelectionDAG &DAG) {
11756   if (Subtarget->hasFp256()) {
11757     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11758     if (Res.getNode())
11759       return Res;
11760   }
11761
11762   return SDValue();
11763 }
11764
11765 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11766                                 SelectionDAG &DAG) {
11767   SDLoc DL(Op);
11768   MVT VT = Op.getSimpleValueType();
11769   SDValue In = Op.getOperand(0);
11770   MVT SVT = In.getSimpleValueType();
11771
11772   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11773     return LowerZERO_EXTEND_AVX512(Op, DAG);
11774
11775   if (Subtarget->hasFp256()) {
11776     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11777     if (Res.getNode())
11778       return Res;
11779   }
11780
11781   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11782          VT.getVectorNumElements() != SVT.getVectorNumElements());
11783   return SDValue();
11784 }
11785
11786 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11787   SDLoc DL(Op);
11788   MVT VT = Op.getSimpleValueType();
11789   SDValue In = Op.getOperand(0);
11790   MVT InVT = In.getSimpleValueType();
11791
11792   if (VT == MVT::i1) {
11793     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11794            "Invalid scalar TRUNCATE operation");
11795     if (InVT.getSizeInBits() >= 32)
11796       return SDValue();
11797     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11798     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11799   }
11800   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11801          "Invalid TRUNCATE operation");
11802
11803   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11804     if (VT.getVectorElementType().getSizeInBits() >=8)
11805       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11806
11807     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11808     unsigned NumElts = InVT.getVectorNumElements();
11809     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11810     if (InVT.getSizeInBits() < 512) {
11811       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11812       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11813       InVT = ExtVT;
11814     }
11815
11816     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11817     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11818     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11819     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11820     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11821                            MachinePointerInfo::getConstantPool(),
11822                            false, false, false, Alignment);
11823     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11824     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11825     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11826   }
11827
11828   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11829     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11830     if (Subtarget->hasInt256()) {
11831       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11832       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11833       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11834                                 ShufMask);
11835       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11836                          DAG.getIntPtrConstant(0));
11837     }
11838
11839     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11840                                DAG.getIntPtrConstant(0));
11841     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11842                                DAG.getIntPtrConstant(2));
11843     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11844     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11845     static const int ShufMask[] = {0, 2, 4, 6};
11846     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11847   }
11848
11849   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11850     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11851     if (Subtarget->hasInt256()) {
11852       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11853
11854       SmallVector<SDValue,32> pshufbMask;
11855       for (unsigned i = 0; i < 2; ++i) {
11856         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11857         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11858         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11859         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11860         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11861         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11862         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11863         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11864         for (unsigned j = 0; j < 8; ++j)
11865           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11866       }
11867       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11868       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11869       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11870
11871       static const int ShufMask[] = {0,  2,  -1,  -1};
11872       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11873                                 &ShufMask[0]);
11874       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11875                        DAG.getIntPtrConstant(0));
11876       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11877     }
11878
11879     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11880                                DAG.getIntPtrConstant(0));
11881
11882     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11883                                DAG.getIntPtrConstant(4));
11884
11885     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11886     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11887
11888     // The PSHUFB mask:
11889     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11890                                    -1, -1, -1, -1, -1, -1, -1, -1};
11891
11892     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11893     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11894     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11895
11896     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11897     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11898
11899     // The MOVLHPS Mask:
11900     static const int ShufMask2[] = {0, 1, 4, 5};
11901     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11902     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11903   }
11904
11905   // Handle truncation of V256 to V128 using shuffles.
11906   if (!VT.is128BitVector() || !InVT.is256BitVector())
11907     return SDValue();
11908
11909   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11910
11911   unsigned NumElems = VT.getVectorNumElements();
11912   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11913
11914   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11915   // Prepare truncation shuffle mask
11916   for (unsigned i = 0; i != NumElems; ++i)
11917     MaskVec[i] = i * 2;
11918   SDValue V = DAG.getVectorShuffle(NVT, DL,
11919                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11920                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11921   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11922                      DAG.getIntPtrConstant(0));
11923 }
11924
11925 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11926                                            SelectionDAG &DAG) const {
11927   assert(!Op.getSimpleValueType().isVector());
11928
11929   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11930     /*IsSigned=*/ true, /*IsReplace=*/ false);
11931   SDValue FIST = Vals.first, StackSlot = Vals.second;
11932   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11933   if (!FIST.getNode()) return Op;
11934
11935   if (StackSlot.getNode())
11936     // Load the result.
11937     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11938                        FIST, StackSlot, MachinePointerInfo(),
11939                        false, false, false, 0);
11940
11941   // The node is the result.
11942   return FIST;
11943 }
11944
11945 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11946                                            SelectionDAG &DAG) const {
11947   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11948     /*IsSigned=*/ false, /*IsReplace=*/ false);
11949   SDValue FIST = Vals.first, StackSlot = Vals.second;
11950   assert(FIST.getNode() && "Unexpected failure");
11951
11952   if (StackSlot.getNode())
11953     // Load the result.
11954     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11955                        FIST, StackSlot, MachinePointerInfo(),
11956                        false, false, false, 0);
11957
11958   // The node is the result.
11959   return FIST;
11960 }
11961
11962 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11963   SDLoc DL(Op);
11964   MVT VT = Op.getSimpleValueType();
11965   SDValue In = Op.getOperand(0);
11966   MVT SVT = In.getSimpleValueType();
11967
11968   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11969
11970   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11971                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11972                                  In, DAG.getUNDEF(SVT)));
11973 }
11974
11975 /// The only differences between FABS and FNEG are the mask and the logic op.
11976 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
11977 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
11978   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
11979          "Wrong opcode for lowering FABS or FNEG.");
11980
11981   bool IsFABS = (Op.getOpcode() == ISD::FABS);
11982
11983   // If this is a FABS and it has an FNEG user, bail out to fold the combination
11984   // into an FNABS. We'll lower the FABS after that if it is still in use.
11985   if (IsFABS)
11986     for (SDNode *User : Op->uses())
11987       if (User->getOpcode() == ISD::FNEG)
11988         return Op;
11989
11990   SDValue Op0 = Op.getOperand(0);
11991   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
11992
11993   SDLoc dl(Op);
11994   MVT VT = Op.getSimpleValueType();
11995   // Assume scalar op for initialization; update for vector if needed.
11996   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
11997   // generate a 16-byte vector constant and logic op even for the scalar case.
11998   // Using a 16-byte mask allows folding the load of the mask with
11999   // the logic op, so it can save (~4 bytes) on code size.
12000   MVT EltVT = VT;
12001   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12002   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12003   // decide if we should generate a 16-byte constant mask when we only need 4 or
12004   // 8 bytes for the scalar case.
12005   if (VT.isVector()) {
12006     EltVT = VT.getVectorElementType();
12007     NumElts = VT.getVectorNumElements();
12008   }
12009
12010   unsigned EltBits = EltVT.getSizeInBits();
12011   LLVMContext *Context = DAG.getContext();
12012   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12013   APInt MaskElt =
12014     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12015   Constant *C = ConstantInt::get(*Context, MaskElt);
12016   C = ConstantVector::getSplat(NumElts, C);
12017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12018   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12019   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12020   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12021                              MachinePointerInfo::getConstantPool(),
12022                              false, false, false, Alignment);
12023
12024   if (VT.isVector()) {
12025     // For a vector, cast operands to a vector type, perform the logic op,
12026     // and cast the result back to the original value type.
12027     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12028     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12029     SDValue Operand = IsFNABS ?
12030       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12031       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12032     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12033     return DAG.getNode(ISD::BITCAST, dl, VT,
12034                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12035   }
12036
12037   // If not vector, then scalar.
12038   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12039   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12040   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12041 }
12042
12043 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12045   LLVMContext *Context = DAG.getContext();
12046   SDValue Op0 = Op.getOperand(0);
12047   SDValue Op1 = Op.getOperand(1);
12048   SDLoc dl(Op);
12049   MVT VT = Op.getSimpleValueType();
12050   MVT SrcVT = Op1.getSimpleValueType();
12051
12052   // If second operand is smaller, extend it first.
12053   if (SrcVT.bitsLT(VT)) {
12054     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12055     SrcVT = VT;
12056   }
12057   // And if it is bigger, shrink it first.
12058   if (SrcVT.bitsGT(VT)) {
12059     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12060     SrcVT = VT;
12061   }
12062
12063   // At this point the operands and the result should have the same
12064   // type, and that won't be f80 since that is not custom lowered.
12065
12066   const fltSemantics &Sem =
12067       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12068   const unsigned SizeInBits = VT.getSizeInBits();
12069
12070   SmallVector<Constant *, 4> CV(
12071       VT == MVT::f64 ? 2 : 4,
12072       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12073
12074   // First, clear all bits but the sign bit from the second operand (sign).
12075   CV[0] = ConstantFP::get(*Context,
12076                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12077   Constant *C = ConstantVector::get(CV);
12078   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12079   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12080                               MachinePointerInfo::getConstantPool(),
12081                               false, false, false, 16);
12082   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12083
12084   // Next, clear the sign bit from the first operand (magnitude).
12085   // If it's a constant, we can clear it here.
12086   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12087     APFloat APF = Op0CN->getValueAPF();
12088     // If the magnitude is a positive zero, the sign bit alone is enough.
12089     if (APF.isPosZero())
12090       return SignBit;
12091     APF.clearSign();
12092     CV[0] = ConstantFP::get(*Context, APF);
12093   } else {
12094     CV[0] = ConstantFP::get(
12095         *Context,
12096         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12097   }
12098   C = ConstantVector::get(CV);
12099   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12100   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12101                             MachinePointerInfo::getConstantPool(),
12102                             false, false, false, 16);
12103   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12104   if (!isa<ConstantFPSDNode>(Op0))
12105     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12106
12107   // OR the magnitude value with the sign bit.
12108   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12109 }
12110
12111 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12112   SDValue N0 = Op.getOperand(0);
12113   SDLoc dl(Op);
12114   MVT VT = Op.getSimpleValueType();
12115
12116   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12117   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12118                                   DAG.getConstant(1, VT));
12119   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12120 }
12121
12122 // Check whether an OR'd tree is PTEST-able.
12123 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12124                                       SelectionDAG &DAG) {
12125   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12126
12127   if (!Subtarget->hasSSE41())
12128     return SDValue();
12129
12130   if (!Op->hasOneUse())
12131     return SDValue();
12132
12133   SDNode *N = Op.getNode();
12134   SDLoc DL(N);
12135
12136   SmallVector<SDValue, 8> Opnds;
12137   DenseMap<SDValue, unsigned> VecInMap;
12138   SmallVector<SDValue, 8> VecIns;
12139   EVT VT = MVT::Other;
12140
12141   // Recognize a special case where a vector is casted into wide integer to
12142   // test all 0s.
12143   Opnds.push_back(N->getOperand(0));
12144   Opnds.push_back(N->getOperand(1));
12145
12146   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12147     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12148     // BFS traverse all OR'd operands.
12149     if (I->getOpcode() == ISD::OR) {
12150       Opnds.push_back(I->getOperand(0));
12151       Opnds.push_back(I->getOperand(1));
12152       // Re-evaluate the number of nodes to be traversed.
12153       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12154       continue;
12155     }
12156
12157     // Quit if a non-EXTRACT_VECTOR_ELT
12158     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12159       return SDValue();
12160
12161     // Quit if without a constant index.
12162     SDValue Idx = I->getOperand(1);
12163     if (!isa<ConstantSDNode>(Idx))
12164       return SDValue();
12165
12166     SDValue ExtractedFromVec = I->getOperand(0);
12167     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12168     if (M == VecInMap.end()) {
12169       VT = ExtractedFromVec.getValueType();
12170       // Quit if not 128/256-bit vector.
12171       if (!VT.is128BitVector() && !VT.is256BitVector())
12172         return SDValue();
12173       // Quit if not the same type.
12174       if (VecInMap.begin() != VecInMap.end() &&
12175           VT != VecInMap.begin()->first.getValueType())
12176         return SDValue();
12177       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12178       VecIns.push_back(ExtractedFromVec);
12179     }
12180     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12181   }
12182
12183   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12184          "Not extracted from 128-/256-bit vector.");
12185
12186   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12187
12188   for (DenseMap<SDValue, unsigned>::const_iterator
12189         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12190     // Quit if not all elements are used.
12191     if (I->second != FullMask)
12192       return SDValue();
12193   }
12194
12195   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12196
12197   // Cast all vectors into TestVT for PTEST.
12198   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12199     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12200
12201   // If more than one full vectors are evaluated, OR them first before PTEST.
12202   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12203     // Each iteration will OR 2 nodes and append the result until there is only
12204     // 1 node left, i.e. the final OR'd value of all vectors.
12205     SDValue LHS = VecIns[Slot];
12206     SDValue RHS = VecIns[Slot + 1];
12207     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12208   }
12209
12210   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12211                      VecIns.back(), VecIns.back());
12212 }
12213
12214 /// \brief return true if \c Op has a use that doesn't just read flags.
12215 static bool hasNonFlagsUse(SDValue Op) {
12216   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12217        ++UI) {
12218     SDNode *User = *UI;
12219     unsigned UOpNo = UI.getOperandNo();
12220     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12221       // Look pass truncate.
12222       UOpNo = User->use_begin().getOperandNo();
12223       User = *User->use_begin();
12224     }
12225
12226     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12227         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12228       return true;
12229   }
12230   return false;
12231 }
12232
12233 /// Emit nodes that will be selected as "test Op0,Op0", or something
12234 /// equivalent.
12235 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12236                                     SelectionDAG &DAG) const {
12237   if (Op.getValueType() == MVT::i1) {
12238     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12239     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12240                        DAG.getConstant(0, MVT::i8));
12241   }
12242   // CF and OF aren't always set the way we want. Determine which
12243   // of these we need.
12244   bool NeedCF = false;
12245   bool NeedOF = false;
12246   switch (X86CC) {
12247   default: break;
12248   case X86::COND_A: case X86::COND_AE:
12249   case X86::COND_B: case X86::COND_BE:
12250     NeedCF = true;
12251     break;
12252   case X86::COND_G: case X86::COND_GE:
12253   case X86::COND_L: case X86::COND_LE:
12254   case X86::COND_O: case X86::COND_NO: {
12255     // Check if we really need to set the
12256     // Overflow flag. If NoSignedWrap is present
12257     // that is not actually needed.
12258     switch (Op->getOpcode()) {
12259     case ISD::ADD:
12260     case ISD::SUB:
12261     case ISD::MUL:
12262     case ISD::SHL: {
12263       const BinaryWithFlagsSDNode *BinNode =
12264           cast<BinaryWithFlagsSDNode>(Op.getNode());
12265       if (BinNode->hasNoSignedWrap())
12266         break;
12267     }
12268     default:
12269       NeedOF = true;
12270       break;
12271     }
12272     break;
12273   }
12274   }
12275   // See if we can use the EFLAGS value from the operand instead of
12276   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12277   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12278   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12279     // Emit a CMP with 0, which is the TEST pattern.
12280     //if (Op.getValueType() == MVT::i1)
12281     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12282     //                     DAG.getConstant(0, MVT::i1));
12283     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12284                        DAG.getConstant(0, Op.getValueType()));
12285   }
12286   unsigned Opcode = 0;
12287   unsigned NumOperands = 0;
12288
12289   // Truncate operations may prevent the merge of the SETCC instruction
12290   // and the arithmetic instruction before it. Attempt to truncate the operands
12291   // of the arithmetic instruction and use a reduced bit-width instruction.
12292   bool NeedTruncation = false;
12293   SDValue ArithOp = Op;
12294   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12295     SDValue Arith = Op->getOperand(0);
12296     // Both the trunc and the arithmetic op need to have one user each.
12297     if (Arith->hasOneUse())
12298       switch (Arith.getOpcode()) {
12299         default: break;
12300         case ISD::ADD:
12301         case ISD::SUB:
12302         case ISD::AND:
12303         case ISD::OR:
12304         case ISD::XOR: {
12305           NeedTruncation = true;
12306           ArithOp = Arith;
12307         }
12308       }
12309   }
12310
12311   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12312   // which may be the result of a CAST.  We use the variable 'Op', which is the
12313   // non-casted variable when we check for possible users.
12314   switch (ArithOp.getOpcode()) {
12315   case ISD::ADD:
12316     // Due to an isel shortcoming, be conservative if this add is likely to be
12317     // selected as part of a load-modify-store instruction. When the root node
12318     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12319     // uses of other nodes in the match, such as the ADD in this case. This
12320     // leads to the ADD being left around and reselected, with the result being
12321     // two adds in the output.  Alas, even if none our users are stores, that
12322     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12323     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12324     // climbing the DAG back to the root, and it doesn't seem to be worth the
12325     // effort.
12326     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12327          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12328       if (UI->getOpcode() != ISD::CopyToReg &&
12329           UI->getOpcode() != ISD::SETCC &&
12330           UI->getOpcode() != ISD::STORE)
12331         goto default_case;
12332
12333     if (ConstantSDNode *C =
12334         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12335       // An add of one will be selected as an INC.
12336       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12337         Opcode = X86ISD::INC;
12338         NumOperands = 1;
12339         break;
12340       }
12341
12342       // An add of negative one (subtract of one) will be selected as a DEC.
12343       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12344         Opcode = X86ISD::DEC;
12345         NumOperands = 1;
12346         break;
12347       }
12348     }
12349
12350     // Otherwise use a regular EFLAGS-setting add.
12351     Opcode = X86ISD::ADD;
12352     NumOperands = 2;
12353     break;
12354   case ISD::SHL:
12355   case ISD::SRL:
12356     // If we have a constant logical shift that's only used in a comparison
12357     // against zero turn it into an equivalent AND. This allows turning it into
12358     // a TEST instruction later.
12359     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12360         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12361       EVT VT = Op.getValueType();
12362       unsigned BitWidth = VT.getSizeInBits();
12363       unsigned ShAmt = Op->getConstantOperandVal(1);
12364       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12365         break;
12366       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12367                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12368                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12369       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12370         break;
12371       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12372                                 DAG.getConstant(Mask, VT));
12373       DAG.ReplaceAllUsesWith(Op, New);
12374       Op = New;
12375     }
12376     break;
12377
12378   case ISD::AND:
12379     // If the primary and result isn't used, don't bother using X86ISD::AND,
12380     // because a TEST instruction will be better.
12381     if (!hasNonFlagsUse(Op))
12382       break;
12383     // FALL THROUGH
12384   case ISD::SUB:
12385   case ISD::OR:
12386   case ISD::XOR:
12387     // Due to the ISEL shortcoming noted above, be conservative if this op is
12388     // likely to be selected as part of a load-modify-store instruction.
12389     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12390            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12391       if (UI->getOpcode() == ISD::STORE)
12392         goto default_case;
12393
12394     // Otherwise use a regular EFLAGS-setting instruction.
12395     switch (ArithOp.getOpcode()) {
12396     default: llvm_unreachable("unexpected operator!");
12397     case ISD::SUB: Opcode = X86ISD::SUB; break;
12398     case ISD::XOR: Opcode = X86ISD::XOR; break;
12399     case ISD::AND: Opcode = X86ISD::AND; break;
12400     case ISD::OR: {
12401       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12402         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12403         if (EFLAGS.getNode())
12404           return EFLAGS;
12405       }
12406       Opcode = X86ISD::OR;
12407       break;
12408     }
12409     }
12410
12411     NumOperands = 2;
12412     break;
12413   case X86ISD::ADD:
12414   case X86ISD::SUB:
12415   case X86ISD::INC:
12416   case X86ISD::DEC:
12417   case X86ISD::OR:
12418   case X86ISD::XOR:
12419   case X86ISD::AND:
12420     return SDValue(Op.getNode(), 1);
12421   default:
12422   default_case:
12423     break;
12424   }
12425
12426   // If we found that truncation is beneficial, perform the truncation and
12427   // update 'Op'.
12428   if (NeedTruncation) {
12429     EVT VT = Op.getValueType();
12430     SDValue WideVal = Op->getOperand(0);
12431     EVT WideVT = WideVal.getValueType();
12432     unsigned ConvertedOp = 0;
12433     // Use a target machine opcode to prevent further DAGCombine
12434     // optimizations that may separate the arithmetic operations
12435     // from the setcc node.
12436     switch (WideVal.getOpcode()) {
12437       default: break;
12438       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12439       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12440       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12441       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12442       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12443     }
12444
12445     if (ConvertedOp) {
12446       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12447       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12448         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12449         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12450         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12451       }
12452     }
12453   }
12454
12455   if (Opcode == 0)
12456     // Emit a CMP with 0, which is the TEST pattern.
12457     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12458                        DAG.getConstant(0, Op.getValueType()));
12459
12460   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12461   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12462
12463   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12464   DAG.ReplaceAllUsesWith(Op, New);
12465   return SDValue(New.getNode(), 1);
12466 }
12467
12468 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12469 /// equivalent.
12470 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12471                                    SDLoc dl, SelectionDAG &DAG) const {
12472   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12473     if (C->getAPIntValue() == 0)
12474       return EmitTest(Op0, X86CC, dl, DAG);
12475
12476      if (Op0.getValueType() == MVT::i1)
12477        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12478   }
12479
12480   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12481        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12482     // Do the comparison at i32 if it's smaller, besides the Atom case.
12483     // This avoids subregister aliasing issues. Keep the smaller reference
12484     // if we're optimizing for size, however, as that'll allow better folding
12485     // of memory operations.
12486     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12487         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12488             Attribute::MinSize) &&
12489         !Subtarget->isAtom()) {
12490       unsigned ExtendOp =
12491           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12492       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12493       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12494     }
12495     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12496     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12497     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12498                               Op0, Op1);
12499     return SDValue(Sub.getNode(), 1);
12500   }
12501   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12502 }
12503
12504 /// Convert a comparison if required by the subtarget.
12505 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12506                                                  SelectionDAG &DAG) const {
12507   // If the subtarget does not support the FUCOMI instruction, floating-point
12508   // comparisons have to be converted.
12509   if (Subtarget->hasCMov() ||
12510       Cmp.getOpcode() != X86ISD::CMP ||
12511       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12512       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12513     return Cmp;
12514
12515   // The instruction selector will select an FUCOM instruction instead of
12516   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12517   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12518   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12519   SDLoc dl(Cmp);
12520   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12521   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12522   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12523                             DAG.getConstant(8, MVT::i8));
12524   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12525   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12526 }
12527
12528 /// The minimum architected relative accuracy is 2^-12. We need one
12529 /// Newton-Raphson step to have a good float result (24 bits of precision).
12530 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12531                                             DAGCombinerInfo &DCI,
12532                                             unsigned &RefinementSteps,
12533                                             bool &UseOneConstNR) const {
12534   // FIXME: We should use instruction latency models to calculate the cost of
12535   // each potential sequence, but this is very hard to do reliably because
12536   // at least Intel's Core* chips have variable timing based on the number of
12537   // significant digits in the divisor and/or sqrt operand.
12538   if (!Subtarget->useSqrtEst())
12539     return SDValue();
12540
12541   EVT VT = Op.getValueType();
12542
12543   // SSE1 has rsqrtss and rsqrtps.
12544   // TODO: Add support for AVX512 (v16f32).
12545   // It is likely not profitable to do this for f64 because a double-precision
12546   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12547   // instructions: convert to single, rsqrtss, convert back to double, refine
12548   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12549   // along with FMA, this could be a throughput win.
12550   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12551       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12552     RefinementSteps = 1;
12553     UseOneConstNR = false;
12554     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12555   }
12556   return SDValue();
12557 }
12558
12559 /// The minimum architected relative accuracy is 2^-12. We need one
12560 /// Newton-Raphson step to have a good float result (24 bits of precision).
12561 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12562                                             DAGCombinerInfo &DCI,
12563                                             unsigned &RefinementSteps) const {
12564   // FIXME: We should use instruction latency models to calculate the cost of
12565   // each potential sequence, but this is very hard to do reliably because
12566   // at least Intel's Core* chips have variable timing based on the number of
12567   // significant digits in the divisor.
12568   if (!Subtarget->useReciprocalEst())
12569     return SDValue();
12570
12571   EVT VT = Op.getValueType();
12572
12573   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12574   // TODO: Add support for AVX512 (v16f32).
12575   // It is likely not profitable to do this for f64 because a double-precision
12576   // reciprocal estimate with refinement on x86 prior to FMA requires
12577   // 15 instructions: convert to single, rcpss, convert back to double, refine
12578   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12579   // along with FMA, this could be a throughput win.
12580   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12581       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12582     RefinementSteps = ReciprocalEstimateRefinementSteps;
12583     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12584   }
12585   return SDValue();
12586 }
12587
12588 static bool isAllOnes(SDValue V) {
12589   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12590   return C && C->isAllOnesValue();
12591 }
12592
12593 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12594 /// if it's possible.
12595 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12596                                      SDLoc dl, SelectionDAG &DAG) const {
12597   SDValue Op0 = And.getOperand(0);
12598   SDValue Op1 = And.getOperand(1);
12599   if (Op0.getOpcode() == ISD::TRUNCATE)
12600     Op0 = Op0.getOperand(0);
12601   if (Op1.getOpcode() == ISD::TRUNCATE)
12602     Op1 = Op1.getOperand(0);
12603
12604   SDValue LHS, RHS;
12605   if (Op1.getOpcode() == ISD::SHL)
12606     std::swap(Op0, Op1);
12607   if (Op0.getOpcode() == ISD::SHL) {
12608     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12609       if (And00C->getZExtValue() == 1) {
12610         // If we looked past a truncate, check that it's only truncating away
12611         // known zeros.
12612         unsigned BitWidth = Op0.getValueSizeInBits();
12613         unsigned AndBitWidth = And.getValueSizeInBits();
12614         if (BitWidth > AndBitWidth) {
12615           APInt Zeros, Ones;
12616           DAG.computeKnownBits(Op0, Zeros, Ones);
12617           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12618             return SDValue();
12619         }
12620         LHS = Op1;
12621         RHS = Op0.getOperand(1);
12622       }
12623   } else if (Op1.getOpcode() == ISD::Constant) {
12624     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12625     uint64_t AndRHSVal = AndRHS->getZExtValue();
12626     SDValue AndLHS = Op0;
12627
12628     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12629       LHS = AndLHS.getOperand(0);
12630       RHS = AndLHS.getOperand(1);
12631     }
12632
12633     // Use BT if the immediate can't be encoded in a TEST instruction.
12634     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12635       LHS = AndLHS;
12636       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12637     }
12638   }
12639
12640   if (LHS.getNode()) {
12641     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12642     // instruction.  Since the shift amount is in-range-or-undefined, we know
12643     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12644     // the encoding for the i16 version is larger than the i32 version.
12645     // Also promote i16 to i32 for performance / code size reason.
12646     if (LHS.getValueType() == MVT::i8 ||
12647         LHS.getValueType() == MVT::i16)
12648       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12649
12650     // If the operand types disagree, extend the shift amount to match.  Since
12651     // BT ignores high bits (like shifts) we can use anyextend.
12652     if (LHS.getValueType() != RHS.getValueType())
12653       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12654
12655     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12656     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12657     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12658                        DAG.getConstant(Cond, MVT::i8), BT);
12659   }
12660
12661   return SDValue();
12662 }
12663
12664 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12665 /// mask CMPs.
12666 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12667                               SDValue &Op1) {
12668   unsigned SSECC;
12669   bool Swap = false;
12670
12671   // SSE Condition code mapping:
12672   //  0 - EQ
12673   //  1 - LT
12674   //  2 - LE
12675   //  3 - UNORD
12676   //  4 - NEQ
12677   //  5 - NLT
12678   //  6 - NLE
12679   //  7 - ORD
12680   switch (SetCCOpcode) {
12681   default: llvm_unreachable("Unexpected SETCC condition");
12682   case ISD::SETOEQ:
12683   case ISD::SETEQ:  SSECC = 0; break;
12684   case ISD::SETOGT:
12685   case ISD::SETGT:  Swap = true; // Fallthrough
12686   case ISD::SETLT:
12687   case ISD::SETOLT: SSECC = 1; break;
12688   case ISD::SETOGE:
12689   case ISD::SETGE:  Swap = true; // Fallthrough
12690   case ISD::SETLE:
12691   case ISD::SETOLE: SSECC = 2; break;
12692   case ISD::SETUO:  SSECC = 3; break;
12693   case ISD::SETUNE:
12694   case ISD::SETNE:  SSECC = 4; break;
12695   case ISD::SETULE: Swap = true; // Fallthrough
12696   case ISD::SETUGE: SSECC = 5; break;
12697   case ISD::SETULT: Swap = true; // Fallthrough
12698   case ISD::SETUGT: SSECC = 6; break;
12699   case ISD::SETO:   SSECC = 7; break;
12700   case ISD::SETUEQ:
12701   case ISD::SETONE: SSECC = 8; break;
12702   }
12703   if (Swap)
12704     std::swap(Op0, Op1);
12705
12706   return SSECC;
12707 }
12708
12709 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12710 // ones, and then concatenate the result back.
12711 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12712   MVT VT = Op.getSimpleValueType();
12713
12714   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12715          "Unsupported value type for operation");
12716
12717   unsigned NumElems = VT.getVectorNumElements();
12718   SDLoc dl(Op);
12719   SDValue CC = Op.getOperand(2);
12720
12721   // Extract the LHS vectors
12722   SDValue LHS = Op.getOperand(0);
12723   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12724   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12725
12726   // Extract the RHS vectors
12727   SDValue RHS = Op.getOperand(1);
12728   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12729   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12730
12731   // Issue the operation on the smaller types and concatenate the result back
12732   MVT EltVT = VT.getVectorElementType();
12733   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12734   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12735                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12736                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12737 }
12738
12739 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12740                                      const X86Subtarget *Subtarget) {
12741   SDValue Op0 = Op.getOperand(0);
12742   SDValue Op1 = Op.getOperand(1);
12743   SDValue CC = Op.getOperand(2);
12744   MVT VT = Op.getSimpleValueType();
12745   SDLoc dl(Op);
12746
12747   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12748          Op.getValueType().getScalarType() == MVT::i1 &&
12749          "Cannot set masked compare for this operation");
12750
12751   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12752   unsigned  Opc = 0;
12753   bool Unsigned = false;
12754   bool Swap = false;
12755   unsigned SSECC;
12756   switch (SetCCOpcode) {
12757   default: llvm_unreachable("Unexpected SETCC condition");
12758   case ISD::SETNE:  SSECC = 4; break;
12759   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12760   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12761   case ISD::SETLT:  Swap = true; //fall-through
12762   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12763   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12764   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12765   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12766   case ISD::SETULE: Unsigned = true; //fall-through
12767   case ISD::SETLE:  SSECC = 2; break;
12768   }
12769
12770   if (Swap)
12771     std::swap(Op0, Op1);
12772   if (Opc)
12773     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12774   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12775   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12776                      DAG.getConstant(SSECC, MVT::i8));
12777 }
12778
12779 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12780 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12781 /// return an empty value.
12782 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12783 {
12784   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12785   if (!BV)
12786     return SDValue();
12787
12788   MVT VT = Op1.getSimpleValueType();
12789   MVT EVT = VT.getVectorElementType();
12790   unsigned n = VT.getVectorNumElements();
12791   SmallVector<SDValue, 8> ULTOp1;
12792
12793   for (unsigned i = 0; i < n; ++i) {
12794     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12795     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12796       return SDValue();
12797
12798     // Avoid underflow.
12799     APInt Val = Elt->getAPIntValue();
12800     if (Val == 0)
12801       return SDValue();
12802
12803     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12804   }
12805
12806   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12807 }
12808
12809 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12810                            SelectionDAG &DAG) {
12811   SDValue Op0 = Op.getOperand(0);
12812   SDValue Op1 = Op.getOperand(1);
12813   SDValue CC = Op.getOperand(2);
12814   MVT VT = Op.getSimpleValueType();
12815   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12816   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12817   SDLoc dl(Op);
12818
12819   if (isFP) {
12820 #ifndef NDEBUG
12821     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12822     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12823 #endif
12824
12825     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12826     unsigned Opc = X86ISD::CMPP;
12827     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12828       assert(VT.getVectorNumElements() <= 16);
12829       Opc = X86ISD::CMPM;
12830     }
12831     // In the two special cases we can't handle, emit two comparisons.
12832     if (SSECC == 8) {
12833       unsigned CC0, CC1;
12834       unsigned CombineOpc;
12835       if (SetCCOpcode == ISD::SETUEQ) {
12836         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12837       } else {
12838         assert(SetCCOpcode == ISD::SETONE);
12839         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12840       }
12841
12842       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12843                                  DAG.getConstant(CC0, MVT::i8));
12844       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12845                                  DAG.getConstant(CC1, MVT::i8));
12846       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12847     }
12848     // Handle all other FP comparisons here.
12849     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12850                        DAG.getConstant(SSECC, MVT::i8));
12851   }
12852
12853   // Break 256-bit integer vector compare into smaller ones.
12854   if (VT.is256BitVector() && !Subtarget->hasInt256())
12855     return Lower256IntVSETCC(Op, DAG);
12856
12857   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12858   EVT OpVT = Op1.getValueType();
12859   if (Subtarget->hasAVX512()) {
12860     if (Op1.getValueType().is512BitVector() ||
12861         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12862         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12863       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12864
12865     // In AVX-512 architecture setcc returns mask with i1 elements,
12866     // But there is no compare instruction for i8 and i16 elements in KNL.
12867     // We are not talking about 512-bit operands in this case, these
12868     // types are illegal.
12869     if (MaskResult &&
12870         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12871          OpVT.getVectorElementType().getSizeInBits() >= 8))
12872       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12873                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12874   }
12875
12876   // We are handling one of the integer comparisons here.  Since SSE only has
12877   // GT and EQ comparisons for integer, swapping operands and multiple
12878   // operations may be required for some comparisons.
12879   unsigned Opc;
12880   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12881   bool Subus = false;
12882
12883   switch (SetCCOpcode) {
12884   default: llvm_unreachable("Unexpected SETCC condition");
12885   case ISD::SETNE:  Invert = true;
12886   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12887   case ISD::SETLT:  Swap = true;
12888   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12889   case ISD::SETGE:  Swap = true;
12890   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12891                     Invert = true; break;
12892   case ISD::SETULT: Swap = true;
12893   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12894                     FlipSigns = true; break;
12895   case ISD::SETUGE: Swap = true;
12896   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12897                     FlipSigns = true; Invert = true; break;
12898   }
12899
12900   // Special case: Use min/max operations for SETULE/SETUGE
12901   MVT VET = VT.getVectorElementType();
12902   bool hasMinMax =
12903        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12904     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12905
12906   if (hasMinMax) {
12907     switch (SetCCOpcode) {
12908     default: break;
12909     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12910     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12911     }
12912
12913     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12914   }
12915
12916   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12917   if (!MinMax && hasSubus) {
12918     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12919     // Op0 u<= Op1:
12920     //   t = psubus Op0, Op1
12921     //   pcmpeq t, <0..0>
12922     switch (SetCCOpcode) {
12923     default: break;
12924     case ISD::SETULT: {
12925       // If the comparison is against a constant we can turn this into a
12926       // setule.  With psubus, setule does not require a swap.  This is
12927       // beneficial because the constant in the register is no longer
12928       // destructed as the destination so it can be hoisted out of a loop.
12929       // Only do this pre-AVX since vpcmp* is no longer destructive.
12930       if (Subtarget->hasAVX())
12931         break;
12932       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12933       if (ULEOp1.getNode()) {
12934         Op1 = ULEOp1;
12935         Subus = true; Invert = false; Swap = false;
12936       }
12937       break;
12938     }
12939     // Psubus is better than flip-sign because it requires no inversion.
12940     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12941     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12942     }
12943
12944     if (Subus) {
12945       Opc = X86ISD::SUBUS;
12946       FlipSigns = false;
12947     }
12948   }
12949
12950   if (Swap)
12951     std::swap(Op0, Op1);
12952
12953   // Check that the operation in question is available (most are plain SSE2,
12954   // but PCMPGTQ and PCMPEQQ have different requirements).
12955   if (VT == MVT::v2i64) {
12956     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12957       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12958
12959       // First cast everything to the right type.
12960       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12961       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12962
12963       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12964       // bits of the inputs before performing those operations. The lower
12965       // compare is always unsigned.
12966       SDValue SB;
12967       if (FlipSigns) {
12968         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12969       } else {
12970         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12971         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12972         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12973                          Sign, Zero, Sign, Zero);
12974       }
12975       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12976       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12977
12978       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12979       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12980       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12981
12982       // Create masks for only the low parts/high parts of the 64 bit integers.
12983       static const int MaskHi[] = { 1, 1, 3, 3 };
12984       static const int MaskLo[] = { 0, 0, 2, 2 };
12985       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12986       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12987       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12988
12989       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12990       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12991
12992       if (Invert)
12993         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12994
12995       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12996     }
12997
12998     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12999       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13000       // pcmpeqd + pshufd + pand.
13001       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13002
13003       // First cast everything to the right type.
13004       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13005       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13006
13007       // Do the compare.
13008       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13009
13010       // Make sure the lower and upper halves are both all-ones.
13011       static const int Mask[] = { 1, 0, 3, 2 };
13012       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13013       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13014
13015       if (Invert)
13016         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13017
13018       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13019     }
13020   }
13021
13022   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13023   // bits of the inputs before performing those operations.
13024   if (FlipSigns) {
13025     EVT EltVT = VT.getVectorElementType();
13026     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13027     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13028     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13029   }
13030
13031   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13032
13033   // If the logical-not of the result is required, perform that now.
13034   if (Invert)
13035     Result = DAG.getNOT(dl, Result, VT);
13036
13037   if (MinMax)
13038     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13039
13040   if (Subus)
13041     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13042                          getZeroVector(VT, Subtarget, DAG, dl));
13043
13044   return Result;
13045 }
13046
13047 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13048
13049   MVT VT = Op.getSimpleValueType();
13050
13051   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13052
13053   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13054          && "SetCC type must be 8-bit or 1-bit integer");
13055   SDValue Op0 = Op.getOperand(0);
13056   SDValue Op1 = Op.getOperand(1);
13057   SDLoc dl(Op);
13058   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13059
13060   // Optimize to BT if possible.
13061   // Lower (X & (1 << N)) == 0 to BT(X, N).
13062   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13063   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13064   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13065       Op1.getOpcode() == ISD::Constant &&
13066       cast<ConstantSDNode>(Op1)->isNullValue() &&
13067       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13068     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13069     if (NewSetCC.getNode()) {
13070       if (VT == MVT::i1)
13071         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13072       return NewSetCC;
13073     }
13074   }
13075
13076   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13077   // these.
13078   if (Op1.getOpcode() == ISD::Constant &&
13079       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13080        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13081       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13082
13083     // If the input is a setcc, then reuse the input setcc or use a new one with
13084     // the inverted condition.
13085     if (Op0.getOpcode() == X86ISD::SETCC) {
13086       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13087       bool Invert = (CC == ISD::SETNE) ^
13088         cast<ConstantSDNode>(Op1)->isNullValue();
13089       if (!Invert)
13090         return Op0;
13091
13092       CCode = X86::GetOppositeBranchCondition(CCode);
13093       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13094                                   DAG.getConstant(CCode, MVT::i8),
13095                                   Op0.getOperand(1));
13096       if (VT == MVT::i1)
13097         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13098       return SetCC;
13099     }
13100   }
13101   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13102       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13103       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13104
13105     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13106     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13107   }
13108
13109   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13110   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13111   if (X86CC == X86::COND_INVALID)
13112     return SDValue();
13113
13114   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13115   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13116   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13117                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13118   if (VT == MVT::i1)
13119     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13120   return SetCC;
13121 }
13122
13123 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13124 static bool isX86LogicalCmp(SDValue Op) {
13125   unsigned Opc = Op.getNode()->getOpcode();
13126   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13127       Opc == X86ISD::SAHF)
13128     return true;
13129   if (Op.getResNo() == 1 &&
13130       (Opc == X86ISD::ADD ||
13131        Opc == X86ISD::SUB ||
13132        Opc == X86ISD::ADC ||
13133        Opc == X86ISD::SBB ||
13134        Opc == X86ISD::SMUL ||
13135        Opc == X86ISD::UMUL ||
13136        Opc == X86ISD::INC ||
13137        Opc == X86ISD::DEC ||
13138        Opc == X86ISD::OR ||
13139        Opc == X86ISD::XOR ||
13140        Opc == X86ISD::AND))
13141     return true;
13142
13143   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13144     return true;
13145
13146   return false;
13147 }
13148
13149 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13150   if (V.getOpcode() != ISD::TRUNCATE)
13151     return false;
13152
13153   SDValue VOp0 = V.getOperand(0);
13154   unsigned InBits = VOp0.getValueSizeInBits();
13155   unsigned Bits = V.getValueSizeInBits();
13156   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13157 }
13158
13159 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13160   bool addTest = true;
13161   SDValue Cond  = Op.getOperand(0);
13162   SDValue Op1 = Op.getOperand(1);
13163   SDValue Op2 = Op.getOperand(2);
13164   SDLoc DL(Op);
13165   EVT VT = Op1.getValueType();
13166   SDValue CC;
13167
13168   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13169   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13170   // sequence later on.
13171   if (Cond.getOpcode() == ISD::SETCC &&
13172       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13173        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13174       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13175     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13176     int SSECC = translateX86FSETCC(
13177         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13178
13179     if (SSECC != 8) {
13180       if (Subtarget->hasAVX512()) {
13181         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13182                                   DAG.getConstant(SSECC, MVT::i8));
13183         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13184       }
13185       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13186                                 DAG.getConstant(SSECC, MVT::i8));
13187       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13188       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13189       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13190     }
13191   }
13192
13193   if (Cond.getOpcode() == ISD::SETCC) {
13194     SDValue NewCond = LowerSETCC(Cond, DAG);
13195     if (NewCond.getNode())
13196       Cond = NewCond;
13197   }
13198
13199   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13200   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13201   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13202   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13203   if (Cond.getOpcode() == X86ISD::SETCC &&
13204       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13205       isZero(Cond.getOperand(1).getOperand(1))) {
13206     SDValue Cmp = Cond.getOperand(1);
13207
13208     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13209
13210     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13211         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13212       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13213
13214       SDValue CmpOp0 = Cmp.getOperand(0);
13215       // Apply further optimizations for special cases
13216       // (select (x != 0), -1, 0) -> neg & sbb
13217       // (select (x == 0), 0, -1) -> neg & sbb
13218       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13219         if (YC->isNullValue() &&
13220             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13221           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13222           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13223                                     DAG.getConstant(0, CmpOp0.getValueType()),
13224                                     CmpOp0);
13225           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13226                                     DAG.getConstant(X86::COND_B, MVT::i8),
13227                                     SDValue(Neg.getNode(), 1));
13228           return Res;
13229         }
13230
13231       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13232                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13233       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13234
13235       SDValue Res =   // Res = 0 or -1.
13236         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13237                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13238
13239       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13240         Res = DAG.getNOT(DL, Res, Res.getValueType());
13241
13242       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13243       if (!N2C || !N2C->isNullValue())
13244         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13245       return Res;
13246     }
13247   }
13248
13249   // Look past (and (setcc_carry (cmp ...)), 1).
13250   if (Cond.getOpcode() == ISD::AND &&
13251       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13252     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13253     if (C && C->getAPIntValue() == 1)
13254       Cond = Cond.getOperand(0);
13255   }
13256
13257   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13258   // setting operand in place of the X86ISD::SETCC.
13259   unsigned CondOpcode = Cond.getOpcode();
13260   if (CondOpcode == X86ISD::SETCC ||
13261       CondOpcode == X86ISD::SETCC_CARRY) {
13262     CC = Cond.getOperand(0);
13263
13264     SDValue Cmp = Cond.getOperand(1);
13265     unsigned Opc = Cmp.getOpcode();
13266     MVT VT = Op.getSimpleValueType();
13267
13268     bool IllegalFPCMov = false;
13269     if (VT.isFloatingPoint() && !VT.isVector() &&
13270         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13271       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13272
13273     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13274         Opc == X86ISD::BT) { // FIXME
13275       Cond = Cmp;
13276       addTest = false;
13277     }
13278   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13279              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13280              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13281               Cond.getOperand(0).getValueType() != MVT::i8)) {
13282     SDValue LHS = Cond.getOperand(0);
13283     SDValue RHS = Cond.getOperand(1);
13284     unsigned X86Opcode;
13285     unsigned X86Cond;
13286     SDVTList VTs;
13287     switch (CondOpcode) {
13288     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13289     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13290     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13291     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13292     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13293     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13294     default: llvm_unreachable("unexpected overflowing operator");
13295     }
13296     if (CondOpcode == ISD::UMULO)
13297       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13298                           MVT::i32);
13299     else
13300       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13301
13302     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13303
13304     if (CondOpcode == ISD::UMULO)
13305       Cond = X86Op.getValue(2);
13306     else
13307       Cond = X86Op.getValue(1);
13308
13309     CC = DAG.getConstant(X86Cond, MVT::i8);
13310     addTest = false;
13311   }
13312
13313   if (addTest) {
13314     // Look pass the truncate if the high bits are known zero.
13315     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13316         Cond = Cond.getOperand(0);
13317
13318     // We know the result of AND is compared against zero. Try to match
13319     // it to BT.
13320     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13321       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13322       if (NewSetCC.getNode()) {
13323         CC = NewSetCC.getOperand(0);
13324         Cond = NewSetCC.getOperand(1);
13325         addTest = false;
13326       }
13327     }
13328   }
13329
13330   if (addTest) {
13331     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13332     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13333   }
13334
13335   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13336   // a <  b ?  0 : -1 -> RES = setcc_carry
13337   // a >= b ? -1 :  0 -> RES = setcc_carry
13338   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13339   if (Cond.getOpcode() == X86ISD::SUB) {
13340     Cond = ConvertCmpIfNecessary(Cond, DAG);
13341     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13342
13343     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13344         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13345       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13346                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13347       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13348         return DAG.getNOT(DL, Res, Res.getValueType());
13349       return Res;
13350     }
13351   }
13352
13353   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13354   // widen the cmov and push the truncate through. This avoids introducing a new
13355   // branch during isel and doesn't add any extensions.
13356   if (Op.getValueType() == MVT::i8 &&
13357       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13358     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13359     if (T1.getValueType() == T2.getValueType() &&
13360         // Blacklist CopyFromReg to avoid partial register stalls.
13361         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13362       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13363       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13364       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13365     }
13366   }
13367
13368   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13369   // condition is true.
13370   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13371   SDValue Ops[] = { Op2, Op1, CC, Cond };
13372   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13373 }
13374
13375 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13376                                        SelectionDAG &DAG) {
13377   MVT VT = Op->getSimpleValueType(0);
13378   SDValue In = Op->getOperand(0);
13379   MVT InVT = In.getSimpleValueType();
13380   MVT VTElt = VT.getVectorElementType();
13381   MVT InVTElt = InVT.getVectorElementType();
13382   SDLoc dl(Op);
13383
13384   // SKX processor
13385   if ((InVTElt == MVT::i1) &&
13386       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13387         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13388
13389        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13390         VTElt.getSizeInBits() <= 16)) ||
13391
13392        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13393         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13394
13395        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13396         VTElt.getSizeInBits() >= 32))))
13397     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13398
13399   unsigned int NumElts = VT.getVectorNumElements();
13400
13401   if (NumElts != 8 && NumElts != 16)
13402     return SDValue();
13403
13404   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13405     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13406       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13407     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13408   }
13409
13410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13411   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13412
13413   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13414   Constant *C = ConstantInt::get(*DAG.getContext(),
13415     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13416
13417   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13418   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13419   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13420                           MachinePointerInfo::getConstantPool(),
13421                           false, false, false, Alignment);
13422   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13423   if (VT.is512BitVector())
13424     return Brcst;
13425   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13426 }
13427
13428 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13429                                 SelectionDAG &DAG) {
13430   MVT VT = Op->getSimpleValueType(0);
13431   SDValue In = Op->getOperand(0);
13432   MVT InVT = In.getSimpleValueType();
13433   SDLoc dl(Op);
13434
13435   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13436     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13437
13438   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13439       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13440       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13441     return SDValue();
13442
13443   if (Subtarget->hasInt256())
13444     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13445
13446   // Optimize vectors in AVX mode
13447   // Sign extend  v8i16 to v8i32 and
13448   //              v4i32 to v4i64
13449   //
13450   // Divide input vector into two parts
13451   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13452   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13453   // concat the vectors to original VT
13454
13455   unsigned NumElems = InVT.getVectorNumElements();
13456   SDValue Undef = DAG.getUNDEF(InVT);
13457
13458   SmallVector<int,8> ShufMask1(NumElems, -1);
13459   for (unsigned i = 0; i != NumElems/2; ++i)
13460     ShufMask1[i] = i;
13461
13462   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13463
13464   SmallVector<int,8> ShufMask2(NumElems, -1);
13465   for (unsigned i = 0; i != NumElems/2; ++i)
13466     ShufMask2[i] = i + NumElems/2;
13467
13468   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13469
13470   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13471                                 VT.getVectorNumElements()/2);
13472
13473   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13474   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13475
13476   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13477 }
13478
13479 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13480 // may emit an illegal shuffle but the expansion is still better than scalar
13481 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13482 // we'll emit a shuffle and a arithmetic shift.
13483 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13484 // TODO: It is possible to support ZExt by zeroing the undef values during
13485 // the shuffle phase or after the shuffle.
13486 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13487                                  SelectionDAG &DAG) {
13488   MVT RegVT = Op.getSimpleValueType();
13489   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13490   assert(RegVT.isInteger() &&
13491          "We only custom lower integer vector sext loads.");
13492
13493   // Nothing useful we can do without SSE2 shuffles.
13494   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13495
13496   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13497   SDLoc dl(Ld);
13498   EVT MemVT = Ld->getMemoryVT();
13499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13500   unsigned RegSz = RegVT.getSizeInBits();
13501
13502   ISD::LoadExtType Ext = Ld->getExtensionType();
13503
13504   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13505          && "Only anyext and sext are currently implemented.");
13506   assert(MemVT != RegVT && "Cannot extend to the same type");
13507   assert(MemVT.isVector() && "Must load a vector from memory");
13508
13509   unsigned NumElems = RegVT.getVectorNumElements();
13510   unsigned MemSz = MemVT.getSizeInBits();
13511   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13512
13513   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13514     // The only way in which we have a legal 256-bit vector result but not the
13515     // integer 256-bit operations needed to directly lower a sextload is if we
13516     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13517     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13518     // correctly legalized. We do this late to allow the canonical form of
13519     // sextload to persist throughout the rest of the DAG combiner -- it wants
13520     // to fold together any extensions it can, and so will fuse a sign_extend
13521     // of an sextload into a sextload targeting a wider value.
13522     SDValue Load;
13523     if (MemSz == 128) {
13524       // Just switch this to a normal load.
13525       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13526                                        "it must be a legal 128-bit vector "
13527                                        "type!");
13528       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13529                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13530                   Ld->isInvariant(), Ld->getAlignment());
13531     } else {
13532       assert(MemSz < 128 &&
13533              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13534       // Do an sext load to a 128-bit vector type. We want to use the same
13535       // number of elements, but elements half as wide. This will end up being
13536       // recursively lowered by this routine, but will succeed as we definitely
13537       // have all the necessary features if we're using AVX1.
13538       EVT HalfEltVT =
13539           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13540       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13541       Load =
13542           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13543                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13544                          Ld->isNonTemporal(), Ld->isInvariant(),
13545                          Ld->getAlignment());
13546     }
13547
13548     // Replace chain users with the new chain.
13549     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13550     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13551
13552     // Finally, do a normal sign-extend to the desired register.
13553     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13554   }
13555
13556   // All sizes must be a power of two.
13557   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13558          "Non-power-of-two elements are not custom lowered!");
13559
13560   // Attempt to load the original value using scalar loads.
13561   // Find the largest scalar type that divides the total loaded size.
13562   MVT SclrLoadTy = MVT::i8;
13563   for (MVT Tp : MVT::integer_valuetypes()) {
13564     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13565       SclrLoadTy = Tp;
13566     }
13567   }
13568
13569   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13570   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13571       (64 <= MemSz))
13572     SclrLoadTy = MVT::f64;
13573
13574   // Calculate the number of scalar loads that we need to perform
13575   // in order to load our vector from memory.
13576   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13577
13578   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13579          "Can only lower sext loads with a single scalar load!");
13580
13581   unsigned loadRegZize = RegSz;
13582   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13583     loadRegZize /= 2;
13584
13585   // Represent our vector as a sequence of elements which are the
13586   // largest scalar that we can load.
13587   EVT LoadUnitVecVT = EVT::getVectorVT(
13588       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13589
13590   // Represent the data using the same element type that is stored in
13591   // memory. In practice, we ''widen'' MemVT.
13592   EVT WideVecVT =
13593       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13594                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13595
13596   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13597          "Invalid vector type");
13598
13599   // We can't shuffle using an illegal type.
13600   assert(TLI.isTypeLegal(WideVecVT) &&
13601          "We only lower types that form legal widened vector types");
13602
13603   SmallVector<SDValue, 8> Chains;
13604   SDValue Ptr = Ld->getBasePtr();
13605   SDValue Increment =
13606       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13607   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13608
13609   for (unsigned i = 0; i < NumLoads; ++i) {
13610     // Perform a single load.
13611     SDValue ScalarLoad =
13612         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13613                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13614                     Ld->getAlignment());
13615     Chains.push_back(ScalarLoad.getValue(1));
13616     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13617     // another round of DAGCombining.
13618     if (i == 0)
13619       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13620     else
13621       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13622                         ScalarLoad, DAG.getIntPtrConstant(i));
13623
13624     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13625   }
13626
13627   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13628
13629   // Bitcast the loaded value to a vector of the original element type, in
13630   // the size of the target vector type.
13631   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13632   unsigned SizeRatio = RegSz / MemSz;
13633
13634   if (Ext == ISD::SEXTLOAD) {
13635     // If we have SSE4.1, we can directly emit a VSEXT node.
13636     if (Subtarget->hasSSE41()) {
13637       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13638       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13639       return Sext;
13640     }
13641
13642     // Otherwise we'll shuffle the small elements in the high bits of the
13643     // larger type and perform an arithmetic shift. If the shift is not legal
13644     // it's better to scalarize.
13645     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13646            "We can't implement a sext load without an arithmetic right shift!");
13647
13648     // Redistribute the loaded elements into the different locations.
13649     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13650     for (unsigned i = 0; i != NumElems; ++i)
13651       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13652
13653     SDValue Shuff = DAG.getVectorShuffle(
13654         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13655
13656     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13657
13658     // Build the arithmetic shift.
13659     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13660                    MemVT.getVectorElementType().getSizeInBits();
13661     Shuff =
13662         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13663
13664     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13665     return Shuff;
13666   }
13667
13668   // Redistribute the loaded elements into the different locations.
13669   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13670   for (unsigned i = 0; i != NumElems; ++i)
13671     ShuffleVec[i * SizeRatio] = i;
13672
13673   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13674                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13675
13676   // Bitcast to the requested type.
13677   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13678   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13679   return Shuff;
13680 }
13681
13682 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13683 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13684 // from the AND / OR.
13685 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13686   Opc = Op.getOpcode();
13687   if (Opc != ISD::OR && Opc != ISD::AND)
13688     return false;
13689   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13690           Op.getOperand(0).hasOneUse() &&
13691           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13692           Op.getOperand(1).hasOneUse());
13693 }
13694
13695 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13696 // 1 and that the SETCC node has a single use.
13697 static bool isXor1OfSetCC(SDValue Op) {
13698   if (Op.getOpcode() != ISD::XOR)
13699     return false;
13700   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13701   if (N1C && N1C->getAPIntValue() == 1) {
13702     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13703       Op.getOperand(0).hasOneUse();
13704   }
13705   return false;
13706 }
13707
13708 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13709   bool addTest = true;
13710   SDValue Chain = Op.getOperand(0);
13711   SDValue Cond  = Op.getOperand(1);
13712   SDValue Dest  = Op.getOperand(2);
13713   SDLoc dl(Op);
13714   SDValue CC;
13715   bool Inverted = false;
13716
13717   if (Cond.getOpcode() == ISD::SETCC) {
13718     // Check for setcc([su]{add,sub,mul}o == 0).
13719     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13720         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13721         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13722         Cond.getOperand(0).getResNo() == 1 &&
13723         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13724          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13725          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13726          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13727          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13728          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13729       Inverted = true;
13730       Cond = Cond.getOperand(0);
13731     } else {
13732       SDValue NewCond = LowerSETCC(Cond, DAG);
13733       if (NewCond.getNode())
13734         Cond = NewCond;
13735     }
13736   }
13737 #if 0
13738   // FIXME: LowerXALUO doesn't handle these!!
13739   else if (Cond.getOpcode() == X86ISD::ADD  ||
13740            Cond.getOpcode() == X86ISD::SUB  ||
13741            Cond.getOpcode() == X86ISD::SMUL ||
13742            Cond.getOpcode() == X86ISD::UMUL)
13743     Cond = LowerXALUO(Cond, DAG);
13744 #endif
13745
13746   // Look pass (and (setcc_carry (cmp ...)), 1).
13747   if (Cond.getOpcode() == ISD::AND &&
13748       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13749     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13750     if (C && C->getAPIntValue() == 1)
13751       Cond = Cond.getOperand(0);
13752   }
13753
13754   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13755   // setting operand in place of the X86ISD::SETCC.
13756   unsigned CondOpcode = Cond.getOpcode();
13757   if (CondOpcode == X86ISD::SETCC ||
13758       CondOpcode == X86ISD::SETCC_CARRY) {
13759     CC = Cond.getOperand(0);
13760
13761     SDValue Cmp = Cond.getOperand(1);
13762     unsigned Opc = Cmp.getOpcode();
13763     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13764     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13765       Cond = Cmp;
13766       addTest = false;
13767     } else {
13768       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13769       default: break;
13770       case X86::COND_O:
13771       case X86::COND_B:
13772         // These can only come from an arithmetic instruction with overflow,
13773         // e.g. SADDO, UADDO.
13774         Cond = Cond.getNode()->getOperand(1);
13775         addTest = false;
13776         break;
13777       }
13778     }
13779   }
13780   CondOpcode = Cond.getOpcode();
13781   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13782       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13783       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13784        Cond.getOperand(0).getValueType() != MVT::i8)) {
13785     SDValue LHS = Cond.getOperand(0);
13786     SDValue RHS = Cond.getOperand(1);
13787     unsigned X86Opcode;
13788     unsigned X86Cond;
13789     SDVTList VTs;
13790     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13791     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13792     // X86ISD::INC).
13793     switch (CondOpcode) {
13794     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13795     case ISD::SADDO:
13796       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13797         if (C->isOne()) {
13798           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13799           break;
13800         }
13801       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13802     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13803     case ISD::SSUBO:
13804       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13805         if (C->isOne()) {
13806           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13807           break;
13808         }
13809       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13810     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13811     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13812     default: llvm_unreachable("unexpected overflowing operator");
13813     }
13814     if (Inverted)
13815       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13816     if (CondOpcode == ISD::UMULO)
13817       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13818                           MVT::i32);
13819     else
13820       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13821
13822     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13823
13824     if (CondOpcode == ISD::UMULO)
13825       Cond = X86Op.getValue(2);
13826     else
13827       Cond = X86Op.getValue(1);
13828
13829     CC = DAG.getConstant(X86Cond, MVT::i8);
13830     addTest = false;
13831   } else {
13832     unsigned CondOpc;
13833     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13834       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13835       if (CondOpc == ISD::OR) {
13836         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13837         // two branches instead of an explicit OR instruction with a
13838         // separate test.
13839         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13840             isX86LogicalCmp(Cmp)) {
13841           CC = Cond.getOperand(0).getOperand(0);
13842           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13843                               Chain, Dest, CC, Cmp);
13844           CC = Cond.getOperand(1).getOperand(0);
13845           Cond = Cmp;
13846           addTest = false;
13847         }
13848       } else { // ISD::AND
13849         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13850         // two branches instead of an explicit AND instruction with a
13851         // separate test. However, we only do this if this block doesn't
13852         // have a fall-through edge, because this requires an explicit
13853         // jmp when the condition is false.
13854         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13855             isX86LogicalCmp(Cmp) &&
13856             Op.getNode()->hasOneUse()) {
13857           X86::CondCode CCode =
13858             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13859           CCode = X86::GetOppositeBranchCondition(CCode);
13860           CC = DAG.getConstant(CCode, MVT::i8);
13861           SDNode *User = *Op.getNode()->use_begin();
13862           // Look for an unconditional branch following this conditional branch.
13863           // We need this because we need to reverse the successors in order
13864           // to implement FCMP_OEQ.
13865           if (User->getOpcode() == ISD::BR) {
13866             SDValue FalseBB = User->getOperand(1);
13867             SDNode *NewBR =
13868               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13869             assert(NewBR == User);
13870             (void)NewBR;
13871             Dest = FalseBB;
13872
13873             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13874                                 Chain, Dest, CC, Cmp);
13875             X86::CondCode CCode =
13876               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13877             CCode = X86::GetOppositeBranchCondition(CCode);
13878             CC = DAG.getConstant(CCode, MVT::i8);
13879             Cond = Cmp;
13880             addTest = false;
13881           }
13882         }
13883       }
13884     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13885       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13886       // It should be transformed during dag combiner except when the condition
13887       // is set by a arithmetics with overflow node.
13888       X86::CondCode CCode =
13889         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13890       CCode = X86::GetOppositeBranchCondition(CCode);
13891       CC = DAG.getConstant(CCode, MVT::i8);
13892       Cond = Cond.getOperand(0).getOperand(1);
13893       addTest = false;
13894     } else if (Cond.getOpcode() == ISD::SETCC &&
13895                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13896       // For FCMP_OEQ, we can emit
13897       // two branches instead of an explicit AND instruction with a
13898       // separate test. However, we only do this if this block doesn't
13899       // have a fall-through edge, because this requires an explicit
13900       // jmp when the condition is false.
13901       if (Op.getNode()->hasOneUse()) {
13902         SDNode *User = *Op.getNode()->use_begin();
13903         // Look for an unconditional branch following this conditional branch.
13904         // We need this because we need to reverse the successors in order
13905         // to implement FCMP_OEQ.
13906         if (User->getOpcode() == ISD::BR) {
13907           SDValue FalseBB = User->getOperand(1);
13908           SDNode *NewBR =
13909             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13910           assert(NewBR == User);
13911           (void)NewBR;
13912           Dest = FalseBB;
13913
13914           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13915                                     Cond.getOperand(0), Cond.getOperand(1));
13916           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13917           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13918           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13919                               Chain, Dest, CC, Cmp);
13920           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13921           Cond = Cmp;
13922           addTest = false;
13923         }
13924       }
13925     } else if (Cond.getOpcode() == ISD::SETCC &&
13926                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13927       // For FCMP_UNE, we can emit
13928       // two branches instead of an explicit AND instruction with a
13929       // separate test. However, we only do this if this block doesn't
13930       // have a fall-through edge, because this requires an explicit
13931       // jmp when the condition is false.
13932       if (Op.getNode()->hasOneUse()) {
13933         SDNode *User = *Op.getNode()->use_begin();
13934         // Look for an unconditional branch following this conditional branch.
13935         // We need this because we need to reverse the successors in order
13936         // to implement FCMP_UNE.
13937         if (User->getOpcode() == ISD::BR) {
13938           SDValue FalseBB = User->getOperand(1);
13939           SDNode *NewBR =
13940             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13941           assert(NewBR == User);
13942           (void)NewBR;
13943
13944           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13945                                     Cond.getOperand(0), Cond.getOperand(1));
13946           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13947           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13948           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13949                               Chain, Dest, CC, Cmp);
13950           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13951           Cond = Cmp;
13952           addTest = false;
13953           Dest = FalseBB;
13954         }
13955       }
13956     }
13957   }
13958
13959   if (addTest) {
13960     // Look pass the truncate if the high bits are known zero.
13961     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13962         Cond = Cond.getOperand(0);
13963
13964     // We know the result of AND is compared against zero. Try to match
13965     // it to BT.
13966     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13967       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13968       if (NewSetCC.getNode()) {
13969         CC = NewSetCC.getOperand(0);
13970         Cond = NewSetCC.getOperand(1);
13971         addTest = false;
13972       }
13973     }
13974   }
13975
13976   if (addTest) {
13977     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13978     CC = DAG.getConstant(X86Cond, MVT::i8);
13979     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13980   }
13981   Cond = ConvertCmpIfNecessary(Cond, DAG);
13982   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13983                      Chain, Dest, CC, Cond);
13984 }
13985
13986 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13987 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13988 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13989 // that the guard pages used by the OS virtual memory manager are allocated in
13990 // correct sequence.
13991 SDValue
13992 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13993                                            SelectionDAG &DAG) const {
13994   MachineFunction &MF = DAG.getMachineFunction();
13995   bool SplitStack = MF.shouldSplitStack();
13996   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
13997                SplitStack;
13998   SDLoc dl(Op);
13999
14000   if (!Lower) {
14001     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14002     SDNode* Node = Op.getNode();
14003
14004     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14005     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14006         " not tell us which reg is the stack pointer!");
14007     EVT VT = Node->getValueType(0);
14008     SDValue Tmp1 = SDValue(Node, 0);
14009     SDValue Tmp2 = SDValue(Node, 1);
14010     SDValue Tmp3 = Node->getOperand(2);
14011     SDValue Chain = Tmp1.getOperand(0);
14012
14013     // Chain the dynamic stack allocation so that it doesn't modify the stack
14014     // pointer when other instructions are using the stack.
14015     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14016         SDLoc(Node));
14017
14018     SDValue Size = Tmp2.getOperand(1);
14019     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14020     Chain = SP.getValue(1);
14021     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14022     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14023     unsigned StackAlign = TFI.getStackAlignment();
14024     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14025     if (Align > StackAlign)
14026       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14027           DAG.getConstant(-(uint64_t)Align, VT));
14028     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14029
14030     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14031         DAG.getIntPtrConstant(0, true), SDValue(),
14032         SDLoc(Node));
14033
14034     SDValue Ops[2] = { Tmp1, Tmp2 };
14035     return DAG.getMergeValues(Ops, dl);
14036   }
14037
14038   // Get the inputs.
14039   SDValue Chain = Op.getOperand(0);
14040   SDValue Size  = Op.getOperand(1);
14041   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14042   EVT VT = Op.getNode()->getValueType(0);
14043
14044   bool Is64Bit = Subtarget->is64Bit();
14045   EVT SPTy = getPointerTy();
14046
14047   if (SplitStack) {
14048     MachineRegisterInfo &MRI = MF.getRegInfo();
14049
14050     if (Is64Bit) {
14051       // The 64 bit implementation of segmented stacks needs to clobber both r10
14052       // r11. This makes it impossible to use it along with nested parameters.
14053       const Function *F = MF.getFunction();
14054
14055       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14056            I != E; ++I)
14057         if (I->hasNestAttr())
14058           report_fatal_error("Cannot use segmented stacks with functions that "
14059                              "have nested arguments.");
14060     }
14061
14062     const TargetRegisterClass *AddrRegClass =
14063       getRegClassFor(getPointerTy());
14064     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14065     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14066     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14067                                 DAG.getRegister(Vreg, SPTy));
14068     SDValue Ops1[2] = { Value, Chain };
14069     return DAG.getMergeValues(Ops1, dl);
14070   } else {
14071     SDValue Flag;
14072     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14073
14074     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14075     Flag = Chain.getValue(1);
14076     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14077
14078     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14079
14080     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14081     unsigned SPReg = RegInfo->getStackRegister();
14082     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14083     Chain = SP.getValue(1);
14084
14085     if (Align) {
14086       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14087                        DAG.getConstant(-(uint64_t)Align, VT));
14088       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14089     }
14090
14091     SDValue Ops1[2] = { SP, Chain };
14092     return DAG.getMergeValues(Ops1, dl);
14093   }
14094 }
14095
14096 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14097   MachineFunction &MF = DAG.getMachineFunction();
14098   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14099
14100   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14101   SDLoc DL(Op);
14102
14103   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14104     // vastart just stores the address of the VarArgsFrameIndex slot into the
14105     // memory location argument.
14106     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14107                                    getPointerTy());
14108     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14109                         MachinePointerInfo(SV), false, false, 0);
14110   }
14111
14112   // __va_list_tag:
14113   //   gp_offset         (0 - 6 * 8)
14114   //   fp_offset         (48 - 48 + 8 * 16)
14115   //   overflow_arg_area (point to parameters coming in memory).
14116   //   reg_save_area
14117   SmallVector<SDValue, 8> MemOps;
14118   SDValue FIN = Op.getOperand(1);
14119   // Store gp_offset
14120   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14121                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14122                                                MVT::i32),
14123                                FIN, MachinePointerInfo(SV), false, false, 0);
14124   MemOps.push_back(Store);
14125
14126   // Store fp_offset
14127   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14128                     FIN, DAG.getIntPtrConstant(4));
14129   Store = DAG.getStore(Op.getOperand(0), DL,
14130                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14131                                        MVT::i32),
14132                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14133   MemOps.push_back(Store);
14134
14135   // Store ptr to overflow_arg_area
14136   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14137                     FIN, DAG.getIntPtrConstant(4));
14138   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14139                                     getPointerTy());
14140   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14141                        MachinePointerInfo(SV, 8),
14142                        false, false, 0);
14143   MemOps.push_back(Store);
14144
14145   // Store ptr to reg_save_area.
14146   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14147                     FIN, DAG.getIntPtrConstant(8));
14148   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14149                                     getPointerTy());
14150   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14151                        MachinePointerInfo(SV, 16), false, false, 0);
14152   MemOps.push_back(Store);
14153   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14154 }
14155
14156 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14157   assert(Subtarget->is64Bit() &&
14158          "LowerVAARG only handles 64-bit va_arg!");
14159   assert((Subtarget->isTargetLinux() ||
14160           Subtarget->isTargetDarwin()) &&
14161           "Unhandled target in LowerVAARG");
14162   assert(Op.getNode()->getNumOperands() == 4);
14163   SDValue Chain = Op.getOperand(0);
14164   SDValue SrcPtr = Op.getOperand(1);
14165   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14166   unsigned Align = Op.getConstantOperandVal(3);
14167   SDLoc dl(Op);
14168
14169   EVT ArgVT = Op.getNode()->getValueType(0);
14170   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14171   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14172   uint8_t ArgMode;
14173
14174   // Decide which area this value should be read from.
14175   // TODO: Implement the AMD64 ABI in its entirety. This simple
14176   // selection mechanism works only for the basic types.
14177   if (ArgVT == MVT::f80) {
14178     llvm_unreachable("va_arg for f80 not yet implemented");
14179   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14180     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14181   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14182     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14183   } else {
14184     llvm_unreachable("Unhandled argument type in LowerVAARG");
14185   }
14186
14187   if (ArgMode == 2) {
14188     // Sanity Check: Make sure using fp_offset makes sense.
14189     assert(!DAG.getTarget().Options.UseSoftFloat &&
14190            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14191                Attribute::NoImplicitFloat)) &&
14192            Subtarget->hasSSE1());
14193   }
14194
14195   // Insert VAARG_64 node into the DAG
14196   // VAARG_64 returns two values: Variable Argument Address, Chain
14197   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14198                        DAG.getConstant(ArgMode, MVT::i8),
14199                        DAG.getConstant(Align, MVT::i32)};
14200   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14201   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14202                                           VTs, InstOps, MVT::i64,
14203                                           MachinePointerInfo(SV),
14204                                           /*Align=*/0,
14205                                           /*Volatile=*/false,
14206                                           /*ReadMem=*/true,
14207                                           /*WriteMem=*/true);
14208   Chain = VAARG.getValue(1);
14209
14210   // Load the next argument and return it
14211   return DAG.getLoad(ArgVT, dl,
14212                      Chain,
14213                      VAARG,
14214                      MachinePointerInfo(),
14215                      false, false, false, 0);
14216 }
14217
14218 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14219                            SelectionDAG &DAG) {
14220   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14221   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14222   SDValue Chain = Op.getOperand(0);
14223   SDValue DstPtr = Op.getOperand(1);
14224   SDValue SrcPtr = Op.getOperand(2);
14225   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14226   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14227   SDLoc DL(Op);
14228
14229   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14230                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14231                        false,
14232                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14233 }
14234
14235 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14236 // amount is a constant. Takes immediate version of shift as input.
14237 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14238                                           SDValue SrcOp, uint64_t ShiftAmt,
14239                                           SelectionDAG &DAG) {
14240   MVT ElementType = VT.getVectorElementType();
14241
14242   // Fold this packed shift into its first operand if ShiftAmt is 0.
14243   if (ShiftAmt == 0)
14244     return SrcOp;
14245
14246   // Check for ShiftAmt >= element width
14247   if (ShiftAmt >= ElementType.getSizeInBits()) {
14248     if (Opc == X86ISD::VSRAI)
14249       ShiftAmt = ElementType.getSizeInBits() - 1;
14250     else
14251       return DAG.getConstant(0, VT);
14252   }
14253
14254   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14255          && "Unknown target vector shift-by-constant node");
14256
14257   // Fold this packed vector shift into a build vector if SrcOp is a
14258   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14259   if (VT == SrcOp.getSimpleValueType() &&
14260       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14261     SmallVector<SDValue, 8> Elts;
14262     unsigned NumElts = SrcOp->getNumOperands();
14263     ConstantSDNode *ND;
14264
14265     switch(Opc) {
14266     default: llvm_unreachable(nullptr);
14267     case X86ISD::VSHLI:
14268       for (unsigned i=0; i!=NumElts; ++i) {
14269         SDValue CurrentOp = SrcOp->getOperand(i);
14270         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14271           Elts.push_back(CurrentOp);
14272           continue;
14273         }
14274         ND = cast<ConstantSDNode>(CurrentOp);
14275         const APInt &C = ND->getAPIntValue();
14276         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14277       }
14278       break;
14279     case X86ISD::VSRLI:
14280       for (unsigned i=0; i!=NumElts; ++i) {
14281         SDValue CurrentOp = SrcOp->getOperand(i);
14282         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14283           Elts.push_back(CurrentOp);
14284           continue;
14285         }
14286         ND = cast<ConstantSDNode>(CurrentOp);
14287         const APInt &C = ND->getAPIntValue();
14288         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14289       }
14290       break;
14291     case X86ISD::VSRAI:
14292       for (unsigned i=0; i!=NumElts; ++i) {
14293         SDValue CurrentOp = SrcOp->getOperand(i);
14294         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14295           Elts.push_back(CurrentOp);
14296           continue;
14297         }
14298         ND = cast<ConstantSDNode>(CurrentOp);
14299         const APInt &C = ND->getAPIntValue();
14300         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14301       }
14302       break;
14303     }
14304
14305     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14306   }
14307
14308   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14309 }
14310
14311 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14312 // may or may not be a constant. Takes immediate version of shift as input.
14313 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14314                                    SDValue SrcOp, SDValue ShAmt,
14315                                    SelectionDAG &DAG) {
14316   MVT SVT = ShAmt.getSimpleValueType();
14317   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14318
14319   // Catch shift-by-constant.
14320   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14321     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14322                                       CShAmt->getZExtValue(), DAG);
14323
14324   // Change opcode to non-immediate version
14325   switch (Opc) {
14326     default: llvm_unreachable("Unknown target vector shift node");
14327     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14328     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14329     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14330   }
14331
14332   const X86Subtarget &Subtarget =
14333       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14334   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14335       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14336     // Let the shuffle legalizer expand this shift amount node.
14337     SDValue Op0 = ShAmt.getOperand(0);
14338     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14339     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14340   } else {
14341     // Need to build a vector containing shift amount.
14342     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14343     SmallVector<SDValue, 4> ShOps;
14344     ShOps.push_back(ShAmt);
14345     if (SVT == MVT::i32) {
14346       ShOps.push_back(DAG.getConstant(0, SVT));
14347       ShOps.push_back(DAG.getUNDEF(SVT));
14348     }
14349     ShOps.push_back(DAG.getUNDEF(SVT));
14350
14351     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14352     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14353   }
14354
14355   // The return type has to be a 128-bit type with the same element
14356   // type as the input type.
14357   MVT EltVT = VT.getVectorElementType();
14358   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14359
14360   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14361   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14362 }
14363
14364 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14365 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14366 /// necessary casting for \p Mask when lowering masking intrinsics.
14367 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14368                                     SDValue PreservedSrc,
14369                                     const X86Subtarget *Subtarget,
14370                                     SelectionDAG &DAG) {
14371     EVT VT = Op.getValueType();
14372     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14373                                   MVT::i1, VT.getVectorNumElements());
14374     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14375                                      Mask.getValueType().getSizeInBits());
14376     SDLoc dl(Op);
14377
14378     assert(MaskVT.isSimple() && "invalid mask type");
14379
14380     if (isAllOnes(Mask))
14381       return Op;
14382
14383     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14384     // are extracted by EXTRACT_SUBVECTOR.
14385     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14386                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14387                               DAG.getIntPtrConstant(0));
14388
14389     switch (Op.getOpcode()) {
14390       default: break;
14391       case X86ISD::PCMPEQM:
14392       case X86ISD::PCMPGTM:
14393       case X86ISD::CMPM:
14394       case X86ISD::CMPMU:
14395         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14396     }
14397     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14398       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14399     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14400 }
14401
14402 /// \brief Creates an SDNode for a predicated scalar operation.
14403 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14404 /// The mask is comming as MVT::i8 and it should be truncated
14405 /// to MVT::i1 while lowering masking intrinsics.
14406 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14407 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14408 /// a scalar instruction.
14409 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14410                                     SDValue PreservedSrc,
14411                                     const X86Subtarget *Subtarget,
14412                                     SelectionDAG &DAG) {
14413     if (isAllOnes(Mask))
14414       return Op;
14415
14416     EVT VT = Op.getValueType();
14417     SDLoc dl(Op);
14418     // The mask should be of type MVT::i1
14419     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14420
14421     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14422       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14423     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14424 }
14425
14426 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14427                                        SelectionDAG &DAG) {
14428   SDLoc dl(Op);
14429   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14430   EVT VT = Op.getValueType();
14431   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14432   if (IntrData) {
14433     switch(IntrData->Type) {
14434     case INTR_TYPE_1OP:
14435       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14436     case INTR_TYPE_2OP:
14437       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14438         Op.getOperand(2));
14439     case INTR_TYPE_3OP:
14440       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14441         Op.getOperand(2), Op.getOperand(3));
14442     case INTR_TYPE_1OP_MASK_RM: {
14443       SDValue Src = Op.getOperand(1);
14444       SDValue Src0 = Op.getOperand(2);
14445       SDValue Mask = Op.getOperand(3);
14446       SDValue RoundingMode = Op.getOperand(4);
14447       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14448                                               RoundingMode),
14449                                   Mask, Src0, Subtarget, DAG);
14450     }
14451     case INTR_TYPE_SCALAR_MASK_RM: {
14452       SDValue Src1 = Op.getOperand(1);
14453       SDValue Src2 = Op.getOperand(2);
14454       SDValue Src0 = Op.getOperand(3);
14455       SDValue Mask = Op.getOperand(4);
14456       // There are 2 kinds of intrinsics in this group:
14457       // (1) With supress-all-exceptions (sae) - 6 operands
14458       // (2) With rounding mode and sae - 7 operands.
14459       if (Op.getNumOperands() == 6) {
14460         SDValue Sae  = Op.getOperand(5);
14461         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14462                                                 Sae),
14463                                     Mask, Src0, Subtarget, DAG);
14464       }
14465       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14466       SDValue RoundingMode  = Op.getOperand(5);
14467       SDValue Sae  = Op.getOperand(6);
14468       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14469                                               RoundingMode, Sae),
14470                                   Mask, Src0, Subtarget, DAG);
14471     }
14472     case INTR_TYPE_2OP_MASK: {
14473       SDValue Src1 = Op.getOperand(1);
14474       SDValue Src2 = Op.getOperand(2);
14475       SDValue PassThru = Op.getOperand(3);
14476       SDValue Mask = Op.getOperand(4);
14477       // We specify 2 possible opcodes for intrinsics with rounding modes.
14478       // First, we check if the intrinsic may have non-default rounding mode,
14479       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14480       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14481       if (IntrWithRoundingModeOpcode != 0) {
14482         SDValue Rnd = Op.getOperand(5);
14483         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14484         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14485           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14486                                       dl, Op.getValueType(),
14487                                       Src1, Src2, Rnd),
14488                                       Mask, PassThru, Subtarget, DAG);
14489         }
14490       }
14491       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14492                                               Src1,Src2),
14493                                   Mask, PassThru, Subtarget, DAG);
14494     }
14495     case FMA_OP_MASK: {
14496       SDValue Src1 = Op.getOperand(1);
14497       SDValue Src2 = Op.getOperand(2);
14498       SDValue Src3 = Op.getOperand(3);
14499       SDValue Mask = Op.getOperand(4);
14500       // We specify 2 possible opcodes for intrinsics with rounding modes.
14501       // First, we check if the intrinsic may have non-default rounding mode,
14502       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14503       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14504       if (IntrWithRoundingModeOpcode != 0) {
14505         SDValue Rnd = Op.getOperand(5);
14506         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14507             X86::STATIC_ROUNDING::CUR_DIRECTION)
14508           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14509                                                   dl, Op.getValueType(),
14510                                                   Src1, Src2, Src3, Rnd),
14511                                       Mask, Src1, Subtarget, DAG);
14512       }
14513       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14514                                               dl, Op.getValueType(),
14515                                               Src1, Src2, Src3),
14516                                   Mask, Src1, Subtarget, DAG);
14517     }
14518     case CMP_MASK:
14519     case CMP_MASK_CC: {
14520       // Comparison intrinsics with masks.
14521       // Example of transformation:
14522       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14523       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14524       // (i8 (bitcast
14525       //   (v8i1 (insert_subvector undef,
14526       //           (v2i1 (and (PCMPEQM %a, %b),
14527       //                      (extract_subvector
14528       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14529       EVT VT = Op.getOperand(1).getValueType();
14530       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14531                                     VT.getVectorNumElements());
14532       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14533       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14534                                        Mask.getValueType().getSizeInBits());
14535       SDValue Cmp;
14536       if (IntrData->Type == CMP_MASK_CC) {
14537         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14538                     Op.getOperand(2), Op.getOperand(3));
14539       } else {
14540         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14541         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14542                     Op.getOperand(2));
14543       }
14544       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14545                                              DAG.getTargetConstant(0, MaskVT),
14546                                              Subtarget, DAG);
14547       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14548                                 DAG.getUNDEF(BitcastVT), CmpMask,
14549                                 DAG.getIntPtrConstant(0));
14550       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14551     }
14552     case COMI: { // Comparison intrinsics
14553       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14554       SDValue LHS = Op.getOperand(1);
14555       SDValue RHS = Op.getOperand(2);
14556       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14557       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14558       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14559       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14560                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14561       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14562     }
14563     case VSHIFT:
14564       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14565                                  Op.getOperand(1), Op.getOperand(2), DAG);
14566     case VSHIFT_MASK:
14567       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14568                                                       Op.getSimpleValueType(),
14569                                                       Op.getOperand(1),
14570                                                       Op.getOperand(2), DAG),
14571                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14572                                   DAG);
14573     case COMPRESS_EXPAND_IN_REG: {
14574       SDValue Mask = Op.getOperand(3);
14575       SDValue DataToCompress = Op.getOperand(1);
14576       SDValue PassThru = Op.getOperand(2);
14577       if (isAllOnes(Mask)) // return data as is
14578         return Op.getOperand(1);
14579       EVT VT = Op.getValueType();
14580       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14581                                     VT.getVectorNumElements());
14582       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14583                                        Mask.getValueType().getSizeInBits());
14584       SDLoc dl(Op);
14585       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14586                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14587                                   DAG.getIntPtrConstant(0));
14588
14589       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14590                          PassThru);
14591     }
14592     case BLEND: {
14593       SDValue Mask = Op.getOperand(3);
14594       EVT VT = Op.getValueType();
14595       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14596                                     VT.getVectorNumElements());
14597       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14598                                        Mask.getValueType().getSizeInBits());
14599       SDLoc dl(Op);
14600       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14601                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14602                                   DAG.getIntPtrConstant(0));
14603       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14604                          Op.getOperand(2));
14605     }
14606     default:
14607       break;
14608     }
14609   }
14610
14611   switch (IntNo) {
14612   default: return SDValue();    // Don't custom lower most intrinsics.
14613
14614   case Intrinsic::x86_avx512_mask_valign_q_512:
14615   case Intrinsic::x86_avx512_mask_valign_d_512:
14616     // Vector source operands are swapped.
14617     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14618                                             Op.getValueType(), Op.getOperand(2),
14619                                             Op.getOperand(1),
14620                                             Op.getOperand(3)),
14621                                 Op.getOperand(5), Op.getOperand(4),
14622                                 Subtarget, DAG);
14623
14624   // ptest and testp intrinsics. The intrinsic these come from are designed to
14625   // return an integer value, not just an instruction so lower it to the ptest
14626   // or testp pattern and a setcc for the result.
14627   case Intrinsic::x86_sse41_ptestz:
14628   case Intrinsic::x86_sse41_ptestc:
14629   case Intrinsic::x86_sse41_ptestnzc:
14630   case Intrinsic::x86_avx_ptestz_256:
14631   case Intrinsic::x86_avx_ptestc_256:
14632   case Intrinsic::x86_avx_ptestnzc_256:
14633   case Intrinsic::x86_avx_vtestz_ps:
14634   case Intrinsic::x86_avx_vtestc_ps:
14635   case Intrinsic::x86_avx_vtestnzc_ps:
14636   case Intrinsic::x86_avx_vtestz_pd:
14637   case Intrinsic::x86_avx_vtestc_pd:
14638   case Intrinsic::x86_avx_vtestnzc_pd:
14639   case Intrinsic::x86_avx_vtestz_ps_256:
14640   case Intrinsic::x86_avx_vtestc_ps_256:
14641   case Intrinsic::x86_avx_vtestnzc_ps_256:
14642   case Intrinsic::x86_avx_vtestz_pd_256:
14643   case Intrinsic::x86_avx_vtestc_pd_256:
14644   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14645     bool IsTestPacked = false;
14646     unsigned X86CC;
14647     switch (IntNo) {
14648     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14649     case Intrinsic::x86_avx_vtestz_ps:
14650     case Intrinsic::x86_avx_vtestz_pd:
14651     case Intrinsic::x86_avx_vtestz_ps_256:
14652     case Intrinsic::x86_avx_vtestz_pd_256:
14653       IsTestPacked = true; // Fallthrough
14654     case Intrinsic::x86_sse41_ptestz:
14655     case Intrinsic::x86_avx_ptestz_256:
14656       // ZF = 1
14657       X86CC = X86::COND_E;
14658       break;
14659     case Intrinsic::x86_avx_vtestc_ps:
14660     case Intrinsic::x86_avx_vtestc_pd:
14661     case Intrinsic::x86_avx_vtestc_ps_256:
14662     case Intrinsic::x86_avx_vtestc_pd_256:
14663       IsTestPacked = true; // Fallthrough
14664     case Intrinsic::x86_sse41_ptestc:
14665     case Intrinsic::x86_avx_ptestc_256:
14666       // CF = 1
14667       X86CC = X86::COND_B;
14668       break;
14669     case Intrinsic::x86_avx_vtestnzc_ps:
14670     case Intrinsic::x86_avx_vtestnzc_pd:
14671     case Intrinsic::x86_avx_vtestnzc_ps_256:
14672     case Intrinsic::x86_avx_vtestnzc_pd_256:
14673       IsTestPacked = true; // Fallthrough
14674     case Intrinsic::x86_sse41_ptestnzc:
14675     case Intrinsic::x86_avx_ptestnzc_256:
14676       // ZF and CF = 0
14677       X86CC = X86::COND_A;
14678       break;
14679     }
14680
14681     SDValue LHS = Op.getOperand(1);
14682     SDValue RHS = Op.getOperand(2);
14683     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14684     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14685     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14686     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14687     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14688   }
14689   case Intrinsic::x86_avx512_kortestz_w:
14690   case Intrinsic::x86_avx512_kortestc_w: {
14691     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14692     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14693     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14694     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14695     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14696     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14697     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14698   }
14699
14700   case Intrinsic::x86_sse42_pcmpistria128:
14701   case Intrinsic::x86_sse42_pcmpestria128:
14702   case Intrinsic::x86_sse42_pcmpistric128:
14703   case Intrinsic::x86_sse42_pcmpestric128:
14704   case Intrinsic::x86_sse42_pcmpistrio128:
14705   case Intrinsic::x86_sse42_pcmpestrio128:
14706   case Intrinsic::x86_sse42_pcmpistris128:
14707   case Intrinsic::x86_sse42_pcmpestris128:
14708   case Intrinsic::x86_sse42_pcmpistriz128:
14709   case Intrinsic::x86_sse42_pcmpestriz128: {
14710     unsigned Opcode;
14711     unsigned X86CC;
14712     switch (IntNo) {
14713     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14714     case Intrinsic::x86_sse42_pcmpistria128:
14715       Opcode = X86ISD::PCMPISTRI;
14716       X86CC = X86::COND_A;
14717       break;
14718     case Intrinsic::x86_sse42_pcmpestria128:
14719       Opcode = X86ISD::PCMPESTRI;
14720       X86CC = X86::COND_A;
14721       break;
14722     case Intrinsic::x86_sse42_pcmpistric128:
14723       Opcode = X86ISD::PCMPISTRI;
14724       X86CC = X86::COND_B;
14725       break;
14726     case Intrinsic::x86_sse42_pcmpestric128:
14727       Opcode = X86ISD::PCMPESTRI;
14728       X86CC = X86::COND_B;
14729       break;
14730     case Intrinsic::x86_sse42_pcmpistrio128:
14731       Opcode = X86ISD::PCMPISTRI;
14732       X86CC = X86::COND_O;
14733       break;
14734     case Intrinsic::x86_sse42_pcmpestrio128:
14735       Opcode = X86ISD::PCMPESTRI;
14736       X86CC = X86::COND_O;
14737       break;
14738     case Intrinsic::x86_sse42_pcmpistris128:
14739       Opcode = X86ISD::PCMPISTRI;
14740       X86CC = X86::COND_S;
14741       break;
14742     case Intrinsic::x86_sse42_pcmpestris128:
14743       Opcode = X86ISD::PCMPESTRI;
14744       X86CC = X86::COND_S;
14745       break;
14746     case Intrinsic::x86_sse42_pcmpistriz128:
14747       Opcode = X86ISD::PCMPISTRI;
14748       X86CC = X86::COND_E;
14749       break;
14750     case Intrinsic::x86_sse42_pcmpestriz128:
14751       Opcode = X86ISD::PCMPESTRI;
14752       X86CC = X86::COND_E;
14753       break;
14754     }
14755     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14756     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14757     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14758     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14759                                 DAG.getConstant(X86CC, MVT::i8),
14760                                 SDValue(PCMP.getNode(), 1));
14761     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14762   }
14763
14764   case Intrinsic::x86_sse42_pcmpistri128:
14765   case Intrinsic::x86_sse42_pcmpestri128: {
14766     unsigned Opcode;
14767     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14768       Opcode = X86ISD::PCMPISTRI;
14769     else
14770       Opcode = X86ISD::PCMPESTRI;
14771
14772     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14773     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14774     return DAG.getNode(Opcode, dl, VTs, NewOps);
14775   }
14776   }
14777 }
14778
14779 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14780                               SDValue Src, SDValue Mask, SDValue Base,
14781                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14782                               const X86Subtarget * Subtarget) {
14783   SDLoc dl(Op);
14784   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14785   assert(C && "Invalid scale type");
14786   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14787   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14788                              Index.getSimpleValueType().getVectorNumElements());
14789   SDValue MaskInReg;
14790   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14791   if (MaskC)
14792     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14793   else
14794     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14795   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14796   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14797   SDValue Segment = DAG.getRegister(0, MVT::i32);
14798   if (Src.getOpcode() == ISD::UNDEF)
14799     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14800   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14801   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14802   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14803   return DAG.getMergeValues(RetOps, dl);
14804 }
14805
14806 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14807                                SDValue Src, SDValue Mask, SDValue Base,
14808                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14809   SDLoc dl(Op);
14810   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14811   assert(C && "Invalid scale type");
14812   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14813   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14814   SDValue Segment = DAG.getRegister(0, MVT::i32);
14815   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14816                              Index.getSimpleValueType().getVectorNumElements());
14817   SDValue MaskInReg;
14818   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14819   if (MaskC)
14820     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14821   else
14822     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14823   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14824   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14825   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14826   return SDValue(Res, 1);
14827 }
14828
14829 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14830                                SDValue Mask, SDValue Base, SDValue Index,
14831                                SDValue ScaleOp, SDValue Chain) {
14832   SDLoc dl(Op);
14833   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14834   assert(C && "Invalid scale type");
14835   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14836   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14837   SDValue Segment = DAG.getRegister(0, MVT::i32);
14838   EVT MaskVT =
14839     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14840   SDValue MaskInReg;
14841   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14842   if (MaskC)
14843     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14844   else
14845     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14846   //SDVTList VTs = DAG.getVTList(MVT::Other);
14847   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14848   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14849   return SDValue(Res, 0);
14850 }
14851
14852 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14853 // read performance monitor counters (x86_rdpmc).
14854 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14855                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14856                               SmallVectorImpl<SDValue> &Results) {
14857   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14858   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14859   SDValue LO, HI;
14860
14861   // The ECX register is used to select the index of the performance counter
14862   // to read.
14863   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14864                                    N->getOperand(2));
14865   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14866
14867   // Reads the content of a 64-bit performance counter and returns it in the
14868   // registers EDX:EAX.
14869   if (Subtarget->is64Bit()) {
14870     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14871     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14872                             LO.getValue(2));
14873   } else {
14874     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14875     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14876                             LO.getValue(2));
14877   }
14878   Chain = HI.getValue(1);
14879
14880   if (Subtarget->is64Bit()) {
14881     // The EAX register is loaded with the low-order 32 bits. The EDX register
14882     // is loaded with the supported high-order bits of the counter.
14883     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14884                               DAG.getConstant(32, MVT::i8));
14885     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14886     Results.push_back(Chain);
14887     return;
14888   }
14889
14890   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14891   SDValue Ops[] = { LO, HI };
14892   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14893   Results.push_back(Pair);
14894   Results.push_back(Chain);
14895 }
14896
14897 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14898 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14899 // also used to custom lower READCYCLECOUNTER nodes.
14900 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14901                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14902                               SmallVectorImpl<SDValue> &Results) {
14903   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14904   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14905   SDValue LO, HI;
14906
14907   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14908   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14909   // and the EAX register is loaded with the low-order 32 bits.
14910   if (Subtarget->is64Bit()) {
14911     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14912     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14913                             LO.getValue(2));
14914   } else {
14915     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14916     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14917                             LO.getValue(2));
14918   }
14919   SDValue Chain = HI.getValue(1);
14920
14921   if (Opcode == X86ISD::RDTSCP_DAG) {
14922     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14923
14924     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14925     // the ECX register. Add 'ecx' explicitly to the chain.
14926     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14927                                      HI.getValue(2));
14928     // Explicitly store the content of ECX at the location passed in input
14929     // to the 'rdtscp' intrinsic.
14930     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14931                          MachinePointerInfo(), false, false, 0);
14932   }
14933
14934   if (Subtarget->is64Bit()) {
14935     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14936     // the EAX register is loaded with the low-order 32 bits.
14937     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14938                               DAG.getConstant(32, MVT::i8));
14939     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14940     Results.push_back(Chain);
14941     return;
14942   }
14943
14944   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14945   SDValue Ops[] = { LO, HI };
14946   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14947   Results.push_back(Pair);
14948   Results.push_back(Chain);
14949 }
14950
14951 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14952                                      SelectionDAG &DAG) {
14953   SmallVector<SDValue, 2> Results;
14954   SDLoc DL(Op);
14955   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14956                           Results);
14957   return DAG.getMergeValues(Results, DL);
14958 }
14959
14960
14961 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14962                                       SelectionDAG &DAG) {
14963   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14964
14965   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
14966   if (!IntrData)
14967     return SDValue();
14968
14969   SDLoc dl(Op);
14970   switch(IntrData->Type) {
14971   default:
14972     llvm_unreachable("Unknown Intrinsic Type");
14973     break;
14974   case RDSEED:
14975   case RDRAND: {
14976     // Emit the node with the right value type.
14977     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14978     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
14979
14980     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14981     // Otherwise return the value from Rand, which is always 0, casted to i32.
14982     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14983                       DAG.getConstant(1, Op->getValueType(1)),
14984                       DAG.getConstant(X86::COND_B, MVT::i32),
14985                       SDValue(Result.getNode(), 1) };
14986     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14987                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14988                                   Ops);
14989
14990     // Return { result, isValid, chain }.
14991     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14992                        SDValue(Result.getNode(), 2));
14993   }
14994   case GATHER: {
14995   //gather(v1, mask, index, base, scale);
14996     SDValue Chain = Op.getOperand(0);
14997     SDValue Src   = Op.getOperand(2);
14998     SDValue Base  = Op.getOperand(3);
14999     SDValue Index = Op.getOperand(4);
15000     SDValue Mask  = Op.getOperand(5);
15001     SDValue Scale = Op.getOperand(6);
15002     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15003                           Subtarget);
15004   }
15005   case SCATTER: {
15006   //scatter(base, mask, index, v1, scale);
15007     SDValue Chain = Op.getOperand(0);
15008     SDValue Base  = Op.getOperand(2);
15009     SDValue Mask  = Op.getOperand(3);
15010     SDValue Index = Op.getOperand(4);
15011     SDValue Src   = Op.getOperand(5);
15012     SDValue Scale = Op.getOperand(6);
15013     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15014   }
15015   case PREFETCH: {
15016     SDValue Hint = Op.getOperand(6);
15017     unsigned HintVal;
15018     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15019         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15020       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15021     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15022     SDValue Chain = Op.getOperand(0);
15023     SDValue Mask  = Op.getOperand(2);
15024     SDValue Index = Op.getOperand(3);
15025     SDValue Base  = Op.getOperand(4);
15026     SDValue Scale = Op.getOperand(5);
15027     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15028   }
15029   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15030   case RDTSC: {
15031     SmallVector<SDValue, 2> Results;
15032     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15033     return DAG.getMergeValues(Results, dl);
15034   }
15035   // Read Performance Monitoring Counters.
15036   case RDPMC: {
15037     SmallVector<SDValue, 2> Results;
15038     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15039     return DAG.getMergeValues(Results, dl);
15040   }
15041   // XTEST intrinsics.
15042   case XTEST: {
15043     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15044     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15045     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15046                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15047                                 InTrans);
15048     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15049     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15050                        Ret, SDValue(InTrans.getNode(), 1));
15051   }
15052   // ADC/ADCX/SBB
15053   case ADX: {
15054     SmallVector<SDValue, 2> Results;
15055     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15056     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15057     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15058                                 DAG.getConstant(-1, MVT::i8));
15059     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15060                               Op.getOperand(4), GenCF.getValue(1));
15061     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15062                                  Op.getOperand(5), MachinePointerInfo(),
15063                                  false, false, 0);
15064     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15065                                 DAG.getConstant(X86::COND_B, MVT::i8),
15066                                 Res.getValue(1));
15067     Results.push_back(SetCC);
15068     Results.push_back(Store);
15069     return DAG.getMergeValues(Results, dl);
15070   }
15071   case COMPRESS_TO_MEM: {
15072     SDLoc dl(Op);
15073     SDValue Mask = Op.getOperand(4);
15074     SDValue DataToCompress = Op.getOperand(3);
15075     SDValue Addr = Op.getOperand(2);
15076     SDValue Chain = Op.getOperand(0);
15077
15078     if (isAllOnes(Mask)) // return just a store
15079       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15080                           MachinePointerInfo(), false, false, 0);
15081
15082     EVT VT = DataToCompress.getValueType();
15083     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15084                                   VT.getVectorNumElements());
15085     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15086                                      Mask.getValueType().getSizeInBits());
15087     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15088                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15089                                 DAG.getIntPtrConstant(0));
15090
15091     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15092                                       DataToCompress, DAG.getUNDEF(VT));
15093     return DAG.getStore(Chain, dl, Compressed, Addr,
15094                         MachinePointerInfo(), false, false, 0);
15095   }
15096   case EXPAND_FROM_MEM: {
15097     SDLoc dl(Op);
15098     SDValue Mask = Op.getOperand(4);
15099     SDValue PathThru = Op.getOperand(3);
15100     SDValue Addr = Op.getOperand(2);
15101     SDValue Chain = Op.getOperand(0);
15102     EVT VT = Op.getValueType();
15103
15104     if (isAllOnes(Mask)) // return just a load
15105       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15106                          false, 0);
15107     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15108                                   VT.getVectorNumElements());
15109     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15110                                      Mask.getValueType().getSizeInBits());
15111     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15112                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15113                                 DAG.getIntPtrConstant(0));
15114
15115     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15116                                    false, false, false, 0);
15117
15118     SDValue Results[] = {
15119         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15120         Chain};
15121     return DAG.getMergeValues(Results, dl);
15122   }
15123   }
15124 }
15125
15126 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15127                                            SelectionDAG &DAG) const {
15128   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15129   MFI->setReturnAddressIsTaken(true);
15130
15131   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15132     return SDValue();
15133
15134   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15135   SDLoc dl(Op);
15136   EVT PtrVT = getPointerTy();
15137
15138   if (Depth > 0) {
15139     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15140     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15141     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15142     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15143                        DAG.getNode(ISD::ADD, dl, PtrVT,
15144                                    FrameAddr, Offset),
15145                        MachinePointerInfo(), false, false, false, 0);
15146   }
15147
15148   // Just load the return address.
15149   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15150   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15151                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15152 }
15153
15154 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15155   MachineFunction &MF = DAG.getMachineFunction();
15156   MachineFrameInfo *MFI = MF.getFrameInfo();
15157   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15158   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15159   EVT VT = Op.getValueType();
15160
15161   MFI->setFrameAddressIsTaken(true);
15162
15163   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15164     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15165     // is not possible to crawl up the stack without looking at the unwind codes
15166     // simultaneously.
15167     int FrameAddrIndex = FuncInfo->getFAIndex();
15168     if (!FrameAddrIndex) {
15169       // Set up a frame object for the return address.
15170       unsigned SlotSize = RegInfo->getSlotSize();
15171       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15172           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15173       FuncInfo->setFAIndex(FrameAddrIndex);
15174     }
15175     return DAG.getFrameIndex(FrameAddrIndex, VT);
15176   }
15177
15178   unsigned FrameReg =
15179       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15180   SDLoc dl(Op);  // FIXME probably not meaningful
15181   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15182   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15183           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15184          "Invalid Frame Register!");
15185   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15186   while (Depth--)
15187     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15188                             MachinePointerInfo(),
15189                             false, false, false, 0);
15190   return FrameAddr;
15191 }
15192
15193 // FIXME? Maybe this could be a TableGen attribute on some registers and
15194 // this table could be generated automatically from RegInfo.
15195 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15196                                               EVT VT) const {
15197   unsigned Reg = StringSwitch<unsigned>(RegName)
15198                        .Case("esp", X86::ESP)
15199                        .Case("rsp", X86::RSP)
15200                        .Default(0);
15201   if (Reg)
15202     return Reg;
15203   report_fatal_error("Invalid register name global variable");
15204 }
15205
15206 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15207                                                      SelectionDAG &DAG) const {
15208   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15209   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15210 }
15211
15212 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15213   SDValue Chain     = Op.getOperand(0);
15214   SDValue Offset    = Op.getOperand(1);
15215   SDValue Handler   = Op.getOperand(2);
15216   SDLoc dl      (Op);
15217
15218   EVT PtrVT = getPointerTy();
15219   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15220   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15221   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15222           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15223          "Invalid Frame Register!");
15224   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15225   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15226
15227   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15228                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15229   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15230   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15231                        false, false, 0);
15232   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15233
15234   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15235                      DAG.getRegister(StoreAddrReg, PtrVT));
15236 }
15237
15238 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15239                                                SelectionDAG &DAG) const {
15240   SDLoc DL(Op);
15241   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15242                      DAG.getVTList(MVT::i32, MVT::Other),
15243                      Op.getOperand(0), Op.getOperand(1));
15244 }
15245
15246 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15247                                                 SelectionDAG &DAG) const {
15248   SDLoc DL(Op);
15249   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15250                      Op.getOperand(0), Op.getOperand(1));
15251 }
15252
15253 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15254   return Op.getOperand(0);
15255 }
15256
15257 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15258                                                 SelectionDAG &DAG) const {
15259   SDValue Root = Op.getOperand(0);
15260   SDValue Trmp = Op.getOperand(1); // trampoline
15261   SDValue FPtr = Op.getOperand(2); // nested function
15262   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15263   SDLoc dl (Op);
15264
15265   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15266   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15267
15268   if (Subtarget->is64Bit()) {
15269     SDValue OutChains[6];
15270
15271     // Large code-model.
15272     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15273     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15274
15275     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15276     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15277
15278     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15279
15280     // Load the pointer to the nested function into R11.
15281     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15282     SDValue Addr = Trmp;
15283     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15284                                 Addr, MachinePointerInfo(TrmpAddr),
15285                                 false, false, 0);
15286
15287     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15288                        DAG.getConstant(2, MVT::i64));
15289     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15290                                 MachinePointerInfo(TrmpAddr, 2),
15291                                 false, false, 2);
15292
15293     // Load the 'nest' parameter value into R10.
15294     // R10 is specified in X86CallingConv.td
15295     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15296     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15297                        DAG.getConstant(10, MVT::i64));
15298     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15299                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15300                                 false, false, 0);
15301
15302     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15303                        DAG.getConstant(12, MVT::i64));
15304     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15305                                 MachinePointerInfo(TrmpAddr, 12),
15306                                 false, false, 2);
15307
15308     // Jump to the nested function.
15309     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15310     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15311                        DAG.getConstant(20, MVT::i64));
15312     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15313                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15314                                 false, false, 0);
15315
15316     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15317     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15318                        DAG.getConstant(22, MVT::i64));
15319     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15320                                 MachinePointerInfo(TrmpAddr, 22),
15321                                 false, false, 0);
15322
15323     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15324   } else {
15325     const Function *Func =
15326       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15327     CallingConv::ID CC = Func->getCallingConv();
15328     unsigned NestReg;
15329
15330     switch (CC) {
15331     default:
15332       llvm_unreachable("Unsupported calling convention");
15333     case CallingConv::C:
15334     case CallingConv::X86_StdCall: {
15335       // Pass 'nest' parameter in ECX.
15336       // Must be kept in sync with X86CallingConv.td
15337       NestReg = X86::ECX;
15338
15339       // Check that ECX wasn't needed by an 'inreg' parameter.
15340       FunctionType *FTy = Func->getFunctionType();
15341       const AttributeSet &Attrs = Func->getAttributes();
15342
15343       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15344         unsigned InRegCount = 0;
15345         unsigned Idx = 1;
15346
15347         for (FunctionType::param_iterator I = FTy->param_begin(),
15348              E = FTy->param_end(); I != E; ++I, ++Idx)
15349           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15350             // FIXME: should only count parameters that are lowered to integers.
15351             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15352
15353         if (InRegCount > 2) {
15354           report_fatal_error("Nest register in use - reduce number of inreg"
15355                              " parameters!");
15356         }
15357       }
15358       break;
15359     }
15360     case CallingConv::X86_FastCall:
15361     case CallingConv::X86_ThisCall:
15362     case CallingConv::Fast:
15363       // Pass 'nest' parameter in EAX.
15364       // Must be kept in sync with X86CallingConv.td
15365       NestReg = X86::EAX;
15366       break;
15367     }
15368
15369     SDValue OutChains[4];
15370     SDValue Addr, Disp;
15371
15372     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15373                        DAG.getConstant(10, MVT::i32));
15374     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15375
15376     // This is storing the opcode for MOV32ri.
15377     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15378     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15379     OutChains[0] = DAG.getStore(Root, dl,
15380                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15381                                 Trmp, MachinePointerInfo(TrmpAddr),
15382                                 false, false, 0);
15383
15384     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15385                        DAG.getConstant(1, MVT::i32));
15386     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15387                                 MachinePointerInfo(TrmpAddr, 1),
15388                                 false, false, 1);
15389
15390     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15391     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15392                        DAG.getConstant(5, MVT::i32));
15393     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15394                                 MachinePointerInfo(TrmpAddr, 5),
15395                                 false, false, 1);
15396
15397     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15398                        DAG.getConstant(6, MVT::i32));
15399     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15400                                 MachinePointerInfo(TrmpAddr, 6),
15401                                 false, false, 1);
15402
15403     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15404   }
15405 }
15406
15407 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15408                                             SelectionDAG &DAG) const {
15409   /*
15410    The rounding mode is in bits 11:10 of FPSR, and has the following
15411    settings:
15412      00 Round to nearest
15413      01 Round to -inf
15414      10 Round to +inf
15415      11 Round to 0
15416
15417   FLT_ROUNDS, on the other hand, expects the following:
15418     -1 Undefined
15419      0 Round to 0
15420      1 Round to nearest
15421      2 Round to +inf
15422      3 Round to -inf
15423
15424   To perform the conversion, we do:
15425     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15426   */
15427
15428   MachineFunction &MF = DAG.getMachineFunction();
15429   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15430   unsigned StackAlignment = TFI.getStackAlignment();
15431   MVT VT = Op.getSimpleValueType();
15432   SDLoc DL(Op);
15433
15434   // Save FP Control Word to stack slot
15435   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15436   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15437
15438   MachineMemOperand *MMO =
15439    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15440                            MachineMemOperand::MOStore, 2, 2);
15441
15442   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15443   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15444                                           DAG.getVTList(MVT::Other),
15445                                           Ops, MVT::i16, MMO);
15446
15447   // Load FP Control Word from stack slot
15448   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15449                             MachinePointerInfo(), false, false, false, 0);
15450
15451   // Transform as necessary
15452   SDValue CWD1 =
15453     DAG.getNode(ISD::SRL, DL, MVT::i16,
15454                 DAG.getNode(ISD::AND, DL, MVT::i16,
15455                             CWD, DAG.getConstant(0x800, MVT::i16)),
15456                 DAG.getConstant(11, MVT::i8));
15457   SDValue CWD2 =
15458     DAG.getNode(ISD::SRL, DL, MVT::i16,
15459                 DAG.getNode(ISD::AND, DL, MVT::i16,
15460                             CWD, DAG.getConstant(0x400, MVT::i16)),
15461                 DAG.getConstant(9, MVT::i8));
15462
15463   SDValue RetVal =
15464     DAG.getNode(ISD::AND, DL, MVT::i16,
15465                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15466                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15467                             DAG.getConstant(1, MVT::i16)),
15468                 DAG.getConstant(3, MVT::i16));
15469
15470   return DAG.getNode((VT.getSizeInBits() < 16 ?
15471                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15472 }
15473
15474 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15475   MVT VT = Op.getSimpleValueType();
15476   EVT OpVT = VT;
15477   unsigned NumBits = VT.getSizeInBits();
15478   SDLoc dl(Op);
15479
15480   Op = Op.getOperand(0);
15481   if (VT == MVT::i8) {
15482     // Zero extend to i32 since there is not an i8 bsr.
15483     OpVT = MVT::i32;
15484     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15485   }
15486
15487   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15488   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15489   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15490
15491   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15492   SDValue Ops[] = {
15493     Op,
15494     DAG.getConstant(NumBits+NumBits-1, OpVT),
15495     DAG.getConstant(X86::COND_E, MVT::i8),
15496     Op.getValue(1)
15497   };
15498   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15499
15500   // Finally xor with NumBits-1.
15501   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15502
15503   if (VT == MVT::i8)
15504     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15505   return Op;
15506 }
15507
15508 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15509   MVT VT = Op.getSimpleValueType();
15510   EVT OpVT = VT;
15511   unsigned NumBits = VT.getSizeInBits();
15512   SDLoc dl(Op);
15513
15514   Op = Op.getOperand(0);
15515   if (VT == MVT::i8) {
15516     // Zero extend to i32 since there is not an i8 bsr.
15517     OpVT = MVT::i32;
15518     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15519   }
15520
15521   // Issue a bsr (scan bits in reverse).
15522   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15523   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15524
15525   // And xor with NumBits-1.
15526   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15527
15528   if (VT == MVT::i8)
15529     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15530   return Op;
15531 }
15532
15533 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15534   MVT VT = Op.getSimpleValueType();
15535   unsigned NumBits = VT.getSizeInBits();
15536   SDLoc dl(Op);
15537   Op = Op.getOperand(0);
15538
15539   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15540   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15541   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15542
15543   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15544   SDValue Ops[] = {
15545     Op,
15546     DAG.getConstant(NumBits, VT),
15547     DAG.getConstant(X86::COND_E, MVT::i8),
15548     Op.getValue(1)
15549   };
15550   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15551 }
15552
15553 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15554 // ones, and then concatenate the result back.
15555 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15556   MVT VT = Op.getSimpleValueType();
15557
15558   assert(VT.is256BitVector() && VT.isInteger() &&
15559          "Unsupported value type for operation");
15560
15561   unsigned NumElems = VT.getVectorNumElements();
15562   SDLoc dl(Op);
15563
15564   // Extract the LHS vectors
15565   SDValue LHS = Op.getOperand(0);
15566   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15567   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15568
15569   // Extract the RHS vectors
15570   SDValue RHS = Op.getOperand(1);
15571   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15572   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15573
15574   MVT EltVT = VT.getVectorElementType();
15575   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15576
15577   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15578                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15579                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15580 }
15581
15582 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15583   assert(Op.getSimpleValueType().is256BitVector() &&
15584          Op.getSimpleValueType().isInteger() &&
15585          "Only handle AVX 256-bit vector integer operation");
15586   return Lower256IntArith(Op, DAG);
15587 }
15588
15589 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15590   assert(Op.getSimpleValueType().is256BitVector() &&
15591          Op.getSimpleValueType().isInteger() &&
15592          "Only handle AVX 256-bit vector integer operation");
15593   return Lower256IntArith(Op, DAG);
15594 }
15595
15596 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15597                         SelectionDAG &DAG) {
15598   SDLoc dl(Op);
15599   MVT VT = Op.getSimpleValueType();
15600
15601   // Decompose 256-bit ops into smaller 128-bit ops.
15602   if (VT.is256BitVector() && !Subtarget->hasInt256())
15603     return Lower256IntArith(Op, DAG);
15604
15605   SDValue A = Op.getOperand(0);
15606   SDValue B = Op.getOperand(1);
15607
15608   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15609   if (VT == MVT::v4i32) {
15610     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15611            "Should not custom lower when pmuldq is available!");
15612
15613     // Extract the odd parts.
15614     static const int UnpackMask[] = { 1, -1, 3, -1 };
15615     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15616     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15617
15618     // Multiply the even parts.
15619     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15620     // Now multiply odd parts.
15621     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15622
15623     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15624     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15625
15626     // Merge the two vectors back together with a shuffle. This expands into 2
15627     // shuffles.
15628     static const int ShufMask[] = { 0, 4, 2, 6 };
15629     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15630   }
15631
15632   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15633          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15634
15635   //  Ahi = psrlqi(a, 32);
15636   //  Bhi = psrlqi(b, 32);
15637   //
15638   //  AloBlo = pmuludq(a, b);
15639   //  AloBhi = pmuludq(a, Bhi);
15640   //  AhiBlo = pmuludq(Ahi, b);
15641
15642   //  AloBhi = psllqi(AloBhi, 32);
15643   //  AhiBlo = psllqi(AhiBlo, 32);
15644   //  return AloBlo + AloBhi + AhiBlo;
15645
15646   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15647   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15648
15649   // Bit cast to 32-bit vectors for MULUDQ
15650   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15651                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15652   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15653   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15654   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15655   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15656
15657   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15658   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15659   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15660
15661   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15662   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15663
15664   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15665   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15666 }
15667
15668 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15669   assert(Subtarget->isTargetWin64() && "Unexpected target");
15670   EVT VT = Op.getValueType();
15671   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15672          "Unexpected return type for lowering");
15673
15674   RTLIB::Libcall LC;
15675   bool isSigned;
15676   switch (Op->getOpcode()) {
15677   default: llvm_unreachable("Unexpected request for libcall!");
15678   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15679   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15680   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15681   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15682   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15683   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15684   }
15685
15686   SDLoc dl(Op);
15687   SDValue InChain = DAG.getEntryNode();
15688
15689   TargetLowering::ArgListTy Args;
15690   TargetLowering::ArgListEntry Entry;
15691   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15692     EVT ArgVT = Op->getOperand(i).getValueType();
15693     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15694            "Unexpected argument type for lowering");
15695     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15696     Entry.Node = StackPtr;
15697     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15698                            false, false, 16);
15699     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15700     Entry.Ty = PointerType::get(ArgTy,0);
15701     Entry.isSExt = false;
15702     Entry.isZExt = false;
15703     Args.push_back(Entry);
15704   }
15705
15706   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15707                                          getPointerTy());
15708
15709   TargetLowering::CallLoweringInfo CLI(DAG);
15710   CLI.setDebugLoc(dl).setChain(InChain)
15711     .setCallee(getLibcallCallingConv(LC),
15712                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15713                Callee, std::move(Args), 0)
15714     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15715
15716   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15717   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15718 }
15719
15720 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15721                              SelectionDAG &DAG) {
15722   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15723   EVT VT = Op0.getValueType();
15724   SDLoc dl(Op);
15725
15726   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15727          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15728
15729   // PMULxD operations multiply each even value (starting at 0) of LHS with
15730   // the related value of RHS and produce a widen result.
15731   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15732   // => <2 x i64> <ae|cg>
15733   //
15734   // In other word, to have all the results, we need to perform two PMULxD:
15735   // 1. one with the even values.
15736   // 2. one with the odd values.
15737   // To achieve #2, with need to place the odd values at an even position.
15738   //
15739   // Place the odd value at an even position (basically, shift all values 1
15740   // step to the left):
15741   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15742   // <a|b|c|d> => <b|undef|d|undef>
15743   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15744   // <e|f|g|h> => <f|undef|h|undef>
15745   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15746
15747   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15748   // ints.
15749   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15750   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15751   unsigned Opcode =
15752       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15753   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15754   // => <2 x i64> <ae|cg>
15755   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15756                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15757   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15758   // => <2 x i64> <bf|dh>
15759   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15760                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15761
15762   // Shuffle it back into the right order.
15763   SDValue Highs, Lows;
15764   if (VT == MVT::v8i32) {
15765     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15766     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15767     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15768     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15769   } else {
15770     const int HighMask[] = {1, 5, 3, 7};
15771     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15772     const int LowMask[] = {0, 4, 2, 6};
15773     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15774   }
15775
15776   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15777   // unsigned multiply.
15778   if (IsSigned && !Subtarget->hasSSE41()) {
15779     SDValue ShAmt =
15780         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15781     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15782                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15783     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15784                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15785
15786     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15787     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15788   }
15789
15790   // The first result of MUL_LOHI is actually the low value, followed by the
15791   // high value.
15792   SDValue Ops[] = {Lows, Highs};
15793   return DAG.getMergeValues(Ops, dl);
15794 }
15795
15796 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15797                                          const X86Subtarget *Subtarget) {
15798   MVT VT = Op.getSimpleValueType();
15799   SDLoc dl(Op);
15800   SDValue R = Op.getOperand(0);
15801   SDValue Amt = Op.getOperand(1);
15802
15803   // Optimize shl/srl/sra with constant shift amount.
15804   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15805     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15806       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15807
15808       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15809           (Subtarget->hasInt256() &&
15810            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15811           (Subtarget->hasAVX512() &&
15812            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15813         if (Op.getOpcode() == ISD::SHL)
15814           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15815                                             DAG);
15816         if (Op.getOpcode() == ISD::SRL)
15817           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15818                                             DAG);
15819         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15820           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15821                                             DAG);
15822       }
15823
15824       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15825         unsigned NumElts = VT.getVectorNumElements();
15826         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15827
15828         if (Op.getOpcode() == ISD::SHL) {
15829           // Make a large shift.
15830           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15831                                                    R, ShiftAmt, DAG);
15832           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15833           // Zero out the rightmost bits.
15834           SmallVector<SDValue, 32> V(
15835               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15836           return DAG.getNode(ISD::AND, dl, VT, SHL,
15837                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15838         }
15839         if (Op.getOpcode() == ISD::SRL) {
15840           // Make a large shift.
15841           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15842                                                    R, ShiftAmt, DAG);
15843           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15844           // Zero out the leftmost bits.
15845           SmallVector<SDValue, 32> V(
15846               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15847           return DAG.getNode(ISD::AND, dl, VT, SRL,
15848                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15849         }
15850         if (Op.getOpcode() == ISD::SRA) {
15851           if (ShiftAmt == 7) {
15852             // R s>> 7  ===  R s< 0
15853             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15854             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15855           }
15856
15857           // R s>> a === ((R u>> a) ^ m) - m
15858           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15859           SmallVector<SDValue, 32> V(NumElts,
15860                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15861           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15862           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15863           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15864           return Res;
15865         }
15866         llvm_unreachable("Unknown shift opcode.");
15867       }
15868     }
15869   }
15870
15871   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15872   if (!Subtarget->is64Bit() &&
15873       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15874       Amt.getOpcode() == ISD::BITCAST &&
15875       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15876     Amt = Amt.getOperand(0);
15877     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15878                      VT.getVectorNumElements();
15879     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15880     uint64_t ShiftAmt = 0;
15881     for (unsigned i = 0; i != Ratio; ++i) {
15882       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15883       if (!C)
15884         return SDValue();
15885       // 6 == Log2(64)
15886       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15887     }
15888     // Check remaining shift amounts.
15889     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15890       uint64_t ShAmt = 0;
15891       for (unsigned j = 0; j != Ratio; ++j) {
15892         ConstantSDNode *C =
15893           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15894         if (!C)
15895           return SDValue();
15896         // 6 == Log2(64)
15897         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15898       }
15899       if (ShAmt != ShiftAmt)
15900         return SDValue();
15901     }
15902     switch (Op.getOpcode()) {
15903     default:
15904       llvm_unreachable("Unknown shift opcode!");
15905     case ISD::SHL:
15906       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15907                                         DAG);
15908     case ISD::SRL:
15909       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15910                                         DAG);
15911     case ISD::SRA:
15912       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15913                                         DAG);
15914     }
15915   }
15916
15917   return SDValue();
15918 }
15919
15920 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15921                                         const X86Subtarget* Subtarget) {
15922   MVT VT = Op.getSimpleValueType();
15923   SDLoc dl(Op);
15924   SDValue R = Op.getOperand(0);
15925   SDValue Amt = Op.getOperand(1);
15926
15927   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15928       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15929       (Subtarget->hasInt256() &&
15930        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15931         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15932        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15933     SDValue BaseShAmt;
15934     EVT EltVT = VT.getVectorElementType();
15935
15936     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
15937       // Check if this build_vector node is doing a splat.
15938       // If so, then set BaseShAmt equal to the splat value.
15939       BaseShAmt = BV->getSplatValue();
15940       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
15941         BaseShAmt = SDValue();
15942     } else {
15943       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15944         Amt = Amt.getOperand(0);
15945
15946       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
15947       if (SVN && SVN->isSplat()) {
15948         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
15949         SDValue InVec = Amt.getOperand(0);
15950         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15951           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
15952                  "Unexpected shuffle index found!");
15953           BaseShAmt = InVec.getOperand(SplatIdx);
15954         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15955            if (ConstantSDNode *C =
15956                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15957              if (C->getZExtValue() == SplatIdx)
15958                BaseShAmt = InVec.getOperand(1);
15959            }
15960         }
15961
15962         if (!BaseShAmt)
15963           // Avoid introducing an extract element from a shuffle.
15964           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
15965                                     DAG.getIntPtrConstant(SplatIdx));
15966       }
15967     }
15968
15969     if (BaseShAmt.getNode()) {
15970       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
15971       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
15972         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
15973       else if (EltVT.bitsLT(MVT::i32))
15974         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15975
15976       switch (Op.getOpcode()) {
15977       default:
15978         llvm_unreachable("Unknown shift opcode!");
15979       case ISD::SHL:
15980         switch (VT.SimpleTy) {
15981         default: return SDValue();
15982         case MVT::v2i64:
15983         case MVT::v4i32:
15984         case MVT::v8i16:
15985         case MVT::v4i64:
15986         case MVT::v8i32:
15987         case MVT::v16i16:
15988         case MVT::v16i32:
15989         case MVT::v8i64:
15990           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15991         }
15992       case ISD::SRA:
15993         switch (VT.SimpleTy) {
15994         default: return SDValue();
15995         case MVT::v4i32:
15996         case MVT::v8i16:
15997         case MVT::v8i32:
15998         case MVT::v16i16:
15999         case MVT::v16i32:
16000         case MVT::v8i64:
16001           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16002         }
16003       case ISD::SRL:
16004         switch (VT.SimpleTy) {
16005         default: return SDValue();
16006         case MVT::v2i64:
16007         case MVT::v4i32:
16008         case MVT::v8i16:
16009         case MVT::v4i64:
16010         case MVT::v8i32:
16011         case MVT::v16i16:
16012         case MVT::v16i32:
16013         case MVT::v8i64:
16014           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16015         }
16016       }
16017     }
16018   }
16019
16020   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16021   if (!Subtarget->is64Bit() &&
16022       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16023       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16024       Amt.getOpcode() == ISD::BITCAST &&
16025       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16026     Amt = Amt.getOperand(0);
16027     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16028                      VT.getVectorNumElements();
16029     std::vector<SDValue> Vals(Ratio);
16030     for (unsigned i = 0; i != Ratio; ++i)
16031       Vals[i] = Amt.getOperand(i);
16032     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16033       for (unsigned j = 0; j != Ratio; ++j)
16034         if (Vals[j] != Amt.getOperand(i + j))
16035           return SDValue();
16036     }
16037     switch (Op.getOpcode()) {
16038     default:
16039       llvm_unreachable("Unknown shift opcode!");
16040     case ISD::SHL:
16041       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16042     case ISD::SRL:
16043       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16044     case ISD::SRA:
16045       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16046     }
16047   }
16048
16049   return SDValue();
16050 }
16051
16052 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16053                           SelectionDAG &DAG) {
16054   MVT VT = Op.getSimpleValueType();
16055   SDLoc dl(Op);
16056   SDValue R = Op.getOperand(0);
16057   SDValue Amt = Op.getOperand(1);
16058   SDValue V;
16059
16060   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16061   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16062
16063   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16064   if (V.getNode())
16065     return V;
16066
16067   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16068   if (V.getNode())
16069       return V;
16070
16071   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16072     return Op;
16073   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16074   if (Subtarget->hasInt256()) {
16075     if (Op.getOpcode() == ISD::SRL &&
16076         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16077          VT == MVT::v4i64 || VT == MVT::v8i32))
16078       return Op;
16079     if (Op.getOpcode() == ISD::SHL &&
16080         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16081          VT == MVT::v4i64 || VT == MVT::v8i32))
16082       return Op;
16083     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16084       return Op;
16085   }
16086
16087   // If possible, lower this packed shift into a vector multiply instead of
16088   // expanding it into a sequence of scalar shifts.
16089   // Do this only if the vector shift count is a constant build_vector.
16090   if (Op.getOpcode() == ISD::SHL &&
16091       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16092        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16093       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16094     SmallVector<SDValue, 8> Elts;
16095     EVT SVT = VT.getScalarType();
16096     unsigned SVTBits = SVT.getSizeInBits();
16097     const APInt &One = APInt(SVTBits, 1);
16098     unsigned NumElems = VT.getVectorNumElements();
16099
16100     for (unsigned i=0; i !=NumElems; ++i) {
16101       SDValue Op = Amt->getOperand(i);
16102       if (Op->getOpcode() == ISD::UNDEF) {
16103         Elts.push_back(Op);
16104         continue;
16105       }
16106
16107       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16108       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16109       uint64_t ShAmt = C.getZExtValue();
16110       if (ShAmt >= SVTBits) {
16111         Elts.push_back(DAG.getUNDEF(SVT));
16112         continue;
16113       }
16114       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16115     }
16116     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16117     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16118   }
16119
16120   // Lower SHL with variable shift amount.
16121   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16122     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16123
16124     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16125     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16126     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16127     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16128   }
16129
16130   // If possible, lower this shift as a sequence of two shifts by
16131   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16132   // Example:
16133   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16134   //
16135   // Could be rewritten as:
16136   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16137   //
16138   // The advantage is that the two shifts from the example would be
16139   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16140   // the vector shift into four scalar shifts plus four pairs of vector
16141   // insert/extract.
16142   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16143       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16144     unsigned TargetOpcode = X86ISD::MOVSS;
16145     bool CanBeSimplified;
16146     // The splat value for the first packed shift (the 'X' from the example).
16147     SDValue Amt1 = Amt->getOperand(0);
16148     // The splat value for the second packed shift (the 'Y' from the example).
16149     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16150                                         Amt->getOperand(2);
16151
16152     // See if it is possible to replace this node with a sequence of
16153     // two shifts followed by a MOVSS/MOVSD
16154     if (VT == MVT::v4i32) {
16155       // Check if it is legal to use a MOVSS.
16156       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16157                         Amt2 == Amt->getOperand(3);
16158       if (!CanBeSimplified) {
16159         // Otherwise, check if we can still simplify this node using a MOVSD.
16160         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16161                           Amt->getOperand(2) == Amt->getOperand(3);
16162         TargetOpcode = X86ISD::MOVSD;
16163         Amt2 = Amt->getOperand(2);
16164       }
16165     } else {
16166       // Do similar checks for the case where the machine value type
16167       // is MVT::v8i16.
16168       CanBeSimplified = Amt1 == Amt->getOperand(1);
16169       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16170         CanBeSimplified = Amt2 == Amt->getOperand(i);
16171
16172       if (!CanBeSimplified) {
16173         TargetOpcode = X86ISD::MOVSD;
16174         CanBeSimplified = true;
16175         Amt2 = Amt->getOperand(4);
16176         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16177           CanBeSimplified = Amt1 == Amt->getOperand(i);
16178         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16179           CanBeSimplified = Amt2 == Amt->getOperand(j);
16180       }
16181     }
16182
16183     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16184         isa<ConstantSDNode>(Amt2)) {
16185       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16186       EVT CastVT = MVT::v4i32;
16187       SDValue Splat1 =
16188         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16189       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16190       SDValue Splat2 =
16191         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16192       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16193       if (TargetOpcode == X86ISD::MOVSD)
16194         CastVT = MVT::v2i64;
16195       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16196       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16197       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16198                                             BitCast1, DAG);
16199       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16200     }
16201   }
16202
16203   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16204     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16205
16206     // a = a << 5;
16207     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16208     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16209
16210     // Turn 'a' into a mask suitable for VSELECT
16211     SDValue VSelM = DAG.getConstant(0x80, VT);
16212     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16213     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16214
16215     SDValue CM1 = DAG.getConstant(0x0f, VT);
16216     SDValue CM2 = DAG.getConstant(0x3f, VT);
16217
16218     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16219     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16220     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16221     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16222     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16223
16224     // a += a
16225     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16226     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16227     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16228
16229     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16230     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16231     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16232     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16233     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16234
16235     // a += a
16236     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16237     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16238     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16239
16240     // return VSELECT(r, r+r, a);
16241     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16242                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16243     return R;
16244   }
16245
16246   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16247   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16248   // solution better.
16249   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16250     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16251     unsigned ExtOpc =
16252         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16253     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16254     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16255     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16256                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16257   }
16258
16259   // Decompose 256-bit shifts into smaller 128-bit shifts.
16260   if (VT.is256BitVector()) {
16261     unsigned NumElems = VT.getVectorNumElements();
16262     MVT EltVT = VT.getVectorElementType();
16263     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16264
16265     // Extract the two vectors
16266     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16267     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16268
16269     // Recreate the shift amount vectors
16270     SDValue Amt1, Amt2;
16271     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16272       // Constant shift amount
16273       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16274       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16275       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16276
16277       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16278       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16279     } else {
16280       // Variable shift amount
16281       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16282       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16283     }
16284
16285     // Issue new vector shifts for the smaller types
16286     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16287     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16288
16289     // Concatenate the result back
16290     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16291   }
16292
16293   return SDValue();
16294 }
16295
16296 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16297   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16298   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16299   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16300   // has only one use.
16301   SDNode *N = Op.getNode();
16302   SDValue LHS = N->getOperand(0);
16303   SDValue RHS = N->getOperand(1);
16304   unsigned BaseOp = 0;
16305   unsigned Cond = 0;
16306   SDLoc DL(Op);
16307   switch (Op.getOpcode()) {
16308   default: llvm_unreachable("Unknown ovf instruction!");
16309   case ISD::SADDO:
16310     // A subtract of one will be selected as a INC. Note that INC doesn't
16311     // set CF, so we can't do this for UADDO.
16312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16313       if (C->isOne()) {
16314         BaseOp = X86ISD::INC;
16315         Cond = X86::COND_O;
16316         break;
16317       }
16318     BaseOp = X86ISD::ADD;
16319     Cond = X86::COND_O;
16320     break;
16321   case ISD::UADDO:
16322     BaseOp = X86ISD::ADD;
16323     Cond = X86::COND_B;
16324     break;
16325   case ISD::SSUBO:
16326     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16327     // set CF, so we can't do this for USUBO.
16328     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16329       if (C->isOne()) {
16330         BaseOp = X86ISD::DEC;
16331         Cond = X86::COND_O;
16332         break;
16333       }
16334     BaseOp = X86ISD::SUB;
16335     Cond = X86::COND_O;
16336     break;
16337   case ISD::USUBO:
16338     BaseOp = X86ISD::SUB;
16339     Cond = X86::COND_B;
16340     break;
16341   case ISD::SMULO:
16342     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16343     Cond = X86::COND_O;
16344     break;
16345   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16346     if (N->getValueType(0) == MVT::i8) {
16347       BaseOp = X86ISD::UMUL8;
16348       Cond = X86::COND_O;
16349       break;
16350     }
16351     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16352                                  MVT::i32);
16353     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16354
16355     SDValue SetCC =
16356       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16357                   DAG.getConstant(X86::COND_O, MVT::i32),
16358                   SDValue(Sum.getNode(), 2));
16359
16360     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16361   }
16362   }
16363
16364   // Also sets EFLAGS.
16365   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16366   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16367
16368   SDValue SetCC =
16369     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16370                 DAG.getConstant(Cond, MVT::i32),
16371                 SDValue(Sum.getNode(), 1));
16372
16373   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16374 }
16375
16376 /// Returns true if the operand type is exactly twice the native width, and
16377 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16378 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16379 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16380 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16381   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16382
16383   if (OpWidth == 64)
16384     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16385   else if (OpWidth == 128)
16386     return Subtarget->hasCmpxchg16b();
16387   else
16388     return false;
16389 }
16390
16391 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16392   return needsCmpXchgNb(SI->getValueOperand()->getType());
16393 }
16394
16395 // Note: this turns large loads into lock cmpxchg8b/16b.
16396 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16397 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16398   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16399   return needsCmpXchgNb(PTy->getElementType());
16400 }
16401
16402 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16403   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16404   const Type *MemType = AI->getType();
16405
16406   // If the operand is too big, we must see if cmpxchg8/16b is available
16407   // and default to library calls otherwise.
16408   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16409     return needsCmpXchgNb(MemType);
16410
16411   AtomicRMWInst::BinOp Op = AI->getOperation();
16412   switch (Op) {
16413   default:
16414     llvm_unreachable("Unknown atomic operation");
16415   case AtomicRMWInst::Xchg:
16416   case AtomicRMWInst::Add:
16417   case AtomicRMWInst::Sub:
16418     // It's better to use xadd, xsub or xchg for these in all cases.
16419     return false;
16420   case AtomicRMWInst::Or:
16421   case AtomicRMWInst::And:
16422   case AtomicRMWInst::Xor:
16423     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16424     // prefix to a normal instruction for these operations.
16425     return !AI->use_empty();
16426   case AtomicRMWInst::Nand:
16427   case AtomicRMWInst::Max:
16428   case AtomicRMWInst::Min:
16429   case AtomicRMWInst::UMax:
16430   case AtomicRMWInst::UMin:
16431     // These always require a non-trivial set of data operations on x86. We must
16432     // use a cmpxchg loop.
16433     return true;
16434   }
16435 }
16436
16437 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16438   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16439   // no-sse2). There isn't any reason to disable it if the target processor
16440   // supports it.
16441   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16442 }
16443
16444 LoadInst *
16445 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16446   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16447   const Type *MemType = AI->getType();
16448   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16449   // there is no benefit in turning such RMWs into loads, and it is actually
16450   // harmful as it introduces a mfence.
16451   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16452     return nullptr;
16453
16454   auto Builder = IRBuilder<>(AI);
16455   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16456   auto SynchScope = AI->getSynchScope();
16457   // We must restrict the ordering to avoid generating loads with Release or
16458   // ReleaseAcquire orderings.
16459   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16460   auto Ptr = AI->getPointerOperand();
16461
16462   // Before the load we need a fence. Here is an example lifted from
16463   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16464   // is required:
16465   // Thread 0:
16466   //   x.store(1, relaxed);
16467   //   r1 = y.fetch_add(0, release);
16468   // Thread 1:
16469   //   y.fetch_add(42, acquire);
16470   //   r2 = x.load(relaxed);
16471   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16472   // lowered to just a load without a fence. A mfence flushes the store buffer,
16473   // making the optimization clearly correct.
16474   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16475   // otherwise, we might be able to be more agressive on relaxed idempotent
16476   // rmw. In practice, they do not look useful, so we don't try to be
16477   // especially clever.
16478   if (SynchScope == SingleThread) {
16479     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16480     // the IR level, so we must wrap it in an intrinsic.
16481     return nullptr;
16482   } else if (hasMFENCE(*Subtarget)) {
16483     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16484             Intrinsic::x86_sse2_mfence);
16485     Builder.CreateCall(MFence);
16486   } else {
16487     // FIXME: it might make sense to use a locked operation here but on a
16488     // different cache-line to prevent cache-line bouncing. In practice it
16489     // is probably a small win, and x86 processors without mfence are rare
16490     // enough that we do not bother.
16491     return nullptr;
16492   }
16493
16494   // Finally we can emit the atomic load.
16495   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16496           AI->getType()->getPrimitiveSizeInBits());
16497   Loaded->setAtomic(Order, SynchScope);
16498   AI->replaceAllUsesWith(Loaded);
16499   AI->eraseFromParent();
16500   return Loaded;
16501 }
16502
16503 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16504                                  SelectionDAG &DAG) {
16505   SDLoc dl(Op);
16506   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16507     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16508   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16509     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16510
16511   // The only fence that needs an instruction is a sequentially-consistent
16512   // cross-thread fence.
16513   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16514     if (hasMFENCE(*Subtarget))
16515       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16516
16517     SDValue Chain = Op.getOperand(0);
16518     SDValue Zero = DAG.getConstant(0, MVT::i32);
16519     SDValue Ops[] = {
16520       DAG.getRegister(X86::ESP, MVT::i32), // Base
16521       DAG.getTargetConstant(1, MVT::i8),   // Scale
16522       DAG.getRegister(0, MVT::i32),        // Index
16523       DAG.getTargetConstant(0, MVT::i32),  // Disp
16524       DAG.getRegister(0, MVT::i32),        // Segment.
16525       Zero,
16526       Chain
16527     };
16528     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16529     return SDValue(Res, 0);
16530   }
16531
16532   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16533   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16534 }
16535
16536 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16537                              SelectionDAG &DAG) {
16538   MVT T = Op.getSimpleValueType();
16539   SDLoc DL(Op);
16540   unsigned Reg = 0;
16541   unsigned size = 0;
16542   switch(T.SimpleTy) {
16543   default: llvm_unreachable("Invalid value type!");
16544   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16545   case MVT::i16: Reg = X86::AX;  size = 2; break;
16546   case MVT::i32: Reg = X86::EAX; size = 4; break;
16547   case MVT::i64:
16548     assert(Subtarget->is64Bit() && "Node not type legal!");
16549     Reg = X86::RAX; size = 8;
16550     break;
16551   }
16552   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16553                                   Op.getOperand(2), SDValue());
16554   SDValue Ops[] = { cpIn.getValue(0),
16555                     Op.getOperand(1),
16556                     Op.getOperand(3),
16557                     DAG.getTargetConstant(size, MVT::i8),
16558                     cpIn.getValue(1) };
16559   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16560   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16561   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16562                                            Ops, T, MMO);
16563
16564   SDValue cpOut =
16565     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16566   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16567                                       MVT::i32, cpOut.getValue(2));
16568   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16569                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16570
16571   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16572   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16573   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16574   return SDValue();
16575 }
16576
16577 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16578                             SelectionDAG &DAG) {
16579   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16580   MVT DstVT = Op.getSimpleValueType();
16581
16582   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16583     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16584     if (DstVT != MVT::f64)
16585       // This conversion needs to be expanded.
16586       return SDValue();
16587
16588     SDValue InVec = Op->getOperand(0);
16589     SDLoc dl(Op);
16590     unsigned NumElts = SrcVT.getVectorNumElements();
16591     EVT SVT = SrcVT.getVectorElementType();
16592
16593     // Widen the vector in input in the case of MVT::v2i32.
16594     // Example: from MVT::v2i32 to MVT::v4i32.
16595     SmallVector<SDValue, 16> Elts;
16596     for (unsigned i = 0, e = NumElts; i != e; ++i)
16597       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16598                                  DAG.getIntPtrConstant(i)));
16599
16600     // Explicitly mark the extra elements as Undef.
16601     Elts.append(NumElts, DAG.getUNDEF(SVT));
16602
16603     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16604     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16605     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16606     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16607                        DAG.getIntPtrConstant(0));
16608   }
16609
16610   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16611          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16612   assert((DstVT == MVT::i64 ||
16613           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16614          "Unexpected custom BITCAST");
16615   // i64 <=> MMX conversions are Legal.
16616   if (SrcVT==MVT::i64 && DstVT.isVector())
16617     return Op;
16618   if (DstVT==MVT::i64 && SrcVT.isVector())
16619     return Op;
16620   // MMX <=> MMX conversions are Legal.
16621   if (SrcVT.isVector() && DstVT.isVector())
16622     return Op;
16623   // All other conversions need to be expanded.
16624   return SDValue();
16625 }
16626
16627 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16628                           SelectionDAG &DAG) {
16629   SDNode *Node = Op.getNode();
16630   SDLoc dl(Node);
16631
16632   Op = Op.getOperand(0);
16633   EVT VT = Op.getValueType();
16634   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16635          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16636
16637   unsigned NumElts = VT.getVectorNumElements();
16638   EVT EltVT = VT.getVectorElementType();
16639   unsigned Len = EltVT.getSizeInBits();
16640
16641   // This is the vectorized version of the "best" algorithm from
16642   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16643   // with a minor tweak to use a series of adds + shifts instead of vector
16644   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16645   //
16646   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16647   //  v8i32 => Always profitable
16648   //
16649   // FIXME: There a couple of possible improvements:
16650   //
16651   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16652   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16653   //
16654   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16655          "CTPOP not implemented for this vector element type.");
16656
16657   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16658   // extra legalization.
16659   bool NeedsBitcast = EltVT == MVT::i32;
16660   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16661
16662   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16663   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16664   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16665
16666   // v = v - ((v >> 1) & 0x55555555...)
16667   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16668   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16669   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16670   if (NeedsBitcast)
16671     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16672
16673   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16674   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16675   if (NeedsBitcast)
16676     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16677
16678   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16679   if (VT != And.getValueType())
16680     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16681   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16682
16683   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16684   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16685   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16686   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16687   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16688
16689   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16690   if (NeedsBitcast) {
16691     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16692     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16693     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16694   }
16695
16696   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16697   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16698   if (VT != AndRHS.getValueType()) {
16699     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16700     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16701   }
16702   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16703
16704   // v = (v + (v >> 4)) & 0x0F0F0F0F...
16705   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16706   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16707   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16708   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16709
16710   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16711   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16712   if (NeedsBitcast) {
16713     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16714     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16715   }
16716   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16717   if (VT != And.getValueType())
16718     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16719
16720   // The algorithm mentioned above uses:
16721   //    v = (v * 0x01010101...) >> (Len - 8)
16722   //
16723   // Change it to use vector adds + vector shifts which yield faster results on
16724   // Haswell than using vector integer multiplication.
16725   //
16726   // For i32 elements:
16727   //    v = v + (v >> 8)
16728   //    v = v + (v >> 16)
16729   //
16730   // For i64 elements:
16731   //    v = v + (v >> 8)
16732   //    v = v + (v >> 16)
16733   //    v = v + (v >> 32)
16734   //
16735   Add = And;
16736   SmallVector<SDValue, 8> Csts;
16737   for (unsigned i = 8; i <= Len/2; i *= 2) {
16738     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16739     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16740     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16741     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16742     Csts.clear();
16743   }
16744
16745   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16746   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16747   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16748   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16749   if (NeedsBitcast) {
16750     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16751     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16752   }
16753   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16754   if (VT != And.getValueType())
16755     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16756
16757   return And;
16758 }
16759
16760 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16761   SDNode *Node = Op.getNode();
16762   SDLoc dl(Node);
16763   EVT T = Node->getValueType(0);
16764   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16765                               DAG.getConstant(0, T), Node->getOperand(2));
16766   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16767                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16768                        Node->getOperand(0),
16769                        Node->getOperand(1), negOp,
16770                        cast<AtomicSDNode>(Node)->getMemOperand(),
16771                        cast<AtomicSDNode>(Node)->getOrdering(),
16772                        cast<AtomicSDNode>(Node)->getSynchScope());
16773 }
16774
16775 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16776   SDNode *Node = Op.getNode();
16777   SDLoc dl(Node);
16778   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16779
16780   // Convert seq_cst store -> xchg
16781   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16782   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16783   //        (The only way to get a 16-byte store is cmpxchg16b)
16784   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16785   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16786       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16787     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16788                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16789                                  Node->getOperand(0),
16790                                  Node->getOperand(1), Node->getOperand(2),
16791                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16792                                  cast<AtomicSDNode>(Node)->getOrdering(),
16793                                  cast<AtomicSDNode>(Node)->getSynchScope());
16794     return Swap.getValue(1);
16795   }
16796   // Other atomic stores have a simple pattern.
16797   return Op;
16798 }
16799
16800 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16801   EVT VT = Op.getNode()->getSimpleValueType(0);
16802
16803   // Let legalize expand this if it isn't a legal type yet.
16804   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16805     return SDValue();
16806
16807   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16808
16809   unsigned Opc;
16810   bool ExtraOp = false;
16811   switch (Op.getOpcode()) {
16812   default: llvm_unreachable("Invalid code");
16813   case ISD::ADDC: Opc = X86ISD::ADD; break;
16814   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16815   case ISD::SUBC: Opc = X86ISD::SUB; break;
16816   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16817   }
16818
16819   if (!ExtraOp)
16820     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16821                        Op.getOperand(1));
16822   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16823                      Op.getOperand(1), Op.getOperand(2));
16824 }
16825
16826 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16827                             SelectionDAG &DAG) {
16828   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16829
16830   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16831   // which returns the values as { float, float } (in XMM0) or
16832   // { double, double } (which is returned in XMM0, XMM1).
16833   SDLoc dl(Op);
16834   SDValue Arg = Op.getOperand(0);
16835   EVT ArgVT = Arg.getValueType();
16836   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16837
16838   TargetLowering::ArgListTy Args;
16839   TargetLowering::ArgListEntry Entry;
16840
16841   Entry.Node = Arg;
16842   Entry.Ty = ArgTy;
16843   Entry.isSExt = false;
16844   Entry.isZExt = false;
16845   Args.push_back(Entry);
16846
16847   bool isF64 = ArgVT == MVT::f64;
16848   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16849   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16850   // the results are returned via SRet in memory.
16851   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16853   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16854
16855   Type *RetTy = isF64
16856     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16857     : (Type*)VectorType::get(ArgTy, 4);
16858
16859   TargetLowering::CallLoweringInfo CLI(DAG);
16860   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16861     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16862
16863   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16864
16865   if (isF64)
16866     // Returned in xmm0 and xmm1.
16867     return CallResult.first;
16868
16869   // Returned in bits 0:31 and 32:64 xmm0.
16870   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16871                                CallResult.first, DAG.getIntPtrConstant(0));
16872   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16873                                CallResult.first, DAG.getIntPtrConstant(1));
16874   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16875   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16876 }
16877
16878 /// LowerOperation - Provide custom lowering hooks for some operations.
16879 ///
16880 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16881   switch (Op.getOpcode()) {
16882   default: llvm_unreachable("Should not custom lower this!");
16883   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16884   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16885     return LowerCMP_SWAP(Op, Subtarget, DAG);
16886   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
16887   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16888   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16889   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16890   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16891   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
16892   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16893   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16894   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16895   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16896   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16897   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16898   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16899   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16900   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16901   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16902   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16903   case ISD::SHL_PARTS:
16904   case ISD::SRA_PARTS:
16905   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16906   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16907   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16908   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16909   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16910   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16911   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16912   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16913   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16914   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16915   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16916   case ISD::FABS:
16917   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
16918   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16919   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16920   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16921   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16922   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16923   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16924   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16925   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16926   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16927   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
16928   case ISD::INTRINSIC_VOID:
16929   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16930   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16931   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16932   case ISD::FRAME_TO_ARGS_OFFSET:
16933                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16934   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16935   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16936   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16937   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16938   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16939   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16940   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16941   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16942   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16943   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16944   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16945   case ISD::UMUL_LOHI:
16946   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16947   case ISD::SRA:
16948   case ISD::SRL:
16949   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16950   case ISD::SADDO:
16951   case ISD::UADDO:
16952   case ISD::SSUBO:
16953   case ISD::USUBO:
16954   case ISD::SMULO:
16955   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16956   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16957   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16958   case ISD::ADDC:
16959   case ISD::ADDE:
16960   case ISD::SUBC:
16961   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16962   case ISD::ADD:                return LowerADD(Op, DAG);
16963   case ISD::SUB:                return LowerSUB(Op, DAG);
16964   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16965   }
16966 }
16967
16968 /// ReplaceNodeResults - Replace a node with an illegal result type
16969 /// with a new node built out of custom code.
16970 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16971                                            SmallVectorImpl<SDValue>&Results,
16972                                            SelectionDAG &DAG) const {
16973   SDLoc dl(N);
16974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16975   switch (N->getOpcode()) {
16976   default:
16977     llvm_unreachable("Do not know how to custom type legalize this operation!");
16978   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
16979   case X86ISD::FMINC:
16980   case X86ISD::FMIN:
16981   case X86ISD::FMAXC:
16982   case X86ISD::FMAX: {
16983     EVT VT = N->getValueType(0);
16984     if (VT != MVT::v2f32)
16985       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
16986     SDValue UNDEF = DAG.getUNDEF(VT);
16987     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16988                               N->getOperand(0), UNDEF);
16989     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16990                               N->getOperand(1), UNDEF);
16991     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
16992     return;
16993   }
16994   case ISD::SIGN_EXTEND_INREG:
16995   case ISD::ADDC:
16996   case ISD::ADDE:
16997   case ISD::SUBC:
16998   case ISD::SUBE:
16999     // We don't want to expand or promote these.
17000     return;
17001   case ISD::SDIV:
17002   case ISD::UDIV:
17003   case ISD::SREM:
17004   case ISD::UREM:
17005   case ISD::SDIVREM:
17006   case ISD::UDIVREM: {
17007     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17008     Results.push_back(V);
17009     return;
17010   }
17011   case ISD::FP_TO_SINT:
17012   case ISD::FP_TO_UINT: {
17013     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17014
17015     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17016       return;
17017
17018     std::pair<SDValue,SDValue> Vals =
17019         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17020     SDValue FIST = Vals.first, StackSlot = Vals.second;
17021     if (FIST.getNode()) {
17022       EVT VT = N->getValueType(0);
17023       // Return a load from the stack slot.
17024       if (StackSlot.getNode())
17025         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17026                                       MachinePointerInfo(),
17027                                       false, false, false, 0));
17028       else
17029         Results.push_back(FIST);
17030     }
17031     return;
17032   }
17033   case ISD::UINT_TO_FP: {
17034     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17035     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17036         N->getValueType(0) != MVT::v2f32)
17037       return;
17038     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17039                                  N->getOperand(0));
17040     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17041                                      MVT::f64);
17042     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17043     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17044                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17045     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17046     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17047     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17048     return;
17049   }
17050   case ISD::FP_ROUND: {
17051     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17052         return;
17053     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17054     Results.push_back(V);
17055     return;
17056   }
17057   case ISD::INTRINSIC_W_CHAIN: {
17058     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17059     switch (IntNo) {
17060     default : llvm_unreachable("Do not know how to custom type "
17061                                "legalize this intrinsic operation!");
17062     case Intrinsic::x86_rdtsc:
17063       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17064                                      Results);
17065     case Intrinsic::x86_rdtscp:
17066       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17067                                      Results);
17068     case Intrinsic::x86_rdpmc:
17069       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17070     }
17071   }
17072   case ISD::READCYCLECOUNTER: {
17073     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17074                                    Results);
17075   }
17076   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17077     EVT T = N->getValueType(0);
17078     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17079     bool Regs64bit = T == MVT::i128;
17080     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17081     SDValue cpInL, cpInH;
17082     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17083                         DAG.getConstant(0, HalfT));
17084     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17085                         DAG.getConstant(1, HalfT));
17086     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17087                              Regs64bit ? X86::RAX : X86::EAX,
17088                              cpInL, SDValue());
17089     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17090                              Regs64bit ? X86::RDX : X86::EDX,
17091                              cpInH, cpInL.getValue(1));
17092     SDValue swapInL, swapInH;
17093     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17094                           DAG.getConstant(0, HalfT));
17095     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17096                           DAG.getConstant(1, HalfT));
17097     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17098                                Regs64bit ? X86::RBX : X86::EBX,
17099                                swapInL, cpInH.getValue(1));
17100     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17101                                Regs64bit ? X86::RCX : X86::ECX,
17102                                swapInH, swapInL.getValue(1));
17103     SDValue Ops[] = { swapInH.getValue(0),
17104                       N->getOperand(1),
17105                       swapInH.getValue(1) };
17106     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17107     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17108     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17109                                   X86ISD::LCMPXCHG8_DAG;
17110     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17111     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17112                                         Regs64bit ? X86::RAX : X86::EAX,
17113                                         HalfT, Result.getValue(1));
17114     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17115                                         Regs64bit ? X86::RDX : X86::EDX,
17116                                         HalfT, cpOutL.getValue(2));
17117     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17118
17119     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17120                                         MVT::i32, cpOutH.getValue(2));
17121     SDValue Success =
17122         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17123                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17124     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17125
17126     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17127     Results.push_back(Success);
17128     Results.push_back(EFLAGS.getValue(1));
17129     return;
17130   }
17131   case ISD::ATOMIC_SWAP:
17132   case ISD::ATOMIC_LOAD_ADD:
17133   case ISD::ATOMIC_LOAD_SUB:
17134   case ISD::ATOMIC_LOAD_AND:
17135   case ISD::ATOMIC_LOAD_OR:
17136   case ISD::ATOMIC_LOAD_XOR:
17137   case ISD::ATOMIC_LOAD_NAND:
17138   case ISD::ATOMIC_LOAD_MIN:
17139   case ISD::ATOMIC_LOAD_MAX:
17140   case ISD::ATOMIC_LOAD_UMIN:
17141   case ISD::ATOMIC_LOAD_UMAX:
17142   case ISD::ATOMIC_LOAD: {
17143     // Delegate to generic TypeLegalization. Situations we can really handle
17144     // should have already been dealt with by AtomicExpandPass.cpp.
17145     break;
17146   }
17147   case ISD::BITCAST: {
17148     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17149     EVT DstVT = N->getValueType(0);
17150     EVT SrcVT = N->getOperand(0)->getValueType(0);
17151
17152     if (SrcVT != MVT::f64 ||
17153         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17154       return;
17155
17156     unsigned NumElts = DstVT.getVectorNumElements();
17157     EVT SVT = DstVT.getVectorElementType();
17158     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17159     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17160                                    MVT::v2f64, N->getOperand(0));
17161     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17162
17163     if (ExperimentalVectorWideningLegalization) {
17164       // If we are legalizing vectors by widening, we already have the desired
17165       // legal vector type, just return it.
17166       Results.push_back(ToVecInt);
17167       return;
17168     }
17169
17170     SmallVector<SDValue, 8> Elts;
17171     for (unsigned i = 0, e = NumElts; i != e; ++i)
17172       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17173                                    ToVecInt, DAG.getIntPtrConstant(i)));
17174
17175     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17176   }
17177   }
17178 }
17179
17180 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17181   switch (Opcode) {
17182   default: return nullptr;
17183   case X86ISD::BSF:                return "X86ISD::BSF";
17184   case X86ISD::BSR:                return "X86ISD::BSR";
17185   case X86ISD::SHLD:               return "X86ISD::SHLD";
17186   case X86ISD::SHRD:               return "X86ISD::SHRD";
17187   case X86ISD::FAND:               return "X86ISD::FAND";
17188   case X86ISD::FANDN:              return "X86ISD::FANDN";
17189   case X86ISD::FOR:                return "X86ISD::FOR";
17190   case X86ISD::FXOR:               return "X86ISD::FXOR";
17191   case X86ISD::FSRL:               return "X86ISD::FSRL";
17192   case X86ISD::FILD:               return "X86ISD::FILD";
17193   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17194   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17195   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17196   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17197   case X86ISD::FLD:                return "X86ISD::FLD";
17198   case X86ISD::FST:                return "X86ISD::FST";
17199   case X86ISD::CALL:               return "X86ISD::CALL";
17200   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17201   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17202   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17203   case X86ISD::BT:                 return "X86ISD::BT";
17204   case X86ISD::CMP:                return "X86ISD::CMP";
17205   case X86ISD::COMI:               return "X86ISD::COMI";
17206   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17207   case X86ISD::CMPM:               return "X86ISD::CMPM";
17208   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17209   case X86ISD::SETCC:              return "X86ISD::SETCC";
17210   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17211   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17212   case X86ISD::CMOV:               return "X86ISD::CMOV";
17213   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17214   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17215   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17216   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17217   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17218   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17219   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17220   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17221   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17222   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17223   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17224   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17225   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17226   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17227   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17228   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17229   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17230   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17231   case X86ISD::HADD:               return "X86ISD::HADD";
17232   case X86ISD::HSUB:               return "X86ISD::HSUB";
17233   case X86ISD::FHADD:              return "X86ISD::FHADD";
17234   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17235   case X86ISD::UMAX:               return "X86ISD::UMAX";
17236   case X86ISD::UMIN:               return "X86ISD::UMIN";
17237   case X86ISD::SMAX:               return "X86ISD::SMAX";
17238   case X86ISD::SMIN:               return "X86ISD::SMIN";
17239   case X86ISD::FMAX:               return "X86ISD::FMAX";
17240   case X86ISD::FMIN:               return "X86ISD::FMIN";
17241   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17242   case X86ISD::FMINC:              return "X86ISD::FMINC";
17243   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17244   case X86ISD::FRCP:               return "X86ISD::FRCP";
17245   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17246   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17247   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17248   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17249   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17250   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17251   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17252   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17253   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17254   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17255   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17256   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17257   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17258   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17259   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17260   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17261   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17262   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17263   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17264   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17265   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17266   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17267   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17268   case X86ISD::VSHL:               return "X86ISD::VSHL";
17269   case X86ISD::VSRL:               return "X86ISD::VSRL";
17270   case X86ISD::VSRA:               return "X86ISD::VSRA";
17271   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17272   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17273   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17274   case X86ISD::CMPP:               return "X86ISD::CMPP";
17275   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17276   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17277   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17278   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17279   case X86ISD::ADD:                return "X86ISD::ADD";
17280   case X86ISD::SUB:                return "X86ISD::SUB";
17281   case X86ISD::ADC:                return "X86ISD::ADC";
17282   case X86ISD::SBB:                return "X86ISD::SBB";
17283   case X86ISD::SMUL:               return "X86ISD::SMUL";
17284   case X86ISD::UMUL:               return "X86ISD::UMUL";
17285   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17286   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17287   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17288   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17289   case X86ISD::INC:                return "X86ISD::INC";
17290   case X86ISD::DEC:                return "X86ISD::DEC";
17291   case X86ISD::OR:                 return "X86ISD::OR";
17292   case X86ISD::XOR:                return "X86ISD::XOR";
17293   case X86ISD::AND:                return "X86ISD::AND";
17294   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17295   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17296   case X86ISD::PTEST:              return "X86ISD::PTEST";
17297   case X86ISD::TESTP:              return "X86ISD::TESTP";
17298   case X86ISD::TESTM:              return "X86ISD::TESTM";
17299   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17300   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17301   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17302   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17303   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17304   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17305   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17306   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17307   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17308   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17309   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17310   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17311   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17312   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17313   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17314   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17315   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17316   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17317   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17318   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17319   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17320   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17321   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17322   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17323   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17324   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17325   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17326   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17327   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17328   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17329   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17330   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17331   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17332   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17333   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17334   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17335   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17336   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17337   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17338   case X86ISD::SAHF:               return "X86ISD::SAHF";
17339   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17340   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17341   case X86ISD::FMADD:              return "X86ISD::FMADD";
17342   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17343   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17344   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17345   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17346   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17347   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17348   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17349   case X86ISD::XTEST:              return "X86ISD::XTEST";
17350   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17351   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17352   case X86ISD::SELECT:             return "X86ISD::SELECT";
17353   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17354   case X86ISD::RCP28:              return "X86ISD::RCP28";
17355   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17356   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17357   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17358   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17359   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17360   }
17361 }
17362
17363 // isLegalAddressingMode - Return true if the addressing mode represented
17364 // by AM is legal for this target, for a load/store of the specified type.
17365 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17366                                               Type *Ty) const {
17367   // X86 supports extremely general addressing modes.
17368   CodeModel::Model M = getTargetMachine().getCodeModel();
17369   Reloc::Model R = getTargetMachine().getRelocationModel();
17370
17371   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17372   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17373     return false;
17374
17375   if (AM.BaseGV) {
17376     unsigned GVFlags =
17377       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17378
17379     // If a reference to this global requires an extra load, we can't fold it.
17380     if (isGlobalStubReference(GVFlags))
17381       return false;
17382
17383     // If BaseGV requires a register for the PIC base, we cannot also have a
17384     // BaseReg specified.
17385     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17386       return false;
17387
17388     // If lower 4G is not available, then we must use rip-relative addressing.
17389     if ((M != CodeModel::Small || R != Reloc::Static) &&
17390         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17391       return false;
17392   }
17393
17394   switch (AM.Scale) {
17395   case 0:
17396   case 1:
17397   case 2:
17398   case 4:
17399   case 8:
17400     // These scales always work.
17401     break;
17402   case 3:
17403   case 5:
17404   case 9:
17405     // These scales are formed with basereg+scalereg.  Only accept if there is
17406     // no basereg yet.
17407     if (AM.HasBaseReg)
17408       return false;
17409     break;
17410   default:  // Other stuff never works.
17411     return false;
17412   }
17413
17414   return true;
17415 }
17416
17417 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17418   unsigned Bits = Ty->getScalarSizeInBits();
17419
17420   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17421   // particularly cheaper than those without.
17422   if (Bits == 8)
17423     return false;
17424
17425   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17426   // variable shifts just as cheap as scalar ones.
17427   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17428     return false;
17429
17430   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17431   // fully general vector.
17432   return true;
17433 }
17434
17435 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17436   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17437     return false;
17438   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17439   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17440   return NumBits1 > NumBits2;
17441 }
17442
17443 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17444   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17445     return false;
17446
17447   if (!isTypeLegal(EVT::getEVT(Ty1)))
17448     return false;
17449
17450   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17451
17452   // Assuming the caller doesn't have a zeroext or signext return parameter,
17453   // truncation all the way down to i1 is valid.
17454   return true;
17455 }
17456
17457 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17458   return isInt<32>(Imm);
17459 }
17460
17461 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17462   // Can also use sub to handle negated immediates.
17463   return isInt<32>(Imm);
17464 }
17465
17466 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17467   if (!VT1.isInteger() || !VT2.isInteger())
17468     return false;
17469   unsigned NumBits1 = VT1.getSizeInBits();
17470   unsigned NumBits2 = VT2.getSizeInBits();
17471   return NumBits1 > NumBits2;
17472 }
17473
17474 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17475   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17476   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17477 }
17478
17479 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17480   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17481   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17482 }
17483
17484 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17485   EVT VT1 = Val.getValueType();
17486   if (isZExtFree(VT1, VT2))
17487     return true;
17488
17489   if (Val.getOpcode() != ISD::LOAD)
17490     return false;
17491
17492   if (!VT1.isSimple() || !VT1.isInteger() ||
17493       !VT2.isSimple() || !VT2.isInteger())
17494     return false;
17495
17496   switch (VT1.getSimpleVT().SimpleTy) {
17497   default: break;
17498   case MVT::i8:
17499   case MVT::i16:
17500   case MVT::i32:
17501     // X86 has 8, 16, and 32-bit zero-extending loads.
17502     return true;
17503   }
17504
17505   return false;
17506 }
17507
17508 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17509
17510 bool
17511 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17512   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17513     return false;
17514
17515   VT = VT.getScalarType();
17516
17517   if (!VT.isSimple())
17518     return false;
17519
17520   switch (VT.getSimpleVT().SimpleTy) {
17521   case MVT::f32:
17522   case MVT::f64:
17523     return true;
17524   default:
17525     break;
17526   }
17527
17528   return false;
17529 }
17530
17531 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17532   // i16 instructions are longer (0x66 prefix) and potentially slower.
17533   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17534 }
17535
17536 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17537 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17538 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17539 /// are assumed to be legal.
17540 bool
17541 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17542                                       EVT VT) const {
17543   if (!VT.isSimple())
17544     return false;
17545
17546   // Very little shuffling can be done for 64-bit vectors right now.
17547   if (VT.getSizeInBits() == 64)
17548     return false;
17549
17550   // We only care that the types being shuffled are legal. The lowering can
17551   // handle any possible shuffle mask that results.
17552   return isTypeLegal(VT.getSimpleVT());
17553 }
17554
17555 bool
17556 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17557                                           EVT VT) const {
17558   // Just delegate to the generic legality, clear masks aren't special.
17559   return isShuffleMaskLegal(Mask, VT);
17560 }
17561
17562 //===----------------------------------------------------------------------===//
17563 //                           X86 Scheduler Hooks
17564 //===----------------------------------------------------------------------===//
17565
17566 /// Utility function to emit xbegin specifying the start of an RTM region.
17567 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17568                                      const TargetInstrInfo *TII) {
17569   DebugLoc DL = MI->getDebugLoc();
17570
17571   const BasicBlock *BB = MBB->getBasicBlock();
17572   MachineFunction::iterator I = MBB;
17573   ++I;
17574
17575   // For the v = xbegin(), we generate
17576   //
17577   // thisMBB:
17578   //  xbegin sinkMBB
17579   //
17580   // mainMBB:
17581   //  eax = -1
17582   //
17583   // sinkMBB:
17584   //  v = eax
17585
17586   MachineBasicBlock *thisMBB = MBB;
17587   MachineFunction *MF = MBB->getParent();
17588   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17589   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17590   MF->insert(I, mainMBB);
17591   MF->insert(I, sinkMBB);
17592
17593   // Transfer the remainder of BB and its successor edges to sinkMBB.
17594   sinkMBB->splice(sinkMBB->begin(), MBB,
17595                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17596   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17597
17598   // thisMBB:
17599   //  xbegin sinkMBB
17600   //  # fallthrough to mainMBB
17601   //  # abortion to sinkMBB
17602   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17603   thisMBB->addSuccessor(mainMBB);
17604   thisMBB->addSuccessor(sinkMBB);
17605
17606   // mainMBB:
17607   //  EAX = -1
17608   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17609   mainMBB->addSuccessor(sinkMBB);
17610
17611   // sinkMBB:
17612   // EAX is live into the sinkMBB
17613   sinkMBB->addLiveIn(X86::EAX);
17614   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17615           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17616     .addReg(X86::EAX);
17617
17618   MI->eraseFromParent();
17619   return sinkMBB;
17620 }
17621
17622 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17623 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17624 // in the .td file.
17625 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17626                                        const TargetInstrInfo *TII) {
17627   unsigned Opc;
17628   switch (MI->getOpcode()) {
17629   default: llvm_unreachable("illegal opcode!");
17630   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17631   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17632   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17633   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17634   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17635   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17636   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17637   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17638   }
17639
17640   DebugLoc dl = MI->getDebugLoc();
17641   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17642
17643   unsigned NumArgs = MI->getNumOperands();
17644   for (unsigned i = 1; i < NumArgs; ++i) {
17645     MachineOperand &Op = MI->getOperand(i);
17646     if (!(Op.isReg() && Op.isImplicit()))
17647       MIB.addOperand(Op);
17648   }
17649   if (MI->hasOneMemOperand())
17650     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17651
17652   BuildMI(*BB, MI, dl,
17653     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17654     .addReg(X86::XMM0);
17655
17656   MI->eraseFromParent();
17657   return BB;
17658 }
17659
17660 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17661 // defs in an instruction pattern
17662 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17663                                        const TargetInstrInfo *TII) {
17664   unsigned Opc;
17665   switch (MI->getOpcode()) {
17666   default: llvm_unreachable("illegal opcode!");
17667   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17668   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17669   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17670   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17671   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17672   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17673   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17674   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17675   }
17676
17677   DebugLoc dl = MI->getDebugLoc();
17678   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17679
17680   unsigned NumArgs = MI->getNumOperands(); // remove the results
17681   for (unsigned i = 1; i < NumArgs; ++i) {
17682     MachineOperand &Op = MI->getOperand(i);
17683     if (!(Op.isReg() && Op.isImplicit()))
17684       MIB.addOperand(Op);
17685   }
17686   if (MI->hasOneMemOperand())
17687     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17688
17689   BuildMI(*BB, MI, dl,
17690     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17691     .addReg(X86::ECX);
17692
17693   MI->eraseFromParent();
17694   return BB;
17695 }
17696
17697 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17698                                       const X86Subtarget *Subtarget) {
17699   DebugLoc dl = MI->getDebugLoc();
17700   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17701   // Address into RAX/EAX, other two args into ECX, EDX.
17702   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17703   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17704   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17705   for (int i = 0; i < X86::AddrNumOperands; ++i)
17706     MIB.addOperand(MI->getOperand(i));
17707
17708   unsigned ValOps = X86::AddrNumOperands;
17709   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17710     .addReg(MI->getOperand(ValOps).getReg());
17711   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17712     .addReg(MI->getOperand(ValOps+1).getReg());
17713
17714   // The instruction doesn't actually take any operands though.
17715   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17716
17717   MI->eraseFromParent(); // The pseudo is gone now.
17718   return BB;
17719 }
17720
17721 MachineBasicBlock *
17722 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17723                                                  MachineBasicBlock *MBB) const {
17724   // Emit va_arg instruction on X86-64.
17725
17726   // Operands to this pseudo-instruction:
17727   // 0  ) Output        : destination address (reg)
17728   // 1-5) Input         : va_list address (addr, i64mem)
17729   // 6  ) ArgSize       : Size (in bytes) of vararg type
17730   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17731   // 8  ) Align         : Alignment of type
17732   // 9  ) EFLAGS (implicit-def)
17733
17734   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17735   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17736
17737   unsigned DestReg = MI->getOperand(0).getReg();
17738   MachineOperand &Base = MI->getOperand(1);
17739   MachineOperand &Scale = MI->getOperand(2);
17740   MachineOperand &Index = MI->getOperand(3);
17741   MachineOperand &Disp = MI->getOperand(4);
17742   MachineOperand &Segment = MI->getOperand(5);
17743   unsigned ArgSize = MI->getOperand(6).getImm();
17744   unsigned ArgMode = MI->getOperand(7).getImm();
17745   unsigned Align = MI->getOperand(8).getImm();
17746
17747   // Memory Reference
17748   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17749   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17750   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17751
17752   // Machine Information
17753   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17754   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17755   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17756   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17757   DebugLoc DL = MI->getDebugLoc();
17758
17759   // struct va_list {
17760   //   i32   gp_offset
17761   //   i32   fp_offset
17762   //   i64   overflow_area (address)
17763   //   i64   reg_save_area (address)
17764   // }
17765   // sizeof(va_list) = 24
17766   // alignment(va_list) = 8
17767
17768   unsigned TotalNumIntRegs = 6;
17769   unsigned TotalNumXMMRegs = 8;
17770   bool UseGPOffset = (ArgMode == 1);
17771   bool UseFPOffset = (ArgMode == 2);
17772   unsigned MaxOffset = TotalNumIntRegs * 8 +
17773                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17774
17775   /* Align ArgSize to a multiple of 8 */
17776   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17777   bool NeedsAlign = (Align > 8);
17778
17779   MachineBasicBlock *thisMBB = MBB;
17780   MachineBasicBlock *overflowMBB;
17781   MachineBasicBlock *offsetMBB;
17782   MachineBasicBlock *endMBB;
17783
17784   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17785   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17786   unsigned OffsetReg = 0;
17787
17788   if (!UseGPOffset && !UseFPOffset) {
17789     // If we only pull from the overflow region, we don't create a branch.
17790     // We don't need to alter control flow.
17791     OffsetDestReg = 0; // unused
17792     OverflowDestReg = DestReg;
17793
17794     offsetMBB = nullptr;
17795     overflowMBB = thisMBB;
17796     endMBB = thisMBB;
17797   } else {
17798     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17799     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17800     // If not, pull from overflow_area. (branch to overflowMBB)
17801     //
17802     //       thisMBB
17803     //         |     .
17804     //         |        .
17805     //     offsetMBB   overflowMBB
17806     //         |        .
17807     //         |     .
17808     //        endMBB
17809
17810     // Registers for the PHI in endMBB
17811     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17812     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17813
17814     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17815     MachineFunction *MF = MBB->getParent();
17816     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17817     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17818     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17819
17820     MachineFunction::iterator MBBIter = MBB;
17821     ++MBBIter;
17822
17823     // Insert the new basic blocks
17824     MF->insert(MBBIter, offsetMBB);
17825     MF->insert(MBBIter, overflowMBB);
17826     MF->insert(MBBIter, endMBB);
17827
17828     // Transfer the remainder of MBB and its successor edges to endMBB.
17829     endMBB->splice(endMBB->begin(), thisMBB,
17830                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17831     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17832
17833     // Make offsetMBB and overflowMBB successors of thisMBB
17834     thisMBB->addSuccessor(offsetMBB);
17835     thisMBB->addSuccessor(overflowMBB);
17836
17837     // endMBB is a successor of both offsetMBB and overflowMBB
17838     offsetMBB->addSuccessor(endMBB);
17839     overflowMBB->addSuccessor(endMBB);
17840
17841     // Load the offset value into a register
17842     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17843     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17844       .addOperand(Base)
17845       .addOperand(Scale)
17846       .addOperand(Index)
17847       .addDisp(Disp, UseFPOffset ? 4 : 0)
17848       .addOperand(Segment)
17849       .setMemRefs(MMOBegin, MMOEnd);
17850
17851     // Check if there is enough room left to pull this argument.
17852     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17853       .addReg(OffsetReg)
17854       .addImm(MaxOffset + 8 - ArgSizeA8);
17855
17856     // Branch to "overflowMBB" if offset >= max
17857     // Fall through to "offsetMBB" otherwise
17858     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17859       .addMBB(overflowMBB);
17860   }
17861
17862   // In offsetMBB, emit code to use the reg_save_area.
17863   if (offsetMBB) {
17864     assert(OffsetReg != 0);
17865
17866     // Read the reg_save_area address.
17867     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17868     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17869       .addOperand(Base)
17870       .addOperand(Scale)
17871       .addOperand(Index)
17872       .addDisp(Disp, 16)
17873       .addOperand(Segment)
17874       .setMemRefs(MMOBegin, MMOEnd);
17875
17876     // Zero-extend the offset
17877     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17878       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17879         .addImm(0)
17880         .addReg(OffsetReg)
17881         .addImm(X86::sub_32bit);
17882
17883     // Add the offset to the reg_save_area to get the final address.
17884     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17885       .addReg(OffsetReg64)
17886       .addReg(RegSaveReg);
17887
17888     // Compute the offset for the next argument
17889     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17890     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17891       .addReg(OffsetReg)
17892       .addImm(UseFPOffset ? 16 : 8);
17893
17894     // Store it back into the va_list.
17895     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17896       .addOperand(Base)
17897       .addOperand(Scale)
17898       .addOperand(Index)
17899       .addDisp(Disp, UseFPOffset ? 4 : 0)
17900       .addOperand(Segment)
17901       .addReg(NextOffsetReg)
17902       .setMemRefs(MMOBegin, MMOEnd);
17903
17904     // Jump to endMBB
17905     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
17906       .addMBB(endMBB);
17907   }
17908
17909   //
17910   // Emit code to use overflow area
17911   //
17912
17913   // Load the overflow_area address into a register.
17914   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17915   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17916     .addOperand(Base)
17917     .addOperand(Scale)
17918     .addOperand(Index)
17919     .addDisp(Disp, 8)
17920     .addOperand(Segment)
17921     .setMemRefs(MMOBegin, MMOEnd);
17922
17923   // If we need to align it, do so. Otherwise, just copy the address
17924   // to OverflowDestReg.
17925   if (NeedsAlign) {
17926     // Align the overflow address
17927     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17928     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17929
17930     // aligned_addr = (addr + (align-1)) & ~(align-1)
17931     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17932       .addReg(OverflowAddrReg)
17933       .addImm(Align-1);
17934
17935     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17936       .addReg(TmpReg)
17937       .addImm(~(uint64_t)(Align-1));
17938   } else {
17939     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17940       .addReg(OverflowAddrReg);
17941   }
17942
17943   // Compute the next overflow address after this argument.
17944   // (the overflow address should be kept 8-byte aligned)
17945   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17946   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17947     .addReg(OverflowDestReg)
17948     .addImm(ArgSizeA8);
17949
17950   // Store the new overflow address.
17951   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17952     .addOperand(Base)
17953     .addOperand(Scale)
17954     .addOperand(Index)
17955     .addDisp(Disp, 8)
17956     .addOperand(Segment)
17957     .addReg(NextAddrReg)
17958     .setMemRefs(MMOBegin, MMOEnd);
17959
17960   // If we branched, emit the PHI to the front of endMBB.
17961   if (offsetMBB) {
17962     BuildMI(*endMBB, endMBB->begin(), DL,
17963             TII->get(X86::PHI), DestReg)
17964       .addReg(OffsetDestReg).addMBB(offsetMBB)
17965       .addReg(OverflowDestReg).addMBB(overflowMBB);
17966   }
17967
17968   // Erase the pseudo instruction
17969   MI->eraseFromParent();
17970
17971   return endMBB;
17972 }
17973
17974 MachineBasicBlock *
17975 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17976                                                  MachineInstr *MI,
17977                                                  MachineBasicBlock *MBB) const {
17978   // Emit code to save XMM registers to the stack. The ABI says that the
17979   // number of registers to save is given in %al, so it's theoretically
17980   // possible to do an indirect jump trick to avoid saving all of them,
17981   // however this code takes a simpler approach and just executes all
17982   // of the stores if %al is non-zero. It's less code, and it's probably
17983   // easier on the hardware branch predictor, and stores aren't all that
17984   // expensive anyway.
17985
17986   // Create the new basic blocks. One block contains all the XMM stores,
17987   // and one block is the final destination regardless of whether any
17988   // stores were performed.
17989   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17990   MachineFunction *F = MBB->getParent();
17991   MachineFunction::iterator MBBIter = MBB;
17992   ++MBBIter;
17993   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17994   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17995   F->insert(MBBIter, XMMSaveMBB);
17996   F->insert(MBBIter, EndMBB);
17997
17998   // Transfer the remainder of MBB and its successor edges to EndMBB.
17999   EndMBB->splice(EndMBB->begin(), MBB,
18000                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18001   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18002
18003   // The original block will now fall through to the XMM save block.
18004   MBB->addSuccessor(XMMSaveMBB);
18005   // The XMMSaveMBB will fall through to the end block.
18006   XMMSaveMBB->addSuccessor(EndMBB);
18007
18008   // Now add the instructions.
18009   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18010   DebugLoc DL = MI->getDebugLoc();
18011
18012   unsigned CountReg = MI->getOperand(0).getReg();
18013   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18014   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18015
18016   if (!Subtarget->isTargetWin64()) {
18017     // If %al is 0, branch around the XMM save block.
18018     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18019     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18020     MBB->addSuccessor(EndMBB);
18021   }
18022
18023   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18024   // that was just emitted, but clearly shouldn't be "saved".
18025   assert((MI->getNumOperands() <= 3 ||
18026           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18027           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18028          && "Expected last argument to be EFLAGS");
18029   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18030   // In the XMM save block, save all the XMM argument registers.
18031   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18032     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18033     MachineMemOperand *MMO =
18034       F->getMachineMemOperand(
18035           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18036         MachineMemOperand::MOStore,
18037         /*Size=*/16, /*Align=*/16);
18038     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18039       .addFrameIndex(RegSaveFrameIndex)
18040       .addImm(/*Scale=*/1)
18041       .addReg(/*IndexReg=*/0)
18042       .addImm(/*Disp=*/Offset)
18043       .addReg(/*Segment=*/0)
18044       .addReg(MI->getOperand(i).getReg())
18045       .addMemOperand(MMO);
18046   }
18047
18048   MI->eraseFromParent();   // The pseudo instruction is gone now.
18049
18050   return EndMBB;
18051 }
18052
18053 // The EFLAGS operand of SelectItr might be missing a kill marker
18054 // because there were multiple uses of EFLAGS, and ISel didn't know
18055 // which to mark. Figure out whether SelectItr should have had a
18056 // kill marker, and set it if it should. Returns the correct kill
18057 // marker value.
18058 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18059                                      MachineBasicBlock* BB,
18060                                      const TargetRegisterInfo* TRI) {
18061   // Scan forward through BB for a use/def of EFLAGS.
18062   MachineBasicBlock::iterator miI(std::next(SelectItr));
18063   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18064     const MachineInstr& mi = *miI;
18065     if (mi.readsRegister(X86::EFLAGS))
18066       return false;
18067     if (mi.definesRegister(X86::EFLAGS))
18068       break; // Should have kill-flag - update below.
18069   }
18070
18071   // If we hit the end of the block, check whether EFLAGS is live into a
18072   // successor.
18073   if (miI == BB->end()) {
18074     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18075                                           sEnd = BB->succ_end();
18076          sItr != sEnd; ++sItr) {
18077       MachineBasicBlock* succ = *sItr;
18078       if (succ->isLiveIn(X86::EFLAGS))
18079         return false;
18080     }
18081   }
18082
18083   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18084   // out. SelectMI should have a kill flag on EFLAGS.
18085   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18086   return true;
18087 }
18088
18089 MachineBasicBlock *
18090 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18091                                      MachineBasicBlock *BB) const {
18092   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18093   DebugLoc DL = MI->getDebugLoc();
18094
18095   // To "insert" a SELECT_CC instruction, we actually have to insert the
18096   // diamond control-flow pattern.  The incoming instruction knows the
18097   // destination vreg to set, the condition code register to branch on, the
18098   // true/false values to select between, and a branch opcode to use.
18099   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18100   MachineFunction::iterator It = BB;
18101   ++It;
18102
18103   //  thisMBB:
18104   //  ...
18105   //   TrueVal = ...
18106   //   cmpTY ccX, r1, r2
18107   //   bCC copy1MBB
18108   //   fallthrough --> copy0MBB
18109   MachineBasicBlock *thisMBB = BB;
18110   MachineFunction *F = BB->getParent();
18111   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18112   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18113   F->insert(It, copy0MBB);
18114   F->insert(It, sinkMBB);
18115
18116   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18117   // live into the sink and copy blocks.
18118   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18119   if (!MI->killsRegister(X86::EFLAGS) &&
18120       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18121     copy0MBB->addLiveIn(X86::EFLAGS);
18122     sinkMBB->addLiveIn(X86::EFLAGS);
18123   }
18124
18125   // Transfer the remainder of BB and its successor edges to sinkMBB.
18126   sinkMBB->splice(sinkMBB->begin(), BB,
18127                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18128   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18129
18130   // Add the true and fallthrough blocks as its successors.
18131   BB->addSuccessor(copy0MBB);
18132   BB->addSuccessor(sinkMBB);
18133
18134   // Create the conditional branch instruction.
18135   unsigned Opc =
18136     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18137   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18138
18139   //  copy0MBB:
18140   //   %FalseValue = ...
18141   //   # fallthrough to sinkMBB
18142   copy0MBB->addSuccessor(sinkMBB);
18143
18144   //  sinkMBB:
18145   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18146   //  ...
18147   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18148           TII->get(X86::PHI), MI->getOperand(0).getReg())
18149     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18150     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18151
18152   MI->eraseFromParent();   // The pseudo instruction is gone now.
18153   return sinkMBB;
18154 }
18155
18156 MachineBasicBlock *
18157 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18158                                         MachineBasicBlock *BB) const {
18159   MachineFunction *MF = BB->getParent();
18160   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18161   DebugLoc DL = MI->getDebugLoc();
18162   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18163
18164   assert(MF->shouldSplitStack());
18165
18166   const bool Is64Bit = Subtarget->is64Bit();
18167   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18168
18169   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18170   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18171
18172   // BB:
18173   //  ... [Till the alloca]
18174   // If stacklet is not large enough, jump to mallocMBB
18175   //
18176   // bumpMBB:
18177   //  Allocate by subtracting from RSP
18178   //  Jump to continueMBB
18179   //
18180   // mallocMBB:
18181   //  Allocate by call to runtime
18182   //
18183   // continueMBB:
18184   //  ...
18185   //  [rest of original BB]
18186   //
18187
18188   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18189   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18190   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18191
18192   MachineRegisterInfo &MRI = MF->getRegInfo();
18193   const TargetRegisterClass *AddrRegClass =
18194     getRegClassFor(getPointerTy());
18195
18196   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18197     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18198     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18199     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18200     sizeVReg = MI->getOperand(1).getReg(),
18201     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18202
18203   MachineFunction::iterator MBBIter = BB;
18204   ++MBBIter;
18205
18206   MF->insert(MBBIter, bumpMBB);
18207   MF->insert(MBBIter, mallocMBB);
18208   MF->insert(MBBIter, continueMBB);
18209
18210   continueMBB->splice(continueMBB->begin(), BB,
18211                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18212   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18213
18214   // Add code to the main basic block to check if the stack limit has been hit,
18215   // and if so, jump to mallocMBB otherwise to bumpMBB.
18216   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18217   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18218     .addReg(tmpSPVReg).addReg(sizeVReg);
18219   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18220     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18221     .addReg(SPLimitVReg);
18222   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18223
18224   // bumpMBB simply decreases the stack pointer, since we know the current
18225   // stacklet has enough space.
18226   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18227     .addReg(SPLimitVReg);
18228   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18229     .addReg(SPLimitVReg);
18230   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18231
18232   // Calls into a routine in libgcc to allocate more space from the heap.
18233   const uint32_t *RegMask =
18234       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18235   if (IsLP64) {
18236     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18237       .addReg(sizeVReg);
18238     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18239       .addExternalSymbol("__morestack_allocate_stack_space")
18240       .addRegMask(RegMask)
18241       .addReg(X86::RDI, RegState::Implicit)
18242       .addReg(X86::RAX, RegState::ImplicitDefine);
18243   } else if (Is64Bit) {
18244     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18245       .addReg(sizeVReg);
18246     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18247       .addExternalSymbol("__morestack_allocate_stack_space")
18248       .addRegMask(RegMask)
18249       .addReg(X86::EDI, RegState::Implicit)
18250       .addReg(X86::EAX, RegState::ImplicitDefine);
18251   } else {
18252     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18253       .addImm(12);
18254     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18255     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18256       .addExternalSymbol("__morestack_allocate_stack_space")
18257       .addRegMask(RegMask)
18258       .addReg(X86::EAX, RegState::ImplicitDefine);
18259   }
18260
18261   if (!Is64Bit)
18262     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18263       .addImm(16);
18264
18265   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18266     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18267   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18268
18269   // Set up the CFG correctly.
18270   BB->addSuccessor(bumpMBB);
18271   BB->addSuccessor(mallocMBB);
18272   mallocMBB->addSuccessor(continueMBB);
18273   bumpMBB->addSuccessor(continueMBB);
18274
18275   // Take care of the PHI nodes.
18276   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18277           MI->getOperand(0).getReg())
18278     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18279     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18280
18281   // Delete the original pseudo instruction.
18282   MI->eraseFromParent();
18283
18284   // And we're done.
18285   return continueMBB;
18286 }
18287
18288 MachineBasicBlock *
18289 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18290                                         MachineBasicBlock *BB) const {
18291   DebugLoc DL = MI->getDebugLoc();
18292
18293   assert(!Subtarget->isTargetMachO());
18294
18295   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18296
18297   MI->eraseFromParent();   // The pseudo instruction is gone now.
18298   return BB;
18299 }
18300
18301 MachineBasicBlock *
18302 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18303                                       MachineBasicBlock *BB) const {
18304   // This is pretty easy.  We're taking the value that we received from
18305   // our load from the relocation, sticking it in either RDI (x86-64)
18306   // or EAX and doing an indirect call.  The return value will then
18307   // be in the normal return register.
18308   MachineFunction *F = BB->getParent();
18309   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18310   DebugLoc DL = MI->getDebugLoc();
18311
18312   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18313   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18314
18315   // Get a register mask for the lowered call.
18316   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18317   // proper register mask.
18318   const uint32_t *RegMask =
18319       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18320   if (Subtarget->is64Bit()) {
18321     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18322                                       TII->get(X86::MOV64rm), X86::RDI)
18323     .addReg(X86::RIP)
18324     .addImm(0).addReg(0)
18325     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18326                       MI->getOperand(3).getTargetFlags())
18327     .addReg(0);
18328     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18329     addDirectMem(MIB, X86::RDI);
18330     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18331   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18332     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18333                                       TII->get(X86::MOV32rm), X86::EAX)
18334     .addReg(0)
18335     .addImm(0).addReg(0)
18336     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18337                       MI->getOperand(3).getTargetFlags())
18338     .addReg(0);
18339     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18340     addDirectMem(MIB, X86::EAX);
18341     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18342   } else {
18343     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18344                                       TII->get(X86::MOV32rm), X86::EAX)
18345     .addReg(TII->getGlobalBaseReg(F))
18346     .addImm(0).addReg(0)
18347     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18348                       MI->getOperand(3).getTargetFlags())
18349     .addReg(0);
18350     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18351     addDirectMem(MIB, X86::EAX);
18352     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18353   }
18354
18355   MI->eraseFromParent(); // The pseudo instruction is gone now.
18356   return BB;
18357 }
18358
18359 MachineBasicBlock *
18360 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18361                                     MachineBasicBlock *MBB) const {
18362   DebugLoc DL = MI->getDebugLoc();
18363   MachineFunction *MF = MBB->getParent();
18364   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18365   MachineRegisterInfo &MRI = MF->getRegInfo();
18366
18367   const BasicBlock *BB = MBB->getBasicBlock();
18368   MachineFunction::iterator I = MBB;
18369   ++I;
18370
18371   // Memory Reference
18372   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18373   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18374
18375   unsigned DstReg;
18376   unsigned MemOpndSlot = 0;
18377
18378   unsigned CurOp = 0;
18379
18380   DstReg = MI->getOperand(CurOp++).getReg();
18381   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18382   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18383   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18384   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18385
18386   MemOpndSlot = CurOp;
18387
18388   MVT PVT = getPointerTy();
18389   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18390          "Invalid Pointer Size!");
18391
18392   // For v = setjmp(buf), we generate
18393   //
18394   // thisMBB:
18395   //  buf[LabelOffset] = restoreMBB
18396   //  SjLjSetup restoreMBB
18397   //
18398   // mainMBB:
18399   //  v_main = 0
18400   //
18401   // sinkMBB:
18402   //  v = phi(main, restore)
18403   //
18404   // restoreMBB:
18405   //  if base pointer being used, load it from frame
18406   //  v_restore = 1
18407
18408   MachineBasicBlock *thisMBB = MBB;
18409   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18410   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18411   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18412   MF->insert(I, mainMBB);
18413   MF->insert(I, sinkMBB);
18414   MF->push_back(restoreMBB);
18415
18416   MachineInstrBuilder MIB;
18417
18418   // Transfer the remainder of BB and its successor edges to sinkMBB.
18419   sinkMBB->splice(sinkMBB->begin(), MBB,
18420                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18421   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18422
18423   // thisMBB:
18424   unsigned PtrStoreOpc = 0;
18425   unsigned LabelReg = 0;
18426   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18427   Reloc::Model RM = MF->getTarget().getRelocationModel();
18428   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18429                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18430
18431   // Prepare IP either in reg or imm.
18432   if (!UseImmLabel) {
18433     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18434     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18435     LabelReg = MRI.createVirtualRegister(PtrRC);
18436     if (Subtarget->is64Bit()) {
18437       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18438               .addReg(X86::RIP)
18439               .addImm(0)
18440               .addReg(0)
18441               .addMBB(restoreMBB)
18442               .addReg(0);
18443     } else {
18444       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18445       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18446               .addReg(XII->getGlobalBaseReg(MF))
18447               .addImm(0)
18448               .addReg(0)
18449               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18450               .addReg(0);
18451     }
18452   } else
18453     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18454   // Store IP
18455   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18456   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18457     if (i == X86::AddrDisp)
18458       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18459     else
18460       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18461   }
18462   if (!UseImmLabel)
18463     MIB.addReg(LabelReg);
18464   else
18465     MIB.addMBB(restoreMBB);
18466   MIB.setMemRefs(MMOBegin, MMOEnd);
18467   // Setup
18468   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18469           .addMBB(restoreMBB);
18470
18471   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18472   MIB.addRegMask(RegInfo->getNoPreservedMask());
18473   thisMBB->addSuccessor(mainMBB);
18474   thisMBB->addSuccessor(restoreMBB);
18475
18476   // mainMBB:
18477   //  EAX = 0
18478   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18479   mainMBB->addSuccessor(sinkMBB);
18480
18481   // sinkMBB:
18482   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18483           TII->get(X86::PHI), DstReg)
18484     .addReg(mainDstReg).addMBB(mainMBB)
18485     .addReg(restoreDstReg).addMBB(restoreMBB);
18486
18487   // restoreMBB:
18488   if (RegInfo->hasBasePointer(*MF)) {
18489     const bool Uses64BitFramePtr =
18490         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18491     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18492     X86FI->setRestoreBasePointer(MF);
18493     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18494     unsigned BasePtr = RegInfo->getBaseRegister();
18495     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18496     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18497                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18498       .setMIFlag(MachineInstr::FrameSetup);
18499   }
18500   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18501   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18502   restoreMBB->addSuccessor(sinkMBB);
18503
18504   MI->eraseFromParent();
18505   return sinkMBB;
18506 }
18507
18508 MachineBasicBlock *
18509 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18510                                      MachineBasicBlock *MBB) const {
18511   DebugLoc DL = MI->getDebugLoc();
18512   MachineFunction *MF = MBB->getParent();
18513   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18514   MachineRegisterInfo &MRI = MF->getRegInfo();
18515
18516   // Memory Reference
18517   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18518   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18519
18520   MVT PVT = getPointerTy();
18521   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18522          "Invalid Pointer Size!");
18523
18524   const TargetRegisterClass *RC =
18525     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18526   unsigned Tmp = MRI.createVirtualRegister(RC);
18527   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18528   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18529   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18530   unsigned SP = RegInfo->getStackRegister();
18531
18532   MachineInstrBuilder MIB;
18533
18534   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18535   const int64_t SPOffset = 2 * PVT.getStoreSize();
18536
18537   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18538   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18539
18540   // Reload FP
18541   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18542   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18543     MIB.addOperand(MI->getOperand(i));
18544   MIB.setMemRefs(MMOBegin, MMOEnd);
18545   // Reload IP
18546   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18547   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18548     if (i == X86::AddrDisp)
18549       MIB.addDisp(MI->getOperand(i), LabelOffset);
18550     else
18551       MIB.addOperand(MI->getOperand(i));
18552   }
18553   MIB.setMemRefs(MMOBegin, MMOEnd);
18554   // Reload SP
18555   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18556   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18557     if (i == X86::AddrDisp)
18558       MIB.addDisp(MI->getOperand(i), SPOffset);
18559     else
18560       MIB.addOperand(MI->getOperand(i));
18561   }
18562   MIB.setMemRefs(MMOBegin, MMOEnd);
18563   // Jump
18564   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18565
18566   MI->eraseFromParent();
18567   return MBB;
18568 }
18569
18570 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18571 // accumulator loops. Writing back to the accumulator allows the coalescer
18572 // to remove extra copies in the loop.
18573 MachineBasicBlock *
18574 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18575                                  MachineBasicBlock *MBB) const {
18576   MachineOperand &AddendOp = MI->getOperand(3);
18577
18578   // Bail out early if the addend isn't a register - we can't switch these.
18579   if (!AddendOp.isReg())
18580     return MBB;
18581
18582   MachineFunction &MF = *MBB->getParent();
18583   MachineRegisterInfo &MRI = MF.getRegInfo();
18584
18585   // Check whether the addend is defined by a PHI:
18586   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18587   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18588   if (!AddendDef.isPHI())
18589     return MBB;
18590
18591   // Look for the following pattern:
18592   // loop:
18593   //   %addend = phi [%entry, 0], [%loop, %result]
18594   //   ...
18595   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18596
18597   // Replace with:
18598   //   loop:
18599   //   %addend = phi [%entry, 0], [%loop, %result]
18600   //   ...
18601   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18602
18603   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18604     assert(AddendDef.getOperand(i).isReg());
18605     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18606     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18607     if (&PHISrcInst == MI) {
18608       // Found a matching instruction.
18609       unsigned NewFMAOpc = 0;
18610       switch (MI->getOpcode()) {
18611         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18612         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18613         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18614         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18615         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18616         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18617         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18618         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18619         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18620         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18621         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18622         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18623         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18624         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18625         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18626         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18627         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18628         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18629         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18630         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18631
18632         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18633         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18634         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18635         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18636         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18637         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18638         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18639         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18640         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18641         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18642         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18643         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18644         default: llvm_unreachable("Unrecognized FMA variant.");
18645       }
18646
18647       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18648       MachineInstrBuilder MIB =
18649         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18650         .addOperand(MI->getOperand(0))
18651         .addOperand(MI->getOperand(3))
18652         .addOperand(MI->getOperand(2))
18653         .addOperand(MI->getOperand(1));
18654       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18655       MI->eraseFromParent();
18656     }
18657   }
18658
18659   return MBB;
18660 }
18661
18662 MachineBasicBlock *
18663 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18664                                                MachineBasicBlock *BB) const {
18665   switch (MI->getOpcode()) {
18666   default: llvm_unreachable("Unexpected instr type to insert");
18667   case X86::TAILJMPd64:
18668   case X86::TAILJMPr64:
18669   case X86::TAILJMPm64:
18670   case X86::TAILJMPd64_REX:
18671   case X86::TAILJMPr64_REX:
18672   case X86::TAILJMPm64_REX:
18673     llvm_unreachable("TAILJMP64 would not be touched here.");
18674   case X86::TCRETURNdi64:
18675   case X86::TCRETURNri64:
18676   case X86::TCRETURNmi64:
18677     return BB;
18678   case X86::WIN_ALLOCA:
18679     return EmitLoweredWinAlloca(MI, BB);
18680   case X86::SEG_ALLOCA_32:
18681   case X86::SEG_ALLOCA_64:
18682     return EmitLoweredSegAlloca(MI, BB);
18683   case X86::TLSCall_32:
18684   case X86::TLSCall_64:
18685     return EmitLoweredTLSCall(MI, BB);
18686   case X86::CMOV_GR8:
18687   case X86::CMOV_FR32:
18688   case X86::CMOV_FR64:
18689   case X86::CMOV_V4F32:
18690   case X86::CMOV_V2F64:
18691   case X86::CMOV_V2I64:
18692   case X86::CMOV_V8F32:
18693   case X86::CMOV_V4F64:
18694   case X86::CMOV_V4I64:
18695   case X86::CMOV_V16F32:
18696   case X86::CMOV_V8F64:
18697   case X86::CMOV_V8I64:
18698   case X86::CMOV_GR16:
18699   case X86::CMOV_GR32:
18700   case X86::CMOV_RFP32:
18701   case X86::CMOV_RFP64:
18702   case X86::CMOV_RFP80:
18703     return EmitLoweredSelect(MI, BB);
18704
18705   case X86::FP32_TO_INT16_IN_MEM:
18706   case X86::FP32_TO_INT32_IN_MEM:
18707   case X86::FP32_TO_INT64_IN_MEM:
18708   case X86::FP64_TO_INT16_IN_MEM:
18709   case X86::FP64_TO_INT32_IN_MEM:
18710   case X86::FP64_TO_INT64_IN_MEM:
18711   case X86::FP80_TO_INT16_IN_MEM:
18712   case X86::FP80_TO_INT32_IN_MEM:
18713   case X86::FP80_TO_INT64_IN_MEM: {
18714     MachineFunction *F = BB->getParent();
18715     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18716     DebugLoc DL = MI->getDebugLoc();
18717
18718     // Change the floating point control register to use "round towards zero"
18719     // mode when truncating to an integer value.
18720     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18721     addFrameReference(BuildMI(*BB, MI, DL,
18722                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18723
18724     // Load the old value of the high byte of the control word...
18725     unsigned OldCW =
18726       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18727     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18728                       CWFrameIdx);
18729
18730     // Set the high part to be round to zero...
18731     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18732       .addImm(0xC7F);
18733
18734     // Reload the modified control word now...
18735     addFrameReference(BuildMI(*BB, MI, DL,
18736                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18737
18738     // Restore the memory image of control word to original value
18739     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18740       .addReg(OldCW);
18741
18742     // Get the X86 opcode to use.
18743     unsigned Opc;
18744     switch (MI->getOpcode()) {
18745     default: llvm_unreachable("illegal opcode!");
18746     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18747     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18748     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18749     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18750     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18751     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18752     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18753     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18754     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18755     }
18756
18757     X86AddressMode AM;
18758     MachineOperand &Op = MI->getOperand(0);
18759     if (Op.isReg()) {
18760       AM.BaseType = X86AddressMode::RegBase;
18761       AM.Base.Reg = Op.getReg();
18762     } else {
18763       AM.BaseType = X86AddressMode::FrameIndexBase;
18764       AM.Base.FrameIndex = Op.getIndex();
18765     }
18766     Op = MI->getOperand(1);
18767     if (Op.isImm())
18768       AM.Scale = Op.getImm();
18769     Op = MI->getOperand(2);
18770     if (Op.isImm())
18771       AM.IndexReg = Op.getImm();
18772     Op = MI->getOperand(3);
18773     if (Op.isGlobal()) {
18774       AM.GV = Op.getGlobal();
18775     } else {
18776       AM.Disp = Op.getImm();
18777     }
18778     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18779                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18780
18781     // Reload the original control word now.
18782     addFrameReference(BuildMI(*BB, MI, DL,
18783                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18784
18785     MI->eraseFromParent();   // The pseudo instruction is gone now.
18786     return BB;
18787   }
18788     // String/text processing lowering.
18789   case X86::PCMPISTRM128REG:
18790   case X86::VPCMPISTRM128REG:
18791   case X86::PCMPISTRM128MEM:
18792   case X86::VPCMPISTRM128MEM:
18793   case X86::PCMPESTRM128REG:
18794   case X86::VPCMPESTRM128REG:
18795   case X86::PCMPESTRM128MEM:
18796   case X86::VPCMPESTRM128MEM:
18797     assert(Subtarget->hasSSE42() &&
18798            "Target must have SSE4.2 or AVX features enabled");
18799     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
18800
18801   // String/text processing lowering.
18802   case X86::PCMPISTRIREG:
18803   case X86::VPCMPISTRIREG:
18804   case X86::PCMPISTRIMEM:
18805   case X86::VPCMPISTRIMEM:
18806   case X86::PCMPESTRIREG:
18807   case X86::VPCMPESTRIREG:
18808   case X86::PCMPESTRIMEM:
18809   case X86::VPCMPESTRIMEM:
18810     assert(Subtarget->hasSSE42() &&
18811            "Target must have SSE4.2 or AVX features enabled");
18812     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
18813
18814   // Thread synchronization.
18815   case X86::MONITOR:
18816     return EmitMonitor(MI, BB, Subtarget);
18817
18818   // xbegin
18819   case X86::XBEGIN:
18820     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
18821
18822   case X86::VASTART_SAVE_XMM_REGS:
18823     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18824
18825   case X86::VAARG_64:
18826     return EmitVAARG64WithCustomInserter(MI, BB);
18827
18828   case X86::EH_SjLj_SetJmp32:
18829   case X86::EH_SjLj_SetJmp64:
18830     return emitEHSjLjSetJmp(MI, BB);
18831
18832   case X86::EH_SjLj_LongJmp32:
18833   case X86::EH_SjLj_LongJmp64:
18834     return emitEHSjLjLongJmp(MI, BB);
18835
18836   case TargetOpcode::STATEPOINT:
18837     // As an implementation detail, STATEPOINT shares the STACKMAP format at
18838     // this point in the process.  We diverge later.
18839     return emitPatchPoint(MI, BB);
18840
18841   case TargetOpcode::STACKMAP:
18842   case TargetOpcode::PATCHPOINT:
18843     return emitPatchPoint(MI, BB);
18844
18845   case X86::VFMADDPDr213r:
18846   case X86::VFMADDPSr213r:
18847   case X86::VFMADDSDr213r:
18848   case X86::VFMADDSSr213r:
18849   case X86::VFMSUBPDr213r:
18850   case X86::VFMSUBPSr213r:
18851   case X86::VFMSUBSDr213r:
18852   case X86::VFMSUBSSr213r:
18853   case X86::VFNMADDPDr213r:
18854   case X86::VFNMADDPSr213r:
18855   case X86::VFNMADDSDr213r:
18856   case X86::VFNMADDSSr213r:
18857   case X86::VFNMSUBPDr213r:
18858   case X86::VFNMSUBPSr213r:
18859   case X86::VFNMSUBSDr213r:
18860   case X86::VFNMSUBSSr213r:
18861   case X86::VFMADDSUBPDr213r:
18862   case X86::VFMADDSUBPSr213r:
18863   case X86::VFMSUBADDPDr213r:
18864   case X86::VFMSUBADDPSr213r:
18865   case X86::VFMADDPDr213rY:
18866   case X86::VFMADDPSr213rY:
18867   case X86::VFMSUBPDr213rY:
18868   case X86::VFMSUBPSr213rY:
18869   case X86::VFNMADDPDr213rY:
18870   case X86::VFNMADDPSr213rY:
18871   case X86::VFNMSUBPDr213rY:
18872   case X86::VFNMSUBPSr213rY:
18873   case X86::VFMADDSUBPDr213rY:
18874   case X86::VFMADDSUBPSr213rY:
18875   case X86::VFMSUBADDPDr213rY:
18876   case X86::VFMSUBADDPSr213rY:
18877     return emitFMA3Instr(MI, BB);
18878   }
18879 }
18880
18881 //===----------------------------------------------------------------------===//
18882 //                           X86 Optimization Hooks
18883 //===----------------------------------------------------------------------===//
18884
18885 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18886                                                       APInt &KnownZero,
18887                                                       APInt &KnownOne,
18888                                                       const SelectionDAG &DAG,
18889                                                       unsigned Depth) const {
18890   unsigned BitWidth = KnownZero.getBitWidth();
18891   unsigned Opc = Op.getOpcode();
18892   assert((Opc >= ISD::BUILTIN_OP_END ||
18893           Opc == ISD::INTRINSIC_WO_CHAIN ||
18894           Opc == ISD::INTRINSIC_W_CHAIN ||
18895           Opc == ISD::INTRINSIC_VOID) &&
18896          "Should use MaskedValueIsZero if you don't know whether Op"
18897          " is a target node!");
18898
18899   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18900   switch (Opc) {
18901   default: break;
18902   case X86ISD::ADD:
18903   case X86ISD::SUB:
18904   case X86ISD::ADC:
18905   case X86ISD::SBB:
18906   case X86ISD::SMUL:
18907   case X86ISD::UMUL:
18908   case X86ISD::INC:
18909   case X86ISD::DEC:
18910   case X86ISD::OR:
18911   case X86ISD::XOR:
18912   case X86ISD::AND:
18913     // These nodes' second result is a boolean.
18914     if (Op.getResNo() == 0)
18915       break;
18916     // Fallthrough
18917   case X86ISD::SETCC:
18918     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18919     break;
18920   case ISD::INTRINSIC_WO_CHAIN: {
18921     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18922     unsigned NumLoBits = 0;
18923     switch (IntId) {
18924     default: break;
18925     case Intrinsic::x86_sse_movmsk_ps:
18926     case Intrinsic::x86_avx_movmsk_ps_256:
18927     case Intrinsic::x86_sse2_movmsk_pd:
18928     case Intrinsic::x86_avx_movmsk_pd_256:
18929     case Intrinsic::x86_mmx_pmovmskb:
18930     case Intrinsic::x86_sse2_pmovmskb_128:
18931     case Intrinsic::x86_avx2_pmovmskb: {
18932       // High bits of movmskp{s|d}, pmovmskb are known zero.
18933       switch (IntId) {
18934         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18935         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18936         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18937         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18938         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18939         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18940         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18941         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18942       }
18943       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18944       break;
18945     }
18946     }
18947     break;
18948   }
18949   }
18950 }
18951
18952 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18953   SDValue Op,
18954   const SelectionDAG &,
18955   unsigned Depth) const {
18956   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18957   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18958     return Op.getValueType().getScalarType().getSizeInBits();
18959
18960   // Fallback case.
18961   return 1;
18962 }
18963
18964 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18965 /// node is a GlobalAddress + offset.
18966 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18967                                        const GlobalValue* &GA,
18968                                        int64_t &Offset) const {
18969   if (N->getOpcode() == X86ISD::Wrapper) {
18970     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18971       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18972       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18973       return true;
18974     }
18975   }
18976   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18977 }
18978
18979 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18980 /// same as extracting the high 128-bit part of 256-bit vector and then
18981 /// inserting the result into the low part of a new 256-bit vector
18982 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18983   EVT VT = SVOp->getValueType(0);
18984   unsigned NumElems = VT.getVectorNumElements();
18985
18986   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18987   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18988     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18989         SVOp->getMaskElt(j) >= 0)
18990       return false;
18991
18992   return true;
18993 }
18994
18995 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18996 /// same as extracting the low 128-bit part of 256-bit vector and then
18997 /// inserting the result into the high part of a new 256-bit vector
18998 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18999   EVT VT = SVOp->getValueType(0);
19000   unsigned NumElems = VT.getVectorNumElements();
19001
19002   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19003   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19004     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19005         SVOp->getMaskElt(j) >= 0)
19006       return false;
19007
19008   return true;
19009 }
19010
19011 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19012 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19013                                         TargetLowering::DAGCombinerInfo &DCI,
19014                                         const X86Subtarget* Subtarget) {
19015   SDLoc dl(N);
19016   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19017   SDValue V1 = SVOp->getOperand(0);
19018   SDValue V2 = SVOp->getOperand(1);
19019   EVT VT = SVOp->getValueType(0);
19020   unsigned NumElems = VT.getVectorNumElements();
19021
19022   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19023       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19024     //
19025     //                   0,0,0,...
19026     //                      |
19027     //    V      UNDEF    BUILD_VECTOR    UNDEF
19028     //     \      /           \           /
19029     //  CONCAT_VECTOR         CONCAT_VECTOR
19030     //         \                  /
19031     //          \                /
19032     //          RESULT: V + zero extended
19033     //
19034     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19035         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19036         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19037       return SDValue();
19038
19039     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19040       return SDValue();
19041
19042     // To match the shuffle mask, the first half of the mask should
19043     // be exactly the first vector, and all the rest a splat with the
19044     // first element of the second one.
19045     for (unsigned i = 0; i != NumElems/2; ++i)
19046       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19047           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19048         return SDValue();
19049
19050     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19051     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19052       if (Ld->hasNUsesOfValue(1, 0)) {
19053         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19054         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19055         SDValue ResNode =
19056           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19057                                   Ld->getMemoryVT(),
19058                                   Ld->getPointerInfo(),
19059                                   Ld->getAlignment(),
19060                                   false/*isVolatile*/, true/*ReadMem*/,
19061                                   false/*WriteMem*/);
19062
19063         // Make sure the newly-created LOAD is in the same position as Ld in
19064         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19065         // and update uses of Ld's output chain to use the TokenFactor.
19066         if (Ld->hasAnyUseOfValue(1)) {
19067           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19068                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19069           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19070           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19071                                  SDValue(ResNode.getNode(), 1));
19072         }
19073
19074         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19075       }
19076     }
19077
19078     // Emit a zeroed vector and insert the desired subvector on its
19079     // first half.
19080     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19081     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19082     return DCI.CombineTo(N, InsV);
19083   }
19084
19085   //===--------------------------------------------------------------------===//
19086   // Combine some shuffles into subvector extracts and inserts:
19087   //
19088
19089   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19090   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19091     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19092     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19093     return DCI.CombineTo(N, InsV);
19094   }
19095
19096   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19097   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19098     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19099     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19100     return DCI.CombineTo(N, InsV);
19101   }
19102
19103   return SDValue();
19104 }
19105
19106 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19107 /// possible.
19108 ///
19109 /// This is the leaf of the recursive combinine below. When we have found some
19110 /// chain of single-use x86 shuffle instructions and accumulated the combined
19111 /// shuffle mask represented by them, this will try to pattern match that mask
19112 /// into either a single instruction if there is a special purpose instruction
19113 /// for this operation, or into a PSHUFB instruction which is a fully general
19114 /// instruction but should only be used to replace chains over a certain depth.
19115 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19116                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19117                                    TargetLowering::DAGCombinerInfo &DCI,
19118                                    const X86Subtarget *Subtarget) {
19119   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19120
19121   // Find the operand that enters the chain. Note that multiple uses are OK
19122   // here, we're not going to remove the operand we find.
19123   SDValue Input = Op.getOperand(0);
19124   while (Input.getOpcode() == ISD::BITCAST)
19125     Input = Input.getOperand(0);
19126
19127   MVT VT = Input.getSimpleValueType();
19128   MVT RootVT = Root.getSimpleValueType();
19129   SDLoc DL(Root);
19130
19131   // Just remove no-op shuffle masks.
19132   if (Mask.size() == 1) {
19133     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19134                   /*AddTo*/ true);
19135     return true;
19136   }
19137
19138   // Use the float domain if the operand type is a floating point type.
19139   bool FloatDomain = VT.isFloatingPoint();
19140
19141   // For floating point shuffles, we don't have free copies in the shuffle
19142   // instructions or the ability to load as part of the instruction, so
19143   // canonicalize their shuffles to UNPCK or MOV variants.
19144   //
19145   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19146   // vectors because it can have a load folded into it that UNPCK cannot. This
19147   // doesn't preclude something switching to the shorter encoding post-RA.
19148   //
19149   // FIXME: Should teach these routines about AVX vector widths.
19150   if (FloatDomain && VT.getSizeInBits() == 128) {
19151     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19152       bool Lo = Mask.equals({0, 0});
19153       unsigned Shuffle;
19154       MVT ShuffleVT;
19155       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19156       // is no slower than UNPCKLPD but has the option to fold the input operand
19157       // into even an unaligned memory load.
19158       if (Lo && Subtarget->hasSSE3()) {
19159         Shuffle = X86ISD::MOVDDUP;
19160         ShuffleVT = MVT::v2f64;
19161       } else {
19162         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19163         // than the UNPCK variants.
19164         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19165         ShuffleVT = MVT::v4f32;
19166       }
19167       if (Depth == 1 && Root->getOpcode() == Shuffle)
19168         return false; // Nothing to do!
19169       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19170       DCI.AddToWorklist(Op.getNode());
19171       if (Shuffle == X86ISD::MOVDDUP)
19172         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19173       else
19174         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19175       DCI.AddToWorklist(Op.getNode());
19176       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19177                     /*AddTo*/ true);
19178       return true;
19179     }
19180     if (Subtarget->hasSSE3() &&
19181         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19182       bool Lo = Mask.equals({0, 0, 2, 2});
19183       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19184       MVT ShuffleVT = MVT::v4f32;
19185       if (Depth == 1 && Root->getOpcode() == Shuffle)
19186         return false; // Nothing to do!
19187       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19188       DCI.AddToWorklist(Op.getNode());
19189       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19190       DCI.AddToWorklist(Op.getNode());
19191       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19192                     /*AddTo*/ true);
19193       return true;
19194     }
19195     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19196       bool Lo = Mask.equals({0, 0, 1, 1});
19197       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19198       MVT ShuffleVT = MVT::v4f32;
19199       if (Depth == 1 && Root->getOpcode() == Shuffle)
19200         return false; // Nothing to do!
19201       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19202       DCI.AddToWorklist(Op.getNode());
19203       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19204       DCI.AddToWorklist(Op.getNode());
19205       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19206                     /*AddTo*/ true);
19207       return true;
19208     }
19209   }
19210
19211   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19212   // variants as none of these have single-instruction variants that are
19213   // superior to the UNPCK formulation.
19214   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19215       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19216        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19217        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19218        Mask.equals(
19219            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19220     bool Lo = Mask[0] == 0;
19221     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19222     if (Depth == 1 && Root->getOpcode() == Shuffle)
19223       return false; // Nothing to do!
19224     MVT ShuffleVT;
19225     switch (Mask.size()) {
19226     case 8:
19227       ShuffleVT = MVT::v8i16;
19228       break;
19229     case 16:
19230       ShuffleVT = MVT::v16i8;
19231       break;
19232     default:
19233       llvm_unreachable("Impossible mask size!");
19234     };
19235     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19236     DCI.AddToWorklist(Op.getNode());
19237     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19238     DCI.AddToWorklist(Op.getNode());
19239     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19240                   /*AddTo*/ true);
19241     return true;
19242   }
19243
19244   // Don't try to re-form single instruction chains under any circumstances now
19245   // that we've done encoding canonicalization for them.
19246   if (Depth < 2)
19247     return false;
19248
19249   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19250   // can replace them with a single PSHUFB instruction profitably. Intel's
19251   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19252   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19253   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19254     SmallVector<SDValue, 16> PSHUFBMask;
19255     int NumBytes = VT.getSizeInBits() / 8;
19256     int Ratio = NumBytes / Mask.size();
19257     for (int i = 0; i < NumBytes; ++i) {
19258       if (Mask[i / Ratio] == SM_SentinelUndef) {
19259         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19260         continue;
19261       }
19262       int M = Mask[i / Ratio] != SM_SentinelZero
19263                   ? Ratio * Mask[i / Ratio] + i % Ratio
19264                   : 255;
19265       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19266     }
19267     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19268     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19269     DCI.AddToWorklist(Op.getNode());
19270     SDValue PSHUFBMaskOp =
19271         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19272     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19273     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19274     DCI.AddToWorklist(Op.getNode());
19275     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19276                   /*AddTo*/ true);
19277     return true;
19278   }
19279
19280   // Failed to find any combines.
19281   return false;
19282 }
19283
19284 /// \brief Fully generic combining of x86 shuffle instructions.
19285 ///
19286 /// This should be the last combine run over the x86 shuffle instructions. Once
19287 /// they have been fully optimized, this will recursively consider all chains
19288 /// of single-use shuffle instructions, build a generic model of the cumulative
19289 /// shuffle operation, and check for simpler instructions which implement this
19290 /// operation. We use this primarily for two purposes:
19291 ///
19292 /// 1) Collapse generic shuffles to specialized single instructions when
19293 ///    equivalent. In most cases, this is just an encoding size win, but
19294 ///    sometimes we will collapse multiple generic shuffles into a single
19295 ///    special-purpose shuffle.
19296 /// 2) Look for sequences of shuffle instructions with 3 or more total
19297 ///    instructions, and replace them with the slightly more expensive SSSE3
19298 ///    PSHUFB instruction if available. We do this as the last combining step
19299 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19300 ///    a suitable short sequence of other instructions. The PHUFB will either
19301 ///    use a register or have to read from memory and so is slightly (but only
19302 ///    slightly) more expensive than the other shuffle instructions.
19303 ///
19304 /// Because this is inherently a quadratic operation (for each shuffle in
19305 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19306 /// This should never be an issue in practice as the shuffle lowering doesn't
19307 /// produce sequences of more than 8 instructions.
19308 ///
19309 /// FIXME: We will currently miss some cases where the redundant shuffling
19310 /// would simplify under the threshold for PSHUFB formation because of
19311 /// combine-ordering. To fix this, we should do the redundant instruction
19312 /// combining in this recursive walk.
19313 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19314                                           ArrayRef<int> RootMask,
19315                                           int Depth, bool HasPSHUFB,
19316                                           SelectionDAG &DAG,
19317                                           TargetLowering::DAGCombinerInfo &DCI,
19318                                           const X86Subtarget *Subtarget) {
19319   // Bound the depth of our recursive combine because this is ultimately
19320   // quadratic in nature.
19321   if (Depth > 8)
19322     return false;
19323
19324   // Directly rip through bitcasts to find the underlying operand.
19325   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19326     Op = Op.getOperand(0);
19327
19328   MVT VT = Op.getSimpleValueType();
19329   if (!VT.isVector())
19330     return false; // Bail if we hit a non-vector.
19331
19332   assert(Root.getSimpleValueType().isVector() &&
19333          "Shuffles operate on vector types!");
19334   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19335          "Can only combine shuffles of the same vector register size.");
19336
19337   if (!isTargetShuffle(Op.getOpcode()))
19338     return false;
19339   SmallVector<int, 16> OpMask;
19340   bool IsUnary;
19341   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19342   // We only can combine unary shuffles which we can decode the mask for.
19343   if (!HaveMask || !IsUnary)
19344     return false;
19345
19346   assert(VT.getVectorNumElements() == OpMask.size() &&
19347          "Different mask size from vector size!");
19348   assert(((RootMask.size() > OpMask.size() &&
19349            RootMask.size() % OpMask.size() == 0) ||
19350           (OpMask.size() > RootMask.size() &&
19351            OpMask.size() % RootMask.size() == 0) ||
19352           OpMask.size() == RootMask.size()) &&
19353          "The smaller number of elements must divide the larger.");
19354   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19355   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19356   assert(((RootRatio == 1 && OpRatio == 1) ||
19357           (RootRatio == 1) != (OpRatio == 1)) &&
19358          "Must not have a ratio for both incoming and op masks!");
19359
19360   SmallVector<int, 16> Mask;
19361   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19362
19363   // Merge this shuffle operation's mask into our accumulated mask. Note that
19364   // this shuffle's mask will be the first applied to the input, followed by the
19365   // root mask to get us all the way to the root value arrangement. The reason
19366   // for this order is that we are recursing up the operation chain.
19367   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19368     int RootIdx = i / RootRatio;
19369     if (RootMask[RootIdx] < 0) {
19370       // This is a zero or undef lane, we're done.
19371       Mask.push_back(RootMask[RootIdx]);
19372       continue;
19373     }
19374
19375     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19376     int OpIdx = RootMaskedIdx / OpRatio;
19377     if (OpMask[OpIdx] < 0) {
19378       // The incoming lanes are zero or undef, it doesn't matter which ones we
19379       // are using.
19380       Mask.push_back(OpMask[OpIdx]);
19381       continue;
19382     }
19383
19384     // Ok, we have non-zero lanes, map them through.
19385     Mask.push_back(OpMask[OpIdx] * OpRatio +
19386                    RootMaskedIdx % OpRatio);
19387   }
19388
19389   // See if we can recurse into the operand to combine more things.
19390   switch (Op.getOpcode()) {
19391     case X86ISD::PSHUFB:
19392       HasPSHUFB = true;
19393     case X86ISD::PSHUFD:
19394     case X86ISD::PSHUFHW:
19395     case X86ISD::PSHUFLW:
19396       if (Op.getOperand(0).hasOneUse() &&
19397           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19398                                         HasPSHUFB, DAG, DCI, Subtarget))
19399         return true;
19400       break;
19401
19402     case X86ISD::UNPCKL:
19403     case X86ISD::UNPCKH:
19404       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19405       // We can't check for single use, we have to check that this shuffle is the only user.
19406       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19407           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19408                                         HasPSHUFB, DAG, DCI, Subtarget))
19409           return true;
19410       break;
19411   }
19412
19413   // Minor canonicalization of the accumulated shuffle mask to make it easier
19414   // to match below. All this does is detect masks with squential pairs of
19415   // elements, and shrink them to the half-width mask. It does this in a loop
19416   // so it will reduce the size of the mask to the minimal width mask which
19417   // performs an equivalent shuffle.
19418   SmallVector<int, 16> WidenedMask;
19419   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19420     Mask = std::move(WidenedMask);
19421     WidenedMask.clear();
19422   }
19423
19424   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19425                                 Subtarget);
19426 }
19427
19428 /// \brief Get the PSHUF-style mask from PSHUF node.
19429 ///
19430 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19431 /// PSHUF-style masks that can be reused with such instructions.
19432 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19433   MVT VT = N.getSimpleValueType();
19434   SmallVector<int, 4> Mask;
19435   bool IsUnary;
19436   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19437   (void)HaveMask;
19438   assert(HaveMask);
19439
19440   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19441   // matter. Check that the upper masks are repeats and remove them.
19442   if (VT.getSizeInBits() > 128) {
19443     int LaneElts = 128 / VT.getScalarSizeInBits();
19444 #ifndef NDEBUG
19445     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19446       for (int j = 0; j < LaneElts; ++j)
19447         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19448                "Mask doesn't repeat in high 128-bit lanes!");
19449 #endif
19450     Mask.resize(LaneElts);
19451   }
19452
19453   switch (N.getOpcode()) {
19454   case X86ISD::PSHUFD:
19455     return Mask;
19456   case X86ISD::PSHUFLW:
19457     Mask.resize(4);
19458     return Mask;
19459   case X86ISD::PSHUFHW:
19460     Mask.erase(Mask.begin(), Mask.begin() + 4);
19461     for (int &M : Mask)
19462       M -= 4;
19463     return Mask;
19464   default:
19465     llvm_unreachable("No valid shuffle instruction found!");
19466   }
19467 }
19468
19469 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19470 ///
19471 /// We walk up the chain and look for a combinable shuffle, skipping over
19472 /// shuffles that we could hoist this shuffle's transformation past without
19473 /// altering anything.
19474 static SDValue
19475 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19476                              SelectionDAG &DAG,
19477                              TargetLowering::DAGCombinerInfo &DCI) {
19478   assert(N.getOpcode() == X86ISD::PSHUFD &&
19479          "Called with something other than an x86 128-bit half shuffle!");
19480   SDLoc DL(N);
19481
19482   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19483   // of the shuffles in the chain so that we can form a fresh chain to replace
19484   // this one.
19485   SmallVector<SDValue, 8> Chain;
19486   SDValue V = N.getOperand(0);
19487   for (; V.hasOneUse(); V = V.getOperand(0)) {
19488     switch (V.getOpcode()) {
19489     default:
19490       return SDValue(); // Nothing combined!
19491
19492     case ISD::BITCAST:
19493       // Skip bitcasts as we always know the type for the target specific
19494       // instructions.
19495       continue;
19496
19497     case X86ISD::PSHUFD:
19498       // Found another dword shuffle.
19499       break;
19500
19501     case X86ISD::PSHUFLW:
19502       // Check that the low words (being shuffled) are the identity in the
19503       // dword shuffle, and the high words are self-contained.
19504       if (Mask[0] != 0 || Mask[1] != 1 ||
19505           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19506         return SDValue();
19507
19508       Chain.push_back(V);
19509       continue;
19510
19511     case X86ISD::PSHUFHW:
19512       // Check that the high words (being shuffled) are the identity in the
19513       // dword shuffle, and the low words are self-contained.
19514       if (Mask[2] != 2 || Mask[3] != 3 ||
19515           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19516         return SDValue();
19517
19518       Chain.push_back(V);
19519       continue;
19520
19521     case X86ISD::UNPCKL:
19522     case X86ISD::UNPCKH:
19523       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19524       // shuffle into a preceding word shuffle.
19525       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19526           V.getSimpleValueType().getScalarType() != MVT::i16)
19527         return SDValue();
19528
19529       // Search for a half-shuffle which we can combine with.
19530       unsigned CombineOp =
19531           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19532       if (V.getOperand(0) != V.getOperand(1) ||
19533           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19534         return SDValue();
19535       Chain.push_back(V);
19536       V = V.getOperand(0);
19537       do {
19538         switch (V.getOpcode()) {
19539         default:
19540           return SDValue(); // Nothing to combine.
19541
19542         case X86ISD::PSHUFLW:
19543         case X86ISD::PSHUFHW:
19544           if (V.getOpcode() == CombineOp)
19545             break;
19546
19547           Chain.push_back(V);
19548
19549           // Fallthrough!
19550         case ISD::BITCAST:
19551           V = V.getOperand(0);
19552           continue;
19553         }
19554         break;
19555       } while (V.hasOneUse());
19556       break;
19557     }
19558     // Break out of the loop if we break out of the switch.
19559     break;
19560   }
19561
19562   if (!V.hasOneUse())
19563     // We fell out of the loop without finding a viable combining instruction.
19564     return SDValue();
19565
19566   // Merge this node's mask and our incoming mask.
19567   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19568   for (int &M : Mask)
19569     M = VMask[M];
19570   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19571                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19572
19573   // Rebuild the chain around this new shuffle.
19574   while (!Chain.empty()) {
19575     SDValue W = Chain.pop_back_val();
19576
19577     if (V.getValueType() != W.getOperand(0).getValueType())
19578       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19579
19580     switch (W.getOpcode()) {
19581     default:
19582       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19583
19584     case X86ISD::UNPCKL:
19585     case X86ISD::UNPCKH:
19586       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19587       break;
19588
19589     case X86ISD::PSHUFD:
19590     case X86ISD::PSHUFLW:
19591     case X86ISD::PSHUFHW:
19592       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19593       break;
19594     }
19595   }
19596   if (V.getValueType() != N.getValueType())
19597     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19598
19599   // Return the new chain to replace N.
19600   return V;
19601 }
19602
19603 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19604 ///
19605 /// We walk up the chain, skipping shuffles of the other half and looking
19606 /// through shuffles which switch halves trying to find a shuffle of the same
19607 /// pair of dwords.
19608 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19609                                         SelectionDAG &DAG,
19610                                         TargetLowering::DAGCombinerInfo &DCI) {
19611   assert(
19612       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19613       "Called with something other than an x86 128-bit half shuffle!");
19614   SDLoc DL(N);
19615   unsigned CombineOpcode = N.getOpcode();
19616
19617   // Walk up a single-use chain looking for a combinable shuffle.
19618   SDValue V = N.getOperand(0);
19619   for (; V.hasOneUse(); V = V.getOperand(0)) {
19620     switch (V.getOpcode()) {
19621     default:
19622       return false; // Nothing combined!
19623
19624     case ISD::BITCAST:
19625       // Skip bitcasts as we always know the type for the target specific
19626       // instructions.
19627       continue;
19628
19629     case X86ISD::PSHUFLW:
19630     case X86ISD::PSHUFHW:
19631       if (V.getOpcode() == CombineOpcode)
19632         break;
19633
19634       // Other-half shuffles are no-ops.
19635       continue;
19636     }
19637     // Break out of the loop if we break out of the switch.
19638     break;
19639   }
19640
19641   if (!V.hasOneUse())
19642     // We fell out of the loop without finding a viable combining instruction.
19643     return false;
19644
19645   // Combine away the bottom node as its shuffle will be accumulated into
19646   // a preceding shuffle.
19647   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19648
19649   // Record the old value.
19650   SDValue Old = V;
19651
19652   // Merge this node's mask and our incoming mask (adjusted to account for all
19653   // the pshufd instructions encountered).
19654   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19655   for (int &M : Mask)
19656     M = VMask[M];
19657   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19658                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19659
19660   // Check that the shuffles didn't cancel each other out. If not, we need to
19661   // combine to the new one.
19662   if (Old != V)
19663     // Replace the combinable shuffle with the combined one, updating all users
19664     // so that we re-evaluate the chain here.
19665     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19666
19667   return true;
19668 }
19669
19670 /// \brief Try to combine x86 target specific shuffles.
19671 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19672                                            TargetLowering::DAGCombinerInfo &DCI,
19673                                            const X86Subtarget *Subtarget) {
19674   SDLoc DL(N);
19675   MVT VT = N.getSimpleValueType();
19676   SmallVector<int, 4> Mask;
19677
19678   switch (N.getOpcode()) {
19679   case X86ISD::PSHUFD:
19680   case X86ISD::PSHUFLW:
19681   case X86ISD::PSHUFHW:
19682     Mask = getPSHUFShuffleMask(N);
19683     assert(Mask.size() == 4);
19684     break;
19685   default:
19686     return SDValue();
19687   }
19688
19689   // Nuke no-op shuffles that show up after combining.
19690   if (isNoopShuffleMask(Mask))
19691     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19692
19693   // Look for simplifications involving one or two shuffle instructions.
19694   SDValue V = N.getOperand(0);
19695   switch (N.getOpcode()) {
19696   default:
19697     break;
19698   case X86ISD::PSHUFLW:
19699   case X86ISD::PSHUFHW:
19700     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19701
19702     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19703       return SDValue(); // We combined away this shuffle, so we're done.
19704
19705     // See if this reduces to a PSHUFD which is no more expensive and can
19706     // combine with more operations. Note that it has to at least flip the
19707     // dwords as otherwise it would have been removed as a no-op.
19708     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19709       int DMask[] = {0, 1, 2, 3};
19710       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19711       DMask[DOffset + 0] = DOffset + 1;
19712       DMask[DOffset + 1] = DOffset + 0;
19713       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19714       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19715       DCI.AddToWorklist(V.getNode());
19716       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19717                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19718       DCI.AddToWorklist(V.getNode());
19719       return DAG.getNode(ISD::BITCAST, DL, VT, V);
19720     }
19721
19722     // Look for shuffle patterns which can be implemented as a single unpack.
19723     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19724     // only works when we have a PSHUFD followed by two half-shuffles.
19725     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19726         (V.getOpcode() == X86ISD::PSHUFLW ||
19727          V.getOpcode() == X86ISD::PSHUFHW) &&
19728         V.getOpcode() != N.getOpcode() &&
19729         V.hasOneUse()) {
19730       SDValue D = V.getOperand(0);
19731       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19732         D = D.getOperand(0);
19733       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19734         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19735         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19736         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19737         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19738         int WordMask[8];
19739         for (int i = 0; i < 4; ++i) {
19740           WordMask[i + NOffset] = Mask[i] + NOffset;
19741           WordMask[i + VOffset] = VMask[i] + VOffset;
19742         }
19743         // Map the word mask through the DWord mask.
19744         int MappedMask[8];
19745         for (int i = 0; i < 8; ++i)
19746           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19747         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19748             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19749           // We can replace all three shuffles with an unpack.
19750           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19751           DCI.AddToWorklist(V.getNode());
19752           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19753                                                 : X86ISD::UNPCKH,
19754                              DL, VT, V, V);
19755         }
19756       }
19757     }
19758
19759     break;
19760
19761   case X86ISD::PSHUFD:
19762     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19763       return NewN;
19764
19765     break;
19766   }
19767
19768   return SDValue();
19769 }
19770
19771 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19772 ///
19773 /// We combine this directly on the abstract vector shuffle nodes so it is
19774 /// easier to generically match. We also insert dummy vector shuffle nodes for
19775 /// the operands which explicitly discard the lanes which are unused by this
19776 /// operation to try to flow through the rest of the combiner the fact that
19777 /// they're unused.
19778 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
19779   SDLoc DL(N);
19780   EVT VT = N->getValueType(0);
19781
19782   // We only handle target-independent shuffles.
19783   // FIXME: It would be easy and harmless to use the target shuffle mask
19784   // extraction tool to support more.
19785   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
19786     return SDValue();
19787
19788   auto *SVN = cast<ShuffleVectorSDNode>(N);
19789   ArrayRef<int> Mask = SVN->getMask();
19790   SDValue V1 = N->getOperand(0);
19791   SDValue V2 = N->getOperand(1);
19792
19793   // We require the first shuffle operand to be the SUB node, and the second to
19794   // be the ADD node.
19795   // FIXME: We should support the commuted patterns.
19796   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
19797     return SDValue();
19798
19799   // If there are other uses of these operations we can't fold them.
19800   if (!V1->hasOneUse() || !V2->hasOneUse())
19801     return SDValue();
19802
19803   // Ensure that both operations have the same operands. Note that we can
19804   // commute the FADD operands.
19805   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
19806   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
19807       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
19808     return SDValue();
19809
19810   // We're looking for blends between FADD and FSUB nodes. We insist on these
19811   // nodes being lined up in a specific expected pattern.
19812   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
19813         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
19814         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
19815     return SDValue();
19816
19817   // Only specific types are legal at this point, assert so we notice if and
19818   // when these change.
19819   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
19820           VT == MVT::v4f64) &&
19821          "Unknown vector type encountered!");
19822
19823   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
19824 }
19825
19826 /// PerformShuffleCombine - Performs several different shuffle combines.
19827 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19828                                      TargetLowering::DAGCombinerInfo &DCI,
19829                                      const X86Subtarget *Subtarget) {
19830   SDLoc dl(N);
19831   SDValue N0 = N->getOperand(0);
19832   SDValue N1 = N->getOperand(1);
19833   EVT VT = N->getValueType(0);
19834
19835   // Don't create instructions with illegal types after legalize types has run.
19836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19837   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19838     return SDValue();
19839
19840   // If we have legalized the vector types, look for blends of FADD and FSUB
19841   // nodes that we can fuse into an ADDSUB node.
19842   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
19843     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
19844       return AddSub;
19845
19846   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19847   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19848       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19849     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19850
19851   // During Type Legalization, when promoting illegal vector types,
19852   // the backend might introduce new shuffle dag nodes and bitcasts.
19853   //
19854   // This code performs the following transformation:
19855   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19856   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19857   //
19858   // We do this only if both the bitcast and the BINOP dag nodes have
19859   // one use. Also, perform this transformation only if the new binary
19860   // operation is legal. This is to avoid introducing dag nodes that
19861   // potentially need to be further expanded (or custom lowered) into a
19862   // less optimal sequence of dag nodes.
19863   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19864       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19865       N0.getOpcode() == ISD::BITCAST) {
19866     SDValue BC0 = N0.getOperand(0);
19867     EVT SVT = BC0.getValueType();
19868     unsigned Opcode = BC0.getOpcode();
19869     unsigned NumElts = VT.getVectorNumElements();
19870
19871     if (BC0.hasOneUse() && SVT.isVector() &&
19872         SVT.getVectorNumElements() * 2 == NumElts &&
19873         TLI.isOperationLegal(Opcode, VT)) {
19874       bool CanFold = false;
19875       switch (Opcode) {
19876       default : break;
19877       case ISD::ADD :
19878       case ISD::FADD :
19879       case ISD::SUB :
19880       case ISD::FSUB :
19881       case ISD::MUL :
19882       case ISD::FMUL :
19883         CanFold = true;
19884       }
19885
19886       unsigned SVTNumElts = SVT.getVectorNumElements();
19887       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19888       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19889         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19890       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19891         CanFold = SVOp->getMaskElt(i) < 0;
19892
19893       if (CanFold) {
19894         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19895         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19896         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19897         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19898       }
19899     }
19900   }
19901
19902   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19903   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19904   // consecutive, non-overlapping, and in the right order.
19905   SmallVector<SDValue, 16> Elts;
19906   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19907     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19908
19909   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19910   if (LD.getNode())
19911     return LD;
19912
19913   if (isTargetShuffle(N->getOpcode())) {
19914     SDValue Shuffle =
19915         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19916     if (Shuffle.getNode())
19917       return Shuffle;
19918
19919     // Try recursively combining arbitrary sequences of x86 shuffle
19920     // instructions into higher-order shuffles. We do this after combining
19921     // specific PSHUF instruction sequences into their minimal form so that we
19922     // can evaluate how many specialized shuffle instructions are involved in
19923     // a particular chain.
19924     SmallVector<int, 1> NonceMask; // Just a placeholder.
19925     NonceMask.push_back(0);
19926     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19927                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19928                                       DCI, Subtarget))
19929       return SDValue(); // This routine will use CombineTo to replace N.
19930   }
19931
19932   return SDValue();
19933 }
19934
19935 /// PerformTruncateCombine - Converts truncate operation to
19936 /// a sequence of vector shuffle operations.
19937 /// It is possible when we truncate 256-bit vector to 128-bit vector
19938 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19939                                       TargetLowering::DAGCombinerInfo &DCI,
19940                                       const X86Subtarget *Subtarget)  {
19941   return SDValue();
19942 }
19943
19944 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19945 /// specific shuffle of a load can be folded into a single element load.
19946 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19947 /// shuffles have been custom lowered so we need to handle those here.
19948 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19949                                          TargetLowering::DAGCombinerInfo &DCI) {
19950   if (DCI.isBeforeLegalizeOps())
19951     return SDValue();
19952
19953   SDValue InVec = N->getOperand(0);
19954   SDValue EltNo = N->getOperand(1);
19955
19956   if (!isa<ConstantSDNode>(EltNo))
19957     return SDValue();
19958
19959   EVT OriginalVT = InVec.getValueType();
19960
19961   if (InVec.getOpcode() == ISD::BITCAST) {
19962     // Don't duplicate a load with other uses.
19963     if (!InVec.hasOneUse())
19964       return SDValue();
19965     EVT BCVT = InVec.getOperand(0).getValueType();
19966     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
19967       return SDValue();
19968     InVec = InVec.getOperand(0);
19969   }
19970
19971   EVT CurrentVT = InVec.getValueType();
19972
19973   if (!isTargetShuffle(InVec.getOpcode()))
19974     return SDValue();
19975
19976   // Don't duplicate a load with other uses.
19977   if (!InVec.hasOneUse())
19978     return SDValue();
19979
19980   SmallVector<int, 16> ShuffleMask;
19981   bool UnaryShuffle;
19982   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
19983                             ShuffleMask, UnaryShuffle))
19984     return SDValue();
19985
19986   // Select the input vector, guarding against out of range extract vector.
19987   unsigned NumElems = CurrentVT.getVectorNumElements();
19988   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19989   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19990   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19991                                          : InVec.getOperand(1);
19992
19993   // If inputs to shuffle are the same for both ops, then allow 2 uses
19994   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
19995                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19996
19997   if (LdNode.getOpcode() == ISD::BITCAST) {
19998     // Don't duplicate a load with other uses.
19999     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20000       return SDValue();
20001
20002     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20003     LdNode = LdNode.getOperand(0);
20004   }
20005
20006   if (!ISD::isNormalLoad(LdNode.getNode()))
20007     return SDValue();
20008
20009   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20010
20011   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20012     return SDValue();
20013
20014   EVT EltVT = N->getValueType(0);
20015   // If there's a bitcast before the shuffle, check if the load type and
20016   // alignment is valid.
20017   unsigned Align = LN0->getAlignment();
20018   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20019   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20020       EltVT.getTypeForEVT(*DAG.getContext()));
20021
20022   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20023     return SDValue();
20024
20025   // All checks match so transform back to vector_shuffle so that DAG combiner
20026   // can finish the job
20027   SDLoc dl(N);
20028
20029   // Create shuffle node taking into account the case that its a unary shuffle
20030   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20031                                    : InVec.getOperand(1);
20032   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20033                                  InVec.getOperand(0), Shuffle,
20034                                  &ShuffleMask[0]);
20035   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20036   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20037                      EltNo);
20038 }
20039
20040 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20041 /// special and don't usually play with other vector types, it's better to
20042 /// handle them early to be sure we emit efficient code by avoiding
20043 /// store-load conversions.
20044 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20045   if (N->getValueType(0) != MVT::x86mmx ||
20046       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20047       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20048     return SDValue();
20049
20050   SDValue V = N->getOperand(0);
20051   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20052   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20053     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20054                        N->getValueType(0), V.getOperand(0));
20055
20056   return SDValue();
20057 }
20058
20059 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20060 /// generation and convert it from being a bunch of shuffles and extracts
20061 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20062 /// storing the value and loading scalars back, while for x64 we should
20063 /// use 64-bit extracts and shifts.
20064 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20065                                          TargetLowering::DAGCombinerInfo &DCI) {
20066   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20067   if (NewOp.getNode())
20068     return NewOp;
20069
20070   SDValue InputVector = N->getOperand(0);
20071
20072   // Detect mmx to i32 conversion through a v2i32 elt extract.
20073   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20074       N->getValueType(0) == MVT::i32 &&
20075       InputVector.getValueType() == MVT::v2i32) {
20076
20077     // The bitcast source is a direct mmx result.
20078     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20079     if (MMXSrc.getValueType() == MVT::x86mmx)
20080       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20081                          N->getValueType(0),
20082                          InputVector.getNode()->getOperand(0));
20083
20084     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20085     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20086     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20087         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20088         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20089         MMXSrcOp.getValueType() == MVT::v1i64 &&
20090         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20091       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20092                          N->getValueType(0),
20093                          MMXSrcOp.getOperand(0));
20094   }
20095
20096   // Only operate on vectors of 4 elements, where the alternative shuffling
20097   // gets to be more expensive.
20098   if (InputVector.getValueType() != MVT::v4i32)
20099     return SDValue();
20100
20101   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20102   // single use which is a sign-extend or zero-extend, and all elements are
20103   // used.
20104   SmallVector<SDNode *, 4> Uses;
20105   unsigned ExtractedElements = 0;
20106   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20107        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20108     if (UI.getUse().getResNo() != InputVector.getResNo())
20109       return SDValue();
20110
20111     SDNode *Extract = *UI;
20112     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20113       return SDValue();
20114
20115     if (Extract->getValueType(0) != MVT::i32)
20116       return SDValue();
20117     if (!Extract->hasOneUse())
20118       return SDValue();
20119     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20120         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20121       return SDValue();
20122     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20123       return SDValue();
20124
20125     // Record which element was extracted.
20126     ExtractedElements |=
20127       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20128
20129     Uses.push_back(Extract);
20130   }
20131
20132   // If not all the elements were used, this may not be worthwhile.
20133   if (ExtractedElements != 15)
20134     return SDValue();
20135
20136   // Ok, we've now decided to do the transformation.
20137   // If 64-bit shifts are legal, use the extract-shift sequence,
20138   // otherwise bounce the vector off the cache.
20139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20140   SDValue Vals[4];
20141   SDLoc dl(InputVector);
20142
20143   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20144     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20145     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20146     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20147       DAG.getConstant(0, VecIdxTy));
20148     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20149       DAG.getConstant(1, VecIdxTy));
20150
20151     SDValue ShAmt = DAG.getConstant(32,
20152       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20153     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20154     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20155       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20156     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20157     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20158       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20159   } else {
20160     // Store the value to a temporary stack slot.
20161     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20162     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20163       MachinePointerInfo(), false, false, 0);
20164
20165     EVT ElementType = InputVector.getValueType().getVectorElementType();
20166     unsigned EltSize = ElementType.getSizeInBits() / 8;
20167
20168     // Replace each use (extract) with a load of the appropriate element.
20169     for (unsigned i = 0; i < 4; ++i) {
20170       uint64_t Offset = EltSize * i;
20171       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20172
20173       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20174                                        StackPtr, OffsetVal);
20175
20176       // Load the scalar.
20177       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20178                             ScalarAddr, MachinePointerInfo(),
20179                             false, false, false, 0);
20180
20181     }
20182   }
20183
20184   // Replace the extracts
20185   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20186     UE = Uses.end(); UI != UE; ++UI) {
20187     SDNode *Extract = *UI;
20188
20189     SDValue Idx = Extract->getOperand(1);
20190     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20191     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20192   }
20193
20194   // The replacement was made in place; don't return anything.
20195   return SDValue();
20196 }
20197
20198 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20199 static std::pair<unsigned, bool>
20200 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20201                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20202   if (!VT.isVector())
20203     return std::make_pair(0, false);
20204
20205   bool NeedSplit = false;
20206   switch (VT.getSimpleVT().SimpleTy) {
20207   default: return std::make_pair(0, false);
20208   case MVT::v4i64:
20209   case MVT::v2i64:
20210     if (!Subtarget->hasVLX())
20211       return std::make_pair(0, false);
20212     break;
20213   case MVT::v64i8:
20214   case MVT::v32i16:
20215     if (!Subtarget->hasBWI())
20216       return std::make_pair(0, false);
20217     break;
20218   case MVT::v16i32:
20219   case MVT::v8i64:
20220     if (!Subtarget->hasAVX512())
20221       return std::make_pair(0, false);
20222     break;
20223   case MVT::v32i8:
20224   case MVT::v16i16:
20225   case MVT::v8i32:
20226     if (!Subtarget->hasAVX2())
20227       NeedSplit = true;
20228     if (!Subtarget->hasAVX())
20229       return std::make_pair(0, false);
20230     break;
20231   case MVT::v16i8:
20232   case MVT::v8i16:
20233   case MVT::v4i32:
20234     if (!Subtarget->hasSSE2())
20235       return std::make_pair(0, false);
20236   }
20237
20238   // SSE2 has only a small subset of the operations.
20239   bool hasUnsigned = Subtarget->hasSSE41() ||
20240                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20241   bool hasSigned = Subtarget->hasSSE41() ||
20242                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20243
20244   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20245
20246   unsigned Opc = 0;
20247   // Check for x CC y ? x : y.
20248   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20249       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20250     switch (CC) {
20251     default: break;
20252     case ISD::SETULT:
20253     case ISD::SETULE:
20254       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20255     case ISD::SETUGT:
20256     case ISD::SETUGE:
20257       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20258     case ISD::SETLT:
20259     case ISD::SETLE:
20260       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20261     case ISD::SETGT:
20262     case ISD::SETGE:
20263       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20264     }
20265   // Check for x CC y ? y : x -- a min/max with reversed arms.
20266   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20267              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20268     switch (CC) {
20269     default: break;
20270     case ISD::SETULT:
20271     case ISD::SETULE:
20272       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20273     case ISD::SETUGT:
20274     case ISD::SETUGE:
20275       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20276     case ISD::SETLT:
20277     case ISD::SETLE:
20278       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20279     case ISD::SETGT:
20280     case ISD::SETGE:
20281       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20282     }
20283   }
20284
20285   return std::make_pair(Opc, NeedSplit);
20286 }
20287
20288 static SDValue
20289 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20290                                       const X86Subtarget *Subtarget) {
20291   SDLoc dl(N);
20292   SDValue Cond = N->getOperand(0);
20293   SDValue LHS = N->getOperand(1);
20294   SDValue RHS = N->getOperand(2);
20295
20296   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20297     SDValue CondSrc = Cond->getOperand(0);
20298     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20299       Cond = CondSrc->getOperand(0);
20300   }
20301
20302   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20303     return SDValue();
20304
20305   // A vselect where all conditions and data are constants can be optimized into
20306   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20307   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20308       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20309     return SDValue();
20310
20311   unsigned MaskValue = 0;
20312   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20313     return SDValue();
20314
20315   MVT VT = N->getSimpleValueType(0);
20316   unsigned NumElems = VT.getVectorNumElements();
20317   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20318   for (unsigned i = 0; i < NumElems; ++i) {
20319     // Be sure we emit undef where we can.
20320     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20321       ShuffleMask[i] = -1;
20322     else
20323       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20324   }
20325
20326   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20327   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20328     return SDValue();
20329   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20330 }
20331
20332 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20333 /// nodes.
20334 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20335                                     TargetLowering::DAGCombinerInfo &DCI,
20336                                     const X86Subtarget *Subtarget) {
20337   SDLoc DL(N);
20338   SDValue Cond = N->getOperand(0);
20339   // Get the LHS/RHS of the select.
20340   SDValue LHS = N->getOperand(1);
20341   SDValue RHS = N->getOperand(2);
20342   EVT VT = LHS.getValueType();
20343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20344
20345   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20346   // instructions match the semantics of the common C idiom x<y?x:y but not
20347   // x<=y?x:y, because of how they handle negative zero (which can be
20348   // ignored in unsafe-math mode).
20349   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20350   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20351       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20352       (Subtarget->hasSSE2() ||
20353        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20354     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20355
20356     unsigned Opcode = 0;
20357     // Check for x CC y ? x : y.
20358     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20359         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20360       switch (CC) {
20361       default: break;
20362       case ISD::SETULT:
20363         // Converting this to a min would handle NaNs incorrectly, and swapping
20364         // the operands would cause it to handle comparisons between positive
20365         // and negative zero incorrectly.
20366         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20367           if (!DAG.getTarget().Options.UnsafeFPMath &&
20368               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20369             break;
20370           std::swap(LHS, RHS);
20371         }
20372         Opcode = X86ISD::FMIN;
20373         break;
20374       case ISD::SETOLE:
20375         // Converting this to a min would handle comparisons between positive
20376         // and negative zero incorrectly.
20377         if (!DAG.getTarget().Options.UnsafeFPMath &&
20378             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20379           break;
20380         Opcode = X86ISD::FMIN;
20381         break;
20382       case ISD::SETULE:
20383         // Converting this to a min would handle both negative zeros and NaNs
20384         // incorrectly, but we can swap the operands to fix both.
20385         std::swap(LHS, RHS);
20386       case ISD::SETOLT:
20387       case ISD::SETLT:
20388       case ISD::SETLE:
20389         Opcode = X86ISD::FMIN;
20390         break;
20391
20392       case ISD::SETOGE:
20393         // Converting this to a max would handle comparisons between positive
20394         // and negative zero incorrectly.
20395         if (!DAG.getTarget().Options.UnsafeFPMath &&
20396             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20397           break;
20398         Opcode = X86ISD::FMAX;
20399         break;
20400       case ISD::SETUGT:
20401         // Converting this to a max would handle NaNs incorrectly, and swapping
20402         // the operands would cause it to handle comparisons between positive
20403         // and negative zero incorrectly.
20404         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20405           if (!DAG.getTarget().Options.UnsafeFPMath &&
20406               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20407             break;
20408           std::swap(LHS, RHS);
20409         }
20410         Opcode = X86ISD::FMAX;
20411         break;
20412       case ISD::SETUGE:
20413         // Converting this to a max would handle both negative zeros and NaNs
20414         // incorrectly, but we can swap the operands to fix both.
20415         std::swap(LHS, RHS);
20416       case ISD::SETOGT:
20417       case ISD::SETGT:
20418       case ISD::SETGE:
20419         Opcode = X86ISD::FMAX;
20420         break;
20421       }
20422     // Check for x CC y ? y : x -- a min/max with reversed arms.
20423     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20424                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20425       switch (CC) {
20426       default: break;
20427       case ISD::SETOGE:
20428         // Converting this to a min would handle comparisons between positive
20429         // and negative zero incorrectly, and swapping the operands would
20430         // cause it to handle NaNs incorrectly.
20431         if (!DAG.getTarget().Options.UnsafeFPMath &&
20432             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20433           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20434             break;
20435           std::swap(LHS, RHS);
20436         }
20437         Opcode = X86ISD::FMIN;
20438         break;
20439       case ISD::SETUGT:
20440         // Converting this to a min would handle NaNs incorrectly.
20441         if (!DAG.getTarget().Options.UnsafeFPMath &&
20442             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20443           break;
20444         Opcode = X86ISD::FMIN;
20445         break;
20446       case ISD::SETUGE:
20447         // Converting this to a min would handle both negative zeros and NaNs
20448         // incorrectly, but we can swap the operands to fix both.
20449         std::swap(LHS, RHS);
20450       case ISD::SETOGT:
20451       case ISD::SETGT:
20452       case ISD::SETGE:
20453         Opcode = X86ISD::FMIN;
20454         break;
20455
20456       case ISD::SETULT:
20457         // Converting this to a max would handle NaNs incorrectly.
20458         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20459           break;
20460         Opcode = X86ISD::FMAX;
20461         break;
20462       case ISD::SETOLE:
20463         // Converting this to a max would handle comparisons between positive
20464         // and negative zero incorrectly, and swapping the operands would
20465         // cause it to handle NaNs incorrectly.
20466         if (!DAG.getTarget().Options.UnsafeFPMath &&
20467             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20468           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20469             break;
20470           std::swap(LHS, RHS);
20471         }
20472         Opcode = X86ISD::FMAX;
20473         break;
20474       case ISD::SETULE:
20475         // Converting this to a max would handle both negative zeros and NaNs
20476         // incorrectly, but we can swap the operands to fix both.
20477         std::swap(LHS, RHS);
20478       case ISD::SETOLT:
20479       case ISD::SETLT:
20480       case ISD::SETLE:
20481         Opcode = X86ISD::FMAX;
20482         break;
20483       }
20484     }
20485
20486     if (Opcode)
20487       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20488   }
20489
20490   EVT CondVT = Cond.getValueType();
20491   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20492       CondVT.getVectorElementType() == MVT::i1) {
20493     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20494     // lowering on KNL. In this case we convert it to
20495     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20496     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20497     // Since SKX these selects have a proper lowering.
20498     EVT OpVT = LHS.getValueType();
20499     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20500         (OpVT.getVectorElementType() == MVT::i8 ||
20501          OpVT.getVectorElementType() == MVT::i16) &&
20502         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20503       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20504       DCI.AddToWorklist(Cond.getNode());
20505       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20506     }
20507   }
20508   // If this is a select between two integer constants, try to do some
20509   // optimizations.
20510   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20511     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20512       // Don't do this for crazy integer types.
20513       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20514         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20515         // so that TrueC (the true value) is larger than FalseC.
20516         bool NeedsCondInvert = false;
20517
20518         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20519             // Efficiently invertible.
20520             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20521              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20522               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20523           NeedsCondInvert = true;
20524           std::swap(TrueC, FalseC);
20525         }
20526
20527         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20528         if (FalseC->getAPIntValue() == 0 &&
20529             TrueC->getAPIntValue().isPowerOf2()) {
20530           if (NeedsCondInvert) // Invert the condition if needed.
20531             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20532                                DAG.getConstant(1, Cond.getValueType()));
20533
20534           // Zero extend the condition if needed.
20535           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20536
20537           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20538           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20539                              DAG.getConstant(ShAmt, MVT::i8));
20540         }
20541
20542         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20543         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20544           if (NeedsCondInvert) // Invert the condition if needed.
20545             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20546                                DAG.getConstant(1, Cond.getValueType()));
20547
20548           // Zero extend the condition if needed.
20549           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20550                              FalseC->getValueType(0), Cond);
20551           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20552                              SDValue(FalseC, 0));
20553         }
20554
20555         // Optimize cases that will turn into an LEA instruction.  This requires
20556         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20557         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20558           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20559           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20560
20561           bool isFastMultiplier = false;
20562           if (Diff < 10) {
20563             switch ((unsigned char)Diff) {
20564               default: break;
20565               case 1:  // result = add base, cond
20566               case 2:  // result = lea base(    , cond*2)
20567               case 3:  // result = lea base(cond, cond*2)
20568               case 4:  // result = lea base(    , cond*4)
20569               case 5:  // result = lea base(cond, cond*4)
20570               case 8:  // result = lea base(    , cond*8)
20571               case 9:  // result = lea base(cond, cond*8)
20572                 isFastMultiplier = true;
20573                 break;
20574             }
20575           }
20576
20577           if (isFastMultiplier) {
20578             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20579             if (NeedsCondInvert) // Invert the condition if needed.
20580               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20581                                  DAG.getConstant(1, Cond.getValueType()));
20582
20583             // Zero extend the condition if needed.
20584             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20585                                Cond);
20586             // Scale the condition by the difference.
20587             if (Diff != 1)
20588               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20589                                  DAG.getConstant(Diff, Cond.getValueType()));
20590
20591             // Add the base if non-zero.
20592             if (FalseC->getAPIntValue() != 0)
20593               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20594                                  SDValue(FalseC, 0));
20595             return Cond;
20596           }
20597         }
20598       }
20599   }
20600
20601   // Canonicalize max and min:
20602   // (x > y) ? x : y -> (x >= y) ? x : y
20603   // (x < y) ? x : y -> (x <= y) ? x : y
20604   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20605   // the need for an extra compare
20606   // against zero. e.g.
20607   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20608   // subl   %esi, %edi
20609   // testl  %edi, %edi
20610   // movl   $0, %eax
20611   // cmovgl %edi, %eax
20612   // =>
20613   // xorl   %eax, %eax
20614   // subl   %esi, $edi
20615   // cmovsl %eax, %edi
20616   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20617       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20618       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20619     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20620     switch (CC) {
20621     default: break;
20622     case ISD::SETLT:
20623     case ISD::SETGT: {
20624       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20625       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20626                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20627       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20628     }
20629     }
20630   }
20631
20632   // Early exit check
20633   if (!TLI.isTypeLegal(VT))
20634     return SDValue();
20635
20636   // Match VSELECTs into subs with unsigned saturation.
20637   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20638       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20639       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20640        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20641     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20642
20643     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20644     // left side invert the predicate to simplify logic below.
20645     SDValue Other;
20646     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20647       Other = RHS;
20648       CC = ISD::getSetCCInverse(CC, true);
20649     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20650       Other = LHS;
20651     }
20652
20653     if (Other.getNode() && Other->getNumOperands() == 2 &&
20654         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20655       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20656       SDValue CondRHS = Cond->getOperand(1);
20657
20658       // Look for a general sub with unsigned saturation first.
20659       // x >= y ? x-y : 0 --> subus x, y
20660       // x >  y ? x-y : 0 --> subus x, y
20661       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20662           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20663         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20664
20665       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20666         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20667           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20668             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20669               // If the RHS is a constant we have to reverse the const
20670               // canonicalization.
20671               // x > C-1 ? x+-C : 0 --> subus x, C
20672               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20673                   CondRHSConst->getAPIntValue() ==
20674                       (-OpRHSConst->getAPIntValue() - 1))
20675                 return DAG.getNode(
20676                     X86ISD::SUBUS, DL, VT, OpLHS,
20677                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20678
20679           // Another special case: If C was a sign bit, the sub has been
20680           // canonicalized into a xor.
20681           // FIXME: Would it be better to use computeKnownBits to determine
20682           //        whether it's safe to decanonicalize the xor?
20683           // x s< 0 ? x^C : 0 --> subus x, C
20684           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20685               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20686               OpRHSConst->getAPIntValue().isSignBit())
20687             // Note that we have to rebuild the RHS constant here to ensure we
20688             // don't rely on particular values of undef lanes.
20689             return DAG.getNode(
20690                 X86ISD::SUBUS, DL, VT, OpLHS,
20691                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20692         }
20693     }
20694   }
20695
20696   // Try to match a min/max vector operation.
20697   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20698     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20699     unsigned Opc = ret.first;
20700     bool NeedSplit = ret.second;
20701
20702     if (Opc && NeedSplit) {
20703       unsigned NumElems = VT.getVectorNumElements();
20704       // Extract the LHS vectors
20705       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20706       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20707
20708       // Extract the RHS vectors
20709       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20710       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20711
20712       // Create min/max for each subvector
20713       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20714       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20715
20716       // Merge the result
20717       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20718     } else if (Opc)
20719       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20720   }
20721
20722   // Simplify vector selection if condition value type matches vselect
20723   // operand type
20724   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20725     assert(Cond.getValueType().isVector() &&
20726            "vector select expects a vector selector!");
20727
20728     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20729     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20730
20731     // Try invert the condition if true value is not all 1s and false value
20732     // is not all 0s.
20733     if (!TValIsAllOnes && !FValIsAllZeros &&
20734         // Check if the selector will be produced by CMPP*/PCMP*
20735         Cond.getOpcode() == ISD::SETCC &&
20736         // Check if SETCC has already been promoted
20737         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20738       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20739       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20740
20741       if (TValIsAllZeros || FValIsAllOnes) {
20742         SDValue CC = Cond.getOperand(2);
20743         ISD::CondCode NewCC =
20744           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20745                                Cond.getOperand(0).getValueType().isInteger());
20746         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20747         std::swap(LHS, RHS);
20748         TValIsAllOnes = FValIsAllOnes;
20749         FValIsAllZeros = TValIsAllZeros;
20750       }
20751     }
20752
20753     if (TValIsAllOnes || FValIsAllZeros) {
20754       SDValue Ret;
20755
20756       if (TValIsAllOnes && FValIsAllZeros)
20757         Ret = Cond;
20758       else if (TValIsAllOnes)
20759         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20760                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20761       else if (FValIsAllZeros)
20762         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20763                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20764
20765       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20766     }
20767   }
20768
20769   // We should generate an X86ISD::BLENDI from a vselect if its argument
20770   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20771   // constants. This specific pattern gets generated when we split a
20772   // selector for a 512 bit vector in a machine without AVX512 (but with
20773   // 256-bit vectors), during legalization:
20774   //
20775   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20776   //
20777   // Iff we find this pattern and the build_vectors are built from
20778   // constants, we translate the vselect into a shuffle_vector that we
20779   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20780   if ((N->getOpcode() == ISD::VSELECT ||
20781        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
20782       !DCI.isBeforeLegalize()) {
20783     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20784     if (Shuffle.getNode())
20785       return Shuffle;
20786   }
20787
20788   // If this is a *dynamic* select (non-constant condition) and we can match
20789   // this node with one of the variable blend instructions, restructure the
20790   // condition so that the blends can use the high bit of each element and use
20791   // SimplifyDemandedBits to simplify the condition operand.
20792   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20793       !DCI.isBeforeLegalize() &&
20794       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20795     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20796
20797     // Don't optimize vector selects that map to mask-registers.
20798     if (BitWidth == 1)
20799       return SDValue();
20800
20801     // We can only handle the cases where VSELECT is directly legal on the
20802     // subtarget. We custom lower VSELECT nodes with constant conditions and
20803     // this makes it hard to see whether a dynamic VSELECT will correctly
20804     // lower, so we both check the operation's status and explicitly handle the
20805     // cases where a *dynamic* blend will fail even though a constant-condition
20806     // blend could be custom lowered.
20807     // FIXME: We should find a better way to handle this class of problems.
20808     // Potentially, we should combine constant-condition vselect nodes
20809     // pre-legalization into shuffles and not mark as many types as custom
20810     // lowered.
20811     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
20812       return SDValue();
20813     // FIXME: We don't support i16-element blends currently. We could and
20814     // should support them by making *all* the bits in the condition be set
20815     // rather than just the high bit and using an i8-element blend.
20816     if (VT.getScalarType() == MVT::i16)
20817       return SDValue();
20818     // Dynamic blending was only available from SSE4.1 onward.
20819     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
20820       return SDValue();
20821     // Byte blends are only available in AVX2
20822     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
20823         !Subtarget->hasAVX2())
20824       return SDValue();
20825
20826     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20827     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20828
20829     APInt KnownZero, KnownOne;
20830     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20831                                           DCI.isBeforeLegalizeOps());
20832     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20833         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
20834                                  TLO)) {
20835       // If we changed the computation somewhere in the DAG, this change
20836       // will affect all users of Cond.
20837       // Make sure it is fine and update all the nodes so that we do not
20838       // use the generic VSELECT anymore. Otherwise, we may perform
20839       // wrong optimizations as we messed up with the actual expectation
20840       // for the vector boolean values.
20841       if (Cond != TLO.Old) {
20842         // Check all uses of that condition operand to check whether it will be
20843         // consumed by non-BLEND instructions, which may depend on all bits are
20844         // set properly.
20845         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20846              I != E; ++I)
20847           if (I->getOpcode() != ISD::VSELECT)
20848             // TODO: Add other opcodes eventually lowered into BLEND.
20849             return SDValue();
20850
20851         // Update all the users of the condition, before committing the change,
20852         // so that the VSELECT optimizations that expect the correct vector
20853         // boolean value will not be triggered.
20854         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20855              I != E; ++I)
20856           DAG.ReplaceAllUsesOfValueWith(
20857               SDValue(*I, 0),
20858               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
20859                           Cond, I->getOperand(1), I->getOperand(2)));
20860         DCI.CommitTargetLoweringOpt(TLO);
20861         return SDValue();
20862       }
20863       // At this point, only Cond is changed. Change the condition
20864       // just for N to keep the opportunity to optimize all other
20865       // users their own way.
20866       DAG.ReplaceAllUsesOfValueWith(
20867           SDValue(N, 0),
20868           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
20869                       TLO.New, N->getOperand(1), N->getOperand(2)));
20870       return SDValue();
20871     }
20872   }
20873
20874   return SDValue();
20875 }
20876
20877 // Check whether a boolean test is testing a boolean value generated by
20878 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20879 // code.
20880 //
20881 // Simplify the following patterns:
20882 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20883 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20884 // to (Op EFLAGS Cond)
20885 //
20886 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20887 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20888 // to (Op EFLAGS !Cond)
20889 //
20890 // where Op could be BRCOND or CMOV.
20891 //
20892 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20893   // Quit if not CMP and SUB with its value result used.
20894   if (Cmp.getOpcode() != X86ISD::CMP &&
20895       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20896       return SDValue();
20897
20898   // Quit if not used as a boolean value.
20899   if (CC != X86::COND_E && CC != X86::COND_NE)
20900     return SDValue();
20901
20902   // Check CMP operands. One of them should be 0 or 1 and the other should be
20903   // an SetCC or extended from it.
20904   SDValue Op1 = Cmp.getOperand(0);
20905   SDValue Op2 = Cmp.getOperand(1);
20906
20907   SDValue SetCC;
20908   const ConstantSDNode* C = nullptr;
20909   bool needOppositeCond = (CC == X86::COND_E);
20910   bool checkAgainstTrue = false; // Is it a comparison against 1?
20911
20912   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20913     SetCC = Op2;
20914   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20915     SetCC = Op1;
20916   else // Quit if all operands are not constants.
20917     return SDValue();
20918
20919   if (C->getZExtValue() == 1) {
20920     needOppositeCond = !needOppositeCond;
20921     checkAgainstTrue = true;
20922   } else if (C->getZExtValue() != 0)
20923     // Quit if the constant is neither 0 or 1.
20924     return SDValue();
20925
20926   bool truncatedToBoolWithAnd = false;
20927   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20928   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20929          SetCC.getOpcode() == ISD::TRUNCATE ||
20930          SetCC.getOpcode() == ISD::AND) {
20931     if (SetCC.getOpcode() == ISD::AND) {
20932       int OpIdx = -1;
20933       ConstantSDNode *CS;
20934       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20935           CS->getZExtValue() == 1)
20936         OpIdx = 1;
20937       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20938           CS->getZExtValue() == 1)
20939         OpIdx = 0;
20940       if (OpIdx == -1)
20941         break;
20942       SetCC = SetCC.getOperand(OpIdx);
20943       truncatedToBoolWithAnd = true;
20944     } else
20945       SetCC = SetCC.getOperand(0);
20946   }
20947
20948   switch (SetCC.getOpcode()) {
20949   case X86ISD::SETCC_CARRY:
20950     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20951     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20952     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20953     // truncated to i1 using 'and'.
20954     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20955       break;
20956     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20957            "Invalid use of SETCC_CARRY!");
20958     // FALL THROUGH
20959   case X86ISD::SETCC:
20960     // Set the condition code or opposite one if necessary.
20961     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20962     if (needOppositeCond)
20963       CC = X86::GetOppositeBranchCondition(CC);
20964     return SetCC.getOperand(1);
20965   case X86ISD::CMOV: {
20966     // Check whether false/true value has canonical one, i.e. 0 or 1.
20967     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20968     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20969     // Quit if true value is not a constant.
20970     if (!TVal)
20971       return SDValue();
20972     // Quit if false value is not a constant.
20973     if (!FVal) {
20974       SDValue Op = SetCC.getOperand(0);
20975       // Skip 'zext' or 'trunc' node.
20976       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20977           Op.getOpcode() == ISD::TRUNCATE)
20978         Op = Op.getOperand(0);
20979       // A special case for rdrand/rdseed, where 0 is set if false cond is
20980       // found.
20981       if ((Op.getOpcode() != X86ISD::RDRAND &&
20982            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20983         return SDValue();
20984     }
20985     // Quit if false value is not the constant 0 or 1.
20986     bool FValIsFalse = true;
20987     if (FVal && FVal->getZExtValue() != 0) {
20988       if (FVal->getZExtValue() != 1)
20989         return SDValue();
20990       // If FVal is 1, opposite cond is needed.
20991       needOppositeCond = !needOppositeCond;
20992       FValIsFalse = false;
20993     }
20994     // Quit if TVal is not the constant opposite of FVal.
20995     if (FValIsFalse && TVal->getZExtValue() != 1)
20996       return SDValue();
20997     if (!FValIsFalse && TVal->getZExtValue() != 0)
20998       return SDValue();
20999     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21000     if (needOppositeCond)
21001       CC = X86::GetOppositeBranchCondition(CC);
21002     return SetCC.getOperand(3);
21003   }
21004   }
21005
21006   return SDValue();
21007 }
21008
21009 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21010 /// Match:
21011 ///   (X86or (X86setcc) (X86setcc))
21012 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21013 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21014                                            X86::CondCode &CC1, SDValue &Flags,
21015                                            bool &isAnd) {
21016   if (Cond->getOpcode() == X86ISD::CMP) {
21017     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21018     if (!CondOp1C || !CondOp1C->isNullValue())
21019       return false;
21020
21021     Cond = Cond->getOperand(0);
21022   }
21023
21024   isAnd = false;
21025
21026   SDValue SetCC0, SetCC1;
21027   switch (Cond->getOpcode()) {
21028   default: return false;
21029   case ISD::AND:
21030   case X86ISD::AND:
21031     isAnd = true;
21032     // fallthru
21033   case ISD::OR:
21034   case X86ISD::OR:
21035     SetCC0 = Cond->getOperand(0);
21036     SetCC1 = Cond->getOperand(1);
21037     break;
21038   };
21039
21040   // Make sure we have SETCC nodes, using the same flags value.
21041   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21042       SetCC1.getOpcode() != X86ISD::SETCC ||
21043       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21044     return false;
21045
21046   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21047   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21048   Flags = SetCC0->getOperand(1);
21049   return true;
21050 }
21051
21052 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21053 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21054                                   TargetLowering::DAGCombinerInfo &DCI,
21055                                   const X86Subtarget *Subtarget) {
21056   SDLoc DL(N);
21057
21058   // If the flag operand isn't dead, don't touch this CMOV.
21059   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21060     return SDValue();
21061
21062   SDValue FalseOp = N->getOperand(0);
21063   SDValue TrueOp = N->getOperand(1);
21064   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21065   SDValue Cond = N->getOperand(3);
21066
21067   if (CC == X86::COND_E || CC == X86::COND_NE) {
21068     switch (Cond.getOpcode()) {
21069     default: break;
21070     case X86ISD::BSR:
21071     case X86ISD::BSF:
21072       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21073       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21074         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21075     }
21076   }
21077
21078   SDValue Flags;
21079
21080   Flags = checkBoolTestSetCCCombine(Cond, CC);
21081   if (Flags.getNode() &&
21082       // Extra check as FCMOV only supports a subset of X86 cond.
21083       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21084     SDValue Ops[] = { FalseOp, TrueOp,
21085                       DAG.getConstant(CC, MVT::i8), Flags };
21086     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21087   }
21088
21089   // If this is a select between two integer constants, try to do some
21090   // optimizations.  Note that the operands are ordered the opposite of SELECT
21091   // operands.
21092   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21093     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21094       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21095       // larger than FalseC (the false value).
21096       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21097         CC = X86::GetOppositeBranchCondition(CC);
21098         std::swap(TrueC, FalseC);
21099         std::swap(TrueOp, FalseOp);
21100       }
21101
21102       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21103       // This is efficient for any integer data type (including i8/i16) and
21104       // shift amount.
21105       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21106         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21107                            DAG.getConstant(CC, MVT::i8), Cond);
21108
21109         // Zero extend the condition if needed.
21110         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21111
21112         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21113         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21114                            DAG.getConstant(ShAmt, MVT::i8));
21115         if (N->getNumValues() == 2)  // Dead flag value?
21116           return DCI.CombineTo(N, Cond, SDValue());
21117         return Cond;
21118       }
21119
21120       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21121       // for any integer data type, including i8/i16.
21122       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21123         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21124                            DAG.getConstant(CC, MVT::i8), Cond);
21125
21126         // Zero extend the condition if needed.
21127         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21128                            FalseC->getValueType(0), Cond);
21129         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21130                            SDValue(FalseC, 0));
21131
21132         if (N->getNumValues() == 2)  // Dead flag value?
21133           return DCI.CombineTo(N, Cond, SDValue());
21134         return Cond;
21135       }
21136
21137       // Optimize cases that will turn into an LEA instruction.  This requires
21138       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21139       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21140         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21141         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21142
21143         bool isFastMultiplier = false;
21144         if (Diff < 10) {
21145           switch ((unsigned char)Diff) {
21146           default: break;
21147           case 1:  // result = add base, cond
21148           case 2:  // result = lea base(    , cond*2)
21149           case 3:  // result = lea base(cond, cond*2)
21150           case 4:  // result = lea base(    , cond*4)
21151           case 5:  // result = lea base(cond, cond*4)
21152           case 8:  // result = lea base(    , cond*8)
21153           case 9:  // result = lea base(cond, cond*8)
21154             isFastMultiplier = true;
21155             break;
21156           }
21157         }
21158
21159         if (isFastMultiplier) {
21160           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21161           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21162                              DAG.getConstant(CC, MVT::i8), Cond);
21163           // Zero extend the condition if needed.
21164           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21165                              Cond);
21166           // Scale the condition by the difference.
21167           if (Diff != 1)
21168             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21169                                DAG.getConstant(Diff, Cond.getValueType()));
21170
21171           // Add the base if non-zero.
21172           if (FalseC->getAPIntValue() != 0)
21173             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21174                                SDValue(FalseC, 0));
21175           if (N->getNumValues() == 2)  // Dead flag value?
21176             return DCI.CombineTo(N, Cond, SDValue());
21177           return Cond;
21178         }
21179       }
21180     }
21181   }
21182
21183   // Handle these cases:
21184   //   (select (x != c), e, c) -> select (x != c), e, x),
21185   //   (select (x == c), c, e) -> select (x == c), x, e)
21186   // where the c is an integer constant, and the "select" is the combination
21187   // of CMOV and CMP.
21188   //
21189   // The rationale for this change is that the conditional-move from a constant
21190   // needs two instructions, however, conditional-move from a register needs
21191   // only one instruction.
21192   //
21193   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21194   //  some instruction-combining opportunities. This opt needs to be
21195   //  postponed as late as possible.
21196   //
21197   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21198     // the DCI.xxxx conditions are provided to postpone the optimization as
21199     // late as possible.
21200
21201     ConstantSDNode *CmpAgainst = nullptr;
21202     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21203         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21204         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21205
21206       if (CC == X86::COND_NE &&
21207           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21208         CC = X86::GetOppositeBranchCondition(CC);
21209         std::swap(TrueOp, FalseOp);
21210       }
21211
21212       if (CC == X86::COND_E &&
21213           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21214         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21215                           DAG.getConstant(CC, MVT::i8), Cond };
21216         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21217       }
21218     }
21219   }
21220
21221   // Fold and/or of setcc's to double CMOV:
21222   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21223   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21224   //
21225   // This combine lets us generate:
21226   //   cmovcc1 (jcc1 if we don't have CMOV)
21227   //   cmovcc2 (same)
21228   // instead of:
21229   //   setcc1
21230   //   setcc2
21231   //   and/or
21232   //   cmovne (jne if we don't have CMOV)
21233   // When we can't use the CMOV instruction, it might increase branch
21234   // mispredicts.
21235   // When we can use CMOV, or when there is no mispredict, this improves
21236   // throughput and reduces register pressure.
21237   //
21238   if (CC == X86::COND_NE) {
21239     SDValue Flags;
21240     X86::CondCode CC0, CC1;
21241     bool isAndSetCC;
21242     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21243       if (isAndSetCC) {
21244         std::swap(FalseOp, TrueOp);
21245         CC0 = X86::GetOppositeBranchCondition(CC0);
21246         CC1 = X86::GetOppositeBranchCondition(CC1);
21247       }
21248
21249       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21250         Flags};
21251       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21252       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21253       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21254       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21255       return CMOV;
21256     }
21257   }
21258
21259   return SDValue();
21260 }
21261
21262 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21263                                                 const X86Subtarget *Subtarget) {
21264   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21265   switch (IntNo) {
21266   default: return SDValue();
21267   // SSE/AVX/AVX2 blend intrinsics.
21268   case Intrinsic::x86_avx2_pblendvb:
21269     // Don't try to simplify this intrinsic if we don't have AVX2.
21270     if (!Subtarget->hasAVX2())
21271       return SDValue();
21272     // FALL-THROUGH
21273   case Intrinsic::x86_avx_blendv_pd_256:
21274   case Intrinsic::x86_avx_blendv_ps_256:
21275     // Don't try to simplify this intrinsic if we don't have AVX.
21276     if (!Subtarget->hasAVX())
21277       return SDValue();
21278     // FALL-THROUGH
21279   case Intrinsic::x86_sse41_blendvps:
21280   case Intrinsic::x86_sse41_blendvpd:
21281   case Intrinsic::x86_sse41_pblendvb: {
21282     SDValue Op0 = N->getOperand(1);
21283     SDValue Op1 = N->getOperand(2);
21284     SDValue Mask = N->getOperand(3);
21285
21286     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21287     if (!Subtarget->hasSSE41())
21288       return SDValue();
21289
21290     // fold (blend A, A, Mask) -> A
21291     if (Op0 == Op1)
21292       return Op0;
21293     // fold (blend A, B, allZeros) -> A
21294     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21295       return Op0;
21296     // fold (blend A, B, allOnes) -> B
21297     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21298       return Op1;
21299
21300     // Simplify the case where the mask is a constant i32 value.
21301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21302       if (C->isNullValue())
21303         return Op0;
21304       if (C->isAllOnesValue())
21305         return Op1;
21306     }
21307
21308     return SDValue();
21309   }
21310
21311   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21312   case Intrinsic::x86_sse2_psrai_w:
21313   case Intrinsic::x86_sse2_psrai_d:
21314   case Intrinsic::x86_avx2_psrai_w:
21315   case Intrinsic::x86_avx2_psrai_d:
21316   case Intrinsic::x86_sse2_psra_w:
21317   case Intrinsic::x86_sse2_psra_d:
21318   case Intrinsic::x86_avx2_psra_w:
21319   case Intrinsic::x86_avx2_psra_d: {
21320     SDValue Op0 = N->getOperand(1);
21321     SDValue Op1 = N->getOperand(2);
21322     EVT VT = Op0.getValueType();
21323     assert(VT.isVector() && "Expected a vector type!");
21324
21325     if (isa<BuildVectorSDNode>(Op1))
21326       Op1 = Op1.getOperand(0);
21327
21328     if (!isa<ConstantSDNode>(Op1))
21329       return SDValue();
21330
21331     EVT SVT = VT.getVectorElementType();
21332     unsigned SVTBits = SVT.getSizeInBits();
21333
21334     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21335     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21336     uint64_t ShAmt = C.getZExtValue();
21337
21338     // Don't try to convert this shift into a ISD::SRA if the shift
21339     // count is bigger than or equal to the element size.
21340     if (ShAmt >= SVTBits)
21341       return SDValue();
21342
21343     // Trivial case: if the shift count is zero, then fold this
21344     // into the first operand.
21345     if (ShAmt == 0)
21346       return Op0;
21347
21348     // Replace this packed shift intrinsic with a target independent
21349     // shift dag node.
21350     SDValue Splat = DAG.getConstant(C, VT);
21351     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21352   }
21353   }
21354 }
21355
21356 /// PerformMulCombine - Optimize a single multiply with constant into two
21357 /// in order to implement it with two cheaper instructions, e.g.
21358 /// LEA + SHL, LEA + LEA.
21359 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21360                                  TargetLowering::DAGCombinerInfo &DCI) {
21361   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21362     return SDValue();
21363
21364   EVT VT = N->getValueType(0);
21365   if (VT != MVT::i64 && VT != MVT::i32)
21366     return SDValue();
21367
21368   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21369   if (!C)
21370     return SDValue();
21371   uint64_t MulAmt = C->getZExtValue();
21372   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21373     return SDValue();
21374
21375   uint64_t MulAmt1 = 0;
21376   uint64_t MulAmt2 = 0;
21377   if ((MulAmt % 9) == 0) {
21378     MulAmt1 = 9;
21379     MulAmt2 = MulAmt / 9;
21380   } else if ((MulAmt % 5) == 0) {
21381     MulAmt1 = 5;
21382     MulAmt2 = MulAmt / 5;
21383   } else if ((MulAmt % 3) == 0) {
21384     MulAmt1 = 3;
21385     MulAmt2 = MulAmt / 3;
21386   }
21387   if (MulAmt2 &&
21388       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21389     SDLoc DL(N);
21390
21391     if (isPowerOf2_64(MulAmt2) &&
21392         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21393       // If second multiplifer is pow2, issue it first. We want the multiply by
21394       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21395       // is an add.
21396       std::swap(MulAmt1, MulAmt2);
21397
21398     SDValue NewMul;
21399     if (isPowerOf2_64(MulAmt1))
21400       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21401                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21402     else
21403       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21404                            DAG.getConstant(MulAmt1, VT));
21405
21406     if (isPowerOf2_64(MulAmt2))
21407       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21408                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21409     else
21410       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21411                            DAG.getConstant(MulAmt2, VT));
21412
21413     // Do not add new nodes to DAG combiner worklist.
21414     DCI.CombineTo(N, NewMul, false);
21415   }
21416   return SDValue();
21417 }
21418
21419 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21420   SDValue N0 = N->getOperand(0);
21421   SDValue N1 = N->getOperand(1);
21422   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21423   EVT VT = N0.getValueType();
21424
21425   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21426   // since the result of setcc_c is all zero's or all ones.
21427   if (VT.isInteger() && !VT.isVector() &&
21428       N1C && N0.getOpcode() == ISD::AND &&
21429       N0.getOperand(1).getOpcode() == ISD::Constant) {
21430     SDValue N00 = N0.getOperand(0);
21431     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21432         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21433           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21434          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21435       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21436       APInt ShAmt = N1C->getAPIntValue();
21437       Mask = Mask.shl(ShAmt);
21438       if (Mask != 0)
21439         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21440                            N00, DAG.getConstant(Mask, VT));
21441     }
21442   }
21443
21444   // Hardware support for vector shifts is sparse which makes us scalarize the
21445   // vector operations in many cases. Also, on sandybridge ADD is faster than
21446   // shl.
21447   // (shl V, 1) -> add V,V
21448   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21449     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21450       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21451       // We shift all of the values by one. In many cases we do not have
21452       // hardware support for this operation. This is better expressed as an ADD
21453       // of two values.
21454       if (N1SplatC->getZExtValue() == 1)
21455         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21456     }
21457
21458   return SDValue();
21459 }
21460
21461 /// \brief Returns a vector of 0s if the node in input is a vector logical
21462 /// shift by a constant amount which is known to be bigger than or equal
21463 /// to the vector element size in bits.
21464 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21465                                       const X86Subtarget *Subtarget) {
21466   EVT VT = N->getValueType(0);
21467
21468   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21469       (!Subtarget->hasInt256() ||
21470        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21471     return SDValue();
21472
21473   SDValue Amt = N->getOperand(1);
21474   SDLoc DL(N);
21475   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21476     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21477       APInt ShiftAmt = AmtSplat->getAPIntValue();
21478       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21479
21480       // SSE2/AVX2 logical shifts always return a vector of 0s
21481       // if the shift amount is bigger than or equal to
21482       // the element size. The constant shift amount will be
21483       // encoded as a 8-bit immediate.
21484       if (ShiftAmt.trunc(8).uge(MaxAmount))
21485         return getZeroVector(VT, Subtarget, DAG, DL);
21486     }
21487
21488   return SDValue();
21489 }
21490
21491 /// PerformShiftCombine - Combine shifts.
21492 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21493                                    TargetLowering::DAGCombinerInfo &DCI,
21494                                    const X86Subtarget *Subtarget) {
21495   if (N->getOpcode() == ISD::SHL) {
21496     SDValue V = PerformSHLCombine(N, DAG);
21497     if (V.getNode()) return V;
21498   }
21499
21500   if (N->getOpcode() != ISD::SRA) {
21501     // Try to fold this logical shift into a zero vector.
21502     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21503     if (V.getNode()) return V;
21504   }
21505
21506   return SDValue();
21507 }
21508
21509 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21510 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21511 // and friends.  Likewise for OR -> CMPNEQSS.
21512 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21513                             TargetLowering::DAGCombinerInfo &DCI,
21514                             const X86Subtarget *Subtarget) {
21515   unsigned opcode;
21516
21517   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21518   // we're requiring SSE2 for both.
21519   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21520     SDValue N0 = N->getOperand(0);
21521     SDValue N1 = N->getOperand(1);
21522     SDValue CMP0 = N0->getOperand(1);
21523     SDValue CMP1 = N1->getOperand(1);
21524     SDLoc DL(N);
21525
21526     // The SETCCs should both refer to the same CMP.
21527     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21528       return SDValue();
21529
21530     SDValue CMP00 = CMP0->getOperand(0);
21531     SDValue CMP01 = CMP0->getOperand(1);
21532     EVT     VT    = CMP00.getValueType();
21533
21534     if (VT == MVT::f32 || VT == MVT::f64) {
21535       bool ExpectingFlags = false;
21536       // Check for any users that want flags:
21537       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21538            !ExpectingFlags && UI != UE; ++UI)
21539         switch (UI->getOpcode()) {
21540         default:
21541         case ISD::BR_CC:
21542         case ISD::BRCOND:
21543         case ISD::SELECT:
21544           ExpectingFlags = true;
21545           break;
21546         case ISD::CopyToReg:
21547         case ISD::SIGN_EXTEND:
21548         case ISD::ZERO_EXTEND:
21549         case ISD::ANY_EXTEND:
21550           break;
21551         }
21552
21553       if (!ExpectingFlags) {
21554         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21555         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21556
21557         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21558           X86::CondCode tmp = cc0;
21559           cc0 = cc1;
21560           cc1 = tmp;
21561         }
21562
21563         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21564             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21565           // FIXME: need symbolic constants for these magic numbers.
21566           // See X86ATTInstPrinter.cpp:printSSECC().
21567           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21568           if (Subtarget->hasAVX512()) {
21569             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21570                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21571             if (N->getValueType(0) != MVT::i1)
21572               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21573                                  FSetCC);
21574             return FSetCC;
21575           }
21576           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21577                                               CMP00.getValueType(), CMP00, CMP01,
21578                                               DAG.getConstant(x86cc, MVT::i8));
21579
21580           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21581           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21582
21583           if (is64BitFP && !Subtarget->is64Bit()) {
21584             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21585             // 64-bit integer, since that's not a legal type. Since
21586             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21587             // bits, but can do this little dance to extract the lowest 32 bits
21588             // and work with those going forward.
21589             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21590                                            OnesOrZeroesF);
21591             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21592                                            Vector64);
21593             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21594                                         Vector32, DAG.getIntPtrConstant(0));
21595             IntVT = MVT::i32;
21596           }
21597
21598           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21599           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21600                                       DAG.getConstant(1, IntVT));
21601           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21602           return OneBitOfTruth;
21603         }
21604       }
21605     }
21606   }
21607   return SDValue();
21608 }
21609
21610 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21611 /// so it can be folded inside ANDNP.
21612 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21613   EVT VT = N->getValueType(0);
21614
21615   // Match direct AllOnes for 128 and 256-bit vectors
21616   if (ISD::isBuildVectorAllOnes(N))
21617     return true;
21618
21619   // Look through a bit convert.
21620   if (N->getOpcode() == ISD::BITCAST)
21621     N = N->getOperand(0).getNode();
21622
21623   // Sometimes the operand may come from a insert_subvector building a 256-bit
21624   // allones vector
21625   if (VT.is256BitVector() &&
21626       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21627     SDValue V1 = N->getOperand(0);
21628     SDValue V2 = N->getOperand(1);
21629
21630     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21631         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21632         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21633         ISD::isBuildVectorAllOnes(V2.getNode()))
21634       return true;
21635   }
21636
21637   return false;
21638 }
21639
21640 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21641 // register. In most cases we actually compare or select YMM-sized registers
21642 // and mixing the two types creates horrible code. This method optimizes
21643 // some of the transition sequences.
21644 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21645                                  TargetLowering::DAGCombinerInfo &DCI,
21646                                  const X86Subtarget *Subtarget) {
21647   EVT VT = N->getValueType(0);
21648   if (!VT.is256BitVector())
21649     return SDValue();
21650
21651   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21652           N->getOpcode() == ISD::ZERO_EXTEND ||
21653           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21654
21655   SDValue Narrow = N->getOperand(0);
21656   EVT NarrowVT = Narrow->getValueType(0);
21657   if (!NarrowVT.is128BitVector())
21658     return SDValue();
21659
21660   if (Narrow->getOpcode() != ISD::XOR &&
21661       Narrow->getOpcode() != ISD::AND &&
21662       Narrow->getOpcode() != ISD::OR)
21663     return SDValue();
21664
21665   SDValue N0  = Narrow->getOperand(0);
21666   SDValue N1  = Narrow->getOperand(1);
21667   SDLoc DL(Narrow);
21668
21669   // The Left side has to be a trunc.
21670   if (N0.getOpcode() != ISD::TRUNCATE)
21671     return SDValue();
21672
21673   // The type of the truncated inputs.
21674   EVT WideVT = N0->getOperand(0)->getValueType(0);
21675   if (WideVT != VT)
21676     return SDValue();
21677
21678   // The right side has to be a 'trunc' or a constant vector.
21679   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21680   ConstantSDNode *RHSConstSplat = nullptr;
21681   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21682     RHSConstSplat = RHSBV->getConstantSplatNode();
21683   if (!RHSTrunc && !RHSConstSplat)
21684     return SDValue();
21685
21686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21687
21688   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21689     return SDValue();
21690
21691   // Set N0 and N1 to hold the inputs to the new wide operation.
21692   N0 = N0->getOperand(0);
21693   if (RHSConstSplat) {
21694     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21695                      SDValue(RHSConstSplat, 0));
21696     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21697     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21698   } else if (RHSTrunc) {
21699     N1 = N1->getOperand(0);
21700   }
21701
21702   // Generate the wide operation.
21703   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21704   unsigned Opcode = N->getOpcode();
21705   switch (Opcode) {
21706   case ISD::ANY_EXTEND:
21707     return Op;
21708   case ISD::ZERO_EXTEND: {
21709     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21710     APInt Mask = APInt::getAllOnesValue(InBits);
21711     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21712     return DAG.getNode(ISD::AND, DL, VT,
21713                        Op, DAG.getConstant(Mask, VT));
21714   }
21715   case ISD::SIGN_EXTEND:
21716     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21717                        Op, DAG.getValueType(NarrowVT));
21718   default:
21719     llvm_unreachable("Unexpected opcode");
21720   }
21721 }
21722
21723 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21724                                  TargetLowering::DAGCombinerInfo &DCI,
21725                                  const X86Subtarget *Subtarget) {
21726   SDValue N0 = N->getOperand(0);
21727   SDValue N1 = N->getOperand(1);
21728   SDLoc DL(N);
21729
21730   // A vector zext_in_reg may be represented as a shuffle,
21731   // feeding into a bitcast (this represents anyext) feeding into
21732   // an and with a mask.
21733   // We'd like to try to combine that into a shuffle with zero
21734   // plus a bitcast, removing the and.
21735   if (N0.getOpcode() != ISD::BITCAST || 
21736       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21737     return SDValue();
21738
21739   // The other side of the AND should be a splat of 2^C, where C
21740   // is the number of bits in the source type.
21741   if (N1.getOpcode() == ISD::BITCAST)
21742     N1 = N1.getOperand(0);
21743   if (N1.getOpcode() != ISD::BUILD_VECTOR)
21744     return SDValue();
21745   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21746
21747   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21748   EVT SrcType = Shuffle->getValueType(0);
21749
21750   // We expect a single-source shuffle
21751   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21752     return SDValue();
21753
21754   unsigned SrcSize = SrcType.getScalarSizeInBits();
21755
21756   APInt SplatValue, SplatUndef;
21757   unsigned SplatBitSize;
21758   bool HasAnyUndefs;
21759   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21760                                 SplatBitSize, HasAnyUndefs))
21761     return SDValue();
21762
21763   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21764   // Make sure the splat matches the mask we expect
21765   if (SplatBitSize > ResSize || 
21766       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21767     return SDValue();
21768
21769   // Make sure the input and output size make sense
21770   if (SrcSize >= ResSize || ResSize % SrcSize)
21771     return SDValue();
21772
21773   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21774   // The number of u's between each two values depends on the ratio between
21775   // the source and dest type.
21776   unsigned ZextRatio = ResSize / SrcSize;
21777   bool IsZext = true;
21778   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
21779     if (i % ZextRatio) {
21780       if (Shuffle->getMaskElt(i) > 0) {
21781         // Expected undef
21782         IsZext = false;
21783         break;
21784       }
21785     } else {
21786       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
21787         // Expected element number
21788         IsZext = false;
21789         break;
21790       }
21791     }
21792   }
21793
21794   if (!IsZext)
21795     return SDValue();
21796
21797   // Ok, perform the transformation - replace the shuffle with
21798   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
21799   // (instead of undef) where the k elements come from the zero vector.
21800   SmallVector<int, 8> Mask;
21801   unsigned NumElems = SrcType.getVectorNumElements();
21802   for (unsigned i = 0; i < NumElems; ++i)
21803     if (i % ZextRatio)
21804       Mask.push_back(NumElems);
21805     else
21806       Mask.push_back(i / ZextRatio);
21807
21808   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
21809     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
21810   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
21811 }
21812
21813 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21814                                  TargetLowering::DAGCombinerInfo &DCI,
21815                                  const X86Subtarget *Subtarget) {
21816   if (DCI.isBeforeLegalizeOps())
21817     return SDValue();
21818
21819   SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
21820   if (Zext.getNode())
21821     return Zext;
21822
21823   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21824   if (R.getNode())
21825     return R;
21826
21827   EVT VT = N->getValueType(0);
21828   SDValue N0 = N->getOperand(0);
21829   SDValue N1 = N->getOperand(1);
21830   SDLoc DL(N);
21831
21832   // Create BEXTR instructions
21833   // BEXTR is ((X >> imm) & (2**size-1))
21834   if (VT == MVT::i32 || VT == MVT::i64) {
21835     // Check for BEXTR.
21836     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21837         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21838       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21839       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21840       if (MaskNode && ShiftNode) {
21841         uint64_t Mask = MaskNode->getZExtValue();
21842         uint64_t Shift = ShiftNode->getZExtValue();
21843         if (isMask_64(Mask)) {
21844           uint64_t MaskSize = countPopulation(Mask);
21845           if (Shift + MaskSize <= VT.getSizeInBits())
21846             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21847                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21848         }
21849       }
21850     } // BEXTR
21851
21852     return SDValue();
21853   }
21854
21855   // Want to form ANDNP nodes:
21856   // 1) In the hopes of then easily combining them with OR and AND nodes
21857   //    to form PBLEND/PSIGN.
21858   // 2) To match ANDN packed intrinsics
21859   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21860     return SDValue();
21861
21862   // Check LHS for vnot
21863   if (N0.getOpcode() == ISD::XOR &&
21864       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21865       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21866     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21867
21868   // Check RHS for vnot
21869   if (N1.getOpcode() == ISD::XOR &&
21870       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21871       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21872     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21873
21874   return SDValue();
21875 }
21876
21877 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21878                                 TargetLowering::DAGCombinerInfo &DCI,
21879                                 const X86Subtarget *Subtarget) {
21880   if (DCI.isBeforeLegalizeOps())
21881     return SDValue();
21882
21883   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21884   if (R.getNode())
21885     return R;
21886
21887   SDValue N0 = N->getOperand(0);
21888   SDValue N1 = N->getOperand(1);
21889   EVT VT = N->getValueType(0);
21890
21891   // look for psign/blend
21892   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21893     if (!Subtarget->hasSSSE3() ||
21894         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21895       return SDValue();
21896
21897     // Canonicalize pandn to RHS
21898     if (N0.getOpcode() == X86ISD::ANDNP)
21899       std::swap(N0, N1);
21900     // or (and (m, y), (pandn m, x))
21901     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21902       SDValue Mask = N1.getOperand(0);
21903       SDValue X    = N1.getOperand(1);
21904       SDValue Y;
21905       if (N0.getOperand(0) == Mask)
21906         Y = N0.getOperand(1);
21907       if (N0.getOperand(1) == Mask)
21908         Y = N0.getOperand(0);
21909
21910       // Check to see if the mask appeared in both the AND and ANDNP and
21911       if (!Y.getNode())
21912         return SDValue();
21913
21914       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21915       // Look through mask bitcast.
21916       if (Mask.getOpcode() == ISD::BITCAST)
21917         Mask = Mask.getOperand(0);
21918       if (X.getOpcode() == ISD::BITCAST)
21919         X = X.getOperand(0);
21920       if (Y.getOpcode() == ISD::BITCAST)
21921         Y = Y.getOperand(0);
21922
21923       EVT MaskVT = Mask.getValueType();
21924
21925       // Validate that the Mask operand is a vector sra node.
21926       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21927       // there is no psrai.b
21928       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21929       unsigned SraAmt = ~0;
21930       if (Mask.getOpcode() == ISD::SRA) {
21931         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21932           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21933             SraAmt = AmtConst->getZExtValue();
21934       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21935         SDValue SraC = Mask.getOperand(1);
21936         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21937       }
21938       if ((SraAmt + 1) != EltBits)
21939         return SDValue();
21940
21941       SDLoc DL(N);
21942
21943       // Now we know we at least have a plendvb with the mask val.  See if
21944       // we can form a psignb/w/d.
21945       // psign = x.type == y.type == mask.type && y = sub(0, x);
21946       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21947           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21948           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21949         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21950                "Unsupported VT for PSIGN");
21951         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21952         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21953       }
21954       // PBLENDVB only available on SSE 4.1
21955       if (!Subtarget->hasSSE41())
21956         return SDValue();
21957
21958       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21959
21960       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21961       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21962       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21963       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21964       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21965     }
21966   }
21967
21968   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21969     return SDValue();
21970
21971   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21972   MachineFunction &MF = DAG.getMachineFunction();
21973   bool OptForSize =
21974       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
21975
21976   // SHLD/SHRD instructions have lower register pressure, but on some
21977   // platforms they have higher latency than the equivalent
21978   // series of shifts/or that would otherwise be generated.
21979   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21980   // have higher latencies and we are not optimizing for size.
21981   if (!OptForSize && Subtarget->isSHLDSlow())
21982     return SDValue();
21983
21984   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21985     std::swap(N0, N1);
21986   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21987     return SDValue();
21988   if (!N0.hasOneUse() || !N1.hasOneUse())
21989     return SDValue();
21990
21991   SDValue ShAmt0 = N0.getOperand(1);
21992   if (ShAmt0.getValueType() != MVT::i8)
21993     return SDValue();
21994   SDValue ShAmt1 = N1.getOperand(1);
21995   if (ShAmt1.getValueType() != MVT::i8)
21996     return SDValue();
21997   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21998     ShAmt0 = ShAmt0.getOperand(0);
21999   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22000     ShAmt1 = ShAmt1.getOperand(0);
22001
22002   SDLoc DL(N);
22003   unsigned Opc = X86ISD::SHLD;
22004   SDValue Op0 = N0.getOperand(0);
22005   SDValue Op1 = N1.getOperand(0);
22006   if (ShAmt0.getOpcode() == ISD::SUB) {
22007     Opc = X86ISD::SHRD;
22008     std::swap(Op0, Op1);
22009     std::swap(ShAmt0, ShAmt1);
22010   }
22011
22012   unsigned Bits = VT.getSizeInBits();
22013   if (ShAmt1.getOpcode() == ISD::SUB) {
22014     SDValue Sum = ShAmt1.getOperand(0);
22015     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22016       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22017       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22018         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22019       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22020         return DAG.getNode(Opc, DL, VT,
22021                            Op0, Op1,
22022                            DAG.getNode(ISD::TRUNCATE, DL,
22023                                        MVT::i8, ShAmt0));
22024     }
22025   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22026     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22027     if (ShAmt0C &&
22028         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22029       return DAG.getNode(Opc, DL, VT,
22030                          N0.getOperand(0), N1.getOperand(0),
22031                          DAG.getNode(ISD::TRUNCATE, DL,
22032                                        MVT::i8, ShAmt0));
22033   }
22034
22035   return SDValue();
22036 }
22037
22038 // Generate NEG and CMOV for integer abs.
22039 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22040   EVT VT = N->getValueType(0);
22041
22042   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22043   // 8-bit integer abs to NEG and CMOV.
22044   if (VT.isInteger() && VT.getSizeInBits() == 8)
22045     return SDValue();
22046
22047   SDValue N0 = N->getOperand(0);
22048   SDValue N1 = N->getOperand(1);
22049   SDLoc DL(N);
22050
22051   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22052   // and change it to SUB and CMOV.
22053   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22054       N0.getOpcode() == ISD::ADD &&
22055       N0.getOperand(1) == N1 &&
22056       N1.getOpcode() == ISD::SRA &&
22057       N1.getOperand(0) == N0.getOperand(0))
22058     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22059       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22060         // Generate SUB & CMOV.
22061         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22062                                   DAG.getConstant(0, VT), N0.getOperand(0));
22063
22064         SDValue Ops[] = { N0.getOperand(0), Neg,
22065                           DAG.getConstant(X86::COND_GE, MVT::i8),
22066                           SDValue(Neg.getNode(), 1) };
22067         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22068       }
22069   return SDValue();
22070 }
22071
22072 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22073 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22074                                  TargetLowering::DAGCombinerInfo &DCI,
22075                                  const X86Subtarget *Subtarget) {
22076   if (DCI.isBeforeLegalizeOps())
22077     return SDValue();
22078
22079   if (Subtarget->hasCMov()) {
22080     SDValue RV = performIntegerAbsCombine(N, DAG);
22081     if (RV.getNode())
22082       return RV;
22083   }
22084
22085   return SDValue();
22086 }
22087
22088 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22089 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22090                                   TargetLowering::DAGCombinerInfo &DCI,
22091                                   const X86Subtarget *Subtarget) {
22092   LoadSDNode *Ld = cast<LoadSDNode>(N);
22093   EVT RegVT = Ld->getValueType(0);
22094   EVT MemVT = Ld->getMemoryVT();
22095   SDLoc dl(Ld);
22096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22097
22098   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22099   // into two 16-byte operations.
22100   ISD::LoadExtType Ext = Ld->getExtensionType();
22101   unsigned Alignment = Ld->getAlignment();
22102   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22103   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22104       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22105     unsigned NumElems = RegVT.getVectorNumElements();
22106     if (NumElems < 2)
22107       return SDValue();
22108
22109     SDValue Ptr = Ld->getBasePtr();
22110     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22111
22112     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22113                                   NumElems/2);
22114     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22115                                 Ld->getPointerInfo(), Ld->isVolatile(),
22116                                 Ld->isNonTemporal(), Ld->isInvariant(),
22117                                 Alignment);
22118     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22119     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22120                                 Ld->getPointerInfo(), Ld->isVolatile(),
22121                                 Ld->isNonTemporal(), Ld->isInvariant(),
22122                                 std::min(16U, Alignment));
22123     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22124                              Load1.getValue(1),
22125                              Load2.getValue(1));
22126
22127     SDValue NewVec = DAG.getUNDEF(RegVT);
22128     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22129     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22130     return DCI.CombineTo(N, NewVec, TF, true);
22131   }
22132
22133   return SDValue();
22134 }
22135
22136 /// PerformMLOADCombine - Resolve extending loads
22137 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22138                                    TargetLowering::DAGCombinerInfo &DCI,
22139                                    const X86Subtarget *Subtarget) {
22140   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22141   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22142     return SDValue();
22143
22144   EVT VT = Mld->getValueType(0);
22145   unsigned NumElems = VT.getVectorNumElements();
22146   EVT LdVT = Mld->getMemoryVT();
22147   SDLoc dl(Mld);
22148
22149   assert(LdVT != VT && "Cannot extend to the same type");
22150   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22151   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22152   // From, To sizes and ElemCount must be pow of two
22153   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22154     "Unexpected size for extending masked load");
22155
22156   unsigned SizeRatio  = ToSz / FromSz;
22157   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22158
22159   // Create a type on which we perform the shuffle
22160   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22161           LdVT.getScalarType(), NumElems*SizeRatio);
22162   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22163
22164   // Convert Src0 value
22165   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22166   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22167     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22168     for (unsigned i = 0; i != NumElems; ++i)
22169       ShuffleVec[i] = i * SizeRatio;
22170
22171     // Can't shuffle using an illegal type.
22172     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22173             && "WideVecVT should be legal");
22174     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22175                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22176   }
22177   // Prepare the new mask
22178   SDValue NewMask;
22179   SDValue Mask = Mld->getMask();
22180   if (Mask.getValueType() == VT) {
22181     // Mask and original value have the same type
22182     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22183     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22184     for (unsigned i = 0; i != NumElems; ++i)
22185       ShuffleVec[i] = i * SizeRatio;
22186     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22187       ShuffleVec[i] = NumElems*SizeRatio;
22188     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22189                                    DAG.getConstant(0, WideVecVT),
22190                                    &ShuffleVec[0]);
22191   }
22192   else {
22193     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22194     unsigned WidenNumElts = NumElems*SizeRatio;
22195     unsigned MaskNumElts = VT.getVectorNumElements();
22196     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22197                                      WidenNumElts);
22198
22199     unsigned NumConcat = WidenNumElts / MaskNumElts;
22200     SmallVector<SDValue, 16> Ops(NumConcat);
22201     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22202     Ops[0] = Mask;
22203     for (unsigned i = 1; i != NumConcat; ++i)
22204       Ops[i] = ZeroVal;
22205
22206     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22207   }
22208
22209   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22210                                      Mld->getBasePtr(), NewMask, WideSrc0,
22211                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22212                                      ISD::NON_EXTLOAD);
22213   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22214   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22215
22216 }
22217 /// PerformMSTORECombine - Resolve truncating stores
22218 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22219                                     const X86Subtarget *Subtarget) {
22220   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22221   if (!Mst->isTruncatingStore())
22222     return SDValue();
22223
22224   EVT VT = Mst->getValue().getValueType();
22225   unsigned NumElems = VT.getVectorNumElements();
22226   EVT StVT = Mst->getMemoryVT();
22227   SDLoc dl(Mst);
22228
22229   assert(StVT != VT && "Cannot truncate to the same type");
22230   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22231   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22232
22233   // From, To sizes and ElemCount must be pow of two
22234   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22235     "Unexpected size for truncating masked store");
22236   // We are going to use the original vector elt for storing.
22237   // Accumulated smaller vector elements must be a multiple of the store size.
22238   assert (((NumElems * FromSz) % ToSz) == 0 &&
22239           "Unexpected ratio for truncating masked store");
22240
22241   unsigned SizeRatio  = FromSz / ToSz;
22242   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22243
22244   // Create a type on which we perform the shuffle
22245   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22246           StVT.getScalarType(), NumElems*SizeRatio);
22247
22248   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22249
22250   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22251   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22252   for (unsigned i = 0; i != NumElems; ++i)
22253     ShuffleVec[i] = i * SizeRatio;
22254
22255   // Can't shuffle using an illegal type.
22256   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22257           && "WideVecVT should be legal");
22258
22259   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22260                                         DAG.getUNDEF(WideVecVT),
22261                                         &ShuffleVec[0]);
22262
22263   SDValue NewMask;
22264   SDValue Mask = Mst->getMask();
22265   if (Mask.getValueType() == VT) {
22266     // Mask and original value have the same type
22267     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22268     for (unsigned i = 0; i != NumElems; ++i)
22269       ShuffleVec[i] = i * SizeRatio;
22270     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22271       ShuffleVec[i] = NumElems*SizeRatio;
22272     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22273                                    DAG.getConstant(0, WideVecVT),
22274                                    &ShuffleVec[0]);
22275   }
22276   else {
22277     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22278     unsigned WidenNumElts = NumElems*SizeRatio;
22279     unsigned MaskNumElts = VT.getVectorNumElements();
22280     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22281                                      WidenNumElts);
22282
22283     unsigned NumConcat = WidenNumElts / MaskNumElts;
22284     SmallVector<SDValue, 16> Ops(NumConcat);
22285     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22286     Ops[0] = Mask;
22287     for (unsigned i = 1; i != NumConcat; ++i)
22288       Ops[i] = ZeroVal;
22289
22290     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22291   }
22292
22293   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22294                             NewMask, StVT, Mst->getMemOperand(), false);
22295 }
22296 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22297 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22298                                    const X86Subtarget *Subtarget) {
22299   StoreSDNode *St = cast<StoreSDNode>(N);
22300   EVT VT = St->getValue().getValueType();
22301   EVT StVT = St->getMemoryVT();
22302   SDLoc dl(St);
22303   SDValue StoredVal = St->getOperand(1);
22304   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22305
22306   // If we are saving a concatenation of two XMM registers and 32-byte stores
22307   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22308   unsigned Alignment = St->getAlignment();
22309   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22310   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22311       StVT == VT && !IsAligned) {
22312     unsigned NumElems = VT.getVectorNumElements();
22313     if (NumElems < 2)
22314       return SDValue();
22315
22316     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22317     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22318
22319     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22320     SDValue Ptr0 = St->getBasePtr();
22321     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22322
22323     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22324                                 St->getPointerInfo(), St->isVolatile(),
22325                                 St->isNonTemporal(), Alignment);
22326     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22327                                 St->getPointerInfo(), St->isVolatile(),
22328                                 St->isNonTemporal(),
22329                                 std::min(16U, Alignment));
22330     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22331   }
22332
22333   // Optimize trunc store (of multiple scalars) to shuffle and store.
22334   // First, pack all of the elements in one place. Next, store to memory
22335   // in fewer chunks.
22336   if (St->isTruncatingStore() && VT.isVector()) {
22337     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22338     unsigned NumElems = VT.getVectorNumElements();
22339     assert(StVT != VT && "Cannot truncate to the same type");
22340     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22341     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22342
22343     // From, To sizes and ElemCount must be pow of two
22344     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22345     // We are going to use the original vector elt for storing.
22346     // Accumulated smaller vector elements must be a multiple of the store size.
22347     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22348
22349     unsigned SizeRatio  = FromSz / ToSz;
22350
22351     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22352
22353     // Create a type on which we perform the shuffle
22354     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22355             StVT.getScalarType(), NumElems*SizeRatio);
22356
22357     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22358
22359     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22360     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22361     for (unsigned i = 0; i != NumElems; ++i)
22362       ShuffleVec[i] = i * SizeRatio;
22363
22364     // Can't shuffle using an illegal type.
22365     if (!TLI.isTypeLegal(WideVecVT))
22366       return SDValue();
22367
22368     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22369                                          DAG.getUNDEF(WideVecVT),
22370                                          &ShuffleVec[0]);
22371     // At this point all of the data is stored at the bottom of the
22372     // register. We now need to save it to mem.
22373
22374     // Find the largest store unit
22375     MVT StoreType = MVT::i8;
22376     for (MVT Tp : MVT::integer_valuetypes()) {
22377       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22378         StoreType = Tp;
22379     }
22380
22381     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22382     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22383         (64 <= NumElems * ToSz))
22384       StoreType = MVT::f64;
22385
22386     // Bitcast the original vector into a vector of store-size units
22387     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22388             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22389     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22390     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22391     SmallVector<SDValue, 8> Chains;
22392     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22393                                         TLI.getPointerTy());
22394     SDValue Ptr = St->getBasePtr();
22395
22396     // Perform one or more big stores into memory.
22397     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22398       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22399                                    StoreType, ShuffWide,
22400                                    DAG.getIntPtrConstant(i));
22401       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22402                                 St->getPointerInfo(), St->isVolatile(),
22403                                 St->isNonTemporal(), St->getAlignment());
22404       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22405       Chains.push_back(Ch);
22406     }
22407
22408     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22409   }
22410
22411   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22412   // the FP state in cases where an emms may be missing.
22413   // A preferable solution to the general problem is to figure out the right
22414   // places to insert EMMS.  This qualifies as a quick hack.
22415
22416   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22417   if (VT.getSizeInBits() != 64)
22418     return SDValue();
22419
22420   const Function *F = DAG.getMachineFunction().getFunction();
22421   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22422   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22423                      && Subtarget->hasSSE2();
22424   if ((VT.isVector() ||
22425        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22426       isa<LoadSDNode>(St->getValue()) &&
22427       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22428       St->getChain().hasOneUse() && !St->isVolatile()) {
22429     SDNode* LdVal = St->getValue().getNode();
22430     LoadSDNode *Ld = nullptr;
22431     int TokenFactorIndex = -1;
22432     SmallVector<SDValue, 8> Ops;
22433     SDNode* ChainVal = St->getChain().getNode();
22434     // Must be a store of a load.  We currently handle two cases:  the load
22435     // is a direct child, and it's under an intervening TokenFactor.  It is
22436     // possible to dig deeper under nested TokenFactors.
22437     if (ChainVal == LdVal)
22438       Ld = cast<LoadSDNode>(St->getChain());
22439     else if (St->getValue().hasOneUse() &&
22440              ChainVal->getOpcode() == ISD::TokenFactor) {
22441       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22442         if (ChainVal->getOperand(i).getNode() == LdVal) {
22443           TokenFactorIndex = i;
22444           Ld = cast<LoadSDNode>(St->getValue());
22445         } else
22446           Ops.push_back(ChainVal->getOperand(i));
22447       }
22448     }
22449
22450     if (!Ld || !ISD::isNormalLoad(Ld))
22451       return SDValue();
22452
22453     // If this is not the MMX case, i.e. we are just turning i64 load/store
22454     // into f64 load/store, avoid the transformation if there are multiple
22455     // uses of the loaded value.
22456     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22457       return SDValue();
22458
22459     SDLoc LdDL(Ld);
22460     SDLoc StDL(N);
22461     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22462     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22463     // pair instead.
22464     if (Subtarget->is64Bit() || F64IsLegal) {
22465       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22466       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22467                                   Ld->getPointerInfo(), Ld->isVolatile(),
22468                                   Ld->isNonTemporal(), Ld->isInvariant(),
22469                                   Ld->getAlignment());
22470       SDValue NewChain = NewLd.getValue(1);
22471       if (TokenFactorIndex != -1) {
22472         Ops.push_back(NewChain);
22473         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22474       }
22475       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22476                           St->getPointerInfo(),
22477                           St->isVolatile(), St->isNonTemporal(),
22478                           St->getAlignment());
22479     }
22480
22481     // Otherwise, lower to two pairs of 32-bit loads / stores.
22482     SDValue LoAddr = Ld->getBasePtr();
22483     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22484                                  DAG.getConstant(4, MVT::i32));
22485
22486     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22487                                Ld->getPointerInfo(),
22488                                Ld->isVolatile(), Ld->isNonTemporal(),
22489                                Ld->isInvariant(), Ld->getAlignment());
22490     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22491                                Ld->getPointerInfo().getWithOffset(4),
22492                                Ld->isVolatile(), Ld->isNonTemporal(),
22493                                Ld->isInvariant(),
22494                                MinAlign(Ld->getAlignment(), 4));
22495
22496     SDValue NewChain = LoLd.getValue(1);
22497     if (TokenFactorIndex != -1) {
22498       Ops.push_back(LoLd);
22499       Ops.push_back(HiLd);
22500       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22501     }
22502
22503     LoAddr = St->getBasePtr();
22504     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22505                          DAG.getConstant(4, MVT::i32));
22506
22507     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22508                                 St->getPointerInfo(),
22509                                 St->isVolatile(), St->isNonTemporal(),
22510                                 St->getAlignment());
22511     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22512                                 St->getPointerInfo().getWithOffset(4),
22513                                 St->isVolatile(),
22514                                 St->isNonTemporal(),
22515                                 MinAlign(St->getAlignment(), 4));
22516     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22517   }
22518   return SDValue();
22519 }
22520
22521 /// Return 'true' if this vector operation is "horizontal"
22522 /// and return the operands for the horizontal operation in LHS and RHS.  A
22523 /// horizontal operation performs the binary operation on successive elements
22524 /// of its first operand, then on successive elements of its second operand,
22525 /// returning the resulting values in a vector.  For example, if
22526 ///   A = < float a0, float a1, float a2, float a3 >
22527 /// and
22528 ///   B = < float b0, float b1, float b2, float b3 >
22529 /// then the result of doing a horizontal operation on A and B is
22530 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22531 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22532 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22533 /// set to A, RHS to B, and the routine returns 'true'.
22534 /// Note that the binary operation should have the property that if one of the
22535 /// operands is UNDEF then the result is UNDEF.
22536 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22537   // Look for the following pattern: if
22538   //   A = < float a0, float a1, float a2, float a3 >
22539   //   B = < float b0, float b1, float b2, float b3 >
22540   // and
22541   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22542   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22543   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22544   // which is A horizontal-op B.
22545
22546   // At least one of the operands should be a vector shuffle.
22547   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22548       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22549     return false;
22550
22551   MVT VT = LHS.getSimpleValueType();
22552
22553   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22554          "Unsupported vector type for horizontal add/sub");
22555
22556   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22557   // operate independently on 128-bit lanes.
22558   unsigned NumElts = VT.getVectorNumElements();
22559   unsigned NumLanes = VT.getSizeInBits()/128;
22560   unsigned NumLaneElts = NumElts / NumLanes;
22561   assert((NumLaneElts % 2 == 0) &&
22562          "Vector type should have an even number of elements in each lane");
22563   unsigned HalfLaneElts = NumLaneElts/2;
22564
22565   // View LHS in the form
22566   //   LHS = VECTOR_SHUFFLE A, B, LMask
22567   // If LHS is not a shuffle then pretend it is the shuffle
22568   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22569   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22570   // type VT.
22571   SDValue A, B;
22572   SmallVector<int, 16> LMask(NumElts);
22573   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22574     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22575       A = LHS.getOperand(0);
22576     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22577       B = LHS.getOperand(1);
22578     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22579     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22580   } else {
22581     if (LHS.getOpcode() != ISD::UNDEF)
22582       A = LHS;
22583     for (unsigned i = 0; i != NumElts; ++i)
22584       LMask[i] = i;
22585   }
22586
22587   // Likewise, view RHS in the form
22588   //   RHS = VECTOR_SHUFFLE C, D, RMask
22589   SDValue C, D;
22590   SmallVector<int, 16> RMask(NumElts);
22591   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22592     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22593       C = RHS.getOperand(0);
22594     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22595       D = RHS.getOperand(1);
22596     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22597     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22598   } else {
22599     if (RHS.getOpcode() != ISD::UNDEF)
22600       C = RHS;
22601     for (unsigned i = 0; i != NumElts; ++i)
22602       RMask[i] = i;
22603   }
22604
22605   // Check that the shuffles are both shuffling the same vectors.
22606   if (!(A == C && B == D) && !(A == D && B == C))
22607     return false;
22608
22609   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22610   if (!A.getNode() && !B.getNode())
22611     return false;
22612
22613   // If A and B occur in reverse order in RHS, then "swap" them (which means
22614   // rewriting the mask).
22615   if (A != C)
22616     CommuteVectorShuffleMask(RMask, NumElts);
22617
22618   // At this point LHS and RHS are equivalent to
22619   //   LHS = VECTOR_SHUFFLE A, B, LMask
22620   //   RHS = VECTOR_SHUFFLE A, B, RMask
22621   // Check that the masks correspond to performing a horizontal operation.
22622   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22623     for (unsigned i = 0; i != NumLaneElts; ++i) {
22624       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22625
22626       // Ignore any UNDEF components.
22627       if (LIdx < 0 || RIdx < 0 ||
22628           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22629           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22630         continue;
22631
22632       // Check that successive elements are being operated on.  If not, this is
22633       // not a horizontal operation.
22634       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22635       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22636       if (!(LIdx == Index && RIdx == Index + 1) &&
22637           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22638         return false;
22639     }
22640   }
22641
22642   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22643   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22644   return true;
22645 }
22646
22647 /// Do target-specific dag combines on floating point adds.
22648 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22649                                   const X86Subtarget *Subtarget) {
22650   EVT VT = N->getValueType(0);
22651   SDValue LHS = N->getOperand(0);
22652   SDValue RHS = N->getOperand(1);
22653
22654   // Try to synthesize horizontal adds from adds of shuffles.
22655   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22656        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22657       isHorizontalBinOp(LHS, RHS, true))
22658     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22659   return SDValue();
22660 }
22661
22662 /// Do target-specific dag combines on floating point subs.
22663 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22664                                   const X86Subtarget *Subtarget) {
22665   EVT VT = N->getValueType(0);
22666   SDValue LHS = N->getOperand(0);
22667   SDValue RHS = N->getOperand(1);
22668
22669   // Try to synthesize horizontal subs from subs of shuffles.
22670   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22671        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22672       isHorizontalBinOp(LHS, RHS, false))
22673     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22674   return SDValue();
22675 }
22676
22677 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22678 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22679   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22680
22681   // F[X]OR(0.0, x) -> x
22682   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22683     if (C->getValueAPF().isPosZero())
22684       return N->getOperand(1);
22685
22686   // F[X]OR(x, 0.0) -> x
22687   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22688     if (C->getValueAPF().isPosZero())
22689       return N->getOperand(0);
22690   return SDValue();
22691 }
22692
22693 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22694 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22695   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22696
22697   // Only perform optimizations if UnsafeMath is used.
22698   if (!DAG.getTarget().Options.UnsafeFPMath)
22699     return SDValue();
22700
22701   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22702   // into FMINC and FMAXC, which are Commutative operations.
22703   unsigned NewOp = 0;
22704   switch (N->getOpcode()) {
22705     default: llvm_unreachable("unknown opcode");
22706     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22707     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22708   }
22709
22710   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22711                      N->getOperand(0), N->getOperand(1));
22712 }
22713
22714 /// Do target-specific dag combines on X86ISD::FAND nodes.
22715 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22716   // FAND(0.0, x) -> 0.0
22717   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22718     if (C->getValueAPF().isPosZero())
22719       return N->getOperand(0);
22720
22721   // FAND(x, 0.0) -> 0.0
22722   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22723     if (C->getValueAPF().isPosZero())
22724       return N->getOperand(1);
22725   
22726   return SDValue();
22727 }
22728
22729 /// Do target-specific dag combines on X86ISD::FANDN nodes
22730 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22731   // FANDN(0.0, x) -> x
22732   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22733     if (C->getValueAPF().isPosZero())
22734       return N->getOperand(1);
22735
22736   // FANDN(x, 0.0) -> 0.0
22737   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22738     if (C->getValueAPF().isPosZero())
22739       return N->getOperand(1);
22740
22741   return SDValue();
22742 }
22743
22744 static SDValue PerformBTCombine(SDNode *N,
22745                                 SelectionDAG &DAG,
22746                                 TargetLowering::DAGCombinerInfo &DCI) {
22747   // BT ignores high bits in the bit index operand.
22748   SDValue Op1 = N->getOperand(1);
22749   if (Op1.hasOneUse()) {
22750     unsigned BitWidth = Op1.getValueSizeInBits();
22751     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22752     APInt KnownZero, KnownOne;
22753     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22754                                           !DCI.isBeforeLegalizeOps());
22755     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22756     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22757         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22758       DCI.CommitTargetLoweringOpt(TLO);
22759   }
22760   return SDValue();
22761 }
22762
22763 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22764   SDValue Op = N->getOperand(0);
22765   if (Op.getOpcode() == ISD::BITCAST)
22766     Op = Op.getOperand(0);
22767   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22768   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22769       VT.getVectorElementType().getSizeInBits() ==
22770       OpVT.getVectorElementType().getSizeInBits()) {
22771     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22772   }
22773   return SDValue();
22774 }
22775
22776 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22777                                                const X86Subtarget *Subtarget) {
22778   EVT VT = N->getValueType(0);
22779   if (!VT.isVector())
22780     return SDValue();
22781
22782   SDValue N0 = N->getOperand(0);
22783   SDValue N1 = N->getOperand(1);
22784   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22785   SDLoc dl(N);
22786
22787   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22788   // both SSE and AVX2 since there is no sign-extended shift right
22789   // operation on a vector with 64-bit elements.
22790   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22791   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22792   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22793       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22794     SDValue N00 = N0.getOperand(0);
22795
22796     // EXTLOAD has a better solution on AVX2,
22797     // it may be replaced with X86ISD::VSEXT node.
22798     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22799       if (!ISD::isNormalLoad(N00.getNode()))
22800         return SDValue();
22801
22802     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22803         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22804                                   N00, N1);
22805       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22806     }
22807   }
22808   return SDValue();
22809 }
22810
22811 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22812                                   TargetLowering::DAGCombinerInfo &DCI,
22813                                   const X86Subtarget *Subtarget) {
22814   SDValue N0 = N->getOperand(0);
22815   EVT VT = N->getValueType(0);
22816
22817   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
22818   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
22819   // This exposes the sext to the sdivrem lowering, so that it directly extends
22820   // from AH (which we otherwise need to do contortions to access).
22821   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
22822       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
22823     SDLoc dl(N);
22824     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22825     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
22826                             N0.getOperand(0), N0.getOperand(1));
22827     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22828     return R.getValue(1);
22829   }
22830
22831   if (!DCI.isBeforeLegalizeOps())
22832     return SDValue();
22833
22834   if (!Subtarget->hasFp256())
22835     return SDValue();
22836
22837   if (VT.isVector() && VT.getSizeInBits() == 256) {
22838     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22839     if (R.getNode())
22840       return R;
22841   }
22842
22843   return SDValue();
22844 }
22845
22846 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22847                                  const X86Subtarget* Subtarget) {
22848   SDLoc dl(N);
22849   EVT VT = N->getValueType(0);
22850
22851   // Let legalize expand this if it isn't a legal type yet.
22852   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22853     return SDValue();
22854
22855   EVT ScalarVT = VT.getScalarType();
22856   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22857       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22858     return SDValue();
22859
22860   SDValue A = N->getOperand(0);
22861   SDValue B = N->getOperand(1);
22862   SDValue C = N->getOperand(2);
22863
22864   bool NegA = (A.getOpcode() == ISD::FNEG);
22865   bool NegB = (B.getOpcode() == ISD::FNEG);
22866   bool NegC = (C.getOpcode() == ISD::FNEG);
22867
22868   // Negative multiplication when NegA xor NegB
22869   bool NegMul = (NegA != NegB);
22870   if (NegA)
22871     A = A.getOperand(0);
22872   if (NegB)
22873     B = B.getOperand(0);
22874   if (NegC)
22875     C = C.getOperand(0);
22876
22877   unsigned Opcode;
22878   if (!NegMul)
22879     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22880   else
22881     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22882
22883   return DAG.getNode(Opcode, dl, VT, A, B, C);
22884 }
22885
22886 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22887                                   TargetLowering::DAGCombinerInfo &DCI,
22888                                   const X86Subtarget *Subtarget) {
22889   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22890   //           (and (i32 x86isd::setcc_carry), 1)
22891   // This eliminates the zext. This transformation is necessary because
22892   // ISD::SETCC is always legalized to i8.
22893   SDLoc dl(N);
22894   SDValue N0 = N->getOperand(0);
22895   EVT VT = N->getValueType(0);
22896
22897   if (N0.getOpcode() == ISD::AND &&
22898       N0.hasOneUse() &&
22899       N0.getOperand(0).hasOneUse()) {
22900     SDValue N00 = N0.getOperand(0);
22901     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22902       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22903       if (!C || C->getZExtValue() != 1)
22904         return SDValue();
22905       return DAG.getNode(ISD::AND, dl, VT,
22906                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22907                                      N00.getOperand(0), N00.getOperand(1)),
22908                          DAG.getConstant(1, VT));
22909     }
22910   }
22911
22912   if (N0.getOpcode() == ISD::TRUNCATE &&
22913       N0.hasOneUse() &&
22914       N0.getOperand(0).hasOneUse()) {
22915     SDValue N00 = N0.getOperand(0);
22916     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22917       return DAG.getNode(ISD::AND, dl, VT,
22918                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22919                                      N00.getOperand(0), N00.getOperand(1)),
22920                          DAG.getConstant(1, VT));
22921     }
22922   }
22923   if (VT.is256BitVector()) {
22924     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22925     if (R.getNode())
22926       return R;
22927   }
22928
22929   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
22930   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
22931   // This exposes the zext to the udivrem lowering, so that it directly extends
22932   // from AH (which we otherwise need to do contortions to access).
22933   if (N0.getOpcode() == ISD::UDIVREM &&
22934       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
22935       (VT == MVT::i32 || VT == MVT::i64)) {
22936     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22937     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
22938                             N0.getOperand(0), N0.getOperand(1));
22939     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22940     return R.getValue(1);
22941   }
22942
22943   return SDValue();
22944 }
22945
22946 // Optimize x == -y --> x+y == 0
22947 //          x != -y --> x+y != 0
22948 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22949                                       const X86Subtarget* Subtarget) {
22950   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22951   SDValue LHS = N->getOperand(0);
22952   SDValue RHS = N->getOperand(1);
22953   EVT VT = N->getValueType(0);
22954   SDLoc DL(N);
22955
22956   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22957     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22958       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22959         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22960                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22961         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22962                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22963       }
22964   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22965     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22966       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22967         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22968                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22969         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22970                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22971       }
22972
22973   if (VT.getScalarType() == MVT::i1) {
22974     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22975       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22976     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22977     if (!IsSEXT0 && !IsVZero0)
22978       return SDValue();
22979     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22980       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22981     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22982
22983     if (!IsSEXT1 && !IsVZero1)
22984       return SDValue();
22985
22986     if (IsSEXT0 && IsVZero1) {
22987       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22988       if (CC == ISD::SETEQ)
22989         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22990       return LHS.getOperand(0);
22991     }
22992     if (IsSEXT1 && IsVZero0) {
22993       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22994       if (CC == ISD::SETEQ)
22995         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22996       return RHS.getOperand(0);
22997     }
22998   }
22999
23000   return SDValue();
23001 }
23002
23003 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23004                                          SelectionDAG &DAG) {
23005   SDLoc dl(Load);
23006   MVT VT = Load->getSimpleValueType(0);
23007   MVT EVT = VT.getVectorElementType();
23008   SDValue Addr = Load->getOperand(1);
23009   SDValue NewAddr = DAG.getNode(
23010       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23011       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23012
23013   SDValue NewLoad =
23014       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23015                   DAG.getMachineFunction().getMachineMemOperand(
23016                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23017   return NewLoad;
23018 }
23019
23020 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23021                                       const X86Subtarget *Subtarget) {
23022   SDLoc dl(N);
23023   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23024   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23025          "X86insertps is only defined for v4x32");
23026
23027   SDValue Ld = N->getOperand(1);
23028   if (MayFoldLoad(Ld)) {
23029     // Extract the countS bits from the immediate so we can get the proper
23030     // address when narrowing the vector load to a specific element.
23031     // When the second source op is a memory address, insertps doesn't use
23032     // countS and just gets an f32 from that address.
23033     unsigned DestIndex =
23034         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23035     
23036     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23037
23038     // Create this as a scalar to vector to match the instruction pattern.
23039     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23040     // countS bits are ignored when loading from memory on insertps, which
23041     // means we don't need to explicitly set them to 0.
23042     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23043                        LoadScalarToVector, N->getOperand(2));
23044   }
23045   return SDValue();
23046 }
23047
23048 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23049   SDValue V0 = N->getOperand(0);
23050   SDValue V1 = N->getOperand(1);
23051   SDLoc DL(N);
23052   EVT VT = N->getValueType(0);
23053
23054   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23055   // operands and changing the mask to 1. This saves us a bunch of
23056   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23057   // x86InstrInfo knows how to commute this back after instruction selection
23058   // if it would help register allocation.
23059   
23060   // TODO: If optimizing for size or a processor that doesn't suffer from
23061   // partial register update stalls, this should be transformed into a MOVSD
23062   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23063
23064   if (VT == MVT::v2f64)
23065     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23066       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23067         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23068         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23069       }
23070
23071   return SDValue();
23072 }
23073
23074 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23075 // as "sbb reg,reg", since it can be extended without zext and produces
23076 // an all-ones bit which is more useful than 0/1 in some cases.
23077 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23078                                MVT VT) {
23079   if (VT == MVT::i8)
23080     return DAG.getNode(ISD::AND, DL, VT,
23081                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23082                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23083                        DAG.getConstant(1, VT));
23084   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23085   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23086                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23087                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23088 }
23089
23090 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23091 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23092                                    TargetLowering::DAGCombinerInfo &DCI,
23093                                    const X86Subtarget *Subtarget) {
23094   SDLoc DL(N);
23095   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23096   SDValue EFLAGS = N->getOperand(1);
23097
23098   if (CC == X86::COND_A) {
23099     // Try to convert COND_A into COND_B in an attempt to facilitate
23100     // materializing "setb reg".
23101     //
23102     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23103     // cannot take an immediate as its first operand.
23104     //
23105     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23106         EFLAGS.getValueType().isInteger() &&
23107         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23108       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23109                                    EFLAGS.getNode()->getVTList(),
23110                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23111       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23112       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23113     }
23114   }
23115
23116   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23117   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23118   // cases.
23119   if (CC == X86::COND_B)
23120     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23121
23122   SDValue Flags;
23123
23124   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23125   if (Flags.getNode()) {
23126     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23127     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23128   }
23129
23130   return SDValue();
23131 }
23132
23133 // Optimize branch condition evaluation.
23134 //
23135 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23136                                     TargetLowering::DAGCombinerInfo &DCI,
23137                                     const X86Subtarget *Subtarget) {
23138   SDLoc DL(N);
23139   SDValue Chain = N->getOperand(0);
23140   SDValue Dest = N->getOperand(1);
23141   SDValue EFLAGS = N->getOperand(3);
23142   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23143
23144   SDValue Flags;
23145
23146   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23147   if (Flags.getNode()) {
23148     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23149     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23150                        Flags);
23151   }
23152
23153   return SDValue();
23154 }
23155
23156 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23157                                                          SelectionDAG &DAG) {
23158   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23159   // optimize away operation when it's from a constant.
23160   //
23161   // The general transformation is:
23162   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23163   //       AND(VECTOR_CMP(x,y), constant2)
23164   //    constant2 = UNARYOP(constant)
23165
23166   // Early exit if this isn't a vector operation, the operand of the
23167   // unary operation isn't a bitwise AND, or if the sizes of the operations
23168   // aren't the same.
23169   EVT VT = N->getValueType(0);
23170   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23171       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23172       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23173     return SDValue();
23174
23175   // Now check that the other operand of the AND is a constant. We could
23176   // make the transformation for non-constant splats as well, but it's unclear
23177   // that would be a benefit as it would not eliminate any operations, just
23178   // perform one more step in scalar code before moving to the vector unit.
23179   if (BuildVectorSDNode *BV =
23180           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23181     // Bail out if the vector isn't a constant.
23182     if (!BV->isConstant())
23183       return SDValue();
23184
23185     // Everything checks out. Build up the new and improved node.
23186     SDLoc DL(N);
23187     EVT IntVT = BV->getValueType(0);
23188     // Create a new constant of the appropriate type for the transformed
23189     // DAG.
23190     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23191     // The AND node needs bitcasts to/from an integer vector type around it.
23192     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23193     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23194                                  N->getOperand(0)->getOperand(0), MaskConst);
23195     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23196     return Res;
23197   }
23198
23199   return SDValue();
23200 }
23201
23202 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23203                                         const X86Subtarget *Subtarget) {
23204   // First try to optimize away the conversion entirely when it's
23205   // conditionally from a constant. Vectors only.
23206   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23207   if (Res != SDValue())
23208     return Res;
23209
23210   // Now move on to more general possibilities.
23211   SDValue Op0 = N->getOperand(0);
23212   EVT InVT = Op0->getValueType(0);
23213
23214   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23215   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23216     SDLoc dl(N);
23217     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23218     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23219     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23220   }
23221
23222   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23223   // a 32-bit target where SSE doesn't support i64->FP operations.
23224   if (Op0.getOpcode() == ISD::LOAD) {
23225     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23226     EVT VT = Ld->getValueType(0);
23227     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23228         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23229         !Subtarget->is64Bit() && VT == MVT::i64) {
23230       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23231           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23232       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23233       return FILDChain;
23234     }
23235   }
23236   return SDValue();
23237 }
23238
23239 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23240 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23241                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23242   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23243   // the result is either zero or one (depending on the input carry bit).
23244   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23245   if (X86::isZeroNode(N->getOperand(0)) &&
23246       X86::isZeroNode(N->getOperand(1)) &&
23247       // We don't have a good way to replace an EFLAGS use, so only do this when
23248       // dead right now.
23249       SDValue(N, 1).use_empty()) {
23250     SDLoc DL(N);
23251     EVT VT = N->getValueType(0);
23252     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23253     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23254                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23255                                            DAG.getConstant(X86::COND_B,MVT::i8),
23256                                            N->getOperand(2)),
23257                                DAG.getConstant(1, VT));
23258     return DCI.CombineTo(N, Res1, CarryOut);
23259   }
23260
23261   return SDValue();
23262 }
23263
23264 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23265 //      (add Y, (setne X, 0)) -> sbb -1, Y
23266 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23267 //      (sub (setne X, 0), Y) -> adc -1, Y
23268 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23269   SDLoc DL(N);
23270
23271   // Look through ZExts.
23272   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23273   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23274     return SDValue();
23275
23276   SDValue SetCC = Ext.getOperand(0);
23277   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23278     return SDValue();
23279
23280   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23281   if (CC != X86::COND_E && CC != X86::COND_NE)
23282     return SDValue();
23283
23284   SDValue Cmp = SetCC.getOperand(1);
23285   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23286       !X86::isZeroNode(Cmp.getOperand(1)) ||
23287       !Cmp.getOperand(0).getValueType().isInteger())
23288     return SDValue();
23289
23290   SDValue CmpOp0 = Cmp.getOperand(0);
23291   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23292                                DAG.getConstant(1, CmpOp0.getValueType()));
23293
23294   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23295   if (CC == X86::COND_NE)
23296     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23297                        DL, OtherVal.getValueType(), OtherVal,
23298                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23299   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23300                      DL, OtherVal.getValueType(), OtherVal,
23301                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23302 }
23303
23304 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23305 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23306                                  const X86Subtarget *Subtarget) {
23307   EVT VT = N->getValueType(0);
23308   SDValue Op0 = N->getOperand(0);
23309   SDValue Op1 = N->getOperand(1);
23310
23311   // Try to synthesize horizontal adds from adds of shuffles.
23312   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23313        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23314       isHorizontalBinOp(Op0, Op1, true))
23315     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23316
23317   return OptimizeConditionalInDecrement(N, DAG);
23318 }
23319
23320 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23321                                  const X86Subtarget *Subtarget) {
23322   SDValue Op0 = N->getOperand(0);
23323   SDValue Op1 = N->getOperand(1);
23324
23325   // X86 can't encode an immediate LHS of a sub. See if we can push the
23326   // negation into a preceding instruction.
23327   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23328     // If the RHS of the sub is a XOR with one use and a constant, invert the
23329     // immediate. Then add one to the LHS of the sub so we can turn
23330     // X-Y -> X+~Y+1, saving one register.
23331     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23332         isa<ConstantSDNode>(Op1.getOperand(1))) {
23333       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23334       EVT VT = Op0.getValueType();
23335       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23336                                    Op1.getOperand(0),
23337                                    DAG.getConstant(~XorC, VT));
23338       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23339                          DAG.getConstant(C->getAPIntValue()+1, VT));
23340     }
23341   }
23342
23343   // Try to synthesize horizontal adds from adds of shuffles.
23344   EVT VT = N->getValueType(0);
23345   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23346        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23347       isHorizontalBinOp(Op0, Op1, true))
23348     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23349
23350   return OptimizeConditionalInDecrement(N, DAG);
23351 }
23352
23353 /// performVZEXTCombine - Performs build vector combines
23354 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23355                                    TargetLowering::DAGCombinerInfo &DCI,
23356                                    const X86Subtarget *Subtarget) {
23357   SDLoc DL(N);
23358   MVT VT = N->getSimpleValueType(0);
23359   SDValue Op = N->getOperand(0);
23360   MVT OpVT = Op.getSimpleValueType();
23361   MVT OpEltVT = OpVT.getVectorElementType();
23362   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23363
23364   // (vzext (bitcast (vzext (x)) -> (vzext x)
23365   SDValue V = Op;
23366   while (V.getOpcode() == ISD::BITCAST)
23367     V = V.getOperand(0);
23368
23369   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23370     MVT InnerVT = V.getSimpleValueType();
23371     MVT InnerEltVT = InnerVT.getVectorElementType();
23372
23373     // If the element sizes match exactly, we can just do one larger vzext. This
23374     // is always an exact type match as vzext operates on integer types.
23375     if (OpEltVT == InnerEltVT) {
23376       assert(OpVT == InnerVT && "Types must match for vzext!");
23377       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23378     }
23379
23380     // The only other way we can combine them is if only a single element of the
23381     // inner vzext is used in the input to the outer vzext.
23382     if (InnerEltVT.getSizeInBits() < InputBits)
23383       return SDValue();
23384
23385     // In this case, the inner vzext is completely dead because we're going to
23386     // only look at bits inside of the low element. Just do the outer vzext on
23387     // a bitcast of the input to the inner.
23388     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23389                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23390   }
23391
23392   // Check if we can bypass extracting and re-inserting an element of an input
23393   // vector. Essentialy:
23394   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23395   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23396       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23397       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23398     SDValue ExtractedV = V.getOperand(0);
23399     SDValue OrigV = ExtractedV.getOperand(0);
23400     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23401       if (ExtractIdx->getZExtValue() == 0) {
23402         MVT OrigVT = OrigV.getSimpleValueType();
23403         // Extract a subvector if necessary...
23404         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23405           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23406           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23407                                     OrigVT.getVectorNumElements() / Ratio);
23408           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23409                               DAG.getIntPtrConstant(0));
23410         }
23411         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23412         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23413       }
23414   }
23415
23416   return SDValue();
23417 }
23418
23419 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23420                                              DAGCombinerInfo &DCI) const {
23421   SelectionDAG &DAG = DCI.DAG;
23422   switch (N->getOpcode()) {
23423   default: break;
23424   case ISD::EXTRACT_VECTOR_ELT:
23425     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23426   case ISD::VSELECT:
23427   case ISD::SELECT:
23428   case X86ISD::SHRUNKBLEND:
23429     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23430   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23431   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23432   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23433   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23434   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23435   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23436   case ISD::SHL:
23437   case ISD::SRA:
23438   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23439   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23440   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23441   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23442   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23443   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23444   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23445   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23446   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23447   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23448   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23449   case X86ISD::FXOR:
23450   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23451   case X86ISD::FMIN:
23452   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23453   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23454   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23455   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23456   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23457   case ISD::ANY_EXTEND:
23458   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23459   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23460   case ISD::SIGN_EXTEND_INREG:
23461     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23462   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23463   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23464   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23465   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23466   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23467   case X86ISD::SHUFP:       // Handle all target specific shuffles
23468   case X86ISD::PALIGNR:
23469   case X86ISD::UNPCKH:
23470   case X86ISD::UNPCKL:
23471   case X86ISD::MOVHLPS:
23472   case X86ISD::MOVLHPS:
23473   case X86ISD::PSHUFB:
23474   case X86ISD::PSHUFD:
23475   case X86ISD::PSHUFHW:
23476   case X86ISD::PSHUFLW:
23477   case X86ISD::MOVSS:
23478   case X86ISD::MOVSD:
23479   case X86ISD::VPERMILPI:
23480   case X86ISD::VPERM2X128:
23481   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23482   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23483   case ISD::INTRINSIC_WO_CHAIN:
23484     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23485   case X86ISD::INSERTPS: {
23486     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23487       return PerformINSERTPSCombine(N, DAG, Subtarget);
23488     break;
23489   }
23490   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23491   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23492   }
23493
23494   return SDValue();
23495 }
23496
23497 /// isTypeDesirableForOp - Return true if the target has native support for
23498 /// the specified value type and it is 'desirable' to use the type for the
23499 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23500 /// instruction encodings are longer and some i16 instructions are slow.
23501 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23502   if (!isTypeLegal(VT))
23503     return false;
23504   if (VT != MVT::i16)
23505     return true;
23506
23507   switch (Opc) {
23508   default:
23509     return true;
23510   case ISD::LOAD:
23511   case ISD::SIGN_EXTEND:
23512   case ISD::ZERO_EXTEND:
23513   case ISD::ANY_EXTEND:
23514   case ISD::SHL:
23515   case ISD::SRL:
23516   case ISD::SUB:
23517   case ISD::ADD:
23518   case ISD::MUL:
23519   case ISD::AND:
23520   case ISD::OR:
23521   case ISD::XOR:
23522     return false;
23523   }
23524 }
23525
23526 /// IsDesirableToPromoteOp - This method query the target whether it is
23527 /// beneficial for dag combiner to promote the specified node. If true, it
23528 /// should return the desired promotion type by reference.
23529 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23530   EVT VT = Op.getValueType();
23531   if (VT != MVT::i16)
23532     return false;
23533
23534   bool Promote = false;
23535   bool Commute = false;
23536   switch (Op.getOpcode()) {
23537   default: break;
23538   case ISD::LOAD: {
23539     LoadSDNode *LD = cast<LoadSDNode>(Op);
23540     // If the non-extending load has a single use and it's not live out, then it
23541     // might be folded.
23542     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23543                                                      Op.hasOneUse()*/) {
23544       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23545              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23546         // The only case where we'd want to promote LOAD (rather then it being
23547         // promoted as an operand is when it's only use is liveout.
23548         if (UI->getOpcode() != ISD::CopyToReg)
23549           return false;
23550       }
23551     }
23552     Promote = true;
23553     break;
23554   }
23555   case ISD::SIGN_EXTEND:
23556   case ISD::ZERO_EXTEND:
23557   case ISD::ANY_EXTEND:
23558     Promote = true;
23559     break;
23560   case ISD::SHL:
23561   case ISD::SRL: {
23562     SDValue N0 = Op.getOperand(0);
23563     // Look out for (store (shl (load), x)).
23564     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23565       return false;
23566     Promote = true;
23567     break;
23568   }
23569   case ISD::ADD:
23570   case ISD::MUL:
23571   case ISD::AND:
23572   case ISD::OR:
23573   case ISD::XOR:
23574     Commute = true;
23575     // fallthrough
23576   case ISD::SUB: {
23577     SDValue N0 = Op.getOperand(0);
23578     SDValue N1 = Op.getOperand(1);
23579     if (!Commute && MayFoldLoad(N1))
23580       return false;
23581     // Avoid disabling potential load folding opportunities.
23582     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23583       return false;
23584     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23585       return false;
23586     Promote = true;
23587   }
23588   }
23589
23590   PVT = MVT::i32;
23591   return Promote;
23592 }
23593
23594 //===----------------------------------------------------------------------===//
23595 //                           X86 Inline Assembly Support
23596 //===----------------------------------------------------------------------===//
23597
23598 // Helper to match a string separated by whitespace.
23599 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23600   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23601
23602   for (StringRef Piece : Pieces) {
23603     if (!S.startswith(Piece)) // Check if the piece matches.
23604       return false;
23605
23606     S = S.substr(Piece.size());
23607     StringRef::size_type Pos = S.find_first_not_of(" \t");
23608     if (Pos == 0) // We matched a prefix.
23609       return false;
23610
23611     S = S.substr(Pos);
23612   }
23613
23614   return S.empty();
23615 }
23616
23617 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23618
23619   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23620     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23621         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23622         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23623
23624       if (AsmPieces.size() == 3)
23625         return true;
23626       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23627         return true;
23628     }
23629   }
23630   return false;
23631 }
23632
23633 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23634   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23635
23636   std::string AsmStr = IA->getAsmString();
23637
23638   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23639   if (!Ty || Ty->getBitWidth() % 16 != 0)
23640     return false;
23641
23642   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23643   SmallVector<StringRef, 4> AsmPieces;
23644   SplitString(AsmStr, AsmPieces, ";\n");
23645
23646   switch (AsmPieces.size()) {
23647   default: return false;
23648   case 1:
23649     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23650     // we will turn this bswap into something that will be lowered to logical
23651     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23652     // lower so don't worry about this.
23653     // bswap $0
23654     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23655         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23656         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23657         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23658         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23659         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23660       // No need to check constraints, nothing other than the equivalent of
23661       // "=r,0" would be valid here.
23662       return IntrinsicLowering::LowerToByteSwap(CI);
23663     }
23664
23665     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23666     if (CI->getType()->isIntegerTy(16) &&
23667         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23668         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23669          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23670       AsmPieces.clear();
23671       const std::string &ConstraintsStr = IA->getConstraintString();
23672       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23673       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23674       if (clobbersFlagRegisters(AsmPieces))
23675         return IntrinsicLowering::LowerToByteSwap(CI);
23676     }
23677     break;
23678   case 3:
23679     if (CI->getType()->isIntegerTy(32) &&
23680         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23681         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23682         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23683         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23684       AsmPieces.clear();
23685       const std::string &ConstraintsStr = IA->getConstraintString();
23686       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23687       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23688       if (clobbersFlagRegisters(AsmPieces))
23689         return IntrinsicLowering::LowerToByteSwap(CI);
23690     }
23691
23692     if (CI->getType()->isIntegerTy(64)) {
23693       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23694       if (Constraints.size() >= 2 &&
23695           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23696           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23697         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23698         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23699             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23700             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23701           return IntrinsicLowering::LowerToByteSwap(CI);
23702       }
23703     }
23704     break;
23705   }
23706   return false;
23707 }
23708
23709 /// getConstraintType - Given a constraint letter, return the type of
23710 /// constraint it is for this target.
23711 X86TargetLowering::ConstraintType
23712 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23713   if (Constraint.size() == 1) {
23714     switch (Constraint[0]) {
23715     case 'R':
23716     case 'q':
23717     case 'Q':
23718     case 'f':
23719     case 't':
23720     case 'u':
23721     case 'y':
23722     case 'x':
23723     case 'Y':
23724     case 'l':
23725       return C_RegisterClass;
23726     case 'a':
23727     case 'b':
23728     case 'c':
23729     case 'd':
23730     case 'S':
23731     case 'D':
23732     case 'A':
23733       return C_Register;
23734     case 'I':
23735     case 'J':
23736     case 'K':
23737     case 'L':
23738     case 'M':
23739     case 'N':
23740     case 'G':
23741     case 'C':
23742     case 'e':
23743     case 'Z':
23744       return C_Other;
23745     default:
23746       break;
23747     }
23748   }
23749   return TargetLowering::getConstraintType(Constraint);
23750 }
23751
23752 /// Examine constraint type and operand type and determine a weight value.
23753 /// This object must already have been set up with the operand type
23754 /// and the current alternative constraint selected.
23755 TargetLowering::ConstraintWeight
23756   X86TargetLowering::getSingleConstraintMatchWeight(
23757     AsmOperandInfo &info, const char *constraint) const {
23758   ConstraintWeight weight = CW_Invalid;
23759   Value *CallOperandVal = info.CallOperandVal;
23760     // If we don't have a value, we can't do a match,
23761     // but allow it at the lowest weight.
23762   if (!CallOperandVal)
23763     return CW_Default;
23764   Type *type = CallOperandVal->getType();
23765   // Look at the constraint type.
23766   switch (*constraint) {
23767   default:
23768     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23769   case 'R':
23770   case 'q':
23771   case 'Q':
23772   case 'a':
23773   case 'b':
23774   case 'c':
23775   case 'd':
23776   case 'S':
23777   case 'D':
23778   case 'A':
23779     if (CallOperandVal->getType()->isIntegerTy())
23780       weight = CW_SpecificReg;
23781     break;
23782   case 'f':
23783   case 't':
23784   case 'u':
23785     if (type->isFloatingPointTy())
23786       weight = CW_SpecificReg;
23787     break;
23788   case 'y':
23789     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23790       weight = CW_SpecificReg;
23791     break;
23792   case 'x':
23793   case 'Y':
23794     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23795         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23796       weight = CW_Register;
23797     break;
23798   case 'I':
23799     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23800       if (C->getZExtValue() <= 31)
23801         weight = CW_Constant;
23802     }
23803     break;
23804   case 'J':
23805     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23806       if (C->getZExtValue() <= 63)
23807         weight = CW_Constant;
23808     }
23809     break;
23810   case 'K':
23811     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23812       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23813         weight = CW_Constant;
23814     }
23815     break;
23816   case 'L':
23817     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23818       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23819         weight = CW_Constant;
23820     }
23821     break;
23822   case 'M':
23823     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23824       if (C->getZExtValue() <= 3)
23825         weight = CW_Constant;
23826     }
23827     break;
23828   case 'N':
23829     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23830       if (C->getZExtValue() <= 0xff)
23831         weight = CW_Constant;
23832     }
23833     break;
23834   case 'G':
23835   case 'C':
23836     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23837       weight = CW_Constant;
23838     }
23839     break;
23840   case 'e':
23841     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23842       if ((C->getSExtValue() >= -0x80000000LL) &&
23843           (C->getSExtValue() <= 0x7fffffffLL))
23844         weight = CW_Constant;
23845     }
23846     break;
23847   case 'Z':
23848     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23849       if (C->getZExtValue() <= 0xffffffff)
23850         weight = CW_Constant;
23851     }
23852     break;
23853   }
23854   return weight;
23855 }
23856
23857 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23858 /// with another that has more specific requirements based on the type of the
23859 /// corresponding operand.
23860 const char *X86TargetLowering::
23861 LowerXConstraint(EVT ConstraintVT) const {
23862   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23863   // 'f' like normal targets.
23864   if (ConstraintVT.isFloatingPoint()) {
23865     if (Subtarget->hasSSE2())
23866       return "Y";
23867     if (Subtarget->hasSSE1())
23868       return "x";
23869   }
23870
23871   return TargetLowering::LowerXConstraint(ConstraintVT);
23872 }
23873
23874 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23875 /// vector.  If it is invalid, don't add anything to Ops.
23876 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23877                                                      std::string &Constraint,
23878                                                      std::vector<SDValue>&Ops,
23879                                                      SelectionDAG &DAG) const {
23880   SDValue Result;
23881
23882   // Only support length 1 constraints for now.
23883   if (Constraint.length() > 1) return;
23884
23885   char ConstraintLetter = Constraint[0];
23886   switch (ConstraintLetter) {
23887   default: break;
23888   case 'I':
23889     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23890       if (C->getZExtValue() <= 31) {
23891         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23892         break;
23893       }
23894     }
23895     return;
23896   case 'J':
23897     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23898       if (C->getZExtValue() <= 63) {
23899         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23900         break;
23901       }
23902     }
23903     return;
23904   case 'K':
23905     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23906       if (isInt<8>(C->getSExtValue())) {
23907         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23908         break;
23909       }
23910     }
23911     return;
23912   case 'L':
23913     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23914       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
23915           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
23916         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
23917         break;
23918       }
23919     }
23920     return;
23921   case 'M':
23922     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23923       if (C->getZExtValue() <= 3) {
23924         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23925         break;
23926       }
23927     }
23928     return;
23929   case 'N':
23930     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23931       if (C->getZExtValue() <= 255) {
23932         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23933         break;
23934       }
23935     }
23936     return;
23937   case 'O':
23938     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23939       if (C->getZExtValue() <= 127) {
23940         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23941         break;
23942       }
23943     }
23944     return;
23945   case 'e': {
23946     // 32-bit signed value
23947     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23948       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23949                                            C->getSExtValue())) {
23950         // Widen to 64 bits here to get it sign extended.
23951         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23952         break;
23953       }
23954     // FIXME gcc accepts some relocatable values here too, but only in certain
23955     // memory models; it's complicated.
23956     }
23957     return;
23958   }
23959   case 'Z': {
23960     // 32-bit unsigned value
23961     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23962       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23963                                            C->getZExtValue())) {
23964         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23965         break;
23966       }
23967     }
23968     // FIXME gcc accepts some relocatable values here too, but only in certain
23969     // memory models; it's complicated.
23970     return;
23971   }
23972   case 'i': {
23973     // Literal immediates are always ok.
23974     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23975       // Widen to 64 bits here to get it sign extended.
23976       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23977       break;
23978     }
23979
23980     // In any sort of PIC mode addresses need to be computed at runtime by
23981     // adding in a register or some sort of table lookup.  These can't
23982     // be used as immediates.
23983     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23984       return;
23985
23986     // If we are in non-pic codegen mode, we allow the address of a global (with
23987     // an optional displacement) to be used with 'i'.
23988     GlobalAddressSDNode *GA = nullptr;
23989     int64_t Offset = 0;
23990
23991     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23992     while (1) {
23993       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23994         Offset += GA->getOffset();
23995         break;
23996       } else if (Op.getOpcode() == ISD::ADD) {
23997         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23998           Offset += C->getZExtValue();
23999           Op = Op.getOperand(0);
24000           continue;
24001         }
24002       } else if (Op.getOpcode() == ISD::SUB) {
24003         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24004           Offset += -C->getZExtValue();
24005           Op = Op.getOperand(0);
24006           continue;
24007         }
24008       }
24009
24010       // Otherwise, this isn't something we can handle, reject it.
24011       return;
24012     }
24013
24014     const GlobalValue *GV = GA->getGlobal();
24015     // If we require an extra load to get this address, as in PIC mode, we
24016     // can't accept it.
24017     if (isGlobalStubReference(
24018             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24019       return;
24020
24021     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24022                                         GA->getValueType(0), Offset);
24023     break;
24024   }
24025   }
24026
24027   if (Result.getNode()) {
24028     Ops.push_back(Result);
24029     return;
24030   }
24031   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24032 }
24033
24034 std::pair<unsigned, const TargetRegisterClass *>
24035 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24036                                                 const std::string &Constraint,
24037                                                 MVT VT) const {
24038   // First, see if this is a constraint that directly corresponds to an LLVM
24039   // register class.
24040   if (Constraint.size() == 1) {
24041     // GCC Constraint Letters
24042     switch (Constraint[0]) {
24043     default: break;
24044       // TODO: Slight differences here in allocation order and leaving
24045       // RIP in the class. Do they matter any more here than they do
24046       // in the normal allocation?
24047     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24048       if (Subtarget->is64Bit()) {
24049         if (VT == MVT::i32 || VT == MVT::f32)
24050           return std::make_pair(0U, &X86::GR32RegClass);
24051         if (VT == MVT::i16)
24052           return std::make_pair(0U, &X86::GR16RegClass);
24053         if (VT == MVT::i8 || VT == MVT::i1)
24054           return std::make_pair(0U, &X86::GR8RegClass);
24055         if (VT == MVT::i64 || VT == MVT::f64)
24056           return std::make_pair(0U, &X86::GR64RegClass);
24057         break;
24058       }
24059       // 32-bit fallthrough
24060     case 'Q':   // Q_REGS
24061       if (VT == MVT::i32 || VT == MVT::f32)
24062         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24063       if (VT == MVT::i16)
24064         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24065       if (VT == MVT::i8 || VT == MVT::i1)
24066         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24067       if (VT == MVT::i64)
24068         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24069       break;
24070     case 'r':   // GENERAL_REGS
24071     case 'l':   // INDEX_REGS
24072       if (VT == MVT::i8 || VT == MVT::i1)
24073         return std::make_pair(0U, &X86::GR8RegClass);
24074       if (VT == MVT::i16)
24075         return std::make_pair(0U, &X86::GR16RegClass);
24076       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24077         return std::make_pair(0U, &X86::GR32RegClass);
24078       return std::make_pair(0U, &X86::GR64RegClass);
24079     case 'R':   // LEGACY_REGS
24080       if (VT == MVT::i8 || VT == MVT::i1)
24081         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24082       if (VT == MVT::i16)
24083         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24084       if (VT == MVT::i32 || !Subtarget->is64Bit())
24085         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24086       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24087     case 'f':  // FP Stack registers.
24088       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24089       // value to the correct fpstack register class.
24090       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24091         return std::make_pair(0U, &X86::RFP32RegClass);
24092       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24093         return std::make_pair(0U, &X86::RFP64RegClass);
24094       return std::make_pair(0U, &X86::RFP80RegClass);
24095     case 'y':   // MMX_REGS if MMX allowed.
24096       if (!Subtarget->hasMMX()) break;
24097       return std::make_pair(0U, &X86::VR64RegClass);
24098     case 'Y':   // SSE_REGS if SSE2 allowed
24099       if (!Subtarget->hasSSE2()) break;
24100       // FALL THROUGH.
24101     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24102       if (!Subtarget->hasSSE1()) break;
24103
24104       switch (VT.SimpleTy) {
24105       default: break;
24106       // Scalar SSE types.
24107       case MVT::f32:
24108       case MVT::i32:
24109         return std::make_pair(0U, &X86::FR32RegClass);
24110       case MVT::f64:
24111       case MVT::i64:
24112         return std::make_pair(0U, &X86::FR64RegClass);
24113       // Vector types.
24114       case MVT::v16i8:
24115       case MVT::v8i16:
24116       case MVT::v4i32:
24117       case MVT::v2i64:
24118       case MVT::v4f32:
24119       case MVT::v2f64:
24120         return std::make_pair(0U, &X86::VR128RegClass);
24121       // AVX types.
24122       case MVT::v32i8:
24123       case MVT::v16i16:
24124       case MVT::v8i32:
24125       case MVT::v4i64:
24126       case MVT::v8f32:
24127       case MVT::v4f64:
24128         return std::make_pair(0U, &X86::VR256RegClass);
24129       case MVT::v8f64:
24130       case MVT::v16f32:
24131       case MVT::v16i32:
24132       case MVT::v8i64:
24133         return std::make_pair(0U, &X86::VR512RegClass);
24134       }
24135       break;
24136     }
24137   }
24138
24139   // Use the default implementation in TargetLowering to convert the register
24140   // constraint into a member of a register class.
24141   std::pair<unsigned, const TargetRegisterClass*> Res;
24142   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24143
24144   // Not found as a standard register?
24145   if (!Res.second) {
24146     // Map st(0) -> st(7) -> ST0
24147     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24148         tolower(Constraint[1]) == 's' &&
24149         tolower(Constraint[2]) == 't' &&
24150         Constraint[3] == '(' &&
24151         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24152         Constraint[5] == ')' &&
24153         Constraint[6] == '}') {
24154
24155       Res.first = X86::FP0+Constraint[4]-'0';
24156       Res.second = &X86::RFP80RegClass;
24157       return Res;
24158     }
24159
24160     // GCC allows "st(0)" to be called just plain "st".
24161     if (StringRef("{st}").equals_lower(Constraint)) {
24162       Res.first = X86::FP0;
24163       Res.second = &X86::RFP80RegClass;
24164       return Res;
24165     }
24166
24167     // flags -> EFLAGS
24168     if (StringRef("{flags}").equals_lower(Constraint)) {
24169       Res.first = X86::EFLAGS;
24170       Res.second = &X86::CCRRegClass;
24171       return Res;
24172     }
24173
24174     // 'A' means EAX + EDX.
24175     if (Constraint == "A") {
24176       Res.first = X86::EAX;
24177       Res.second = &X86::GR32_ADRegClass;
24178       return Res;
24179     }
24180     return Res;
24181   }
24182
24183   // Otherwise, check to see if this is a register class of the wrong value
24184   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24185   // turn into {ax},{dx}.
24186   if (Res.second->hasType(VT))
24187     return Res;   // Correct type already, nothing to do.
24188
24189   // All of the single-register GCC register classes map their values onto
24190   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24191   // really want an 8-bit or 32-bit register, map to the appropriate register
24192   // class and return the appropriate register.
24193   if (Res.second == &X86::GR16RegClass) {
24194     if (VT == MVT::i8 || VT == MVT::i1) {
24195       unsigned DestReg = 0;
24196       switch (Res.first) {
24197       default: break;
24198       case X86::AX: DestReg = X86::AL; break;
24199       case X86::DX: DestReg = X86::DL; break;
24200       case X86::CX: DestReg = X86::CL; break;
24201       case X86::BX: DestReg = X86::BL; break;
24202       }
24203       if (DestReg) {
24204         Res.first = DestReg;
24205         Res.second = &X86::GR8RegClass;
24206       }
24207     } else if (VT == MVT::i32 || VT == MVT::f32) {
24208       unsigned DestReg = 0;
24209       switch (Res.first) {
24210       default: break;
24211       case X86::AX: DestReg = X86::EAX; break;
24212       case X86::DX: DestReg = X86::EDX; break;
24213       case X86::CX: DestReg = X86::ECX; break;
24214       case X86::BX: DestReg = X86::EBX; break;
24215       case X86::SI: DestReg = X86::ESI; break;
24216       case X86::DI: DestReg = X86::EDI; break;
24217       case X86::BP: DestReg = X86::EBP; break;
24218       case X86::SP: DestReg = X86::ESP; break;
24219       }
24220       if (DestReg) {
24221         Res.first = DestReg;
24222         Res.second = &X86::GR32RegClass;
24223       }
24224     } else if (VT == MVT::i64 || VT == MVT::f64) {
24225       unsigned DestReg = 0;
24226       switch (Res.first) {
24227       default: break;
24228       case X86::AX: DestReg = X86::RAX; break;
24229       case X86::DX: DestReg = X86::RDX; break;
24230       case X86::CX: DestReg = X86::RCX; break;
24231       case X86::BX: DestReg = X86::RBX; break;
24232       case X86::SI: DestReg = X86::RSI; break;
24233       case X86::DI: DestReg = X86::RDI; break;
24234       case X86::BP: DestReg = X86::RBP; break;
24235       case X86::SP: DestReg = X86::RSP; break;
24236       }
24237       if (DestReg) {
24238         Res.first = DestReg;
24239         Res.second = &X86::GR64RegClass;
24240       }
24241     }
24242   } else if (Res.second == &X86::FR32RegClass ||
24243              Res.second == &X86::FR64RegClass ||
24244              Res.second == &X86::VR128RegClass ||
24245              Res.second == &X86::VR256RegClass ||
24246              Res.second == &X86::FR32XRegClass ||
24247              Res.second == &X86::FR64XRegClass ||
24248              Res.second == &X86::VR128XRegClass ||
24249              Res.second == &X86::VR256XRegClass ||
24250              Res.second == &X86::VR512RegClass) {
24251     // Handle references to XMM physical registers that got mapped into the
24252     // wrong class.  This can happen with constraints like {xmm0} where the
24253     // target independent register mapper will just pick the first match it can
24254     // find, ignoring the required type.
24255
24256     if (VT == MVT::f32 || VT == MVT::i32)
24257       Res.second = &X86::FR32RegClass;
24258     else if (VT == MVT::f64 || VT == MVT::i64)
24259       Res.second = &X86::FR64RegClass;
24260     else if (X86::VR128RegClass.hasType(VT))
24261       Res.second = &X86::VR128RegClass;
24262     else if (X86::VR256RegClass.hasType(VT))
24263       Res.second = &X86::VR256RegClass;
24264     else if (X86::VR512RegClass.hasType(VT))
24265       Res.second = &X86::VR512RegClass;
24266   }
24267
24268   return Res;
24269 }
24270
24271 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24272                                             Type *Ty) const {
24273   // Scaling factors are not free at all.
24274   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24275   // will take 2 allocations in the out of order engine instead of 1
24276   // for plain addressing mode, i.e. inst (reg1).
24277   // E.g.,
24278   // vaddps (%rsi,%drx), %ymm0, %ymm1
24279   // Requires two allocations (one for the load, one for the computation)
24280   // whereas:
24281   // vaddps (%rsi), %ymm0, %ymm1
24282   // Requires just 1 allocation, i.e., freeing allocations for other operations
24283   // and having less micro operations to execute.
24284   //
24285   // For some X86 architectures, this is even worse because for instance for
24286   // stores, the complex addressing mode forces the instruction to use the
24287   // "load" ports instead of the dedicated "store" port.
24288   // E.g., on Haswell:
24289   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24290   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24291   if (isLegalAddressingMode(AM, Ty))
24292     // Scale represents reg2 * scale, thus account for 1
24293     // as soon as we use a second register.
24294     return AM.Scale != 0;
24295   return -1;
24296 }
24297
24298 bool X86TargetLowering::isTargetFTOL() const {
24299   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24300 }