[X86] Add support for builtin to read performance monitoring counters.
[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 "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorShuffleLowering(
62     "x86-experimental-vector-shuffle-lowering", cl::init(false),
63     cl::desc("Enable an experimental vector shuffle lowering code path."),
64     cl::Hidden);
65
66 // Forward declarations.
67 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
68                        SDValue V2);
69
70 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
71                                 SelectionDAG &DAG, SDLoc dl,
72                                 unsigned vectorWidth) {
73   assert((vectorWidth == 128 || vectorWidth == 256) &&
74          "Unsupported vector width");
75   EVT VT = Vec.getValueType();
76   EVT ElVT = VT.getVectorElementType();
77   unsigned Factor = VT.getSizeInBits()/vectorWidth;
78   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
79                                   VT.getVectorNumElements()/Factor);
80
81   // Extract from UNDEF is UNDEF.
82   if (Vec.getOpcode() == ISD::UNDEF)
83     return DAG.getUNDEF(ResultVT);
84
85   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
86   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
87
88   // This is the index of the first element of the vectorWidth-bit chunk
89   // we want.
90   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
91                                * ElemsPerChunk);
92
93   // If the input is a buildvector just emit a smaller one.
94   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
95     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
96                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
97                                     ElemsPerChunk));
98
99   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
100   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
101                                VecIdx);
102
103   return Result;
104
105 }
106 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
107 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
108 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
109 /// instructions or a simple subregister reference. Idx is an index in the
110 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
111 /// lowering EXTRACT_VECTOR_ELT operations easier.
112 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
113                                    SelectionDAG &DAG, SDLoc dl) {
114   assert((Vec.getValueType().is256BitVector() ||
115           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
117 }
118
119 /// Generate a DAG to grab 256-bits from a 512-bit vector.
120 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
121                                    SelectionDAG &DAG, SDLoc dl) {
122   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
124 }
125
126 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
127                                unsigned IdxVal, SelectionDAG &DAG,
128                                SDLoc dl, unsigned vectorWidth) {
129   assert((vectorWidth == 128 || vectorWidth == 256) &&
130          "Unsupported vector width");
131   // Inserting UNDEF is Result
132   if (Vec.getOpcode() == ISD::UNDEF)
133     return Result;
134   EVT VT = Vec.getValueType();
135   EVT ElVT = VT.getVectorElementType();
136   EVT ResultVT = Result.getValueType();
137
138   // Insert the relevant vectorWidth bits.
139   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
140
141   // This is the index of the first element of the vectorWidth-bit chunk
142   // we want.
143   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
144                                * ElemsPerChunk);
145
146   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
147   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
148                      VecIdx);
149 }
150 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
151 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
152 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
153 /// simple superregister reference.  Idx is an index in the 128 bits
154 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
155 /// lowering INSERT_VECTOR_ELT operations easier.
156 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
161 }
162
163 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
168 }
169
170 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
171 /// instructions. This is used because creating CONCAT_VECTOR nodes of
172 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
173 /// large BUILD_VECTORS.
174 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
189   if (TT.isOSBinFormatMachO()) {
190     if (TT.getArch() == Triple::x86_64)
191       return new X86_64MachoTargetObjectFile();
192     return new TargetLoweringObjectFileMachO();
193   }
194
195   if (TT.isOSLinux())
196     return new X86LinuxTargetObjectFile();
197   if (TT.isOSBinFormatELF())
198     return new TargetLoweringObjectFileELF();
199   if (TT.isKnownWindowsMSVCEnvironment())
200     return new X86WindowsTargetObjectFile();
201   if (TT.isOSBinFormatCOFF())
202     return new TargetLoweringObjectFileCOFF();
203   llvm_unreachable("unknown subtarget type");
204 }
205
206 // FIXME: This should stop caching the target machine as soon as
207 // we can remove resetOperationActions et al.
208 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
209   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
210   Subtarget = &TM.getSubtarget<X86Subtarget>();
211   X86ScalarSSEf64 = Subtarget->hasSSE2();
212   X86ScalarSSEf32 = Subtarget->hasSSE1();
213   TD = getDataLayout();
214
215   resetOperationActions();
216 }
217
218 void X86TargetLowering::resetOperationActions() {
219   const TargetMachine &TM = getTargetMachine();
220   static bool FirstTimeThrough = true;
221
222   // If none of the target options have changed, then we don't need to reset the
223   // operation actions.
224   if (!FirstTimeThrough && TO == TM.Options) return;
225
226   if (!FirstTimeThrough) {
227     // Reinitialize the actions.
228     initActions();
229     FirstTimeThrough = false;
230   }
231
232   TO = TM.Options;
233
234   // Set up the TargetLowering object.
235   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
236
237   // X86 is weird, it always uses i8 for shift amounts and setcc results.
238   setBooleanContents(ZeroOrOneBooleanContent);
239   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
240   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
241
242   // For 64-bit since we have so many registers use the ILP scheduler, for
243   // 32-bit code use the register pressure specific scheduling.
244   // For Atom, always use ILP scheduling.
245   if (Subtarget->isAtom())
246     setSchedulingPreference(Sched::ILP);
247   else if (Subtarget->is64Bit())
248     setSchedulingPreference(Sched::ILP);
249   else
250     setSchedulingPreference(Sched::RegPressure);
251   const X86RegisterInfo *RegInfo =
252     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
253   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
254
255   // Bypass expensive divides on Atom when compiling with O2
256   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
257     addBypassSlowDiv(32, 8);
258     if (Subtarget->is64Bit())
259       addBypassSlowDiv(64, 16);
260   }
261
262   if (Subtarget->isTargetKnownWindowsMSVC()) {
263     // Setup Windows compiler runtime calls.
264     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
265     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
266     setLibcallName(RTLIB::SREM_I64, "_allrem");
267     setLibcallName(RTLIB::UREM_I64, "_aullrem");
268     setLibcallName(RTLIB::MUL_I64, "_allmul");
269     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
270     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
271     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
272     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
273     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
274
275     // The _ftol2 runtime function has an unusual calling conv, which
276     // is modeled by a special pseudo-instruction.
277     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
278     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
279     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
280     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
281   }
282
283   if (Subtarget->isTargetDarwin()) {
284     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
285     setUseUnderscoreSetJmp(false);
286     setUseUnderscoreLongJmp(false);
287   } else if (Subtarget->isTargetWindowsGNU()) {
288     // MS runtime is weird: it exports _setjmp, but longjmp!
289     setUseUnderscoreSetJmp(true);
290     setUseUnderscoreLongJmp(false);
291   } else {
292     setUseUnderscoreSetJmp(true);
293     setUseUnderscoreLongJmp(true);
294   }
295
296   // Set up the register classes.
297   addRegisterClass(MVT::i8, &X86::GR8RegClass);
298   addRegisterClass(MVT::i16, &X86::GR16RegClass);
299   addRegisterClass(MVT::i32, &X86::GR32RegClass);
300   if (Subtarget->is64Bit())
301     addRegisterClass(MVT::i64, &X86::GR64RegClass);
302
303   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
304
305   // We don't accept any truncstore of integer registers.
306   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
307   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
308   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
309   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
310   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
311   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
312
313   // SETOEQ and SETUNE require checking two conditions.
314   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
315   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
316   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
317   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
318   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
319   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
320
321   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
322   // operation.
323   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
324   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
325   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
326
327   if (Subtarget->is64Bit()) {
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
329     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
330   } else if (!TM.Options.UseSoftFloat) {
331     // We have an algorithm for SSE2->double, and we turn this into a
332     // 64-bit FILD followed by conditional FADD for other targets.
333     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
334     // We have an algorithm for SSE2, and we turn this into a 64-bit
335     // FILD for other targets.
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
337   }
338
339   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
340   // this operation.
341   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
342   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
343
344   if (!TM.Options.UseSoftFloat) {
345     // SSE has no i16 to fp conversion, only i32
346     if (X86ScalarSSEf32) {
347       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348       // f32 and f64 cases are Legal, f80 case is not
349       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
350     } else {
351       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
352       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
353     }
354   } else {
355     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
356     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
357   }
358
359   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
360   // are Legal, f80 is custom lowered.
361   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
362   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
363
364   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
365   // this operation.
366   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
367   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
368
369   if (X86ScalarSSEf32) {
370     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
371     // f32 and f64 cases are Legal, f80 case is not
372     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
373   } else {
374     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
375     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
376   }
377
378   // Handle FP_TO_UINT by promoting the destination to a larger signed
379   // conversion.
380   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
381   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
382   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
383
384   if (Subtarget->is64Bit()) {
385     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
386     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
387   } else if (!TM.Options.UseSoftFloat) {
388     // Since AVX is a superset of SSE3, only check for SSE here.
389     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
390       // Expand FP_TO_UINT into a select.
391       // FIXME: We would like to use a Custom expander here eventually to do
392       // the optimal thing for SSE vs. the default expansion in the legalizer.
393       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
394     else
395       // With SSE3 we can use fisttpll to convert to a signed i64; without
396       // SSE, we're stuck with a fistpll.
397       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
398   }
399
400   if (isTargetFTOL()) {
401     // Use the _ftol2 runtime function, which has a pseudo-instruction
402     // to handle its weird calling convention.
403     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
404   }
405
406   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
407   if (!X86ScalarSSEf64) {
408     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
409     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
410     if (Subtarget->is64Bit()) {
411       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
412       // Without SSE, i64->f64 goes through memory.
413       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
414     }
415   }
416
417   // Scalar integer divide and remainder are lowered to use operations that
418   // produce two results, to match the available instructions. This exposes
419   // the two-result form to trivial CSE, which is able to combine x/y and x%y
420   // into a single instruction.
421   //
422   // Scalar integer multiply-high is also lowered to use two-result
423   // operations, to match the available instructions. However, plain multiply
424   // (low) operations are left as Legal, as there are single-result
425   // instructions for this in x86. Using the two-result multiply instructions
426   // when both high and low results are needed must be arranged by dagcombine.
427   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
428     MVT VT = IntVTs[i];
429     setOperationAction(ISD::MULHS, VT, Expand);
430     setOperationAction(ISD::MULHU, VT, Expand);
431     setOperationAction(ISD::SDIV, VT, Expand);
432     setOperationAction(ISD::UDIV, VT, Expand);
433     setOperationAction(ISD::SREM, VT, Expand);
434     setOperationAction(ISD::UREM, VT, Expand);
435
436     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
437     setOperationAction(ISD::ADDC, VT, Custom);
438     setOperationAction(ISD::ADDE, VT, Custom);
439     setOperationAction(ISD::SUBC, VT, Custom);
440     setOperationAction(ISD::SUBE, VT, Custom);
441   }
442
443   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
444   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
445   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
446   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
447   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
448   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
449   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
450   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
451   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
453   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
454   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
455   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
456   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
457   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
459   if (Subtarget->is64Bit())
460     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
461   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
462   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
463   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
464   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
465   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
466   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
467   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
468   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
469
470   // Promote the i8 variants and force them on up to i32 which has a shorter
471   // encoding.
472   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
473   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
474   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
475   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
476   if (Subtarget->hasBMI()) {
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
479     if (Subtarget->is64Bit())
480       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
481   } else {
482     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
483     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
484     if (Subtarget->is64Bit())
485       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
486   }
487
488   if (Subtarget->hasLZCNT()) {
489     // When promoting the i8 variants, force them to i32 for a shorter
490     // encoding.
491     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
492     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
494     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
495     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
496     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
497     if (Subtarget->is64Bit())
498       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
499   } else {
500     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
501     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
502     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
504     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
505     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
506     if (Subtarget->is64Bit()) {
507       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
508       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
509     }
510   }
511
512   if (Subtarget->hasPOPCNT()) {
513     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
514   } else {
515     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
516     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
517     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
518     if (Subtarget->is64Bit())
519       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
520   }
521
522   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
523
524   if (!Subtarget->hasMOVBE())
525     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
526
527   // These should be promoted to a larger select which is supported.
528   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
529   // X86 wants to expand cmov itself.
530   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
531   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
532   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
533   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
534   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
535   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
536   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
537   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
538   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
539   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
540   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
541   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
544     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
545   }
546   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
547   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
548   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
549   // support continuation, user-level threading, and etc.. As a result, no
550   // other SjLj exception interfaces are implemented and please don't build
551   // your own exception handling based on them.
552   // LLVM/Clang supports zero-cost DWARF exception handling.
553   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
554   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
555
556   // Darwin ABI issue.
557   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
558   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
559   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
560   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
561   if (Subtarget->is64Bit())
562     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
563   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
564   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
567     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
568     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
569     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
570     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
571   }
572   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
573   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
574   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
575   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
576   if (Subtarget->is64Bit()) {
577     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
578     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
579     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
580   }
581
582   if (Subtarget->hasSSE1())
583     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
584
585   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
586
587   // Expand certain atomics
588   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
589     MVT VT = IntVTs[i];
590     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
592     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
593   }
594
595   if (!Subtarget->is64Bit()) {
596     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
597     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
598     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
599     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
600     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
601     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
602     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
603     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
604     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
605     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
606     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
607     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
608   }
609
610   if (Subtarget->hasCmpxchg16b()) {
611     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
612   }
613
614   // FIXME - use subtarget debug flags
615   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
616       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
617     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
618   }
619
620   if (Subtarget->is64Bit()) {
621     setExceptionPointerRegister(X86::RAX);
622     setExceptionSelectorRegister(X86::RDX);
623   } else {
624     setExceptionPointerRegister(X86::EAX);
625     setExceptionSelectorRegister(X86::EDX);
626   }
627   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
628   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
629
630   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
631   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
632
633   setOperationAction(ISD::TRAP, MVT::Other, Legal);
634   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
635
636   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
637   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
638   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
639   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
640     // TargetInfo::X86_64ABIBuiltinVaList
641     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
642     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
643   } else {
644     // TargetInfo::CharPtrBuiltinVaList
645     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
646     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
647   }
648
649   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
650   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
651
652   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
653                      MVT::i64 : MVT::i32, Custom);
654
655   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
656     // f32 and f64 use SSE.
657     // Set up the FP register classes.
658     addRegisterClass(MVT::f32, &X86::FR32RegClass);
659     addRegisterClass(MVT::f64, &X86::FR64RegClass);
660
661     // Use ANDPD to simulate FABS.
662     setOperationAction(ISD::FABS , MVT::f64, Custom);
663     setOperationAction(ISD::FABS , MVT::f32, Custom);
664
665     // Use XORP to simulate FNEG.
666     setOperationAction(ISD::FNEG , MVT::f64, Custom);
667     setOperationAction(ISD::FNEG , MVT::f32, Custom);
668
669     // Use ANDPD and ORPD to simulate FCOPYSIGN.
670     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
672
673     // Lower this to FGETSIGNx86 plus an AND.
674     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
675     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
676
677     // We don't support sin/cos/fmod
678     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
679     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
680     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
681     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
682     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
683     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
684
685     // Expand FP immediates into loads from the stack, except for the special
686     // cases we handle.
687     addLegalFPImmediate(APFloat(+0.0)); // xorpd
688     addLegalFPImmediate(APFloat(+0.0f)); // xorps
689   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
690     // Use SSE for f32, x87 for f64.
691     // Set up the FP register classes.
692     addRegisterClass(MVT::f32, &X86::FR32RegClass);
693     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
694
695     // Use ANDPS to simulate FABS.
696     setOperationAction(ISD::FABS , MVT::f32, Custom);
697
698     // Use XORP to simulate FNEG.
699     setOperationAction(ISD::FNEG , MVT::f32, Custom);
700
701     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
702
703     // Use ANDPS and ORPS to simulate FCOPYSIGN.
704     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
705     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
706
707     // We don't support sin/cos/fmod
708     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
709     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
710     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
711
712     // Special cases we handle for FP constants.
713     addLegalFPImmediate(APFloat(+0.0f)); // xorps
714     addLegalFPImmediate(APFloat(+0.0)); // FLD0
715     addLegalFPImmediate(APFloat(+1.0)); // FLD1
716     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
717     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
718
719     if (!TM.Options.UnsafeFPMath) {
720       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
721       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
722       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
723     }
724   } else if (!TM.Options.UseSoftFloat) {
725     // f32 and f64 in x87.
726     // Set up the FP register classes.
727     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
728     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
729
730     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
731     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
732     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
733     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
734
735     if (!TM.Options.UnsafeFPMath) {
736       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
737       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
738       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
739       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
740       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
741       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
742     }
743     addLegalFPImmediate(APFloat(+0.0)); // FLD0
744     addLegalFPImmediate(APFloat(+1.0)); // FLD1
745     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
746     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
747     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
748     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
749     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
750     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
751   }
752
753   // We don't support FMA.
754   setOperationAction(ISD::FMA, MVT::f64, Expand);
755   setOperationAction(ISD::FMA, MVT::f32, Expand);
756
757   // Long double always uses X87.
758   if (!TM.Options.UseSoftFloat) {
759     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
760     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
761     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
762     {
763       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
764       addLegalFPImmediate(TmpFlt);  // FLD0
765       TmpFlt.changeSign();
766       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
767
768       bool ignored;
769       APFloat TmpFlt2(+1.0);
770       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
771                       &ignored);
772       addLegalFPImmediate(TmpFlt2);  // FLD1
773       TmpFlt2.changeSign();
774       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
775     }
776
777     if (!TM.Options.UnsafeFPMath) {
778       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
779       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
780       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
781     }
782
783     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
784     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
785     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
786     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
787     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
788     setOperationAction(ISD::FMA, MVT::f80, Expand);
789   }
790
791   // Always use a library call for pow.
792   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
793   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
794   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
795
796   setOperationAction(ISD::FLOG, MVT::f80, Expand);
797   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
798   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
799   setOperationAction(ISD::FEXP, MVT::f80, Expand);
800   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
801
802   // First set operation action for all vector types to either promote
803   // (for widening) or expand (for scalarization). Then we will selectively
804   // turn on ones that can be effectively codegen'd.
805   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
806            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
807     MVT VT = (MVT::SimpleValueType)i;
808     setOperationAction(ISD::ADD , VT, Expand);
809     setOperationAction(ISD::SUB , VT, Expand);
810     setOperationAction(ISD::FADD, VT, Expand);
811     setOperationAction(ISD::FNEG, VT, Expand);
812     setOperationAction(ISD::FSUB, VT, Expand);
813     setOperationAction(ISD::MUL , VT, Expand);
814     setOperationAction(ISD::FMUL, VT, Expand);
815     setOperationAction(ISD::SDIV, VT, Expand);
816     setOperationAction(ISD::UDIV, VT, Expand);
817     setOperationAction(ISD::FDIV, VT, Expand);
818     setOperationAction(ISD::SREM, VT, Expand);
819     setOperationAction(ISD::UREM, VT, Expand);
820     setOperationAction(ISD::LOAD, VT, Expand);
821     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
822     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
823     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
824     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
826     setOperationAction(ISD::FABS, VT, Expand);
827     setOperationAction(ISD::FSIN, VT, Expand);
828     setOperationAction(ISD::FSINCOS, VT, Expand);
829     setOperationAction(ISD::FCOS, VT, Expand);
830     setOperationAction(ISD::FSINCOS, VT, Expand);
831     setOperationAction(ISD::FREM, VT, Expand);
832     setOperationAction(ISD::FMA,  VT, Expand);
833     setOperationAction(ISD::FPOWI, VT, Expand);
834     setOperationAction(ISD::FSQRT, VT, Expand);
835     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
836     setOperationAction(ISD::FFLOOR, VT, Expand);
837     setOperationAction(ISD::FCEIL, VT, Expand);
838     setOperationAction(ISD::FTRUNC, VT, Expand);
839     setOperationAction(ISD::FRINT, VT, Expand);
840     setOperationAction(ISD::FNEARBYINT, VT, Expand);
841     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
842     setOperationAction(ISD::MULHS, VT, Expand);
843     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
844     setOperationAction(ISD::MULHU, VT, Expand);
845     setOperationAction(ISD::SDIVREM, VT, Expand);
846     setOperationAction(ISD::UDIVREM, VT, Expand);
847     setOperationAction(ISD::FPOW, VT, Expand);
848     setOperationAction(ISD::CTPOP, VT, Expand);
849     setOperationAction(ISD::CTTZ, VT, Expand);
850     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
851     setOperationAction(ISD::CTLZ, VT, Expand);
852     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
853     setOperationAction(ISD::SHL, VT, Expand);
854     setOperationAction(ISD::SRA, VT, Expand);
855     setOperationAction(ISD::SRL, VT, Expand);
856     setOperationAction(ISD::ROTL, VT, Expand);
857     setOperationAction(ISD::ROTR, VT, Expand);
858     setOperationAction(ISD::BSWAP, VT, Expand);
859     setOperationAction(ISD::SETCC, VT, Expand);
860     setOperationAction(ISD::FLOG, VT, Expand);
861     setOperationAction(ISD::FLOG2, VT, Expand);
862     setOperationAction(ISD::FLOG10, VT, Expand);
863     setOperationAction(ISD::FEXP, VT, Expand);
864     setOperationAction(ISD::FEXP2, VT, Expand);
865     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
866     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
867     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
869     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
870     setOperationAction(ISD::TRUNCATE, VT, Expand);
871     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
872     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
873     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
874     setOperationAction(ISD::VSELECT, VT, Expand);
875     setOperationAction(ISD::SELECT_CC, VT, Expand);
876     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
877              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
878       setTruncStoreAction(VT,
879                           (MVT::SimpleValueType)InnerVT, Expand);
880     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
881     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
882     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
883   }
884
885   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886   // with -msoft-float, disable use of MMX as well.
887   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889     // No operations on x86mmx supported, everything uses intrinsics.
890   }
891
892   // MMX-sized vectors (other than x86mmx) are expected to be expanded
893   // into smaller operations.
894   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
895   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
896   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
897   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
898   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
899   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
900   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
901   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
902   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
903   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
904   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
905   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
906   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
907   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
908   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
909   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
910   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
911   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
912   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
913   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
914   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
915   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
916   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
917   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
918   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
919   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
920   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
921   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
922   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
923
924   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
926
927     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
928     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
929     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
930     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
931     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
932     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
933     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
934     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
935     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
936     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
939   }
940
941   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
942     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
943
944     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
945     // registers cannot be used even for integer operations.
946     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
947     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
948     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
949     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
950
951     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
952     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
953     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
954     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
955     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
956     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
957     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
958     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
959     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
960     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
961     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
962     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
963     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
964     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
965     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
966     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
972     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
973
974     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
975     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
976     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
977     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
978
979     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
980     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
984
985     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
986     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
987       MVT VT = (MVT::SimpleValueType)i;
988       // Do not attempt to custom lower non-power-of-2 vectors
989       if (!isPowerOf2_32(VT.getVectorNumElements()))
990         continue;
991       // Do not attempt to custom lower non-128-bit vectors
992       if (!VT.is128BitVector())
993         continue;
994       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
995       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
997     }
998
999     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1000     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1001     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1002     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1003     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1005
1006     if (Subtarget->is64Bit()) {
1007       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1008       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1009     }
1010
1011     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1012     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1013       MVT VT = (MVT::SimpleValueType)i;
1014
1015       // Do not attempt to promote non-128-bit vectors
1016       if (!VT.is128BitVector())
1017         continue;
1018
1019       setOperationAction(ISD::AND,    VT, Promote);
1020       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1021       setOperationAction(ISD::OR,     VT, Promote);
1022       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1023       setOperationAction(ISD::XOR,    VT, Promote);
1024       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1025       setOperationAction(ISD::LOAD,   VT, Promote);
1026       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1027       setOperationAction(ISD::SELECT, VT, Promote);
1028       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1029     }
1030
1031     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1032
1033     // Custom lower v2i64 and v2f64 selects.
1034     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1035     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1036     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1037     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1038
1039     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1040     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1041
1042     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1043     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1044     // As there is no 64-bit GPR available, we need build a special custom
1045     // sequence to convert from v2i32 to v2f32.
1046     if (!Subtarget->is64Bit())
1047       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1048
1049     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1050     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1051
1052     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1053
1054     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1055     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1056     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1057   }
1058
1059   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1060     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1061     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1062     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1063     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1064     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1068     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1070
1071     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1076     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1077     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1078     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1079     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1080     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1081
1082     // FIXME: Do we need to handle scalar-to-vector here?
1083     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1084
1085     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1086     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1087     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1088     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1089     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1090     // There is no BLENDI for byte vectors. We don't need to custom lower
1091     // some vselects for now.
1092     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1093
1094     // i8 and i16 vectors are custom , because the source register and source
1095     // source memory operand types are not the same width.  f32 vectors are
1096     // custom since the immediate controlling the insert encodes additional
1097     // information.
1098     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1099     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1100     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1101     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1102
1103     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1104     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1105     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1106     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1107
1108     // FIXME: these should be Legal but thats only for the case where
1109     // the index is constant.  For now custom expand to deal with that.
1110     if (Subtarget->is64Bit()) {
1111       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1112       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1113     }
1114   }
1115
1116   if (Subtarget->hasSSE2()) {
1117     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1118     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1119
1120     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1121     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1122
1123     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1124     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1125
1126     // In the customized shift lowering, the legal cases in AVX2 will be
1127     // recognized.
1128     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1129     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1130
1131     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1132     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1133
1134     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1135   }
1136
1137   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1138     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1139     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1140     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1141     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1142     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1143     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1144
1145     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1146     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1148
1149     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1150     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1151     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1152     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1153     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1154     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1155     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1156     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1157     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1158     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1159     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1160     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1161
1162     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1163     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1164     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1165     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1166     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1167     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1168     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1169     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1170     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1171     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1172     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1173     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1174
1175     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1176     // even though v8i16 is a legal type.
1177     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1178     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1179     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1180
1181     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1182     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1183     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1184
1185     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1186     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1187
1188     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1189
1190     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1191     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1192
1193     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1194     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1195
1196     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1197     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1198
1199     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1200     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1201     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1202     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1203
1204     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1205     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1206     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1207
1208     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1209     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1210     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1211     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1212
1213     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1214     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1215     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1216     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1217     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1218     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1219     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1220     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1221     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1222     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1223     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1224     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1225
1226     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1227       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1228       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1229       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1230       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1231       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1232       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1233     }
1234
1235     if (Subtarget->hasInt256()) {
1236       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1237       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1238       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1239       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1240
1241       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1242       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1243       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1244       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1245
1246       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1247       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1248       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1249       // Don't lower v32i8 because there is no 128-bit byte mul
1250
1251       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1252       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1253       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1254       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1255
1256       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1257       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1258     } else {
1259       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1260       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1261       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1262       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1263
1264       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1265       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1266       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1267       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1268
1269       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1271       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1272       // Don't lower v32i8 because there is no 128-bit byte mul
1273     }
1274
1275     // In the customized shift lowering, the legal cases in AVX2 will be
1276     // recognized.
1277     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1278     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1279
1280     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1281     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1282
1283     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1284
1285     // Custom lower several nodes for 256-bit types.
1286     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1287              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1288       MVT VT = (MVT::SimpleValueType)i;
1289
1290       // Extract subvector is special because the value type
1291       // (result) is 128-bit but the source is 256-bit wide.
1292       if (VT.is128BitVector())
1293         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1294
1295       // Do not attempt to custom lower other non-256-bit vectors
1296       if (!VT.is256BitVector())
1297         continue;
1298
1299       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1300       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1301       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1302       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1303       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1304       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1305       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1306     }
1307
1308     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1309     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1310       MVT VT = (MVT::SimpleValueType)i;
1311
1312       // Do not attempt to promote non-256-bit vectors
1313       if (!VT.is256BitVector())
1314         continue;
1315
1316       setOperationAction(ISD::AND,    VT, Promote);
1317       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1318       setOperationAction(ISD::OR,     VT, Promote);
1319       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1320       setOperationAction(ISD::XOR,    VT, Promote);
1321       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1322       setOperationAction(ISD::LOAD,   VT, Promote);
1323       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1324       setOperationAction(ISD::SELECT, VT, Promote);
1325       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1326     }
1327   }
1328
1329   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1330     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1331     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1332     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1333     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1334
1335     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1336     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1337     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1338
1339     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1340     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1341     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1342     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1343     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1344     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1350
1351     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1357
1358     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1363     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1365     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1366
1367     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1368     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1369     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1371     if (Subtarget->is64Bit()) {
1372       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1373       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1374       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1375       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1376     }
1377     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1379     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1380     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1381     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1384     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1385     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1386     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1387
1388     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1391     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1392     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1393     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1394     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1395     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1396     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1397     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1398     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1399     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1400     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1401
1402     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1403     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1404     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1405     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1406     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1407     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1408
1409     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1410     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1411
1412     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1413
1414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1415     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1416     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1417     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1418     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1419     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1420     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1421     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1422     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1423
1424     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1425     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1426
1427     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1428     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1429
1430     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1431
1432     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1433     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1434
1435     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1436     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1437
1438     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1439     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1440
1441     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1442     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1443     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1444     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1445     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1446     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1447
1448     if (Subtarget->hasCDI()) {
1449       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1450       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1451     }
1452
1453     // Custom lower several nodes.
1454     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1455              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1456       MVT VT = (MVT::SimpleValueType)i;
1457
1458       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1459       // Extract subvector is special because the value type
1460       // (result) is 256/128-bit but the source is 512-bit wide.
1461       if (VT.is128BitVector() || VT.is256BitVector())
1462         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1463
1464       if (VT.getVectorElementType() == MVT::i1)
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1466
1467       // Do not attempt to custom lower other non-512-bit vectors
1468       if (!VT.is512BitVector())
1469         continue;
1470
1471       if ( EltSize >= 32) {
1472         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1473         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1474         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1475         setOperationAction(ISD::VSELECT,             VT, Legal);
1476         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1477         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1478         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1479       }
1480     }
1481     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1482       MVT VT = (MVT::SimpleValueType)i;
1483
1484       // Do not attempt to promote non-256-bit vectors
1485       if (!VT.is512BitVector())
1486         continue;
1487
1488       setOperationAction(ISD::SELECT, VT, Promote);
1489       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1490     }
1491   }// has  AVX-512
1492
1493   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1494   // of this type with custom code.
1495   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1496            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1497     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1498                        Custom);
1499   }
1500
1501   // We want to custom lower some of our intrinsics.
1502   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505   if (!Subtarget->is64Bit())
1506     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1507
1508   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509   // handle type legalization for these operations here.
1510   //
1511   // FIXME: We really should do custom legalization for addition and
1512   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1513   // than generic legalization for 64-bit multiplication-with-overflow, though.
1514   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515     // Add/Sub/Mul with overflow operations are custom lowered.
1516     MVT VT = IntVTs[i];
1517     setOperationAction(ISD::SADDO, VT, Custom);
1518     setOperationAction(ISD::UADDO, VT, Custom);
1519     setOperationAction(ISD::SSUBO, VT, Custom);
1520     setOperationAction(ISD::USUBO, VT, Custom);
1521     setOperationAction(ISD::SMULO, VT, Custom);
1522     setOperationAction(ISD::UMULO, VT, Custom);
1523   }
1524
1525   // There are no 8-bit 3-address imul/mul instructions
1526   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1527   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1528
1529   if (!Subtarget->is64Bit()) {
1530     // These libcalls are not available in 32-bit.
1531     setLibcallName(RTLIB::SHL_I128, nullptr);
1532     setLibcallName(RTLIB::SRL_I128, nullptr);
1533     setLibcallName(RTLIB::SRA_I128, nullptr);
1534   }
1535
1536   // Combine sin / cos into one node or libcall if possible.
1537   if (Subtarget->hasSinCos()) {
1538     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1539     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1540     if (Subtarget->isTargetDarwin()) {
1541       // For MacOSX, we don't want to the normal expansion of a libcall to
1542       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1543       // traffic.
1544       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1545       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1546     }
1547   }
1548
1549   if (Subtarget->isTargetWin64()) {
1550     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1551     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1552     setOperationAction(ISD::SREM, MVT::i128, Custom);
1553     setOperationAction(ISD::UREM, MVT::i128, Custom);
1554     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1555     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1556   }
1557
1558   // We have target-specific dag combine patterns for the following nodes:
1559   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1560   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1561   setTargetDAGCombine(ISD::VSELECT);
1562   setTargetDAGCombine(ISD::SELECT);
1563   setTargetDAGCombine(ISD::SHL);
1564   setTargetDAGCombine(ISD::SRA);
1565   setTargetDAGCombine(ISD::SRL);
1566   setTargetDAGCombine(ISD::OR);
1567   setTargetDAGCombine(ISD::AND);
1568   setTargetDAGCombine(ISD::ADD);
1569   setTargetDAGCombine(ISD::FADD);
1570   setTargetDAGCombine(ISD::FSUB);
1571   setTargetDAGCombine(ISD::FMA);
1572   setTargetDAGCombine(ISD::SUB);
1573   setTargetDAGCombine(ISD::LOAD);
1574   setTargetDAGCombine(ISD::STORE);
1575   setTargetDAGCombine(ISD::ZERO_EXTEND);
1576   setTargetDAGCombine(ISD::ANY_EXTEND);
1577   setTargetDAGCombine(ISD::SIGN_EXTEND);
1578   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1579   setTargetDAGCombine(ISD::TRUNCATE);
1580   setTargetDAGCombine(ISD::SINT_TO_FP);
1581   setTargetDAGCombine(ISD::SETCC);
1582   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1583   setTargetDAGCombine(ISD::BUILD_VECTOR);
1584   if (Subtarget->is64Bit())
1585     setTargetDAGCombine(ISD::MUL);
1586   setTargetDAGCombine(ISD::XOR);
1587
1588   computeRegisterProperties();
1589
1590   // On Darwin, -Os means optimize for size without hurting performance,
1591   // do not reduce the limit.
1592   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1593   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1594   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1595   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1597   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1598   setPrefLoopAlignment(4); // 2^4 bytes.
1599
1600   // Predictable cmov don't hurt on atom because it's in-order.
1601   PredictableSelectIsExpensive = !Subtarget->isAtom();
1602
1603   setPrefFunctionAlignment(4); // 2^4 bytes.
1604 }
1605
1606 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1607   if (!VT.isVector())
1608     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1609
1610   if (Subtarget->hasAVX512())
1611     switch(VT.getVectorNumElements()) {
1612     case  8: return MVT::v8i1;
1613     case 16: return MVT::v16i1;
1614   }
1615
1616   return VT.changeVectorElementTypeToInteger();
1617 }
1618
1619 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1620 /// the desired ByVal argument alignment.
1621 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1622   if (MaxAlign == 16)
1623     return;
1624   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1625     if (VTy->getBitWidth() == 128)
1626       MaxAlign = 16;
1627   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1628     unsigned EltAlign = 0;
1629     getMaxByValAlign(ATy->getElementType(), EltAlign);
1630     if (EltAlign > MaxAlign)
1631       MaxAlign = EltAlign;
1632   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1633     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1634       unsigned EltAlign = 0;
1635       getMaxByValAlign(STy->getElementType(i), EltAlign);
1636       if (EltAlign > MaxAlign)
1637         MaxAlign = EltAlign;
1638       if (MaxAlign == 16)
1639         break;
1640     }
1641   }
1642 }
1643
1644 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1645 /// function arguments in the caller parameter area. For X86, aggregates
1646 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1647 /// are at 4-byte boundaries.
1648 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1649   if (Subtarget->is64Bit()) {
1650     // Max of 8 and alignment of type.
1651     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1652     if (TyAlign > 8)
1653       return TyAlign;
1654     return 8;
1655   }
1656
1657   unsigned Align = 4;
1658   if (Subtarget->hasSSE1())
1659     getMaxByValAlign(Ty, Align);
1660   return Align;
1661 }
1662
1663 /// getOptimalMemOpType - Returns the target specific optimal type for load
1664 /// and store operations as a result of memset, memcpy, and memmove
1665 /// lowering. If DstAlign is zero that means it's safe to destination
1666 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1667 /// means there isn't a need to check it against alignment requirement,
1668 /// probably because the source does not need to be loaded. If 'IsMemset' is
1669 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1670 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1671 /// source is constant so it does not need to be loaded.
1672 /// It returns EVT::Other if the type should be determined using generic
1673 /// target-independent logic.
1674 EVT
1675 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1676                                        unsigned DstAlign, unsigned SrcAlign,
1677                                        bool IsMemset, bool ZeroMemset,
1678                                        bool MemcpyStrSrc,
1679                                        MachineFunction &MF) const {
1680   const Function *F = MF.getFunction();
1681   if ((!IsMemset || ZeroMemset) &&
1682       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1683                                        Attribute::NoImplicitFloat)) {
1684     if (Size >= 16 &&
1685         (Subtarget->isUnalignedMemAccessFast() ||
1686          ((DstAlign == 0 || DstAlign >= 16) &&
1687           (SrcAlign == 0 || SrcAlign >= 16)))) {
1688       if (Size >= 32) {
1689         if (Subtarget->hasInt256())
1690           return MVT::v8i32;
1691         if (Subtarget->hasFp256())
1692           return MVT::v8f32;
1693       }
1694       if (Subtarget->hasSSE2())
1695         return MVT::v4i32;
1696       if (Subtarget->hasSSE1())
1697         return MVT::v4f32;
1698     } else if (!MemcpyStrSrc && Size >= 8 &&
1699                !Subtarget->is64Bit() &&
1700                Subtarget->hasSSE2()) {
1701       // Do not use f64 to lower memcpy if source is string constant. It's
1702       // better to use i32 to avoid the loads.
1703       return MVT::f64;
1704     }
1705   }
1706   if (Subtarget->is64Bit() && Size >= 8)
1707     return MVT::i64;
1708   return MVT::i32;
1709 }
1710
1711 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1712   if (VT == MVT::f32)
1713     return X86ScalarSSEf32;
1714   else if (VT == MVT::f64)
1715     return X86ScalarSSEf64;
1716   return true;
1717 }
1718
1719 bool
1720 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1721                                                  unsigned,
1722                                                  bool *Fast) const {
1723   if (Fast)
1724     *Fast = Subtarget->isUnalignedMemAccessFast();
1725   return true;
1726 }
1727
1728 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1729 /// current function.  The returned value is a member of the
1730 /// MachineJumpTableInfo::JTEntryKind enum.
1731 unsigned X86TargetLowering::getJumpTableEncoding() const {
1732   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1733   // symbol.
1734   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1735       Subtarget->isPICStyleGOT())
1736     return MachineJumpTableInfo::EK_Custom32;
1737
1738   // Otherwise, use the normal jump table encoding heuristics.
1739   return TargetLowering::getJumpTableEncoding();
1740 }
1741
1742 const MCExpr *
1743 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1744                                              const MachineBasicBlock *MBB,
1745                                              unsigned uid,MCContext &Ctx) const{
1746   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1747          Subtarget->isPICStyleGOT());
1748   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1749   // entries.
1750   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1751                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1752 }
1753
1754 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1755 /// jumptable.
1756 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1757                                                     SelectionDAG &DAG) const {
1758   if (!Subtarget->is64Bit())
1759     // This doesn't have SDLoc associated with it, but is not really the
1760     // same as a Register.
1761     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1762   return Table;
1763 }
1764
1765 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1766 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1767 /// MCExpr.
1768 const MCExpr *X86TargetLowering::
1769 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1770                              MCContext &Ctx) const {
1771   // X86-64 uses RIP relative addressing based on the jump table label.
1772   if (Subtarget->isPICStyleRIPRel())
1773     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1774
1775   // Otherwise, the reference is relative to the PIC base.
1776   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1777 }
1778
1779 // FIXME: Why this routine is here? Move to RegInfo!
1780 std::pair<const TargetRegisterClass*, uint8_t>
1781 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1782   const TargetRegisterClass *RRC = nullptr;
1783   uint8_t Cost = 1;
1784   switch (VT.SimpleTy) {
1785   default:
1786     return TargetLowering::findRepresentativeClass(VT);
1787   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1788     RRC = Subtarget->is64Bit() ?
1789       (const TargetRegisterClass*)&X86::GR64RegClass :
1790       (const TargetRegisterClass*)&X86::GR32RegClass;
1791     break;
1792   case MVT::x86mmx:
1793     RRC = &X86::VR64RegClass;
1794     break;
1795   case MVT::f32: case MVT::f64:
1796   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1797   case MVT::v4f32: case MVT::v2f64:
1798   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1799   case MVT::v4f64:
1800     RRC = &X86::VR128RegClass;
1801     break;
1802   }
1803   return std::make_pair(RRC, Cost);
1804 }
1805
1806 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1807                                                unsigned &Offset) const {
1808   if (!Subtarget->isTargetLinux())
1809     return false;
1810
1811   if (Subtarget->is64Bit()) {
1812     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1813     Offset = 0x28;
1814     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1815       AddressSpace = 256;
1816     else
1817       AddressSpace = 257;
1818   } else {
1819     // %gs:0x14 on i386
1820     Offset = 0x14;
1821     AddressSpace = 256;
1822   }
1823   return true;
1824 }
1825
1826 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1827                                             unsigned DestAS) const {
1828   assert(SrcAS != DestAS && "Expected different address spaces!");
1829
1830   return SrcAS < 256 && DestAS < 256;
1831 }
1832
1833 //===----------------------------------------------------------------------===//
1834 //               Return Value Calling Convention Implementation
1835 //===----------------------------------------------------------------------===//
1836
1837 #include "X86GenCallingConv.inc"
1838
1839 bool
1840 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1841                                   MachineFunction &MF, bool isVarArg,
1842                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1843                         LLVMContext &Context) const {
1844   SmallVector<CCValAssign, 16> RVLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1846                  RVLocs, Context);
1847   return CCInfo.CheckReturn(Outs, RetCC_X86);
1848 }
1849
1850 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1851   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1852   return ScratchRegs;
1853 }
1854
1855 SDValue
1856 X86TargetLowering::LowerReturn(SDValue Chain,
1857                                CallingConv::ID CallConv, bool isVarArg,
1858                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1859                                const SmallVectorImpl<SDValue> &OutVals,
1860                                SDLoc dl, SelectionDAG &DAG) const {
1861   MachineFunction &MF = DAG.getMachineFunction();
1862   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1863
1864   SmallVector<CCValAssign, 16> RVLocs;
1865   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1866                  RVLocs, *DAG.getContext());
1867   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1868
1869   SDValue Flag;
1870   SmallVector<SDValue, 6> RetOps;
1871   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1872   // Operand #1 = Bytes To Pop
1873   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1874                    MVT::i16));
1875
1876   // Copy the result values into the output registers.
1877   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1878     CCValAssign &VA = RVLocs[i];
1879     assert(VA.isRegLoc() && "Can only return in registers!");
1880     SDValue ValToCopy = OutVals[i];
1881     EVT ValVT = ValToCopy.getValueType();
1882
1883     // Promote values to the appropriate types
1884     if (VA.getLocInfo() == CCValAssign::SExt)
1885       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1886     else if (VA.getLocInfo() == CCValAssign::ZExt)
1887       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1888     else if (VA.getLocInfo() == CCValAssign::AExt)
1889       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1890     else if (VA.getLocInfo() == CCValAssign::BCvt)
1891       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1892
1893     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1894            "Unexpected FP-extend for return value.");  
1895
1896     // If this is x86-64, and we disabled SSE, we can't return FP values,
1897     // or SSE or MMX vectors.
1898     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1899          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1900           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1901       report_fatal_error("SSE register return with SSE disabled");
1902     }
1903     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1904     // llvm-gcc has never done it right and no one has noticed, so this
1905     // should be OK for now.
1906     if (ValVT == MVT::f64 &&
1907         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1908       report_fatal_error("SSE2 register return with SSE2 disabled");
1909
1910     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1911     // the RET instruction and handled by the FP Stackifier.
1912     if (VA.getLocReg() == X86::ST0 ||
1913         VA.getLocReg() == X86::ST1) {
1914       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1915       // change the value to the FP stack register class.
1916       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1917         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1918       RetOps.push_back(ValToCopy);
1919       // Don't emit a copytoreg.
1920       continue;
1921     }
1922
1923     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1924     // which is returned in RAX / RDX.
1925     if (Subtarget->is64Bit()) {
1926       if (ValVT == MVT::x86mmx) {
1927         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1928           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1929           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1930                                   ValToCopy);
1931           // If we don't have SSE2 available, convert to v4f32 so the generated
1932           // register is legal.
1933           if (!Subtarget->hasSSE2())
1934             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1935         }
1936       }
1937     }
1938
1939     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1940     Flag = Chain.getValue(1);
1941     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1942   }
1943
1944   // The x86-64 ABIs require that for returning structs by value we copy
1945   // the sret argument into %rax/%eax (depending on ABI) for the return.
1946   // Win32 requires us to put the sret argument to %eax as well.
1947   // We saved the argument into a virtual register in the entry block,
1948   // so now we copy the value out and into %rax/%eax.
1949   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1950       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1951     MachineFunction &MF = DAG.getMachineFunction();
1952     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1953     unsigned Reg = FuncInfo->getSRetReturnReg();
1954     assert(Reg &&
1955            "SRetReturnReg should have been set in LowerFormalArguments().");
1956     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1957
1958     unsigned RetValReg
1959         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1960           X86::RAX : X86::EAX;
1961     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1962     Flag = Chain.getValue(1);
1963
1964     // RAX/EAX now acts like a return value.
1965     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1966   }
1967
1968   RetOps[0] = Chain;  // Update chain.
1969
1970   // Add the flag if we have it.
1971   if (Flag.getNode())
1972     RetOps.push_back(Flag);
1973
1974   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1975 }
1976
1977 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1978   if (N->getNumValues() != 1)
1979     return false;
1980   if (!N->hasNUsesOfValue(1, 0))
1981     return false;
1982
1983   SDValue TCChain = Chain;
1984   SDNode *Copy = *N->use_begin();
1985   if (Copy->getOpcode() == ISD::CopyToReg) {
1986     // If the copy has a glue operand, we conservatively assume it isn't safe to
1987     // perform a tail call.
1988     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1989       return false;
1990     TCChain = Copy->getOperand(0);
1991   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1992     return false;
1993
1994   bool HasRet = false;
1995   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1996        UI != UE; ++UI) {
1997     if (UI->getOpcode() != X86ISD::RET_FLAG)
1998       return false;
1999     HasRet = true;
2000   }
2001
2002   if (!HasRet)
2003     return false;
2004
2005   Chain = TCChain;
2006   return true;
2007 }
2008
2009 MVT
2010 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2011                                             ISD::NodeType ExtendKind) const {
2012   MVT ReturnMVT;
2013   // TODO: Is this also valid on 32-bit?
2014   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2015     ReturnMVT = MVT::i8;
2016   else
2017     ReturnMVT = MVT::i32;
2018
2019   MVT MinVT = getRegisterType(ReturnMVT);
2020   return VT.bitsLT(MinVT) ? MinVT : VT;
2021 }
2022
2023 /// LowerCallResult - Lower the result values of a call into the
2024 /// appropriate copies out of appropriate physical registers.
2025 ///
2026 SDValue
2027 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2028                                    CallingConv::ID CallConv, bool isVarArg,
2029                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2030                                    SDLoc dl, SelectionDAG &DAG,
2031                                    SmallVectorImpl<SDValue> &InVals) const {
2032
2033   // Assign locations to each value returned by this call.
2034   SmallVector<CCValAssign, 16> RVLocs;
2035   bool Is64Bit = Subtarget->is64Bit();
2036   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2037                  DAG.getTarget(), RVLocs, *DAG.getContext());
2038   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2039
2040   // Copy all of the result registers out of their specified physreg.
2041   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2042     CCValAssign &VA = RVLocs[i];
2043     EVT CopyVT = VA.getValVT();
2044
2045     // If this is x86-64, and we disabled SSE, we can't return FP values
2046     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2047         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2048       report_fatal_error("SSE register return with SSE disabled");
2049     }
2050
2051     SDValue Val;
2052
2053     // If this is a call to a function that returns an fp value on the floating
2054     // point stack, we must guarantee the value is popped from the stack, so
2055     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2056     // if the return value is not used. We use the FpPOP_RETVAL instruction
2057     // instead.
2058     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2059       // If we prefer to use the value in xmm registers, copy it out as f80 and
2060       // use a truncate to move it from fp stack reg to xmm reg.
2061       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2062       SDValue Ops[] = { Chain, InFlag };
2063       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2064                                          MVT::Other, MVT::Glue, Ops), 1);
2065       Val = Chain.getValue(0);
2066
2067       // Round the f80 to the right size, which also moves it to the appropriate
2068       // xmm register.
2069       if (CopyVT != VA.getValVT())
2070         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2071                           // This truncation won't change the value.
2072                           DAG.getIntPtrConstant(1));
2073     } else {
2074       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2075                                  CopyVT, InFlag).getValue(1);
2076       Val = Chain.getValue(0);
2077     }
2078     InFlag = Chain.getValue(2);
2079     InVals.push_back(Val);
2080   }
2081
2082   return Chain;
2083 }
2084
2085 //===----------------------------------------------------------------------===//
2086 //                C & StdCall & Fast Calling Convention implementation
2087 //===----------------------------------------------------------------------===//
2088 //  StdCall calling convention seems to be standard for many Windows' API
2089 //  routines and around. It differs from C calling convention just a little:
2090 //  callee should clean up the stack, not caller. Symbols should be also
2091 //  decorated in some fancy way :) It doesn't support any vector arguments.
2092 //  For info on fast calling convention see Fast Calling Convention (tail call)
2093 //  implementation LowerX86_32FastCCCallTo.
2094
2095 /// CallIsStructReturn - Determines whether a call uses struct return
2096 /// semantics.
2097 enum StructReturnType {
2098   NotStructReturn,
2099   RegStructReturn,
2100   StackStructReturn
2101 };
2102 static StructReturnType
2103 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2104   if (Outs.empty())
2105     return NotStructReturn;
2106
2107   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2108   if (!Flags.isSRet())
2109     return NotStructReturn;
2110   if (Flags.isInReg())
2111     return RegStructReturn;
2112   return StackStructReturn;
2113 }
2114
2115 /// ArgsAreStructReturn - Determines whether a function uses struct
2116 /// return semantics.
2117 static StructReturnType
2118 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2119   if (Ins.empty())
2120     return NotStructReturn;
2121
2122   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2123   if (!Flags.isSRet())
2124     return NotStructReturn;
2125   if (Flags.isInReg())
2126     return RegStructReturn;
2127   return StackStructReturn;
2128 }
2129
2130 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2131 /// by "Src" to address "Dst" with size and alignment information specified by
2132 /// the specific parameter attribute. The copy will be passed as a byval
2133 /// function parameter.
2134 static SDValue
2135 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2136                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2137                           SDLoc dl) {
2138   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2139
2140   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2141                        /*isVolatile*/false, /*AlwaysInline=*/true,
2142                        MachinePointerInfo(), MachinePointerInfo());
2143 }
2144
2145 /// IsTailCallConvention - Return true if the calling convention is one that
2146 /// supports tail call optimization.
2147 static bool IsTailCallConvention(CallingConv::ID CC) {
2148   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2149           CC == CallingConv::HiPE);
2150 }
2151
2152 /// \brief Return true if the calling convention is a C calling convention.
2153 static bool IsCCallConvention(CallingConv::ID CC) {
2154   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2155           CC == CallingConv::X86_64_SysV);
2156 }
2157
2158 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2159   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2160     return false;
2161
2162   CallSite CS(CI);
2163   CallingConv::ID CalleeCC = CS.getCallingConv();
2164   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2165     return false;
2166
2167   return true;
2168 }
2169
2170 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2171 /// a tailcall target by changing its ABI.
2172 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2173                                    bool GuaranteedTailCallOpt) {
2174   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2175 }
2176
2177 SDValue
2178 X86TargetLowering::LowerMemArgument(SDValue Chain,
2179                                     CallingConv::ID CallConv,
2180                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2181                                     SDLoc dl, SelectionDAG &DAG,
2182                                     const CCValAssign &VA,
2183                                     MachineFrameInfo *MFI,
2184                                     unsigned i) const {
2185   // Create the nodes corresponding to a load from this parameter slot.
2186   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2187   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2188       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2189   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2190   EVT ValVT;
2191
2192   // If value is passed by pointer we have address passed instead of the value
2193   // itself.
2194   if (VA.getLocInfo() == CCValAssign::Indirect)
2195     ValVT = VA.getLocVT();
2196   else
2197     ValVT = VA.getValVT();
2198
2199   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2200   // changed with more analysis.
2201   // In case of tail call optimization mark all arguments mutable. Since they
2202   // could be overwritten by lowering of arguments in case of a tail call.
2203   if (Flags.isByVal()) {
2204     unsigned Bytes = Flags.getByValSize();
2205     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2206     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2207     return DAG.getFrameIndex(FI, getPointerTy());
2208   } else {
2209     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2210                                     VA.getLocMemOffset(), isImmutable);
2211     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2212     return DAG.getLoad(ValVT, dl, Chain, FIN,
2213                        MachinePointerInfo::getFixedStack(FI),
2214                        false, false, false, 0);
2215   }
2216 }
2217
2218 SDValue
2219 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2220                                         CallingConv::ID CallConv,
2221                                         bool isVarArg,
2222                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2223                                         SDLoc dl,
2224                                         SelectionDAG &DAG,
2225                                         SmallVectorImpl<SDValue> &InVals)
2226                                           const {
2227   MachineFunction &MF = DAG.getMachineFunction();
2228   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2229
2230   const Function* Fn = MF.getFunction();
2231   if (Fn->hasExternalLinkage() &&
2232       Subtarget->isTargetCygMing() &&
2233       Fn->getName() == "main")
2234     FuncInfo->setForceFramePointer(true);
2235
2236   MachineFrameInfo *MFI = MF.getFrameInfo();
2237   bool Is64Bit = Subtarget->is64Bit();
2238   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2239
2240   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2241          "Var args not supported with calling convention fastcc, ghc or hipe");
2242
2243   // Assign locations to all of the incoming arguments.
2244   SmallVector<CCValAssign, 16> ArgLocs;
2245   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2246                  ArgLocs, *DAG.getContext());
2247
2248   // Allocate shadow area for Win64
2249   if (IsWin64)
2250     CCInfo.AllocateStack(32, 8);
2251
2252   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2253
2254   unsigned LastVal = ~0U;
2255   SDValue ArgValue;
2256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2257     CCValAssign &VA = ArgLocs[i];
2258     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2259     // places.
2260     assert(VA.getValNo() != LastVal &&
2261            "Don't support value assigned to multiple locs yet");
2262     (void)LastVal;
2263     LastVal = VA.getValNo();
2264
2265     if (VA.isRegLoc()) {
2266       EVT RegVT = VA.getLocVT();
2267       const TargetRegisterClass *RC;
2268       if (RegVT == MVT::i32)
2269         RC = &X86::GR32RegClass;
2270       else if (Is64Bit && RegVT == MVT::i64)
2271         RC = &X86::GR64RegClass;
2272       else if (RegVT == MVT::f32)
2273         RC = &X86::FR32RegClass;
2274       else if (RegVT == MVT::f64)
2275         RC = &X86::FR64RegClass;
2276       else if (RegVT.is512BitVector())
2277         RC = &X86::VR512RegClass;
2278       else if (RegVT.is256BitVector())
2279         RC = &X86::VR256RegClass;
2280       else if (RegVT.is128BitVector())
2281         RC = &X86::VR128RegClass;
2282       else if (RegVT == MVT::x86mmx)
2283         RC = &X86::VR64RegClass;
2284       else if (RegVT == MVT::i1)
2285         RC = &X86::VK1RegClass;
2286       else if (RegVT == MVT::v8i1)
2287         RC = &X86::VK8RegClass;
2288       else if (RegVT == MVT::v16i1)
2289         RC = &X86::VK16RegClass;
2290       else
2291         llvm_unreachable("Unknown argument type!");
2292
2293       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2294       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2295
2296       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2297       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2298       // right size.
2299       if (VA.getLocInfo() == CCValAssign::SExt)
2300         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2301                                DAG.getValueType(VA.getValVT()));
2302       else if (VA.getLocInfo() == CCValAssign::ZExt)
2303         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2304                                DAG.getValueType(VA.getValVT()));
2305       else if (VA.getLocInfo() == CCValAssign::BCvt)
2306         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2307
2308       if (VA.isExtInLoc()) {
2309         // Handle MMX values passed in XMM regs.
2310         if (RegVT.isVector())
2311           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2312         else
2313           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2314       }
2315     } else {
2316       assert(VA.isMemLoc());
2317       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2318     }
2319
2320     // If value is passed via pointer - do a load.
2321     if (VA.getLocInfo() == CCValAssign::Indirect)
2322       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2323                              MachinePointerInfo(), false, false, false, 0);
2324
2325     InVals.push_back(ArgValue);
2326   }
2327
2328   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2329     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2330       // The x86-64 ABIs require that for returning structs by value we copy
2331       // the sret argument into %rax/%eax (depending on ABI) for the return.
2332       // Win32 requires us to put the sret argument to %eax as well.
2333       // Save the argument into a virtual register so that we can access it
2334       // from the return points.
2335       if (Ins[i].Flags.isSRet()) {
2336         unsigned Reg = FuncInfo->getSRetReturnReg();
2337         if (!Reg) {
2338           MVT PtrTy = getPointerTy();
2339           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2340           FuncInfo->setSRetReturnReg(Reg);
2341         }
2342         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2343         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2344         break;
2345       }
2346     }
2347   }
2348
2349   unsigned StackSize = CCInfo.getNextStackOffset();
2350   // Align stack specially for tail calls.
2351   if (FuncIsMadeTailCallSafe(CallConv,
2352                              MF.getTarget().Options.GuaranteedTailCallOpt))
2353     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2354
2355   // If the function takes variable number of arguments, make a frame index for
2356   // the start of the first vararg value... for expansion of llvm.va_start.
2357   if (isVarArg) {
2358     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2359                     CallConv != CallingConv::X86_ThisCall)) {
2360       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2361     }
2362     if (Is64Bit) {
2363       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2364
2365       // FIXME: We should really autogenerate these arrays
2366       static const MCPhysReg GPR64ArgRegsWin64[] = {
2367         X86::RCX, X86::RDX, X86::R8,  X86::R9
2368       };
2369       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2370         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2371       };
2372       static const MCPhysReg XMMArgRegs64Bit[] = {
2373         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2374         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2375       };
2376       const MCPhysReg *GPR64ArgRegs;
2377       unsigned NumXMMRegs = 0;
2378
2379       if (IsWin64) {
2380         // The XMM registers which might contain var arg parameters are shadowed
2381         // in their paired GPR.  So we only need to save the GPR to their home
2382         // slots.
2383         TotalNumIntRegs = 4;
2384         GPR64ArgRegs = GPR64ArgRegsWin64;
2385       } else {
2386         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2387         GPR64ArgRegs = GPR64ArgRegs64Bit;
2388
2389         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2390                                                 TotalNumXMMRegs);
2391       }
2392       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2393                                                        TotalNumIntRegs);
2394
2395       bool NoImplicitFloatOps = Fn->getAttributes().
2396         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2397       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2398              "SSE register cannot be used when SSE is disabled!");
2399       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2400                NoImplicitFloatOps) &&
2401              "SSE register cannot be used when SSE is disabled!");
2402       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2403           !Subtarget->hasSSE1())
2404         // Kernel mode asks for SSE to be disabled, so don't push them
2405         // on the stack.
2406         TotalNumXMMRegs = 0;
2407
2408       if (IsWin64) {
2409         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2410         // Get to the caller-allocated home save location.  Add 8 to account
2411         // for the return address.
2412         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2413         FuncInfo->setRegSaveFrameIndex(
2414           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2415         // Fixup to set vararg frame on shadow area (4 x i64).
2416         if (NumIntRegs < 4)
2417           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2418       } else {
2419         // For X86-64, if there are vararg parameters that are passed via
2420         // registers, then we must store them to their spots on the stack so
2421         // they may be loaded by deferencing the result of va_next.
2422         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2423         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2424         FuncInfo->setRegSaveFrameIndex(
2425           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2426                                false));
2427       }
2428
2429       // Store the integer parameter registers.
2430       SmallVector<SDValue, 8> MemOps;
2431       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2432                                         getPointerTy());
2433       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2434       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2435         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2436                                   DAG.getIntPtrConstant(Offset));
2437         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2438                                      &X86::GR64RegClass);
2439         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2440         SDValue Store =
2441           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2442                        MachinePointerInfo::getFixedStack(
2443                          FuncInfo->getRegSaveFrameIndex(), Offset),
2444                        false, false, 0);
2445         MemOps.push_back(Store);
2446         Offset += 8;
2447       }
2448
2449       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2450         // Now store the XMM (fp + vector) parameter registers.
2451         SmallVector<SDValue, 11> SaveXMMOps;
2452         SaveXMMOps.push_back(Chain);
2453
2454         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2455         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2456         SaveXMMOps.push_back(ALVal);
2457
2458         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2459                                FuncInfo->getRegSaveFrameIndex()));
2460         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2461                                FuncInfo->getVarArgsFPOffset()));
2462
2463         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2464           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2465                                        &X86::VR128RegClass);
2466           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2467           SaveXMMOps.push_back(Val);
2468         }
2469         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2470                                      MVT::Other, SaveXMMOps));
2471       }
2472
2473       if (!MemOps.empty())
2474         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2475     }
2476   }
2477
2478   // Some CCs need callee pop.
2479   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2480                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2481     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2482   } else {
2483     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2484     // If this is an sret function, the return should pop the hidden pointer.
2485     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2486         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2487         argsAreStructReturn(Ins) == StackStructReturn)
2488       FuncInfo->setBytesToPopOnReturn(4);
2489   }
2490
2491   if (!Is64Bit) {
2492     // RegSaveFrameIndex is X86-64 only.
2493     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2494     if (CallConv == CallingConv::X86_FastCall ||
2495         CallConv == CallingConv::X86_ThisCall)
2496       // fastcc functions can't have varargs.
2497       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2498   }
2499
2500   FuncInfo->setArgumentStackSize(StackSize);
2501
2502   return Chain;
2503 }
2504
2505 SDValue
2506 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2507                                     SDValue StackPtr, SDValue Arg,
2508                                     SDLoc dl, SelectionDAG &DAG,
2509                                     const CCValAssign &VA,
2510                                     ISD::ArgFlagsTy Flags) const {
2511   unsigned LocMemOffset = VA.getLocMemOffset();
2512   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2513   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2514   if (Flags.isByVal())
2515     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2516
2517   return DAG.getStore(Chain, dl, Arg, PtrOff,
2518                       MachinePointerInfo::getStack(LocMemOffset),
2519                       false, false, 0);
2520 }
2521
2522 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2523 /// optimization is performed and it is required.
2524 SDValue
2525 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2526                                            SDValue &OutRetAddr, SDValue Chain,
2527                                            bool IsTailCall, bool Is64Bit,
2528                                            int FPDiff, SDLoc dl) const {
2529   // Adjust the Return address stack slot.
2530   EVT VT = getPointerTy();
2531   OutRetAddr = getReturnAddressFrameIndex(DAG);
2532
2533   // Load the "old" Return address.
2534   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2535                            false, false, false, 0);
2536   return SDValue(OutRetAddr.getNode(), 1);
2537 }
2538
2539 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2540 /// optimization is performed and it is required (FPDiff!=0).
2541 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2542                                         SDValue Chain, SDValue RetAddrFrIdx,
2543                                         EVT PtrVT, unsigned SlotSize,
2544                                         int FPDiff, SDLoc dl) {
2545   // Store the return address to the appropriate stack slot.
2546   if (!FPDiff) return Chain;
2547   // Calculate the new stack slot for the return address.
2548   int NewReturnAddrFI =
2549     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2550                                          false);
2551   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2552   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2553                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2554                        false, false, 0);
2555   return Chain;
2556 }
2557
2558 SDValue
2559 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2560                              SmallVectorImpl<SDValue> &InVals) const {
2561   SelectionDAG &DAG                     = CLI.DAG;
2562   SDLoc &dl                             = CLI.DL;
2563   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2564   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2565   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2566   SDValue Chain                         = CLI.Chain;
2567   SDValue Callee                        = CLI.Callee;
2568   CallingConv::ID CallConv              = CLI.CallConv;
2569   bool &isTailCall                      = CLI.IsTailCall;
2570   bool isVarArg                         = CLI.IsVarArg;
2571
2572   MachineFunction &MF = DAG.getMachineFunction();
2573   bool Is64Bit        = Subtarget->is64Bit();
2574   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2575   StructReturnType SR = callIsStructReturn(Outs);
2576   bool IsSibcall      = false;
2577
2578   if (MF.getTarget().Options.DisableTailCalls)
2579     isTailCall = false;
2580
2581   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2582   if (IsMustTail) {
2583     // Force this to be a tail call.  The verifier rules are enough to ensure
2584     // that we can lower this successfully without moving the return address
2585     // around.
2586     isTailCall = true;
2587   } else if (isTailCall) {
2588     // Check if it's really possible to do a tail call.
2589     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2590                     isVarArg, SR != NotStructReturn,
2591                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2592                     Outs, OutVals, Ins, DAG);
2593
2594     // Sibcalls are automatically detected tailcalls which do not require
2595     // ABI changes.
2596     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2597       IsSibcall = true;
2598
2599     if (isTailCall)
2600       ++NumTailCalls;
2601   }
2602
2603   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2604          "Var args not supported with calling convention fastcc, ghc or hipe");
2605
2606   // Analyze operands of the call, assigning locations to each operand.
2607   SmallVector<CCValAssign, 16> ArgLocs;
2608   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2609                  ArgLocs, *DAG.getContext());
2610
2611   // Allocate shadow area for Win64
2612   if (IsWin64)
2613     CCInfo.AllocateStack(32, 8);
2614
2615   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2616
2617   // Get a count of how many bytes are to be pushed on the stack.
2618   unsigned NumBytes = CCInfo.getNextStackOffset();
2619   if (IsSibcall)
2620     // This is a sibcall. The memory operands are available in caller's
2621     // own caller's stack.
2622     NumBytes = 0;
2623   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2624            IsTailCallConvention(CallConv))
2625     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2626
2627   int FPDiff = 0;
2628   if (isTailCall && !IsSibcall && !IsMustTail) {
2629     // Lower arguments at fp - stackoffset + fpdiff.
2630     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2631     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2632
2633     FPDiff = NumBytesCallerPushed - NumBytes;
2634
2635     // Set the delta of movement of the returnaddr stackslot.
2636     // But only set if delta is greater than previous delta.
2637     if (FPDiff < X86Info->getTCReturnAddrDelta())
2638       X86Info->setTCReturnAddrDelta(FPDiff);
2639   }
2640
2641   unsigned NumBytesToPush = NumBytes;
2642   unsigned NumBytesToPop = NumBytes;
2643
2644   // If we have an inalloca argument, all stack space has already been allocated
2645   // for us and be right at the top of the stack.  We don't support multiple
2646   // arguments passed in memory when using inalloca.
2647   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2648     NumBytesToPush = 0;
2649     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2650            "an inalloca argument must be the only memory argument");
2651   }
2652
2653   if (!IsSibcall)
2654     Chain = DAG.getCALLSEQ_START(
2655         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2656
2657   SDValue RetAddrFrIdx;
2658   // Load return address for tail calls.
2659   if (isTailCall && FPDiff)
2660     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2661                                     Is64Bit, FPDiff, dl);
2662
2663   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2664   SmallVector<SDValue, 8> MemOpChains;
2665   SDValue StackPtr;
2666
2667   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2668   // of tail call optimization arguments are handle later.
2669   const X86RegisterInfo *RegInfo =
2670     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2671   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2672     // Skip inalloca arguments, they have already been written.
2673     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2674     if (Flags.isInAlloca())
2675       continue;
2676
2677     CCValAssign &VA = ArgLocs[i];
2678     EVT RegVT = VA.getLocVT();
2679     SDValue Arg = OutVals[i];
2680     bool isByVal = Flags.isByVal();
2681
2682     // Promote the value if needed.
2683     switch (VA.getLocInfo()) {
2684     default: llvm_unreachable("Unknown loc info!");
2685     case CCValAssign::Full: break;
2686     case CCValAssign::SExt:
2687       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2688       break;
2689     case CCValAssign::ZExt:
2690       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2691       break;
2692     case CCValAssign::AExt:
2693       if (RegVT.is128BitVector()) {
2694         // Special case: passing MMX values in XMM registers.
2695         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2696         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2697         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2698       } else
2699         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2700       break;
2701     case CCValAssign::BCvt:
2702       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2703       break;
2704     case CCValAssign::Indirect: {
2705       // Store the argument.
2706       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2707       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2708       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2709                            MachinePointerInfo::getFixedStack(FI),
2710                            false, false, 0);
2711       Arg = SpillSlot;
2712       break;
2713     }
2714     }
2715
2716     if (VA.isRegLoc()) {
2717       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2718       if (isVarArg && IsWin64) {
2719         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2720         // shadow reg if callee is a varargs function.
2721         unsigned ShadowReg = 0;
2722         switch (VA.getLocReg()) {
2723         case X86::XMM0: ShadowReg = X86::RCX; break;
2724         case X86::XMM1: ShadowReg = X86::RDX; break;
2725         case X86::XMM2: ShadowReg = X86::R8; break;
2726         case X86::XMM3: ShadowReg = X86::R9; break;
2727         }
2728         if (ShadowReg)
2729           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2730       }
2731     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2732       assert(VA.isMemLoc());
2733       if (!StackPtr.getNode())
2734         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2735                                       getPointerTy());
2736       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2737                                              dl, DAG, VA, Flags));
2738     }
2739   }
2740
2741   if (!MemOpChains.empty())
2742     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2743
2744   if (Subtarget->isPICStyleGOT()) {
2745     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2746     // GOT pointer.
2747     if (!isTailCall) {
2748       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2749                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2750     } else {
2751       // If we are tail calling and generating PIC/GOT style code load the
2752       // address of the callee into ECX. The value in ecx is used as target of
2753       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2754       // for tail calls on PIC/GOT architectures. Normally we would just put the
2755       // address of GOT into ebx and then call target@PLT. But for tail calls
2756       // ebx would be restored (since ebx is callee saved) before jumping to the
2757       // target@PLT.
2758
2759       // Note: The actual moving to ECX is done further down.
2760       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2761       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2762           !G->getGlobal()->hasProtectedVisibility())
2763         Callee = LowerGlobalAddress(Callee, DAG);
2764       else if (isa<ExternalSymbolSDNode>(Callee))
2765         Callee = LowerExternalSymbol(Callee, DAG);
2766     }
2767   }
2768
2769   if (Is64Bit && isVarArg && !IsWin64) {
2770     // From AMD64 ABI document:
2771     // For calls that may call functions that use varargs or stdargs
2772     // (prototype-less calls or calls to functions containing ellipsis (...) in
2773     // the declaration) %al is used as hidden argument to specify the number
2774     // of SSE registers used. The contents of %al do not need to match exactly
2775     // the number of registers, but must be an ubound on the number of SSE
2776     // registers used and is in the range 0 - 8 inclusive.
2777
2778     // Count the number of XMM registers allocated.
2779     static const MCPhysReg XMMArgRegs[] = {
2780       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2781       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2782     };
2783     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2784     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2785            && "SSE registers cannot be used when SSE is disabled");
2786
2787     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2788                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2789   }
2790
2791   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2792   // don't need this because the eligibility check rejects calls that require
2793   // shuffling arguments passed in memory.
2794   if (!IsSibcall && isTailCall) {
2795     // Force all the incoming stack arguments to be loaded from the stack
2796     // before any new outgoing arguments are stored to the stack, because the
2797     // outgoing stack slots may alias the incoming argument stack slots, and
2798     // the alias isn't otherwise explicit. This is slightly more conservative
2799     // than necessary, because it means that each store effectively depends
2800     // on every argument instead of just those arguments it would clobber.
2801     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2802
2803     SmallVector<SDValue, 8> MemOpChains2;
2804     SDValue FIN;
2805     int FI = 0;
2806     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2807       CCValAssign &VA = ArgLocs[i];
2808       if (VA.isRegLoc())
2809         continue;
2810       assert(VA.isMemLoc());
2811       SDValue Arg = OutVals[i];
2812       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2813       // Skip inalloca arguments.  They don't require any work.
2814       if (Flags.isInAlloca())
2815         continue;
2816       // Create frame index.
2817       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2818       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2819       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2820       FIN = DAG.getFrameIndex(FI, getPointerTy());
2821
2822       if (Flags.isByVal()) {
2823         // Copy relative to framepointer.
2824         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2825         if (!StackPtr.getNode())
2826           StackPtr = DAG.getCopyFromReg(Chain, dl,
2827                                         RegInfo->getStackRegister(),
2828                                         getPointerTy());
2829         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2830
2831         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2832                                                          ArgChain,
2833                                                          Flags, DAG, dl));
2834       } else {
2835         // Store relative to framepointer.
2836         MemOpChains2.push_back(
2837           DAG.getStore(ArgChain, dl, Arg, FIN,
2838                        MachinePointerInfo::getFixedStack(FI),
2839                        false, false, 0));
2840       }
2841     }
2842
2843     if (!MemOpChains2.empty())
2844       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2845
2846     // Store the return address to the appropriate stack slot.
2847     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2848                                      getPointerTy(), RegInfo->getSlotSize(),
2849                                      FPDiff, dl);
2850   }
2851
2852   // Build a sequence of copy-to-reg nodes chained together with token chain
2853   // and flag operands which copy the outgoing args into registers.
2854   SDValue InFlag;
2855   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2856     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2857                              RegsToPass[i].second, InFlag);
2858     InFlag = Chain.getValue(1);
2859   }
2860
2861   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2862     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2863     // In the 64-bit large code model, we have to make all calls
2864     // through a register, since the call instruction's 32-bit
2865     // pc-relative offset may not be large enough to hold the whole
2866     // address.
2867   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2868     // If the callee is a GlobalAddress node (quite common, every direct call
2869     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2870     // it.
2871
2872     // We should use extra load for direct calls to dllimported functions in
2873     // non-JIT mode.
2874     const GlobalValue *GV = G->getGlobal();
2875     if (!GV->hasDLLImportStorageClass()) {
2876       unsigned char OpFlags = 0;
2877       bool ExtraLoad = false;
2878       unsigned WrapperKind = ISD::DELETED_NODE;
2879
2880       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2881       // external symbols most go through the PLT in PIC mode.  If the symbol
2882       // has hidden or protected visibility, or if it is static or local, then
2883       // we don't need to use the PLT - we can directly call it.
2884       if (Subtarget->isTargetELF() &&
2885           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2886           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2887         OpFlags = X86II::MO_PLT;
2888       } else if (Subtarget->isPICStyleStubAny() &&
2889                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2890                  (!Subtarget->getTargetTriple().isMacOSX() ||
2891                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2892         // PC-relative references to external symbols should go through $stub,
2893         // unless we're building with the leopard linker or later, which
2894         // automatically synthesizes these stubs.
2895         OpFlags = X86II::MO_DARWIN_STUB;
2896       } else if (Subtarget->isPICStyleRIPRel() &&
2897                  isa<Function>(GV) &&
2898                  cast<Function>(GV)->getAttributes().
2899                    hasAttribute(AttributeSet::FunctionIndex,
2900                                 Attribute::NonLazyBind)) {
2901         // If the function is marked as non-lazy, generate an indirect call
2902         // which loads from the GOT directly. This avoids runtime overhead
2903         // at the cost of eager binding (and one extra byte of encoding).
2904         OpFlags = X86II::MO_GOTPCREL;
2905         WrapperKind = X86ISD::WrapperRIP;
2906         ExtraLoad = true;
2907       }
2908
2909       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2910                                           G->getOffset(), OpFlags);
2911
2912       // Add a wrapper if needed.
2913       if (WrapperKind != ISD::DELETED_NODE)
2914         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2915       // Add extra indirection if needed.
2916       if (ExtraLoad)
2917         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2918                              MachinePointerInfo::getGOT(),
2919                              false, false, false, 0);
2920     }
2921   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2922     unsigned char OpFlags = 0;
2923
2924     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2925     // external symbols should go through the PLT.
2926     if (Subtarget->isTargetELF() &&
2927         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2928       OpFlags = X86II::MO_PLT;
2929     } else if (Subtarget->isPICStyleStubAny() &&
2930                (!Subtarget->getTargetTriple().isMacOSX() ||
2931                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2932       // PC-relative references to external symbols should go through $stub,
2933       // unless we're building with the leopard linker or later, which
2934       // automatically synthesizes these stubs.
2935       OpFlags = X86II::MO_DARWIN_STUB;
2936     }
2937
2938     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2939                                          OpFlags);
2940   }
2941
2942   // Returns a chain & a flag for retval copy to use.
2943   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2944   SmallVector<SDValue, 8> Ops;
2945
2946   if (!IsSibcall && isTailCall) {
2947     Chain = DAG.getCALLSEQ_END(Chain,
2948                                DAG.getIntPtrConstant(NumBytesToPop, true),
2949                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2950     InFlag = Chain.getValue(1);
2951   }
2952
2953   Ops.push_back(Chain);
2954   Ops.push_back(Callee);
2955
2956   if (isTailCall)
2957     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2958
2959   // Add argument registers to the end of the list so that they are known live
2960   // into the call.
2961   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2962     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2963                                   RegsToPass[i].second.getValueType()));
2964
2965   // Add a register mask operand representing the call-preserved registers.
2966   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2967   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2968   assert(Mask && "Missing call preserved mask for calling convention");
2969   Ops.push_back(DAG.getRegisterMask(Mask));
2970
2971   if (InFlag.getNode())
2972     Ops.push_back(InFlag);
2973
2974   if (isTailCall) {
2975     // We used to do:
2976     //// If this is the first return lowered for this function, add the regs
2977     //// to the liveout set for the function.
2978     // This isn't right, although it's probably harmless on x86; liveouts
2979     // should be computed from returns not tail calls.  Consider a void
2980     // function making a tail call to a function returning int.
2981     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2982   }
2983
2984   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2985   InFlag = Chain.getValue(1);
2986
2987   // Create the CALLSEQ_END node.
2988   unsigned NumBytesForCalleeToPop;
2989   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2990                        DAG.getTarget().Options.GuaranteedTailCallOpt))
2991     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2992   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2993            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2994            SR == StackStructReturn)
2995     // If this is a call to a struct-return function, the callee
2996     // pops the hidden struct pointer, so we have to push it back.
2997     // This is common for Darwin/X86, Linux & Mingw32 targets.
2998     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2999     NumBytesForCalleeToPop = 4;
3000   else
3001     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3002
3003   // Returns a flag for retval copy to use.
3004   if (!IsSibcall) {
3005     Chain = DAG.getCALLSEQ_END(Chain,
3006                                DAG.getIntPtrConstant(NumBytesToPop, true),
3007                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3008                                                      true),
3009                                InFlag, dl);
3010     InFlag = Chain.getValue(1);
3011   }
3012
3013   // Handle result values, copying them out of physregs into vregs that we
3014   // return.
3015   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3016                          Ins, dl, DAG, InVals);
3017 }
3018
3019 //===----------------------------------------------------------------------===//
3020 //                Fast Calling Convention (tail call) implementation
3021 //===----------------------------------------------------------------------===//
3022
3023 //  Like std call, callee cleans arguments, convention except that ECX is
3024 //  reserved for storing the tail called function address. Only 2 registers are
3025 //  free for argument passing (inreg). Tail call optimization is performed
3026 //  provided:
3027 //                * tailcallopt is enabled
3028 //                * caller/callee are fastcc
3029 //  On X86_64 architecture with GOT-style position independent code only local
3030 //  (within module) calls are supported at the moment.
3031 //  To keep the stack aligned according to platform abi the function
3032 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3033 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3034 //  If a tail called function callee has more arguments than the caller the
3035 //  caller needs to make sure that there is room to move the RETADDR to. This is
3036 //  achieved by reserving an area the size of the argument delta right after the
3037 //  original REtADDR, but before the saved framepointer or the spilled registers
3038 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3039 //  stack layout:
3040 //    arg1
3041 //    arg2
3042 //    RETADDR
3043 //    [ new RETADDR
3044 //      move area ]
3045 //    (possible EBP)
3046 //    ESI
3047 //    EDI
3048 //    local1 ..
3049
3050 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3051 /// for a 16 byte align requirement.
3052 unsigned
3053 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3054                                                SelectionDAG& DAG) const {
3055   MachineFunction &MF = DAG.getMachineFunction();
3056   const TargetMachine &TM = MF.getTarget();
3057   const X86RegisterInfo *RegInfo =
3058     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3059   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3060   unsigned StackAlignment = TFI.getStackAlignment();
3061   uint64_t AlignMask = StackAlignment - 1;
3062   int64_t Offset = StackSize;
3063   unsigned SlotSize = RegInfo->getSlotSize();
3064   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3065     // Number smaller than 12 so just add the difference.
3066     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3067   } else {
3068     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3069     Offset = ((~AlignMask) & Offset) + StackAlignment +
3070       (StackAlignment-SlotSize);
3071   }
3072   return Offset;
3073 }
3074
3075 /// MatchingStackOffset - Return true if the given stack call argument is
3076 /// already available in the same position (relatively) of the caller's
3077 /// incoming argument stack.
3078 static
3079 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3080                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3081                          const X86InstrInfo *TII) {
3082   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3083   int FI = INT_MAX;
3084   if (Arg.getOpcode() == ISD::CopyFromReg) {
3085     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3086     if (!TargetRegisterInfo::isVirtualRegister(VR))
3087       return false;
3088     MachineInstr *Def = MRI->getVRegDef(VR);
3089     if (!Def)
3090       return false;
3091     if (!Flags.isByVal()) {
3092       if (!TII->isLoadFromStackSlot(Def, FI))
3093         return false;
3094     } else {
3095       unsigned Opcode = Def->getOpcode();
3096       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3097           Def->getOperand(1).isFI()) {
3098         FI = Def->getOperand(1).getIndex();
3099         Bytes = Flags.getByValSize();
3100       } else
3101         return false;
3102     }
3103   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3104     if (Flags.isByVal())
3105       // ByVal argument is passed in as a pointer but it's now being
3106       // dereferenced. e.g.
3107       // define @foo(%struct.X* %A) {
3108       //   tail call @bar(%struct.X* byval %A)
3109       // }
3110       return false;
3111     SDValue Ptr = Ld->getBasePtr();
3112     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3113     if (!FINode)
3114       return false;
3115     FI = FINode->getIndex();
3116   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3117     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3118     FI = FINode->getIndex();
3119     Bytes = Flags.getByValSize();
3120   } else
3121     return false;
3122
3123   assert(FI != INT_MAX);
3124   if (!MFI->isFixedObjectIndex(FI))
3125     return false;
3126   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3127 }
3128
3129 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3130 /// for tail call optimization. Targets which want to do tail call
3131 /// optimization should implement this function.
3132 bool
3133 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3134                                                      CallingConv::ID CalleeCC,
3135                                                      bool isVarArg,
3136                                                      bool isCalleeStructRet,
3137                                                      bool isCallerStructRet,
3138                                                      Type *RetTy,
3139                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3140                                     const SmallVectorImpl<SDValue> &OutVals,
3141                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3142                                                      SelectionDAG &DAG) const {
3143   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3144     return false;
3145
3146   // If -tailcallopt is specified, make fastcc functions tail-callable.
3147   const MachineFunction &MF = DAG.getMachineFunction();
3148   const Function *CallerF = MF.getFunction();
3149
3150   // If the function return type is x86_fp80 and the callee return type is not,
3151   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3152   // perform a tailcall optimization here.
3153   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3154     return false;
3155
3156   CallingConv::ID CallerCC = CallerF->getCallingConv();
3157   bool CCMatch = CallerCC == CalleeCC;
3158   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3159   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3160
3161   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3162     if (IsTailCallConvention(CalleeCC) && CCMatch)
3163       return true;
3164     return false;
3165   }
3166
3167   // Look for obvious safe cases to perform tail call optimization that do not
3168   // require ABI changes. This is what gcc calls sibcall.
3169
3170   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3171   // emit a special epilogue.
3172   const X86RegisterInfo *RegInfo =
3173     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3174   if (RegInfo->needsStackRealignment(MF))
3175     return false;
3176
3177   // Also avoid sibcall optimization if either caller or callee uses struct
3178   // return semantics.
3179   if (isCalleeStructRet || isCallerStructRet)
3180     return false;
3181
3182   // An stdcall/thiscall caller is expected to clean up its arguments; the
3183   // callee isn't going to do that.
3184   // FIXME: this is more restrictive than needed. We could produce a tailcall
3185   // when the stack adjustment matches. For example, with a thiscall that takes
3186   // only one argument.
3187   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3188                    CallerCC == CallingConv::X86_ThisCall))
3189     return false;
3190
3191   // Do not sibcall optimize vararg calls unless all arguments are passed via
3192   // registers.
3193   if (isVarArg && !Outs.empty()) {
3194
3195     // Optimizing for varargs on Win64 is unlikely to be safe without
3196     // additional testing.
3197     if (IsCalleeWin64 || IsCallerWin64)
3198       return false;
3199
3200     SmallVector<CCValAssign, 16> ArgLocs;
3201     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3202                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3203
3204     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3205     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3206       if (!ArgLocs[i].isRegLoc())
3207         return false;
3208   }
3209
3210   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3211   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3212   // this into a sibcall.
3213   bool Unused = false;
3214   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3215     if (!Ins[i].Used) {
3216       Unused = true;
3217       break;
3218     }
3219   }
3220   if (Unused) {
3221     SmallVector<CCValAssign, 16> RVLocs;
3222     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3223                    DAG.getTarget(), RVLocs, *DAG.getContext());
3224     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3225     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3226       CCValAssign &VA = RVLocs[i];
3227       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3228         return false;
3229     }
3230   }
3231
3232   // If the calling conventions do not match, then we'd better make sure the
3233   // results are returned in the same way as what the caller expects.
3234   if (!CCMatch) {
3235     SmallVector<CCValAssign, 16> RVLocs1;
3236     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3237                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3238     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3239
3240     SmallVector<CCValAssign, 16> RVLocs2;
3241     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3242                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3243     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3244
3245     if (RVLocs1.size() != RVLocs2.size())
3246       return false;
3247     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3248       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3249         return false;
3250       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3251         return false;
3252       if (RVLocs1[i].isRegLoc()) {
3253         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3254           return false;
3255       } else {
3256         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3257           return false;
3258       }
3259     }
3260   }
3261
3262   // If the callee takes no arguments then go on to check the results of the
3263   // call.
3264   if (!Outs.empty()) {
3265     // Check if stack adjustment is needed. For now, do not do this if any
3266     // argument is passed on the stack.
3267     SmallVector<CCValAssign, 16> ArgLocs;
3268     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3269                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3270
3271     // Allocate shadow area for Win64
3272     if (IsCalleeWin64)
3273       CCInfo.AllocateStack(32, 8);
3274
3275     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3276     if (CCInfo.getNextStackOffset()) {
3277       MachineFunction &MF = DAG.getMachineFunction();
3278       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3279         return false;
3280
3281       // Check if the arguments are already laid out in the right way as
3282       // the caller's fixed stack objects.
3283       MachineFrameInfo *MFI = MF.getFrameInfo();
3284       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3285       const X86InstrInfo *TII =
3286           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3287       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3288         CCValAssign &VA = ArgLocs[i];
3289         SDValue Arg = OutVals[i];
3290         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3291         if (VA.getLocInfo() == CCValAssign::Indirect)
3292           return false;
3293         if (!VA.isRegLoc()) {
3294           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3295                                    MFI, MRI, TII))
3296             return false;
3297         }
3298       }
3299     }
3300
3301     // If the tailcall address may be in a register, then make sure it's
3302     // possible to register allocate for it. In 32-bit, the call address can
3303     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3304     // callee-saved registers are restored. These happen to be the same
3305     // registers used to pass 'inreg' arguments so watch out for those.
3306     if (!Subtarget->is64Bit() &&
3307         ((!isa<GlobalAddressSDNode>(Callee) &&
3308           !isa<ExternalSymbolSDNode>(Callee)) ||
3309          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3310       unsigned NumInRegs = 0;
3311       // In PIC we need an extra register to formulate the address computation
3312       // for the callee.
3313       unsigned MaxInRegs =
3314         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3315
3316       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3317         CCValAssign &VA = ArgLocs[i];
3318         if (!VA.isRegLoc())
3319           continue;
3320         unsigned Reg = VA.getLocReg();
3321         switch (Reg) {
3322         default: break;
3323         case X86::EAX: case X86::EDX: case X86::ECX:
3324           if (++NumInRegs == MaxInRegs)
3325             return false;
3326           break;
3327         }
3328       }
3329     }
3330   }
3331
3332   return true;
3333 }
3334
3335 FastISel *
3336 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3337                                   const TargetLibraryInfo *libInfo) const {
3338   return X86::createFastISel(funcInfo, libInfo);
3339 }
3340
3341 //===----------------------------------------------------------------------===//
3342 //                           Other Lowering Hooks
3343 //===----------------------------------------------------------------------===//
3344
3345 static bool MayFoldLoad(SDValue Op) {
3346   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3347 }
3348
3349 static bool MayFoldIntoStore(SDValue Op) {
3350   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3351 }
3352
3353 static bool isTargetShuffle(unsigned Opcode) {
3354   switch(Opcode) {
3355   default: return false;
3356   case X86ISD::PSHUFD:
3357   case X86ISD::PSHUFHW:
3358   case X86ISD::PSHUFLW:
3359   case X86ISD::SHUFP:
3360   case X86ISD::PALIGNR:
3361   case X86ISD::MOVLHPS:
3362   case X86ISD::MOVLHPD:
3363   case X86ISD::MOVHLPS:
3364   case X86ISD::MOVLPS:
3365   case X86ISD::MOVLPD:
3366   case X86ISD::MOVSHDUP:
3367   case X86ISD::MOVSLDUP:
3368   case X86ISD::MOVDDUP:
3369   case X86ISD::MOVSS:
3370   case X86ISD::MOVSD:
3371   case X86ISD::UNPCKL:
3372   case X86ISD::UNPCKH:
3373   case X86ISD::VPERMILP:
3374   case X86ISD::VPERM2X128:
3375   case X86ISD::VPERMI:
3376     return true;
3377   }
3378 }
3379
3380 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3381                                     SDValue V1, SelectionDAG &DAG) {
3382   switch(Opc) {
3383   default: llvm_unreachable("Unknown x86 shuffle node");
3384   case X86ISD::MOVSHDUP:
3385   case X86ISD::MOVSLDUP:
3386   case X86ISD::MOVDDUP:
3387     return DAG.getNode(Opc, dl, VT, V1);
3388   }
3389 }
3390
3391 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3392                                     SDValue V1, unsigned TargetMask,
3393                                     SelectionDAG &DAG) {
3394   switch(Opc) {
3395   default: llvm_unreachable("Unknown x86 shuffle node");
3396   case X86ISD::PSHUFD:
3397   case X86ISD::PSHUFHW:
3398   case X86ISD::PSHUFLW:
3399   case X86ISD::VPERMILP:
3400   case X86ISD::VPERMI:
3401     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3402   }
3403 }
3404
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406                                     SDValue V1, SDValue V2, unsigned TargetMask,
3407                                     SelectionDAG &DAG) {
3408   switch(Opc) {
3409   default: llvm_unreachable("Unknown x86 shuffle node");
3410   case X86ISD::PALIGNR:
3411   case X86ISD::SHUFP:
3412   case X86ISD::VPERM2X128:
3413     return DAG.getNode(Opc, dl, VT, V1, V2,
3414                        DAG.getConstant(TargetMask, MVT::i8));
3415   }
3416 }
3417
3418 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3419                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3420   switch(Opc) {
3421   default: llvm_unreachable("Unknown x86 shuffle node");
3422   case X86ISD::MOVLHPS:
3423   case X86ISD::MOVLHPD:
3424   case X86ISD::MOVHLPS:
3425   case X86ISD::MOVLPS:
3426   case X86ISD::MOVLPD:
3427   case X86ISD::MOVSS:
3428   case X86ISD::MOVSD:
3429   case X86ISD::UNPCKL:
3430   case X86ISD::UNPCKH:
3431     return DAG.getNode(Opc, dl, VT, V1, V2);
3432   }
3433 }
3434
3435 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3436   MachineFunction &MF = DAG.getMachineFunction();
3437   const X86RegisterInfo *RegInfo =
3438     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3439   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3440   int ReturnAddrIndex = FuncInfo->getRAIndex();
3441
3442   if (ReturnAddrIndex == 0) {
3443     // Set up a frame object for the return address.
3444     unsigned SlotSize = RegInfo->getSlotSize();
3445     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3446                                                            -(int64_t)SlotSize,
3447                                                            false);
3448     FuncInfo->setRAIndex(ReturnAddrIndex);
3449   }
3450
3451   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3452 }
3453
3454 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3455                                        bool hasSymbolicDisplacement) {
3456   // Offset should fit into 32 bit immediate field.
3457   if (!isInt<32>(Offset))
3458     return false;
3459
3460   // If we don't have a symbolic displacement - we don't have any extra
3461   // restrictions.
3462   if (!hasSymbolicDisplacement)
3463     return true;
3464
3465   // FIXME: Some tweaks might be needed for medium code model.
3466   if (M != CodeModel::Small && M != CodeModel::Kernel)
3467     return false;
3468
3469   // For small code model we assume that latest object is 16MB before end of 31
3470   // bits boundary. We may also accept pretty large negative constants knowing
3471   // that all objects are in the positive half of address space.
3472   if (M == CodeModel::Small && Offset < 16*1024*1024)
3473     return true;
3474
3475   // For kernel code model we know that all object resist in the negative half
3476   // of 32bits address space. We may not accept negative offsets, since they may
3477   // be just off and we may accept pretty large positive ones.
3478   if (M == CodeModel::Kernel && Offset > 0)
3479     return true;
3480
3481   return false;
3482 }
3483
3484 /// isCalleePop - Determines whether the callee is required to pop its
3485 /// own arguments. Callee pop is necessary to support tail calls.
3486 bool X86::isCalleePop(CallingConv::ID CallingConv,
3487                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3488   if (IsVarArg)
3489     return false;
3490
3491   switch (CallingConv) {
3492   default:
3493     return false;
3494   case CallingConv::X86_StdCall:
3495     return !is64Bit;
3496   case CallingConv::X86_FastCall:
3497     return !is64Bit;
3498   case CallingConv::X86_ThisCall:
3499     return !is64Bit;
3500   case CallingConv::Fast:
3501     return TailCallOpt;
3502   case CallingConv::GHC:
3503     return TailCallOpt;
3504   case CallingConv::HiPE:
3505     return TailCallOpt;
3506   }
3507 }
3508
3509 /// \brief Return true if the condition is an unsigned comparison operation.
3510 static bool isX86CCUnsigned(unsigned X86CC) {
3511   switch (X86CC) {
3512   default: llvm_unreachable("Invalid integer condition!");
3513   case X86::COND_E:     return true;
3514   case X86::COND_G:     return false;
3515   case X86::COND_GE:    return false;
3516   case X86::COND_L:     return false;
3517   case X86::COND_LE:    return false;
3518   case X86::COND_NE:    return true;
3519   case X86::COND_B:     return true;
3520   case X86::COND_A:     return true;
3521   case X86::COND_BE:    return true;
3522   case X86::COND_AE:    return true;
3523   }
3524   llvm_unreachable("covered switch fell through?!");
3525 }
3526
3527 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3528 /// specific condition code, returning the condition code and the LHS/RHS of the
3529 /// comparison to make.
3530 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3531                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3532   if (!isFP) {
3533     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3534       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3535         // X > -1   -> X == 0, jump !sign.
3536         RHS = DAG.getConstant(0, RHS.getValueType());
3537         return X86::COND_NS;
3538       }
3539       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3540         // X < 0   -> X == 0, jump on sign.
3541         return X86::COND_S;
3542       }
3543       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3544         // X < 1   -> X <= 0
3545         RHS = DAG.getConstant(0, RHS.getValueType());
3546         return X86::COND_LE;
3547       }
3548     }
3549
3550     switch (SetCCOpcode) {
3551     default: llvm_unreachable("Invalid integer condition!");
3552     case ISD::SETEQ:  return X86::COND_E;
3553     case ISD::SETGT:  return X86::COND_G;
3554     case ISD::SETGE:  return X86::COND_GE;
3555     case ISD::SETLT:  return X86::COND_L;
3556     case ISD::SETLE:  return X86::COND_LE;
3557     case ISD::SETNE:  return X86::COND_NE;
3558     case ISD::SETULT: return X86::COND_B;
3559     case ISD::SETUGT: return X86::COND_A;
3560     case ISD::SETULE: return X86::COND_BE;
3561     case ISD::SETUGE: return X86::COND_AE;
3562     }
3563   }
3564
3565   // First determine if it is required or is profitable to flip the operands.
3566
3567   // If LHS is a foldable load, but RHS is not, flip the condition.
3568   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3569       !ISD::isNON_EXTLoad(RHS.getNode())) {
3570     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3571     std::swap(LHS, RHS);
3572   }
3573
3574   switch (SetCCOpcode) {
3575   default: break;
3576   case ISD::SETOLT:
3577   case ISD::SETOLE:
3578   case ISD::SETUGT:
3579   case ISD::SETUGE:
3580     std::swap(LHS, RHS);
3581     break;
3582   }
3583
3584   // On a floating point condition, the flags are set as follows:
3585   // ZF  PF  CF   op
3586   //  0 | 0 | 0 | X > Y
3587   //  0 | 0 | 1 | X < Y
3588   //  1 | 0 | 0 | X == Y
3589   //  1 | 1 | 1 | unordered
3590   switch (SetCCOpcode) {
3591   default: llvm_unreachable("Condcode should be pre-legalized away");
3592   case ISD::SETUEQ:
3593   case ISD::SETEQ:   return X86::COND_E;
3594   case ISD::SETOLT:              // flipped
3595   case ISD::SETOGT:
3596   case ISD::SETGT:   return X86::COND_A;
3597   case ISD::SETOLE:              // flipped
3598   case ISD::SETOGE:
3599   case ISD::SETGE:   return X86::COND_AE;
3600   case ISD::SETUGT:              // flipped
3601   case ISD::SETULT:
3602   case ISD::SETLT:   return X86::COND_B;
3603   case ISD::SETUGE:              // flipped
3604   case ISD::SETULE:
3605   case ISD::SETLE:   return X86::COND_BE;
3606   case ISD::SETONE:
3607   case ISD::SETNE:   return X86::COND_NE;
3608   case ISD::SETUO:   return X86::COND_P;
3609   case ISD::SETO:    return X86::COND_NP;
3610   case ISD::SETOEQ:
3611   case ISD::SETUNE:  return X86::COND_INVALID;
3612   }
3613 }
3614
3615 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3616 /// code. Current x86 isa includes the following FP cmov instructions:
3617 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3618 static bool hasFPCMov(unsigned X86CC) {
3619   switch (X86CC) {
3620   default:
3621     return false;
3622   case X86::COND_B:
3623   case X86::COND_BE:
3624   case X86::COND_E:
3625   case X86::COND_P:
3626   case X86::COND_A:
3627   case X86::COND_AE:
3628   case X86::COND_NE:
3629   case X86::COND_NP:
3630     return true;
3631   }
3632 }
3633
3634 /// isFPImmLegal - Returns true if the target can instruction select the
3635 /// specified FP immediate natively. If false, the legalizer will
3636 /// materialize the FP immediate as a load from a constant pool.
3637 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3638   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3639     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3640       return true;
3641   }
3642   return false;
3643 }
3644
3645 /// \brief Returns true if it is beneficial to convert a load of a constant
3646 /// to just the constant itself.
3647 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3648                                                           Type *Ty) const {
3649   assert(Ty->isIntegerTy());
3650
3651   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3652   if (BitSize == 0 || BitSize > 64)
3653     return false;
3654   return true;
3655 }
3656
3657 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3658 /// the specified range (L, H].
3659 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3660   return (Val < 0) || (Val >= Low && Val < Hi);
3661 }
3662
3663 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3664 /// specified value.
3665 static bool isUndefOrEqual(int Val, int CmpVal) {
3666   return (Val < 0 || Val == CmpVal);
3667 }
3668
3669 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3670 /// from position Pos and ending in Pos+Size, falls within the specified
3671 /// sequential range (L, L+Pos]. or is undef.
3672 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3673                                        unsigned Pos, unsigned Size, int Low) {
3674   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3675     if (!isUndefOrEqual(Mask[i], Low))
3676       return false;
3677   return true;
3678 }
3679
3680 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3682 /// the second operand.
3683 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3684   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3685     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3686   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3687     return (Mask[0] < 2 && Mask[1] < 2);
3688   return false;
3689 }
3690
3691 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3692 /// is suitable for input to PSHUFHW.
3693 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3694   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3695     return false;
3696
3697   // Lower quadword copied in order or undef.
3698   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3699     return false;
3700
3701   // Upper quadword shuffled.
3702   for (unsigned i = 4; i != 8; ++i)
3703     if (!isUndefOrInRange(Mask[i], 4, 8))
3704       return false;
3705
3706   if (VT == MVT::v16i16) {
3707     // Lower quadword copied in order or undef.
3708     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3709       return false;
3710
3711     // Upper quadword shuffled.
3712     for (unsigned i = 12; i != 16; ++i)
3713       if (!isUndefOrInRange(Mask[i], 12, 16))
3714         return false;
3715   }
3716
3717   return true;
3718 }
3719
3720 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3721 /// is suitable for input to PSHUFLW.
3722 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3723   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3724     return false;
3725
3726   // Upper quadword copied in order.
3727   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3728     return false;
3729
3730   // Lower quadword shuffled.
3731   for (unsigned i = 0; i != 4; ++i)
3732     if (!isUndefOrInRange(Mask[i], 0, 4))
3733       return false;
3734
3735   if (VT == MVT::v16i16) {
3736     // Upper quadword copied in order.
3737     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3738       return false;
3739
3740     // Lower quadword shuffled.
3741     for (unsigned i = 8; i != 12; ++i)
3742       if (!isUndefOrInRange(Mask[i], 8, 12))
3743         return false;
3744   }
3745
3746   return true;
3747 }
3748
3749 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3750 /// is suitable for input to PALIGNR.
3751 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3752                           const X86Subtarget *Subtarget) {
3753   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3754       (VT.is256BitVector() && !Subtarget->hasInt256()))
3755     return false;
3756
3757   unsigned NumElts = VT.getVectorNumElements();
3758   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3759   unsigned NumLaneElts = NumElts/NumLanes;
3760
3761   // Do not handle 64-bit element shuffles with palignr.
3762   if (NumLaneElts == 2)
3763     return false;
3764
3765   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3766     unsigned i;
3767     for (i = 0; i != NumLaneElts; ++i) {
3768       if (Mask[i+l] >= 0)
3769         break;
3770     }
3771
3772     // Lane is all undef, go to next lane
3773     if (i == NumLaneElts)
3774       continue;
3775
3776     int Start = Mask[i+l];
3777
3778     // Make sure its in this lane in one of the sources
3779     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3780         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3781       return false;
3782
3783     // If not lane 0, then we must match lane 0
3784     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3785       return false;
3786
3787     // Correct second source to be contiguous with first source
3788     if (Start >= (int)NumElts)
3789       Start -= NumElts - NumLaneElts;
3790
3791     // Make sure we're shifting in the right direction.
3792     if (Start <= (int)(i+l))
3793       return false;
3794
3795     Start -= i;
3796
3797     // Check the rest of the elements to see if they are consecutive.
3798     for (++i; i != NumLaneElts; ++i) {
3799       int Idx = Mask[i+l];
3800
3801       // Make sure its in this lane
3802       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3803           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3804         return false;
3805
3806       // If not lane 0, then we must match lane 0
3807       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3808         return false;
3809
3810       if (Idx >= (int)NumElts)
3811         Idx -= NumElts - NumLaneElts;
3812
3813       if (!isUndefOrEqual(Idx, Start+i))
3814         return false;
3815
3816     }
3817   }
3818
3819   return true;
3820 }
3821
3822 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3823 /// the two vector operands have swapped position.
3824 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3825                                      unsigned NumElems) {
3826   for (unsigned i = 0; i != NumElems; ++i) {
3827     int idx = Mask[i];
3828     if (idx < 0)
3829       continue;
3830     else if (idx < (int)NumElems)
3831       Mask[i] = idx + NumElems;
3832     else
3833       Mask[i] = idx - NumElems;
3834   }
3835 }
3836
3837 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3838 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3839 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3840 /// reverse of what x86 shuffles want.
3841 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3842
3843   unsigned NumElems = VT.getVectorNumElements();
3844   unsigned NumLanes = VT.getSizeInBits()/128;
3845   unsigned NumLaneElems = NumElems/NumLanes;
3846
3847   if (NumLaneElems != 2 && NumLaneElems != 4)
3848     return false;
3849
3850   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3851   bool symetricMaskRequired =
3852     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3853
3854   // VSHUFPSY divides the resulting vector into 4 chunks.
3855   // The sources are also splitted into 4 chunks, and each destination
3856   // chunk must come from a different source chunk.
3857   //
3858   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3859   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3860   //
3861   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3862   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3863   //
3864   // VSHUFPDY divides the resulting vector into 4 chunks.
3865   // The sources are also splitted into 4 chunks, and each destination
3866   // chunk must come from a different source chunk.
3867   //
3868   //  SRC1 =>      X3       X2       X1       X0
3869   //  SRC2 =>      Y3       Y2       Y1       Y0
3870   //
3871   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3872   //
3873   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3874   unsigned HalfLaneElems = NumLaneElems/2;
3875   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3876     for (unsigned i = 0; i != NumLaneElems; ++i) {
3877       int Idx = Mask[i+l];
3878       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3879       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3880         return false;
3881       // For VSHUFPSY, the mask of the second half must be the same as the
3882       // first but with the appropriate offsets. This works in the same way as
3883       // VPERMILPS works with masks.
3884       if (!symetricMaskRequired || Idx < 0)
3885         continue;
3886       if (MaskVal[i] < 0) {
3887         MaskVal[i] = Idx - l;
3888         continue;
3889       }
3890       if ((signed)(Idx - l) != MaskVal[i])
3891         return false;
3892     }
3893   }
3894
3895   return true;
3896 }
3897
3898 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3899 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3900 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3901   if (!VT.is128BitVector())
3902     return false;
3903
3904   unsigned NumElems = VT.getVectorNumElements();
3905
3906   if (NumElems != 4)
3907     return false;
3908
3909   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3910   return isUndefOrEqual(Mask[0], 6) &&
3911          isUndefOrEqual(Mask[1], 7) &&
3912          isUndefOrEqual(Mask[2], 2) &&
3913          isUndefOrEqual(Mask[3], 3);
3914 }
3915
3916 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3917 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3918 /// <2, 3, 2, 3>
3919 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3920   if (!VT.is128BitVector())
3921     return false;
3922
3923   unsigned NumElems = VT.getVectorNumElements();
3924
3925   if (NumElems != 4)
3926     return false;
3927
3928   return isUndefOrEqual(Mask[0], 2) &&
3929          isUndefOrEqual(Mask[1], 3) &&
3930          isUndefOrEqual(Mask[2], 2) &&
3931          isUndefOrEqual(Mask[3], 3);
3932 }
3933
3934 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3935 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3936 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3937   if (!VT.is128BitVector())
3938     return false;
3939
3940   unsigned NumElems = VT.getVectorNumElements();
3941
3942   if (NumElems != 2 && NumElems != 4)
3943     return false;
3944
3945   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3946     if (!isUndefOrEqual(Mask[i], i + NumElems))
3947       return false;
3948
3949   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3950     if (!isUndefOrEqual(Mask[i], i))
3951       return false;
3952
3953   return true;
3954 }
3955
3956 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3957 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3958 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3959   if (!VT.is128BitVector())
3960     return false;
3961
3962   unsigned NumElems = VT.getVectorNumElements();
3963
3964   if (NumElems != 2 && NumElems != 4)
3965     return false;
3966
3967   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3968     if (!isUndefOrEqual(Mask[i], i))
3969       return false;
3970
3971   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3972     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3973       return false;
3974
3975   return true;
3976 }
3977
3978 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3980 /// i. e: If all but one element come from the same vector.
3981 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3982   // TODO: Deal with AVX's VINSERTPS
3983   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3984     return false;
3985
3986   unsigned CorrectPosV1 = 0;
3987   unsigned CorrectPosV2 = 0;
3988   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3989     if (Mask[i] == -1) {
3990       ++CorrectPosV1;
3991       ++CorrectPosV2;
3992       continue;
3993     }
3994
3995     if (Mask[i] == i)
3996       ++CorrectPosV1;
3997     else if (Mask[i] == i + 4)
3998       ++CorrectPosV2;
3999   }
4000
4001   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4002     // We have 3 elements (undefs count as elements from any vector) from one
4003     // vector, and one from another.
4004     return true;
4005
4006   return false;
4007 }
4008
4009 //
4010 // Some special combinations that can be optimized.
4011 //
4012 static
4013 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4014                                SelectionDAG &DAG) {
4015   MVT VT = SVOp->getSimpleValueType(0);
4016   SDLoc dl(SVOp);
4017
4018   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4019     return SDValue();
4020
4021   ArrayRef<int> Mask = SVOp->getMask();
4022
4023   // These are the special masks that may be optimized.
4024   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4025   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4026   bool MatchEvenMask = true;
4027   bool MatchOddMask  = true;
4028   for (int i=0; i<8; ++i) {
4029     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4030       MatchEvenMask = false;
4031     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4032       MatchOddMask = false;
4033   }
4034
4035   if (!MatchEvenMask && !MatchOddMask)
4036     return SDValue();
4037
4038   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4039
4040   SDValue Op0 = SVOp->getOperand(0);
4041   SDValue Op1 = SVOp->getOperand(1);
4042
4043   if (MatchEvenMask) {
4044     // Shift the second operand right to 32 bits.
4045     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4046     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4047   } else {
4048     // Shift the first operand left to 32 bits.
4049     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4050     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4051   }
4052   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4053   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4054 }
4055
4056 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4058 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4059                          bool HasInt256, bool V2IsSplat = false) {
4060
4061   assert(VT.getSizeInBits() >= 128 &&
4062          "Unsupported vector type for unpckl");
4063
4064   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4065   unsigned NumLanes;
4066   unsigned NumOf256BitLanes;
4067   unsigned NumElts = VT.getVectorNumElements();
4068   if (VT.is256BitVector()) {
4069     if (NumElts != 4 && NumElts != 8 &&
4070         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4071     return false;
4072     NumLanes = 2;
4073     NumOf256BitLanes = 1;
4074   } else if (VT.is512BitVector()) {
4075     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4076            "Unsupported vector type for unpckh");
4077     NumLanes = 2;
4078     NumOf256BitLanes = 2;
4079   } else {
4080     NumLanes = 1;
4081     NumOf256BitLanes = 1;
4082   }
4083
4084   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4085   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4086
4087   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4088     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4089       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4090         int BitI  = Mask[l256*NumEltsInStride+l+i];
4091         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4092         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4093           return false;
4094         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4095           return false;
4096         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4097           return false;
4098       }
4099     }
4100   }
4101   return true;
4102 }
4103
4104 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4105 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4106 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4107                          bool HasInt256, bool V2IsSplat = false) {
4108   assert(VT.getSizeInBits() >= 128 &&
4109          "Unsupported vector type for unpckh");
4110
4111   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4112   unsigned NumLanes;
4113   unsigned NumOf256BitLanes;
4114   unsigned NumElts = VT.getVectorNumElements();
4115   if (VT.is256BitVector()) {
4116     if (NumElts != 4 && NumElts != 8 &&
4117         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4118     return false;
4119     NumLanes = 2;
4120     NumOf256BitLanes = 1;
4121   } else if (VT.is512BitVector()) {
4122     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4123            "Unsupported vector type for unpckh");
4124     NumLanes = 2;
4125     NumOf256BitLanes = 2;
4126   } else {
4127     NumLanes = 1;
4128     NumOf256BitLanes = 1;
4129   }
4130
4131   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4132   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4133
4134   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4135     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4136       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4137         int BitI  = Mask[l256*NumEltsInStride+l+i];
4138         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4139         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4140           return false;
4141         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4142           return false;
4143         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4144           return false;
4145       }
4146     }
4147   }
4148   return true;
4149 }
4150
4151 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4152 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4153 /// <0, 0, 1, 1>
4154 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4155   unsigned NumElts = VT.getVectorNumElements();
4156   bool Is256BitVec = VT.is256BitVector();
4157
4158   if (VT.is512BitVector())
4159     return false;
4160   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4161          "Unsupported vector type for unpckh");
4162
4163   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4164       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4165     return false;
4166
4167   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4168   // FIXME: Need a better way to get rid of this, there's no latency difference
4169   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4170   // the former later. We should also remove the "_undef" special mask.
4171   if (NumElts == 4 && Is256BitVec)
4172     return false;
4173
4174   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4175   // independently on 128-bit lanes.
4176   unsigned NumLanes = VT.getSizeInBits()/128;
4177   unsigned NumLaneElts = NumElts/NumLanes;
4178
4179   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4180     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4181       int BitI  = Mask[l+i];
4182       int BitI1 = Mask[l+i+1];
4183
4184       if (!isUndefOrEqual(BitI, j))
4185         return false;
4186       if (!isUndefOrEqual(BitI1, j))
4187         return false;
4188     }
4189   }
4190
4191   return true;
4192 }
4193
4194 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4195 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4196 /// <2, 2, 3, 3>
4197 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4198   unsigned NumElts = VT.getVectorNumElements();
4199
4200   if (VT.is512BitVector())
4201     return false;
4202
4203   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4204          "Unsupported vector type for unpckh");
4205
4206   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4207       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4208     return false;
4209
4210   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4211   // independently on 128-bit lanes.
4212   unsigned NumLanes = VT.getSizeInBits()/128;
4213   unsigned NumLaneElts = NumElts/NumLanes;
4214
4215   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4216     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4217       int BitI  = Mask[l+i];
4218       int BitI1 = Mask[l+i+1];
4219       if (!isUndefOrEqual(BitI, j))
4220         return false;
4221       if (!isUndefOrEqual(BitI1, j))
4222         return false;
4223     }
4224   }
4225   return true;
4226 }
4227
4228 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4229 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4230 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4231   if (!VT.is512BitVector())
4232     return false;
4233
4234   unsigned NumElts = VT.getVectorNumElements();
4235   unsigned HalfSize = NumElts/2;
4236   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4237     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4238       *Imm = 1;
4239       return true;
4240     }
4241   }
4242   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4243     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4244       *Imm = 0;
4245       return true;
4246     }
4247   }
4248   return false;
4249 }
4250
4251 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4252 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4253 /// MOVSD, and MOVD, i.e. setting the lowest element.
4254 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4255   if (VT.getVectorElementType().getSizeInBits() < 32)
4256     return false;
4257   if (!VT.is128BitVector())
4258     return false;
4259
4260   unsigned NumElts = VT.getVectorNumElements();
4261
4262   if (!isUndefOrEqual(Mask[0], NumElts))
4263     return false;
4264
4265   for (unsigned i = 1; i != NumElts; ++i)
4266     if (!isUndefOrEqual(Mask[i], i))
4267       return false;
4268
4269   return true;
4270 }
4271
4272 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4273 /// as permutations between 128-bit chunks or halves. As an example: this
4274 /// shuffle bellow:
4275 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4276 /// The first half comes from the second half of V1 and the second half from the
4277 /// the second half of V2.
4278 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4279   if (!HasFp256 || !VT.is256BitVector())
4280     return false;
4281
4282   // The shuffle result is divided into half A and half B. In total the two
4283   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4284   // B must come from C, D, E or F.
4285   unsigned HalfSize = VT.getVectorNumElements()/2;
4286   bool MatchA = false, MatchB = false;
4287
4288   // Check if A comes from one of C, D, E, F.
4289   for (unsigned Half = 0; Half != 4; ++Half) {
4290     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4291       MatchA = true;
4292       break;
4293     }
4294   }
4295
4296   // Check if B comes from one of C, D, E, F.
4297   for (unsigned Half = 0; Half != 4; ++Half) {
4298     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4299       MatchB = true;
4300       break;
4301     }
4302   }
4303
4304   return MatchA && MatchB;
4305 }
4306
4307 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4308 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4309 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4310   MVT VT = SVOp->getSimpleValueType(0);
4311
4312   unsigned HalfSize = VT.getVectorNumElements()/2;
4313
4314   unsigned FstHalf = 0, SndHalf = 0;
4315   for (unsigned i = 0; i < HalfSize; ++i) {
4316     if (SVOp->getMaskElt(i) > 0) {
4317       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4318       break;
4319     }
4320   }
4321   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4322     if (SVOp->getMaskElt(i) > 0) {
4323       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4324       break;
4325     }
4326   }
4327
4328   return (FstHalf | (SndHalf << 4));
4329 }
4330
4331 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4332 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4333   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4334   if (EltSize < 32)
4335     return false;
4336
4337   unsigned NumElts = VT.getVectorNumElements();
4338   Imm8 = 0;
4339   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4340     for (unsigned i = 0; i != NumElts; ++i) {
4341       if (Mask[i] < 0)
4342         continue;
4343       Imm8 |= Mask[i] << (i*2);
4344     }
4345     return true;
4346   }
4347
4348   unsigned LaneSize = 4;
4349   SmallVector<int, 4> MaskVal(LaneSize, -1);
4350
4351   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4352     for (unsigned i = 0; i != LaneSize; ++i) {
4353       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4354         return false;
4355       if (Mask[i+l] < 0)
4356         continue;
4357       if (MaskVal[i] < 0) {
4358         MaskVal[i] = Mask[i+l] - l;
4359         Imm8 |= MaskVal[i] << (i*2);
4360         continue;
4361       }
4362       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4363         return false;
4364     }
4365   }
4366   return true;
4367 }
4368
4369 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4370 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4371 /// Note that VPERMIL mask matching is different depending whether theunderlying
4372 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4373 /// to the same elements of the low, but to the higher half of the source.
4374 /// In VPERMILPD the two lanes could be shuffled independently of each other
4375 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4376 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4377   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4378   if (VT.getSizeInBits() < 256 || EltSize < 32)
4379     return false;
4380   bool symetricMaskRequired = (EltSize == 32);
4381   unsigned NumElts = VT.getVectorNumElements();
4382
4383   unsigned NumLanes = VT.getSizeInBits()/128;
4384   unsigned LaneSize = NumElts/NumLanes;
4385   // 2 or 4 elements in one lane
4386
4387   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4388   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4389     for (unsigned i = 0; i != LaneSize; ++i) {
4390       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4391         return false;
4392       if (symetricMaskRequired) {
4393         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4394           ExpectedMaskVal[i] = Mask[i+l] - l;
4395           continue;
4396         }
4397         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4398           return false;
4399       }
4400     }
4401   }
4402   return true;
4403 }
4404
4405 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4406 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4407 /// element of vector 2 and the other elements to come from vector 1 in order.
4408 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4409                                bool V2IsSplat = false, bool V2IsUndef = false) {
4410   if (!VT.is128BitVector())
4411     return false;
4412
4413   unsigned NumOps = VT.getVectorNumElements();
4414   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4415     return false;
4416
4417   if (!isUndefOrEqual(Mask[0], 0))
4418     return false;
4419
4420   for (unsigned i = 1; i != NumOps; ++i)
4421     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4422           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4423           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4424       return false;
4425
4426   return true;
4427 }
4428
4429 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4431 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4432 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4433                            const X86Subtarget *Subtarget) {
4434   if (!Subtarget->hasSSE3())
4435     return false;
4436
4437   unsigned NumElems = VT.getVectorNumElements();
4438
4439   if ((VT.is128BitVector() && NumElems != 4) ||
4440       (VT.is256BitVector() && NumElems != 8) ||
4441       (VT.is512BitVector() && NumElems != 16))
4442     return false;
4443
4444   // "i+1" is the value the indexed mask element must have
4445   for (unsigned i = 0; i != NumElems; i += 2)
4446     if (!isUndefOrEqual(Mask[i], i+1) ||
4447         !isUndefOrEqual(Mask[i+1], i+1))
4448       return false;
4449
4450   return true;
4451 }
4452
4453 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4454 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4455 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4456 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4457                            const X86Subtarget *Subtarget) {
4458   if (!Subtarget->hasSSE3())
4459     return false;
4460
4461   unsigned NumElems = VT.getVectorNumElements();
4462
4463   if ((VT.is128BitVector() && NumElems != 4) ||
4464       (VT.is256BitVector() && NumElems != 8) ||
4465       (VT.is512BitVector() && NumElems != 16))
4466     return false;
4467
4468   // "i" is the value the indexed mask element must have
4469   for (unsigned i = 0; i != NumElems; i += 2)
4470     if (!isUndefOrEqual(Mask[i], i) ||
4471         !isUndefOrEqual(Mask[i+1], i))
4472       return false;
4473
4474   return true;
4475 }
4476
4477 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4478 /// specifies a shuffle of elements that is suitable for input to 256-bit
4479 /// version of MOVDDUP.
4480 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4481   if (!HasFp256 || !VT.is256BitVector())
4482     return false;
4483
4484   unsigned NumElts = VT.getVectorNumElements();
4485   if (NumElts != 4)
4486     return false;
4487
4488   for (unsigned i = 0; i != NumElts/2; ++i)
4489     if (!isUndefOrEqual(Mask[i], 0))
4490       return false;
4491   for (unsigned i = NumElts/2; i != NumElts; ++i)
4492     if (!isUndefOrEqual(Mask[i], NumElts/2))
4493       return false;
4494   return true;
4495 }
4496
4497 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to 128-bit
4499 /// version of MOVDDUP.
4500 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4501   if (!VT.is128BitVector())
4502     return false;
4503
4504   unsigned e = VT.getVectorNumElements() / 2;
4505   for (unsigned i = 0; i != e; ++i)
4506     if (!isUndefOrEqual(Mask[i], i))
4507       return false;
4508   for (unsigned i = 0; i != e; ++i)
4509     if (!isUndefOrEqual(Mask[e+i], i))
4510       return false;
4511   return true;
4512 }
4513
4514 /// isVEXTRACTIndex - Return true if the specified
4515 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4516 /// suitable for instruction that extract 128 or 256 bit vectors
4517 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4518   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4519   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4520     return false;
4521
4522   // The index should be aligned on a vecWidth-bit boundary.
4523   uint64_t Index =
4524     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4525
4526   MVT VT = N->getSimpleValueType(0);
4527   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4528   bool Result = (Index * ElSize) % vecWidth == 0;
4529
4530   return Result;
4531 }
4532
4533 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4534 /// operand specifies a subvector insert that is suitable for input to
4535 /// insertion of 128 or 256-bit subvectors
4536 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4537   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4538   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4539     return false;
4540   // The index should be aligned on a vecWidth-bit boundary.
4541   uint64_t Index =
4542     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4543
4544   MVT VT = N->getSimpleValueType(0);
4545   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4546   bool Result = (Index * ElSize) % vecWidth == 0;
4547
4548   return Result;
4549 }
4550
4551 bool X86::isVINSERT128Index(SDNode *N) {
4552   return isVINSERTIndex(N, 128);
4553 }
4554
4555 bool X86::isVINSERT256Index(SDNode *N) {
4556   return isVINSERTIndex(N, 256);
4557 }
4558
4559 bool X86::isVEXTRACT128Index(SDNode *N) {
4560   return isVEXTRACTIndex(N, 128);
4561 }
4562
4563 bool X86::isVEXTRACT256Index(SDNode *N) {
4564   return isVEXTRACTIndex(N, 256);
4565 }
4566
4567 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4568 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4569 /// Handles 128-bit and 256-bit.
4570 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4571   MVT VT = N->getSimpleValueType(0);
4572
4573   assert((VT.getSizeInBits() >= 128) &&
4574          "Unsupported vector type for PSHUF/SHUFP");
4575
4576   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4577   // independently on 128-bit lanes.
4578   unsigned NumElts = VT.getVectorNumElements();
4579   unsigned NumLanes = VT.getSizeInBits()/128;
4580   unsigned NumLaneElts = NumElts/NumLanes;
4581
4582   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4583          "Only supports 2, 4 or 8 elements per lane");
4584
4585   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4586   unsigned Mask = 0;
4587   for (unsigned i = 0; i != NumElts; ++i) {
4588     int Elt = N->getMaskElt(i);
4589     if (Elt < 0) continue;
4590     Elt &= NumLaneElts - 1;
4591     unsigned ShAmt = (i << Shift) % 8;
4592     Mask |= Elt << ShAmt;
4593   }
4594
4595   return Mask;
4596 }
4597
4598 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4599 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4600 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4601   MVT VT = N->getSimpleValueType(0);
4602
4603   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4604          "Unsupported vector type for PSHUFHW");
4605
4606   unsigned NumElts = VT.getVectorNumElements();
4607
4608   unsigned Mask = 0;
4609   for (unsigned l = 0; l != NumElts; l += 8) {
4610     // 8 nodes per lane, but we only care about the last 4.
4611     for (unsigned i = 0; i < 4; ++i) {
4612       int Elt = N->getMaskElt(l+i+4);
4613       if (Elt < 0) continue;
4614       Elt &= 0x3; // only 2-bits.
4615       Mask |= Elt << (i * 2);
4616     }
4617   }
4618
4619   return Mask;
4620 }
4621
4622 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4623 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4624 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4625   MVT VT = N->getSimpleValueType(0);
4626
4627   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4628          "Unsupported vector type for PSHUFHW");
4629
4630   unsigned NumElts = VT.getVectorNumElements();
4631
4632   unsigned Mask = 0;
4633   for (unsigned l = 0; l != NumElts; l += 8) {
4634     // 8 nodes per lane, but we only care about the first 4.
4635     for (unsigned i = 0; i < 4; ++i) {
4636       int Elt = N->getMaskElt(l+i);
4637       if (Elt < 0) continue;
4638       Elt &= 0x3; // only 2-bits
4639       Mask |= Elt << (i * 2);
4640     }
4641   }
4642
4643   return Mask;
4644 }
4645
4646 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4647 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4648 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4649   MVT VT = SVOp->getSimpleValueType(0);
4650   unsigned EltSize = VT.is512BitVector() ? 1 :
4651     VT.getVectorElementType().getSizeInBits() >> 3;
4652
4653   unsigned NumElts = VT.getVectorNumElements();
4654   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4655   unsigned NumLaneElts = NumElts/NumLanes;
4656
4657   int Val = 0;
4658   unsigned i;
4659   for (i = 0; i != NumElts; ++i) {
4660     Val = SVOp->getMaskElt(i);
4661     if (Val >= 0)
4662       break;
4663   }
4664   if (Val >= (int)NumElts)
4665     Val -= NumElts - NumLaneElts;
4666
4667   assert(Val - i > 0 && "PALIGNR imm should be positive");
4668   return (Val - i) * EltSize;
4669 }
4670
4671 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4672   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4673   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4674     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4675
4676   uint64_t Index =
4677     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4678
4679   MVT VecVT = N->getOperand(0).getSimpleValueType();
4680   MVT ElVT = VecVT.getVectorElementType();
4681
4682   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4683   return Index / NumElemsPerChunk;
4684 }
4685
4686 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4687   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4688   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4689     llvm_unreachable("Illegal insert subvector for VINSERT");
4690
4691   uint64_t Index =
4692     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4693
4694   MVT VecVT = N->getSimpleValueType(0);
4695   MVT ElVT = VecVT.getVectorElementType();
4696
4697   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4698   return Index / NumElemsPerChunk;
4699 }
4700
4701 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4702 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4703 /// and VINSERTI128 instructions.
4704 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4705   return getExtractVEXTRACTImmediate(N, 128);
4706 }
4707
4708 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4709 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4710 /// and VINSERTI64x4 instructions.
4711 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4712   return getExtractVEXTRACTImmediate(N, 256);
4713 }
4714
4715 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4716 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4717 /// and VINSERTI128 instructions.
4718 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4719   return getInsertVINSERTImmediate(N, 128);
4720 }
4721
4722 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4723 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4724 /// and VINSERTI64x4 instructions.
4725 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4726   return getInsertVINSERTImmediate(N, 256);
4727 }
4728
4729 /// isZero - Returns true if Elt is a constant integer zero
4730 static bool isZero(SDValue V) {
4731   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4732   return C && C->isNullValue();
4733 }
4734
4735 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4736 /// constant +0.0.
4737 bool X86::isZeroNode(SDValue Elt) {
4738   if (isZero(Elt))
4739     return true;
4740   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4741     return CFP->getValueAPF().isPosZero();
4742   return false;
4743 }
4744
4745 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4746 /// their permute mask.
4747 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4748                                     SelectionDAG &DAG) {
4749   MVT VT = SVOp->getSimpleValueType(0);
4750   unsigned NumElems = VT.getVectorNumElements();
4751   SmallVector<int, 8> MaskVec;
4752
4753   for (unsigned i = 0; i != NumElems; ++i) {
4754     int Idx = SVOp->getMaskElt(i);
4755     if (Idx >= 0) {
4756       if (Idx < (int)NumElems)
4757         Idx += NumElems;
4758       else
4759         Idx -= NumElems;
4760     }
4761     MaskVec.push_back(Idx);
4762   }
4763   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4764                               SVOp->getOperand(0), &MaskVec[0]);
4765 }
4766
4767 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4768 /// match movhlps. The lower half elements should come from upper half of
4769 /// V1 (and in order), and the upper half elements should come from the upper
4770 /// half of V2 (and in order).
4771 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4772   if (!VT.is128BitVector())
4773     return false;
4774   if (VT.getVectorNumElements() != 4)
4775     return false;
4776   for (unsigned i = 0, e = 2; i != e; ++i)
4777     if (!isUndefOrEqual(Mask[i], i+2))
4778       return false;
4779   for (unsigned i = 2; i != 4; ++i)
4780     if (!isUndefOrEqual(Mask[i], i+4))
4781       return false;
4782   return true;
4783 }
4784
4785 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4786 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4787 /// required.
4788 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4789   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4790     return false;
4791   N = N->getOperand(0).getNode();
4792   if (!ISD::isNON_EXTLoad(N))
4793     return false;
4794   if (LD)
4795     *LD = cast<LoadSDNode>(N);
4796   return true;
4797 }
4798
4799 // Test whether the given value is a vector value which will be legalized
4800 // into a load.
4801 static bool WillBeConstantPoolLoad(SDNode *N) {
4802   if (N->getOpcode() != ISD::BUILD_VECTOR)
4803     return false;
4804
4805   // Check for any non-constant elements.
4806   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4807     switch (N->getOperand(i).getNode()->getOpcode()) {
4808     case ISD::UNDEF:
4809     case ISD::ConstantFP:
4810     case ISD::Constant:
4811       break;
4812     default:
4813       return false;
4814     }
4815
4816   // Vectors of all-zeros and all-ones are materialized with special
4817   // instructions rather than being loaded.
4818   return !ISD::isBuildVectorAllZeros(N) &&
4819          !ISD::isBuildVectorAllOnes(N);
4820 }
4821
4822 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4823 /// match movlp{s|d}. The lower half elements should come from lower half of
4824 /// V1 (and in order), and the upper half elements should come from the upper
4825 /// half of V2 (and in order). And since V1 will become the source of the
4826 /// MOVLP, it must be either a vector load or a scalar load to vector.
4827 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4828                                ArrayRef<int> Mask, MVT VT) {
4829   if (!VT.is128BitVector())
4830     return false;
4831
4832   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4833     return false;
4834   // Is V2 is a vector load, don't do this transformation. We will try to use
4835   // load folding shufps op.
4836   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4837     return false;
4838
4839   unsigned NumElems = VT.getVectorNumElements();
4840
4841   if (NumElems != 2 && NumElems != 4)
4842     return false;
4843   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4844     if (!isUndefOrEqual(Mask[i], i))
4845       return false;
4846   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4847     if (!isUndefOrEqual(Mask[i], i+NumElems))
4848       return false;
4849   return true;
4850 }
4851
4852 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4853 /// all the same.
4854 static bool isSplatVector(SDNode *N) {
4855   if (N->getOpcode() != ISD::BUILD_VECTOR)
4856     return false;
4857
4858   SDValue SplatValue = N->getOperand(0);
4859   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4860     if (N->getOperand(i) != SplatValue)
4861       return false;
4862   return true;
4863 }
4864
4865 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4866 /// to an zero vector.
4867 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4868 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4869   SDValue V1 = N->getOperand(0);
4870   SDValue V2 = N->getOperand(1);
4871   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4872   for (unsigned i = 0; i != NumElems; ++i) {
4873     int Idx = N->getMaskElt(i);
4874     if (Idx >= (int)NumElems) {
4875       unsigned Opc = V2.getOpcode();
4876       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4877         continue;
4878       if (Opc != ISD::BUILD_VECTOR ||
4879           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4880         return false;
4881     } else if (Idx >= 0) {
4882       unsigned Opc = V1.getOpcode();
4883       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4884         continue;
4885       if (Opc != ISD::BUILD_VECTOR ||
4886           !X86::isZeroNode(V1.getOperand(Idx)))
4887         return false;
4888     }
4889   }
4890   return true;
4891 }
4892
4893 /// getZeroVector - Returns a vector of specified type with all zero elements.
4894 ///
4895 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4896                              SelectionDAG &DAG, SDLoc dl) {
4897   assert(VT.isVector() && "Expected a vector type");
4898
4899   // Always build SSE zero vectors as <4 x i32> bitcasted
4900   // to their dest type. This ensures they get CSE'd.
4901   SDValue Vec;
4902   if (VT.is128BitVector()) {  // SSE
4903     if (Subtarget->hasSSE2()) {  // SSE2
4904       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4905       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4906     } else { // SSE1
4907       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4908       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4909     }
4910   } else if (VT.is256BitVector()) { // AVX
4911     if (Subtarget->hasInt256()) { // AVX2
4912       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4913       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4915     } else {
4916       // 256-bit logic and arithmetic instructions in AVX are all
4917       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4918       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4919       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4921     }
4922   } else if (VT.is512BitVector()) { // AVX-512
4923       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4924       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4925                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4926       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4927   } else if (VT.getScalarType() == MVT::i1) {
4928     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4929     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4930     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4931     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4932   } else
4933     llvm_unreachable("Unexpected vector type");
4934
4935   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4936 }
4937
4938 /// getOnesVector - Returns a vector of specified type with all bits set.
4939 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4940 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4941 /// Then bitcast to their original type, ensuring they get CSE'd.
4942 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4943                              SDLoc dl) {
4944   assert(VT.isVector() && "Expected a vector type");
4945
4946   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4947   SDValue Vec;
4948   if (VT.is256BitVector()) {
4949     if (HasInt256) { // AVX2
4950       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4952     } else { // AVX
4953       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4954       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4955     }
4956   } else if (VT.is128BitVector()) {
4957     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4958   } else
4959     llvm_unreachable("Unexpected vector type");
4960
4961   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4962 }
4963
4964 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4965 /// that point to V2 points to its first element.
4966 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4967   for (unsigned i = 0; i != NumElems; ++i) {
4968     if (Mask[i] > (int)NumElems) {
4969       Mask[i] = NumElems;
4970     }
4971   }
4972 }
4973
4974 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4975 /// operation of specified width.
4976 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4977                        SDValue V2) {
4978   unsigned NumElems = VT.getVectorNumElements();
4979   SmallVector<int, 8> Mask;
4980   Mask.push_back(NumElems);
4981   for (unsigned i = 1; i != NumElems; ++i)
4982     Mask.push_back(i);
4983   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4984 }
4985
4986 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4987 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4988                           SDValue V2) {
4989   unsigned NumElems = VT.getVectorNumElements();
4990   SmallVector<int, 8> Mask;
4991   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4992     Mask.push_back(i);
4993     Mask.push_back(i + NumElems);
4994   }
4995   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4996 }
4997
4998 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4999 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5000                           SDValue V2) {
5001   unsigned NumElems = VT.getVectorNumElements();
5002   SmallVector<int, 8> Mask;
5003   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5004     Mask.push_back(i + Half);
5005     Mask.push_back(i + NumElems + Half);
5006   }
5007   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5008 }
5009
5010 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5011 // a generic shuffle instruction because the target has no such instructions.
5012 // Generate shuffles which repeat i16 and i8 several times until they can be
5013 // represented by v4f32 and then be manipulated by target suported shuffles.
5014 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5015   MVT VT = V.getSimpleValueType();
5016   int NumElems = VT.getVectorNumElements();
5017   SDLoc dl(V);
5018
5019   while (NumElems > 4) {
5020     if (EltNo < NumElems/2) {
5021       V = getUnpackl(DAG, dl, VT, V, V);
5022     } else {
5023       V = getUnpackh(DAG, dl, VT, V, V);
5024       EltNo -= NumElems/2;
5025     }
5026     NumElems >>= 1;
5027   }
5028   return V;
5029 }
5030
5031 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5032 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5033   MVT VT = V.getSimpleValueType();
5034   SDLoc dl(V);
5035
5036   if (VT.is128BitVector()) {
5037     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5038     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5039     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5040                              &SplatMask[0]);
5041   } else if (VT.is256BitVector()) {
5042     // To use VPERMILPS to splat scalars, the second half of indicies must
5043     // refer to the higher part, which is a duplication of the lower one,
5044     // because VPERMILPS can only handle in-lane permutations.
5045     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5046                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5047
5048     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5049     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5050                              &SplatMask[0]);
5051   } else
5052     llvm_unreachable("Vector size not supported");
5053
5054   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5055 }
5056
5057 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5058 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5059   MVT SrcVT = SV->getSimpleValueType(0);
5060   SDValue V1 = SV->getOperand(0);
5061   SDLoc dl(SV);
5062
5063   int EltNo = SV->getSplatIndex();
5064   int NumElems = SrcVT.getVectorNumElements();
5065   bool Is256BitVec = SrcVT.is256BitVector();
5066
5067   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5068          "Unknown how to promote splat for type");
5069
5070   // Extract the 128-bit part containing the splat element and update
5071   // the splat element index when it refers to the higher register.
5072   if (Is256BitVec) {
5073     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5074     if (EltNo >= NumElems/2)
5075       EltNo -= NumElems/2;
5076   }
5077
5078   // All i16 and i8 vector types can't be used directly by a generic shuffle
5079   // instruction because the target has no such instruction. Generate shuffles
5080   // which repeat i16 and i8 several times until they fit in i32, and then can
5081   // be manipulated by target suported shuffles.
5082   MVT EltVT = SrcVT.getVectorElementType();
5083   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5084     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5085
5086   // Recreate the 256-bit vector and place the same 128-bit vector
5087   // into the low and high part. This is necessary because we want
5088   // to use VPERM* to shuffle the vectors
5089   if (Is256BitVec) {
5090     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5091   }
5092
5093   return getLegalSplat(DAG, V1, EltNo);
5094 }
5095
5096 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5097 /// vector of zero or undef vector.  This produces a shuffle where the low
5098 /// element of V2 is swizzled into the zero/undef vector, landing at element
5099 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5100 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5101                                            bool IsZero,
5102                                            const X86Subtarget *Subtarget,
5103                                            SelectionDAG &DAG) {
5104   MVT VT = V2.getSimpleValueType();
5105   SDValue V1 = IsZero
5106     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5107   unsigned NumElems = VT.getVectorNumElements();
5108   SmallVector<int, 16> MaskVec;
5109   for (unsigned i = 0; i != NumElems; ++i)
5110     // If this is the insertion idx, put the low elt of V2 here.
5111     MaskVec.push_back(i == Idx ? NumElems : i);
5112   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5113 }
5114
5115 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5116 /// target specific opcode. Returns true if the Mask could be calculated.
5117 /// Sets IsUnary to true if only uses one source.
5118 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5119                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5120   unsigned NumElems = VT.getVectorNumElements();
5121   SDValue ImmN;
5122
5123   IsUnary = false;
5124   switch(N->getOpcode()) {
5125   case X86ISD::SHUFP:
5126     ImmN = N->getOperand(N->getNumOperands()-1);
5127     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5128     break;
5129   case X86ISD::UNPCKH:
5130     DecodeUNPCKHMask(VT, Mask);
5131     break;
5132   case X86ISD::UNPCKL:
5133     DecodeUNPCKLMask(VT, Mask);
5134     break;
5135   case X86ISD::MOVHLPS:
5136     DecodeMOVHLPSMask(NumElems, Mask);
5137     break;
5138   case X86ISD::MOVLHPS:
5139     DecodeMOVLHPSMask(NumElems, Mask);
5140     break;
5141   case X86ISD::PALIGNR:
5142     ImmN = N->getOperand(N->getNumOperands()-1);
5143     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5144     break;
5145   case X86ISD::PSHUFD:
5146   case X86ISD::VPERMILP:
5147     ImmN = N->getOperand(N->getNumOperands()-1);
5148     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5149     IsUnary = true;
5150     break;
5151   case X86ISD::PSHUFHW:
5152     ImmN = N->getOperand(N->getNumOperands()-1);
5153     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154     IsUnary = true;
5155     break;
5156   case X86ISD::PSHUFLW:
5157     ImmN = N->getOperand(N->getNumOperands()-1);
5158     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5159     IsUnary = true;
5160     break;
5161   case X86ISD::VPERMI:
5162     ImmN = N->getOperand(N->getNumOperands()-1);
5163     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5164     IsUnary = true;
5165     break;
5166   case X86ISD::MOVSS:
5167   case X86ISD::MOVSD: {
5168     // The index 0 always comes from the first element of the second source,
5169     // this is why MOVSS and MOVSD are used in the first place. The other
5170     // elements come from the other positions of the first source vector
5171     Mask.push_back(NumElems);
5172     for (unsigned i = 1; i != NumElems; ++i) {
5173       Mask.push_back(i);
5174     }
5175     break;
5176   }
5177   case X86ISD::VPERM2X128:
5178     ImmN = N->getOperand(N->getNumOperands()-1);
5179     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180     if (Mask.empty()) return false;
5181     break;
5182   case X86ISD::MOVDDUP:
5183   case X86ISD::MOVLHPD:
5184   case X86ISD::MOVLPD:
5185   case X86ISD::MOVLPS:
5186   case X86ISD::MOVSHDUP:
5187   case X86ISD::MOVSLDUP:
5188     // Not yet implemented
5189     return false;
5190   default: llvm_unreachable("unknown target shuffle node");
5191   }
5192
5193   return true;
5194 }
5195
5196 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5197 /// element of the result of the vector shuffle.
5198 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5199                                    unsigned Depth) {
5200   if (Depth == 6)
5201     return SDValue();  // Limit search depth.
5202
5203   SDValue V = SDValue(N, 0);
5204   EVT VT = V.getValueType();
5205   unsigned Opcode = V.getOpcode();
5206
5207   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5208   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5209     int Elt = SV->getMaskElt(Index);
5210
5211     if (Elt < 0)
5212       return DAG.getUNDEF(VT.getVectorElementType());
5213
5214     unsigned NumElems = VT.getVectorNumElements();
5215     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5216                                          : SV->getOperand(1);
5217     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5218   }
5219
5220   // Recurse into target specific vector shuffles to find scalars.
5221   if (isTargetShuffle(Opcode)) {
5222     MVT ShufVT = V.getSimpleValueType();
5223     unsigned NumElems = ShufVT.getVectorNumElements();
5224     SmallVector<int, 16> ShuffleMask;
5225     bool IsUnary;
5226
5227     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5228       return SDValue();
5229
5230     int Elt = ShuffleMask[Index];
5231     if (Elt < 0)
5232       return DAG.getUNDEF(ShufVT.getVectorElementType());
5233
5234     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5235                                          : N->getOperand(1);
5236     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5237                                Depth+1);
5238   }
5239
5240   // Actual nodes that may contain scalar elements
5241   if (Opcode == ISD::BITCAST) {
5242     V = V.getOperand(0);
5243     EVT SrcVT = V.getValueType();
5244     unsigned NumElems = VT.getVectorNumElements();
5245
5246     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5247       return SDValue();
5248   }
5249
5250   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5251     return (Index == 0) ? V.getOperand(0)
5252                         : DAG.getUNDEF(VT.getVectorElementType());
5253
5254   if (V.getOpcode() == ISD::BUILD_VECTOR)
5255     return V.getOperand(Index);
5256
5257   return SDValue();
5258 }
5259
5260 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5261 /// shuffle operation which come from a consecutively from a zero. The
5262 /// search can start in two different directions, from left or right.
5263 /// We count undefs as zeros until PreferredNum is reached.
5264 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5265                                          unsigned NumElems, bool ZerosFromLeft,
5266                                          SelectionDAG &DAG,
5267                                          unsigned PreferredNum = -1U) {
5268   unsigned NumZeros = 0;
5269   for (unsigned i = 0; i != NumElems; ++i) {
5270     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5271     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5272     if (!Elt.getNode())
5273       break;
5274
5275     if (X86::isZeroNode(Elt))
5276       ++NumZeros;
5277     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5278       NumZeros = std::min(NumZeros + 1, PreferredNum);
5279     else
5280       break;
5281   }
5282
5283   return NumZeros;
5284 }
5285
5286 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5287 /// correspond consecutively to elements from one of the vector operands,
5288 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5289 static
5290 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5291                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5292                               unsigned NumElems, unsigned &OpNum) {
5293   bool SeenV1 = false;
5294   bool SeenV2 = false;
5295
5296   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5297     int Idx = SVOp->getMaskElt(i);
5298     // Ignore undef indicies
5299     if (Idx < 0)
5300       continue;
5301
5302     if (Idx < (int)NumElems)
5303       SeenV1 = true;
5304     else
5305       SeenV2 = true;
5306
5307     // Only accept consecutive elements from the same vector
5308     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5309       return false;
5310   }
5311
5312   OpNum = SeenV1 ? 0 : 1;
5313   return true;
5314 }
5315
5316 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5317 /// logical left shift of a vector.
5318 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5319                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5320   unsigned NumElems =
5321     SVOp->getSimpleValueType(0).getVectorNumElements();
5322   unsigned NumZeros = getNumOfConsecutiveZeros(
5323       SVOp, NumElems, false /* check zeros from right */, DAG,
5324       SVOp->getMaskElt(0));
5325   unsigned OpSrc;
5326
5327   if (!NumZeros)
5328     return false;
5329
5330   // Considering the elements in the mask that are not consecutive zeros,
5331   // check if they consecutively come from only one of the source vectors.
5332   //
5333   //               V1 = {X, A, B, C}     0
5334   //                         \  \  \    /
5335   //   vector_shuffle V1, V2 <1, 2, 3, X>
5336   //
5337   if (!isShuffleMaskConsecutive(SVOp,
5338             0,                   // Mask Start Index
5339             NumElems-NumZeros,   // Mask End Index(exclusive)
5340             NumZeros,            // Where to start looking in the src vector
5341             NumElems,            // Number of elements in vector
5342             OpSrc))              // Which source operand ?
5343     return false;
5344
5345   isLeft = false;
5346   ShAmt = NumZeros;
5347   ShVal = SVOp->getOperand(OpSrc);
5348   return true;
5349 }
5350
5351 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5352 /// logical left shift of a vector.
5353 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5354                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5355   unsigned NumElems =
5356     SVOp->getSimpleValueType(0).getVectorNumElements();
5357   unsigned NumZeros = getNumOfConsecutiveZeros(
5358       SVOp, NumElems, true /* check zeros from left */, DAG,
5359       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5360   unsigned OpSrc;
5361
5362   if (!NumZeros)
5363     return false;
5364
5365   // Considering the elements in the mask that are not consecutive zeros,
5366   // check if they consecutively come from only one of the source vectors.
5367   //
5368   //                           0    { A, B, X, X } = V2
5369   //                          / \    /  /
5370   //   vector_shuffle V1, V2 <X, X, 4, 5>
5371   //
5372   if (!isShuffleMaskConsecutive(SVOp,
5373             NumZeros,     // Mask Start Index
5374             NumElems,     // Mask End Index(exclusive)
5375             0,            // Where to start looking in the src vector
5376             NumElems,     // Number of elements in vector
5377             OpSrc))       // Which source operand ?
5378     return false;
5379
5380   isLeft = true;
5381   ShAmt = NumZeros;
5382   ShVal = SVOp->getOperand(OpSrc);
5383   return true;
5384 }
5385
5386 /// isVectorShift - Returns true if the shuffle can be implemented as a
5387 /// logical left or right shift of a vector.
5388 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5389                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5390   // Although the logic below support any bitwidth size, there are no
5391   // shift instructions which handle more than 128-bit vectors.
5392   if (!SVOp->getSimpleValueType(0).is128BitVector())
5393     return false;
5394
5395   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5396       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5397     return true;
5398
5399   return false;
5400 }
5401
5402 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5403 ///
5404 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5405                                        unsigned NumNonZero, unsigned NumZero,
5406                                        SelectionDAG &DAG,
5407                                        const X86Subtarget* Subtarget,
5408                                        const TargetLowering &TLI) {
5409   if (NumNonZero > 8)
5410     return SDValue();
5411
5412   SDLoc dl(Op);
5413   SDValue V;
5414   bool First = true;
5415   for (unsigned i = 0; i < 16; ++i) {
5416     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5417     if (ThisIsNonZero && First) {
5418       if (NumZero)
5419         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5420       else
5421         V = DAG.getUNDEF(MVT::v8i16);
5422       First = false;
5423     }
5424
5425     if ((i & 1) != 0) {
5426       SDValue ThisElt, LastElt;
5427       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5428       if (LastIsNonZero) {
5429         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5430                               MVT::i16, Op.getOperand(i-1));
5431       }
5432       if (ThisIsNonZero) {
5433         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5434         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5435                               ThisElt, DAG.getConstant(8, MVT::i8));
5436         if (LastIsNonZero)
5437           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5438       } else
5439         ThisElt = LastElt;
5440
5441       if (ThisElt.getNode())
5442         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5443                         DAG.getIntPtrConstant(i/2));
5444     }
5445   }
5446
5447   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5448 }
5449
5450 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5451 ///
5452 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5453                                      unsigned NumNonZero, unsigned NumZero,
5454                                      SelectionDAG &DAG,
5455                                      const X86Subtarget* Subtarget,
5456                                      const TargetLowering &TLI) {
5457   if (NumNonZero > 4)
5458     return SDValue();
5459
5460   SDLoc dl(Op);
5461   SDValue V;
5462   bool First = true;
5463   for (unsigned i = 0; i < 8; ++i) {
5464     bool isNonZero = (NonZeros & (1 << i)) != 0;
5465     if (isNonZero) {
5466       if (First) {
5467         if (NumZero)
5468           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5469         else
5470           V = DAG.getUNDEF(MVT::v8i16);
5471         First = false;
5472       }
5473       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5474                       MVT::v8i16, V, Op.getOperand(i),
5475                       DAG.getIntPtrConstant(i));
5476     }
5477   }
5478
5479   return V;
5480 }
5481
5482 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5483 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5484                                      unsigned NonZeros, unsigned NumNonZero,
5485                                      unsigned NumZero, SelectionDAG &DAG,
5486                                      const X86Subtarget *Subtarget,
5487                                      const TargetLowering &TLI) {
5488   // We know there's at least one non-zero element
5489   unsigned FirstNonZeroIdx = 0;
5490   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5492          X86::isZeroNode(FirstNonZero)) {
5493     ++FirstNonZeroIdx;
5494     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5495   }
5496
5497   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5498       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5499     return SDValue();
5500
5501   SDValue V = FirstNonZero.getOperand(0);
5502   MVT VVT = V.getSimpleValueType();
5503   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5504     return SDValue();
5505
5506   unsigned FirstNonZeroDst =
5507       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5508   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5509   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5510   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5511
5512   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5513     SDValue Elem = Op.getOperand(Idx);
5514     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5515       continue;
5516
5517     // TODO: What else can be here? Deal with it.
5518     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5519       return SDValue();
5520
5521     // TODO: Some optimizations are still possible here
5522     // ex: Getting one element from a vector, and the rest from another.
5523     if (Elem.getOperand(0) != V)
5524       return SDValue();
5525
5526     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5527     if (Dst == Idx)
5528       ++CorrectIdx;
5529     else if (IncorrectIdx == -1U) {
5530       IncorrectIdx = Idx;
5531       IncorrectDst = Dst;
5532     } else
5533       // There was already one element with an incorrect index.
5534       // We can't optimize this case to an insertps.
5535       return SDValue();
5536   }
5537
5538   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5539     SDLoc dl(Op);
5540     EVT VT = Op.getSimpleValueType();
5541     unsigned ElementMoveMask = 0;
5542     if (IncorrectIdx == -1U)
5543       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5544     else
5545       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5546
5547     SDValue InsertpsMask =
5548         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5549     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5550   }
5551
5552   return SDValue();
5553 }
5554
5555 /// getVShift - Return a vector logical shift node.
5556 ///
5557 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5558                          unsigned NumBits, SelectionDAG &DAG,
5559                          const TargetLowering &TLI, SDLoc dl) {
5560   assert(VT.is128BitVector() && "Unknown type for VShift");
5561   EVT ShVT = MVT::v2i64;
5562   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5563   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5564   return DAG.getNode(ISD::BITCAST, dl, VT,
5565                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5566                              DAG.getConstant(NumBits,
5567                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5568 }
5569
5570 static SDValue
5571 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5572
5573   // Check if the scalar load can be widened into a vector load. And if
5574   // the address is "base + cst" see if the cst can be "absorbed" into
5575   // the shuffle mask.
5576   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5577     SDValue Ptr = LD->getBasePtr();
5578     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5579       return SDValue();
5580     EVT PVT = LD->getValueType(0);
5581     if (PVT != MVT::i32 && PVT != MVT::f32)
5582       return SDValue();
5583
5584     int FI = -1;
5585     int64_t Offset = 0;
5586     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5587       FI = FINode->getIndex();
5588       Offset = 0;
5589     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5590                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5591       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5592       Offset = Ptr.getConstantOperandVal(1);
5593       Ptr = Ptr.getOperand(0);
5594     } else {
5595       return SDValue();
5596     }
5597
5598     // FIXME: 256-bit vector instructions don't require a strict alignment,
5599     // improve this code to support it better.
5600     unsigned RequiredAlign = VT.getSizeInBits()/8;
5601     SDValue Chain = LD->getChain();
5602     // Make sure the stack object alignment is at least 16 or 32.
5603     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5604     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5605       if (MFI->isFixedObjectIndex(FI)) {
5606         // Can't change the alignment. FIXME: It's possible to compute
5607         // the exact stack offset and reference FI + adjust offset instead.
5608         // If someone *really* cares about this. That's the way to implement it.
5609         return SDValue();
5610       } else {
5611         MFI->setObjectAlignment(FI, RequiredAlign);
5612       }
5613     }
5614
5615     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5616     // Ptr + (Offset & ~15).
5617     if (Offset < 0)
5618       return SDValue();
5619     if ((Offset % RequiredAlign) & 3)
5620       return SDValue();
5621     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5622     if (StartOffset)
5623       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5624                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5625
5626     int EltNo = (Offset - StartOffset) >> 2;
5627     unsigned NumElems = VT.getVectorNumElements();
5628
5629     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5630     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5631                              LD->getPointerInfo().getWithOffset(StartOffset),
5632                              false, false, false, 0);
5633
5634     SmallVector<int, 8> Mask;
5635     for (unsigned i = 0; i != NumElems; ++i)
5636       Mask.push_back(EltNo);
5637
5638     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5639   }
5640
5641   return SDValue();
5642 }
5643
5644 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5645 /// vector of type 'VT', see if the elements can be replaced by a single large
5646 /// load which has the same value as a build_vector whose operands are 'elts'.
5647 ///
5648 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5649 ///
5650 /// FIXME: we'd also like to handle the case where the last elements are zero
5651 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5652 /// There's even a handy isZeroNode for that purpose.
5653 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5654                                         SDLoc &DL, SelectionDAG &DAG,
5655                                         bool isAfterLegalize) {
5656   EVT EltVT = VT.getVectorElementType();
5657   unsigned NumElems = Elts.size();
5658
5659   LoadSDNode *LDBase = nullptr;
5660   unsigned LastLoadedElt = -1U;
5661
5662   // For each element in the initializer, see if we've found a load or an undef.
5663   // If we don't find an initial load element, or later load elements are
5664   // non-consecutive, bail out.
5665   for (unsigned i = 0; i < NumElems; ++i) {
5666     SDValue Elt = Elts[i];
5667
5668     if (!Elt.getNode() ||
5669         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5670       return SDValue();
5671     if (!LDBase) {
5672       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5673         return SDValue();
5674       LDBase = cast<LoadSDNode>(Elt.getNode());
5675       LastLoadedElt = i;
5676       continue;
5677     }
5678     if (Elt.getOpcode() == ISD::UNDEF)
5679       continue;
5680
5681     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5682     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5683       return SDValue();
5684     LastLoadedElt = i;
5685   }
5686
5687   // If we have found an entire vector of loads and undefs, then return a large
5688   // load of the entire vector width starting at the base pointer.  If we found
5689   // consecutive loads for the low half, generate a vzext_load node.
5690   if (LastLoadedElt == NumElems - 1) {
5691
5692     if (isAfterLegalize &&
5693         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5694       return SDValue();
5695
5696     SDValue NewLd = SDValue();
5697
5698     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5699       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5700                           LDBase->getPointerInfo(),
5701                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5702                           LDBase->isInvariant(), 0);
5703     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5704                         LDBase->getPointerInfo(),
5705                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5706                         LDBase->isInvariant(), LDBase->getAlignment());
5707
5708     if (LDBase->hasAnyUseOfValue(1)) {
5709       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5710                                      SDValue(LDBase, 1),
5711                                      SDValue(NewLd.getNode(), 1));
5712       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5713       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5714                              SDValue(NewLd.getNode(), 1));
5715     }
5716
5717     return NewLd;
5718   }
5719   if (NumElems == 4 && LastLoadedElt == 1 &&
5720       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5721     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5722     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5723     SDValue ResNode =
5724         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5725                                 LDBase->getPointerInfo(),
5726                                 LDBase->getAlignment(),
5727                                 false/*isVolatile*/, true/*ReadMem*/,
5728                                 false/*WriteMem*/);
5729
5730     // Make sure the newly-created LOAD is in the same position as LDBase in
5731     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5732     // update uses of LDBase's output chain to use the TokenFactor.
5733     if (LDBase->hasAnyUseOfValue(1)) {
5734       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5735                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5736       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5737       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5738                              SDValue(ResNode.getNode(), 1));
5739     }
5740
5741     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5742   }
5743   return SDValue();
5744 }
5745
5746 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5747 /// to generate a splat value for the following cases:
5748 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5749 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5750 /// a scalar load, or a constant.
5751 /// The VBROADCAST node is returned when a pattern is found,
5752 /// or SDValue() otherwise.
5753 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5754                                     SelectionDAG &DAG) {
5755   if (!Subtarget->hasFp256())
5756     return SDValue();
5757
5758   MVT VT = Op.getSimpleValueType();
5759   SDLoc dl(Op);
5760
5761   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5762          "Unsupported vector type for broadcast.");
5763
5764   SDValue Ld;
5765   bool ConstSplatVal;
5766
5767   switch (Op.getOpcode()) {
5768     default:
5769       // Unknown pattern found.
5770       return SDValue();
5771
5772     case ISD::BUILD_VECTOR: {
5773       // The BUILD_VECTOR node must be a splat.
5774       if (!isSplatVector(Op.getNode()))
5775         return SDValue();
5776
5777       Ld = Op.getOperand(0);
5778       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5779                      Ld.getOpcode() == ISD::ConstantFP);
5780
5781       // The suspected load node has several users. Make sure that all
5782       // of its users are from the BUILD_VECTOR node.
5783       // Constants may have multiple users.
5784       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5785         return SDValue();
5786       break;
5787     }
5788
5789     case ISD::VECTOR_SHUFFLE: {
5790       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5791
5792       // Shuffles must have a splat mask where the first element is
5793       // broadcasted.
5794       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5795         return SDValue();
5796
5797       SDValue Sc = Op.getOperand(0);
5798       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5799           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5800
5801         if (!Subtarget->hasInt256())
5802           return SDValue();
5803
5804         // Use the register form of the broadcast instruction available on AVX2.
5805         if (VT.getSizeInBits() >= 256)
5806           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5807         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5808       }
5809
5810       Ld = Sc.getOperand(0);
5811       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5812                        Ld.getOpcode() == ISD::ConstantFP);
5813
5814       // The scalar_to_vector node and the suspected
5815       // load node must have exactly one user.
5816       // Constants may have multiple users.
5817
5818       // AVX-512 has register version of the broadcast
5819       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5820         Ld.getValueType().getSizeInBits() >= 32;
5821       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5822           !hasRegVer))
5823         return SDValue();
5824       break;
5825     }
5826   }
5827
5828   bool IsGE256 = (VT.getSizeInBits() >= 256);
5829
5830   // Handle the broadcasting a single constant scalar from the constant pool
5831   // into a vector. On Sandybridge it is still better to load a constant vector
5832   // from the constant pool and not to broadcast it from a scalar.
5833   if (ConstSplatVal && Subtarget->hasInt256()) {
5834     EVT CVT = Ld.getValueType();
5835     assert(!CVT.isVector() && "Must not broadcast a vector type");
5836     unsigned ScalarSize = CVT.getSizeInBits();
5837
5838     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5839       const Constant *C = nullptr;
5840       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5841         C = CI->getConstantIntValue();
5842       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5843         C = CF->getConstantFPValue();
5844
5845       assert(C && "Invalid constant type");
5846
5847       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5848       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5849       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5850       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5851                        MachinePointerInfo::getConstantPool(),
5852                        false, false, false, Alignment);
5853
5854       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5855     }
5856   }
5857
5858   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5859   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5860
5861   // Handle AVX2 in-register broadcasts.
5862   if (!IsLoad && Subtarget->hasInt256() &&
5863       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5864     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865
5866   // The scalar source must be a normal load.
5867   if (!IsLoad)
5868     return SDValue();
5869
5870   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5871     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5872
5873   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5874   // double since there is no vbroadcastsd xmm
5875   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5876     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5877       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5878   }
5879
5880   // Unsupported broadcast.
5881   return SDValue();
5882 }
5883
5884 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5885 /// underlying vector and index.
5886 ///
5887 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5888 /// index.
5889 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5890                                          SDValue ExtIdx) {
5891   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5892   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5893     return Idx;
5894
5895   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5896   // lowered this:
5897   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5898   // to:
5899   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5900   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5901   //                           undef)
5902   //                       Constant<0>)
5903   // In this case the vector is the extract_subvector expression and the index
5904   // is 2, as specified by the shuffle.
5905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5906   SDValue ShuffleVec = SVOp->getOperand(0);
5907   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5908   assert(ShuffleVecVT.getVectorElementType() ==
5909          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5910
5911   int ShuffleIdx = SVOp->getMaskElt(Idx);
5912   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5913     ExtractedFromVec = ShuffleVec;
5914     return ShuffleIdx;
5915   }
5916   return Idx;
5917 }
5918
5919 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5920   MVT VT = Op.getSimpleValueType();
5921
5922   // Skip if insert_vec_elt is not supported.
5923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5924   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5925     return SDValue();
5926
5927   SDLoc DL(Op);
5928   unsigned NumElems = Op.getNumOperands();
5929
5930   SDValue VecIn1;
5931   SDValue VecIn2;
5932   SmallVector<unsigned, 4> InsertIndices;
5933   SmallVector<int, 8> Mask(NumElems, -1);
5934
5935   for (unsigned i = 0; i != NumElems; ++i) {
5936     unsigned Opc = Op.getOperand(i).getOpcode();
5937
5938     if (Opc == ISD::UNDEF)
5939       continue;
5940
5941     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5942       // Quit if more than 1 elements need inserting.
5943       if (InsertIndices.size() > 1)
5944         return SDValue();
5945
5946       InsertIndices.push_back(i);
5947       continue;
5948     }
5949
5950     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5951     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5952     // Quit if non-constant index.
5953     if (!isa<ConstantSDNode>(ExtIdx))
5954       return SDValue();
5955     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5956
5957     // Quit if extracted from vector of different type.
5958     if (ExtractedFromVec.getValueType() != VT)
5959       return SDValue();
5960
5961     if (!VecIn1.getNode())
5962       VecIn1 = ExtractedFromVec;
5963     else if (VecIn1 != ExtractedFromVec) {
5964       if (!VecIn2.getNode())
5965         VecIn2 = ExtractedFromVec;
5966       else if (VecIn2 != ExtractedFromVec)
5967         // Quit if more than 2 vectors to shuffle
5968         return SDValue();
5969     }
5970
5971     if (ExtractedFromVec == VecIn1)
5972       Mask[i] = Idx;
5973     else if (ExtractedFromVec == VecIn2)
5974       Mask[i] = Idx + NumElems;
5975   }
5976
5977   if (!VecIn1.getNode())
5978     return SDValue();
5979
5980   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5981   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5982   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5983     unsigned Idx = InsertIndices[i];
5984     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5985                      DAG.getIntPtrConstant(Idx));
5986   }
5987
5988   return NV;
5989 }
5990
5991 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5992 SDValue
5993 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5994
5995   MVT VT = Op.getSimpleValueType();
5996   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5997          "Unexpected type in LowerBUILD_VECTORvXi1!");
5998
5999   SDLoc dl(Op);
6000   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6001     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6002     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6004   }
6005
6006   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6007     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6008     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6009     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6010   }
6011
6012   bool AllContants = true;
6013   uint64_t Immediate = 0;
6014   int NonConstIdx = -1;
6015   bool IsSplat = true;
6016   unsigned NumNonConsts = 0;
6017   unsigned NumConsts = 0;
6018   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6019     SDValue In = Op.getOperand(idx);
6020     if (In.getOpcode() == ISD::UNDEF)
6021       continue;
6022     if (!isa<ConstantSDNode>(In)) {
6023       AllContants = false;
6024       NonConstIdx = idx;
6025       NumNonConsts++;
6026     }
6027     else {
6028       NumConsts++;
6029       if (cast<ConstantSDNode>(In)->getZExtValue())
6030       Immediate |= (1ULL << idx);
6031     }
6032     if (In != Op.getOperand(0))
6033       IsSplat = false;
6034   }
6035
6036   if (AllContants) {
6037     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6038       DAG.getConstant(Immediate, MVT::i16));
6039     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6040                        DAG.getIntPtrConstant(0));
6041   }
6042
6043   if (NumNonConsts == 1 && NonConstIdx != 0) {
6044     SDValue DstVec;
6045     if (NumConsts) {
6046       SDValue VecAsImm = DAG.getConstant(Immediate,
6047                                          MVT::getIntegerVT(VT.getSizeInBits()));
6048       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6049     }
6050     else 
6051       DstVec = DAG.getUNDEF(VT);
6052     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6053                        Op.getOperand(NonConstIdx),
6054                        DAG.getIntPtrConstant(NonConstIdx));
6055   }
6056   if (!IsSplat && (NonConstIdx != 0))
6057     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6058   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6059   SDValue Select;
6060   if (IsSplat)
6061     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6062                           DAG.getConstant(-1, SelectVT),
6063                           DAG.getConstant(0, SelectVT));
6064   else
6065     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6066                          DAG.getConstant((Immediate | 1), SelectVT),
6067                          DAG.getConstant(Immediate, SelectVT));
6068   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6069 }
6070
6071 /// \brief Return true if \p N implements a horizontal binop and return the
6072 /// operands for the horizontal binop into V0 and V1.
6073 /// 
6074 /// This is a helper function of PerformBUILD_VECTORCombine.
6075 /// This function checks that the build_vector \p N in input implements a
6076 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6077 /// operation to match.
6078 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6079 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6080 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6081 /// arithmetic sub.
6082 ///
6083 /// This function only analyzes elements of \p N whose indices are
6084 /// in range [BaseIdx, LastIdx).
6085 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6086                               SelectionDAG &DAG,
6087                               unsigned BaseIdx, unsigned LastIdx,
6088                               SDValue &V0, SDValue &V1) {
6089   EVT VT = N->getValueType(0);
6090
6091   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6092   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6093          "Invalid Vector in input!");
6094   
6095   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6096   bool CanFold = true;
6097   unsigned ExpectedVExtractIdx = BaseIdx;
6098   unsigned NumElts = LastIdx - BaseIdx;
6099   V0 = DAG.getUNDEF(VT);
6100   V1 = DAG.getUNDEF(VT);
6101
6102   // Check if N implements a horizontal binop.
6103   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6104     SDValue Op = N->getOperand(i + BaseIdx);
6105
6106     // Skip UNDEFs.
6107     if (Op->getOpcode() == ISD::UNDEF) {
6108       // Update the expected vector extract index.
6109       if (i * 2 == NumElts)
6110         ExpectedVExtractIdx = BaseIdx;
6111       ExpectedVExtractIdx += 2;
6112       continue;
6113     }
6114
6115     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6116
6117     if (!CanFold)
6118       break;
6119
6120     SDValue Op0 = Op.getOperand(0);
6121     SDValue Op1 = Op.getOperand(1);
6122
6123     // Try to match the following pattern:
6124     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6125     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6126         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127         Op0.getOperand(0) == Op1.getOperand(0) &&
6128         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6129         isa<ConstantSDNode>(Op1.getOperand(1)));
6130     if (!CanFold)
6131       break;
6132
6133     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6134     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6135
6136     if (i * 2 < NumElts) {
6137       if (V0.getOpcode() == ISD::UNDEF)
6138         V0 = Op0.getOperand(0);
6139     } else {
6140       if (V1.getOpcode() == ISD::UNDEF)
6141         V1 = Op0.getOperand(0);
6142       if (i * 2 == NumElts)
6143         ExpectedVExtractIdx = BaseIdx;
6144     }
6145
6146     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6147     if (I0 == ExpectedVExtractIdx)
6148       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6149     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6150       // Try to match the following dag sequence:
6151       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6152       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6153     } else
6154       CanFold = false;
6155
6156     ExpectedVExtractIdx += 2;
6157   }
6158
6159   return CanFold;
6160 }
6161
6162 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6163 /// a concat_vector. 
6164 ///
6165 /// This is a helper function of PerformBUILD_VECTORCombine.
6166 /// This function expects two 256-bit vectors called V0 and V1.
6167 /// At first, each vector is split into two separate 128-bit vectors.
6168 /// Then, the resulting 128-bit vectors are used to implement two
6169 /// horizontal binary operations. 
6170 ///
6171 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6172 ///
6173 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6174 /// the two new horizontal binop.
6175 /// When Mode is set, the first horizontal binop dag node would take as input
6176 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6177 /// horizontal binop dag node would take as input the lower 128-bit of V1
6178 /// and the upper 128-bit of V1.
6179 ///   Example:
6180 ///     HADD V0_LO, V0_HI
6181 ///     HADD V1_LO, V1_HI
6182 ///
6183 /// Otherwise, the first horizontal binop dag node takes as input the lower
6184 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6185 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6186 ///   Example:
6187 ///     HADD V0_LO, V1_LO
6188 ///     HADD V0_HI, V1_HI
6189 ///
6190 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6191 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6192 /// the upper 128-bits of the result.
6193 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6194                                      SDLoc DL, SelectionDAG &DAG,
6195                                      unsigned X86Opcode, bool Mode,
6196                                      bool isUndefLO, bool isUndefHI) {
6197   EVT VT = V0.getValueType();
6198   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6199          "Invalid nodes in input!");
6200
6201   unsigned NumElts = VT.getVectorNumElements();
6202   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6203   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6204   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6205   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6206   EVT NewVT = V0_LO.getValueType();
6207
6208   SDValue LO = DAG.getUNDEF(NewVT);
6209   SDValue HI = DAG.getUNDEF(NewVT);
6210
6211   if (Mode) {
6212     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6214       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6215     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6216       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6217   } else {
6218     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6219     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6220                        V1_LO->getOpcode() != ISD::UNDEF))
6221       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6222
6223     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6224                        V1_HI->getOpcode() != ISD::UNDEF))
6225       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6226   }
6227
6228   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6229 }
6230
6231 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6232 /// sequence of 'vadd + vsub + blendi'.
6233 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6234                            const X86Subtarget *Subtarget) {
6235   SDLoc DL(BV);
6236   EVT VT = BV->getValueType(0);
6237   unsigned NumElts = VT.getVectorNumElements();
6238   SDValue InVec0 = DAG.getUNDEF(VT);
6239   SDValue InVec1 = DAG.getUNDEF(VT);
6240
6241   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6242           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6243
6244   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6246   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6247     return SDValue();
6248
6249   // Odd-numbered elements in the input build vector are obtained from
6250   // adding two integer/float elements.
6251   // Even-numbered elements in the input build vector are obtained from
6252   // subtracting two integer/float elements.
6253   unsigned ExpectedOpcode = ISD::FSUB;
6254   unsigned NextExpectedOpcode = ISD::FADD;
6255   bool AddFound = false;
6256   bool SubFound = false;
6257
6258   for (unsigned i = 0, e = NumElts; i != e; i++) {
6259     SDValue Op = BV->getOperand(i);
6260       
6261     // Skip 'undef' values.
6262     unsigned Opcode = Op.getOpcode();
6263     if (Opcode == ISD::UNDEF) {
6264       std::swap(ExpectedOpcode, NextExpectedOpcode);
6265       continue;
6266     }
6267       
6268     // Early exit if we found an unexpected opcode.
6269     if (Opcode != ExpectedOpcode)
6270       return SDValue();
6271
6272     SDValue Op0 = Op.getOperand(0);
6273     SDValue Op1 = Op.getOperand(1);
6274
6275     // Try to match the following pattern:
6276     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6277     // Early exit if we cannot match that sequence.
6278     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6281         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6282         Op0.getOperand(1) != Op1.getOperand(1))
6283       return SDValue();
6284
6285     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6286     if (I0 != i)
6287       return SDValue();
6288
6289     // We found a valid add/sub node. Update the information accordingly.
6290     if (i & 1)
6291       AddFound = true;
6292     else
6293       SubFound = true;
6294
6295     // Update InVec0 and InVec1.
6296     if (InVec0.getOpcode() == ISD::UNDEF)
6297       InVec0 = Op0.getOperand(0);
6298     if (InVec1.getOpcode() == ISD::UNDEF)
6299       InVec1 = Op1.getOperand(0);
6300
6301     // Make sure that operands in input to each add/sub node always
6302     // come from a same pair of vectors.
6303     if (InVec0 != Op0.getOperand(0)) {
6304       if (ExpectedOpcode == ISD::FSUB)
6305         return SDValue();
6306
6307       // FADD is commutable. Try to commute the operands
6308       // and then test again.
6309       std::swap(Op0, Op1);
6310       if (InVec0 != Op0.getOperand(0))
6311         return SDValue();
6312     }
6313
6314     if (InVec1 != Op1.getOperand(0))
6315       return SDValue();
6316
6317     // Update the pair of expected opcodes.
6318     std::swap(ExpectedOpcode, NextExpectedOpcode);
6319   }
6320
6321   // Don't try to fold this build_vector into a VSELECT if it has
6322   // too many UNDEF operands.
6323   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6324       InVec1.getOpcode() != ISD::UNDEF) {
6325     // Emit a sequence of vector add and sub followed by a VSELECT.
6326     // The new VSELECT will be lowered into a BLENDI.
6327     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6328     // and emit a single ADDSUB instruction.
6329     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6330     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6331
6332     // Construct the VSELECT mask.
6333     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6334     EVT SVT = MaskVT.getVectorElementType();
6335     unsigned SVTBits = SVT.getSizeInBits();
6336     SmallVector<SDValue, 8> Ops;
6337
6338     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6339       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6340                             APInt::getAllOnesValue(SVTBits);
6341       SDValue Constant = DAG.getConstant(Value, SVT);
6342       Ops.push_back(Constant);
6343     }
6344
6345     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6346     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6347   }
6348   
6349   return SDValue();
6350 }
6351
6352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6353                                           const X86Subtarget *Subtarget) {
6354   SDLoc DL(N);
6355   EVT VT = N->getValueType(0);
6356   unsigned NumElts = VT.getVectorNumElements();
6357   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6358   SDValue InVec0, InVec1;
6359
6360   // Try to match an ADDSUB.
6361   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6362       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6363     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6364     if (Value.getNode())
6365       return Value;
6366   }
6367
6368   // Try to match horizontal ADD/SUB.
6369   unsigned NumUndefsLO = 0;
6370   unsigned NumUndefsHI = 0;
6371   unsigned Half = NumElts/2;
6372
6373   // Count the number of UNDEF operands in the build_vector in input.
6374   for (unsigned i = 0, e = Half; i != e; ++i)
6375     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6376       NumUndefsLO++;
6377
6378   for (unsigned i = Half, e = NumElts; i != e; ++i)
6379     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6380       NumUndefsHI++;
6381
6382   // Early exit if this is either a build_vector of all UNDEFs or all the
6383   // operands but one are UNDEF.
6384   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6385     return SDValue();
6386
6387   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6388     // Try to match an SSE3 float HADD/HSUB.
6389     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6390       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6391     
6392     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6393       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6394   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6395     // Try to match an SSSE3 integer HADD/HSUB.
6396     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6397       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6398     
6399     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6400       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6401   }
6402   
6403   if (!Subtarget->hasAVX())
6404     return SDValue();
6405
6406   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6407     // Try to match an AVX horizontal add/sub of packed single/double
6408     // precision floating point values from 256-bit vectors.
6409     SDValue InVec2, InVec3;
6410     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6411         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6412         ((InVec0.getOpcode() == ISD::UNDEF ||
6413           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6414         ((InVec1.getOpcode() == ISD::UNDEF ||
6415           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6416       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6417
6418     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6419         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6420         ((InVec0.getOpcode() == ISD::UNDEF ||
6421           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6422         ((InVec1.getOpcode() == ISD::UNDEF ||
6423           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6424       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6425   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6426     // Try to match an AVX2 horizontal add/sub of signed integers.
6427     SDValue InVec2, InVec3;
6428     unsigned X86Opcode;
6429     bool CanFold = true;
6430
6431     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6432         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6433         ((InVec0.getOpcode() == ISD::UNDEF ||
6434           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435         ((InVec1.getOpcode() == ISD::UNDEF ||
6436           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437       X86Opcode = X86ISD::HADD;
6438     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6439         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6440         ((InVec0.getOpcode() == ISD::UNDEF ||
6441           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6442         ((InVec1.getOpcode() == ISD::UNDEF ||
6443           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6444       X86Opcode = X86ISD::HSUB;
6445     else
6446       CanFold = false;
6447
6448     if (CanFold) {
6449       // Fold this build_vector into a single horizontal add/sub.
6450       // Do this only if the target has AVX2.
6451       if (Subtarget->hasAVX2())
6452         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6453  
6454       // Do not try to expand this build_vector into a pair of horizontal
6455       // add/sub if we can emit a pair of scalar add/sub.
6456       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6457         return SDValue();
6458
6459       // Convert this build_vector into a pair of horizontal binop followed by
6460       // a concat vector.
6461       bool isUndefLO = NumUndefsLO == Half;
6462       bool isUndefHI = NumUndefsHI == Half;
6463       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6464                                    isUndefLO, isUndefHI);
6465     }
6466   }
6467
6468   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6469        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6470     unsigned X86Opcode;
6471     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6472       X86Opcode = X86ISD::HADD;
6473     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6474       X86Opcode = X86ISD::HSUB;
6475     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6476       X86Opcode = X86ISD::FHADD;
6477     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6478       X86Opcode = X86ISD::FHSUB;
6479     else
6480       return SDValue();
6481
6482     // Don't try to expand this build_vector into a pair of horizontal add/sub
6483     // if we can simply emit a pair of scalar add/sub.
6484     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6485       return SDValue();
6486
6487     // Convert this build_vector into two horizontal add/sub followed by
6488     // a concat vector.
6489     bool isUndefLO = NumUndefsLO == Half;
6490     bool isUndefHI = NumUndefsHI == Half;
6491     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6492                                  isUndefLO, isUndefHI);
6493   }
6494
6495   return SDValue();
6496 }
6497
6498 SDValue
6499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6500   SDLoc dl(Op);
6501
6502   MVT VT = Op.getSimpleValueType();
6503   MVT ExtVT = VT.getVectorElementType();
6504   unsigned NumElems = Op.getNumOperands();
6505
6506   // Generate vectors for predicate vectors.
6507   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6508     return LowerBUILD_VECTORvXi1(Op, DAG);
6509
6510   // Vectors containing all zeros can be matched by pxor and xorps later
6511   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6512     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6513     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6514     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6515       return Op;
6516
6517     return getZeroVector(VT, Subtarget, DAG, dl);
6518   }
6519
6520   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6521   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6522   // vpcmpeqd on 256-bit vectors.
6523   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6524     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6525       return Op;
6526
6527     if (!VT.is512BitVector())
6528       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6529   }
6530
6531   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6532   if (Broadcast.getNode())
6533     return Broadcast;
6534
6535   unsigned EVTBits = ExtVT.getSizeInBits();
6536
6537   unsigned NumZero  = 0;
6538   unsigned NumNonZero = 0;
6539   unsigned NonZeros = 0;
6540   bool IsAllConstants = true;
6541   SmallSet<SDValue, 8> Values;
6542   for (unsigned i = 0; i < NumElems; ++i) {
6543     SDValue Elt = Op.getOperand(i);
6544     if (Elt.getOpcode() == ISD::UNDEF)
6545       continue;
6546     Values.insert(Elt);
6547     if (Elt.getOpcode() != ISD::Constant &&
6548         Elt.getOpcode() != ISD::ConstantFP)
6549       IsAllConstants = false;
6550     if (X86::isZeroNode(Elt))
6551       NumZero++;
6552     else {
6553       NonZeros |= (1 << i);
6554       NumNonZero++;
6555     }
6556   }
6557
6558   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6559   if (NumNonZero == 0)
6560     return DAG.getUNDEF(VT);
6561
6562   // Special case for single non-zero, non-undef, element.
6563   if (NumNonZero == 1) {
6564     unsigned Idx = countTrailingZeros(NonZeros);
6565     SDValue Item = Op.getOperand(Idx);
6566
6567     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6568     // the value are obviously zero, truncate the value to i32 and do the
6569     // insertion that way.  Only do this if the value is non-constant or if the
6570     // value is a constant being inserted into element 0.  It is cheaper to do
6571     // a constant pool load than it is to do a movd + shuffle.
6572     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6573         (!IsAllConstants || Idx == 0)) {
6574       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6575         // Handle SSE only.
6576         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6577         EVT VecVT = MVT::v4i32;
6578         unsigned VecElts = 4;
6579
6580         // Truncate the value (which may itself be a constant) to i32, and
6581         // convert it to a vector with movd (S2V+shuffle to zero extend).
6582         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6583         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6584         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6585
6586         // Now we have our 32-bit value zero extended in the low element of
6587         // a vector.  If Idx != 0, swizzle it into place.
6588         if (Idx != 0) {
6589           SmallVector<int, 4> Mask;
6590           Mask.push_back(Idx);
6591           for (unsigned i = 1; i != VecElts; ++i)
6592             Mask.push_back(i);
6593           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6594                                       &Mask[0]);
6595         }
6596         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6597       }
6598     }
6599
6600     // If we have a constant or non-constant insertion into the low element of
6601     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6602     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6603     // depending on what the source datatype is.
6604     if (Idx == 0) {
6605       if (NumZero == 0)
6606         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6607
6608       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6609           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6610         if (VT.is256BitVector() || VT.is512BitVector()) {
6611           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6612           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6613                              Item, DAG.getIntPtrConstant(0));
6614         }
6615         assert(VT.is128BitVector() && "Expected an SSE value type!");
6616         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6617         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6618         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6619       }
6620
6621       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6622         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6623         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6624         if (VT.is256BitVector()) {
6625           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6626           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6627         } else {
6628           assert(VT.is128BitVector() && "Expected an SSE value type!");
6629           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6630         }
6631         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6632       }
6633     }
6634
6635     // Is it a vector logical left shift?
6636     if (NumElems == 2 && Idx == 1 &&
6637         X86::isZeroNode(Op.getOperand(0)) &&
6638         !X86::isZeroNode(Op.getOperand(1))) {
6639       unsigned NumBits = VT.getSizeInBits();
6640       return getVShift(true, VT,
6641                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6642                                    VT, Op.getOperand(1)),
6643                        NumBits/2, DAG, *this, dl);
6644     }
6645
6646     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6647       return SDValue();
6648
6649     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6650     // is a non-constant being inserted into an element other than the low one,
6651     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6652     // movd/movss) to move this into the low element, then shuffle it into
6653     // place.
6654     if (EVTBits == 32) {
6655       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6656
6657       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6658       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6659       SmallVector<int, 8> MaskVec;
6660       for (unsigned i = 0; i != NumElems; ++i)
6661         MaskVec.push_back(i == Idx ? 0 : 1);
6662       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6663     }
6664   }
6665
6666   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6667   if (Values.size() == 1) {
6668     if (EVTBits == 32) {
6669       // Instead of a shuffle like this:
6670       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6671       // Check if it's possible to issue this instead.
6672       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6673       unsigned Idx = countTrailingZeros(NonZeros);
6674       SDValue Item = Op.getOperand(Idx);
6675       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6676         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6677     }
6678     return SDValue();
6679   }
6680
6681   // A vector full of immediates; various special cases are already
6682   // handled, so this is best done with a single constant-pool load.
6683   if (IsAllConstants)
6684     return SDValue();
6685
6686   // For AVX-length vectors, build the individual 128-bit pieces and use
6687   // shuffles to put them in place.
6688   if (VT.is256BitVector() || VT.is512BitVector()) {
6689     SmallVector<SDValue, 64> V;
6690     for (unsigned i = 0; i != NumElems; ++i)
6691       V.push_back(Op.getOperand(i));
6692
6693     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6694
6695     // Build both the lower and upper subvector.
6696     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6697                                 makeArrayRef(&V[0], NumElems/2));
6698     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6699                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6700
6701     // Recreate the wider vector with the lower and upper part.
6702     if (VT.is256BitVector())
6703       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6704     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6705   }
6706
6707   // Let legalizer expand 2-wide build_vectors.
6708   if (EVTBits == 64) {
6709     if (NumNonZero == 1) {
6710       // One half is zero or undef.
6711       unsigned Idx = countTrailingZeros(NonZeros);
6712       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6713                                  Op.getOperand(Idx));
6714       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6715     }
6716     return SDValue();
6717   }
6718
6719   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6720   if (EVTBits == 8 && NumElems == 16) {
6721     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6722                                         Subtarget, *this);
6723     if (V.getNode()) return V;
6724   }
6725
6726   if (EVTBits == 16 && NumElems == 8) {
6727     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6728                                       Subtarget, *this);
6729     if (V.getNode()) return V;
6730   }
6731
6732   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6733   if (EVTBits == 32 && NumElems == 4) {
6734     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6735                                       NumZero, DAG, Subtarget, *this);
6736     if (V.getNode())
6737       return V;
6738   }
6739
6740   // If element VT is == 32 bits, turn it into a number of shuffles.
6741   SmallVector<SDValue, 8> V(NumElems);
6742   if (NumElems == 4 && NumZero > 0) {
6743     for (unsigned i = 0; i < 4; ++i) {
6744       bool isZero = !(NonZeros & (1 << i));
6745       if (isZero)
6746         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6747       else
6748         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6749     }
6750
6751     for (unsigned i = 0; i < 2; ++i) {
6752       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6753         default: break;
6754         case 0:
6755           V[i] = V[i*2];  // Must be a zero vector.
6756           break;
6757         case 1:
6758           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6759           break;
6760         case 2:
6761           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6762           break;
6763         case 3:
6764           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6765           break;
6766       }
6767     }
6768
6769     bool Reverse1 = (NonZeros & 0x3) == 2;
6770     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6771     int MaskVec[] = {
6772       Reverse1 ? 1 : 0,
6773       Reverse1 ? 0 : 1,
6774       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6775       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6776     };
6777     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6778   }
6779
6780   if (Values.size() > 1 && VT.is128BitVector()) {
6781     // Check for a build vector of consecutive loads.
6782     for (unsigned i = 0; i < NumElems; ++i)
6783       V[i] = Op.getOperand(i);
6784
6785     // Check for elements which are consecutive loads.
6786     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6787     if (LD.getNode())
6788       return LD;
6789
6790     // Check for a build vector from mostly shuffle plus few inserting.
6791     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6792     if (Sh.getNode())
6793       return Sh;
6794
6795     // For SSE 4.1, use insertps to put the high elements into the low element.
6796     if (getSubtarget()->hasSSE41()) {
6797       SDValue Result;
6798       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6799         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6800       else
6801         Result = DAG.getUNDEF(VT);
6802
6803       for (unsigned i = 1; i < NumElems; ++i) {
6804         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6805         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6806                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6807       }
6808       return Result;
6809     }
6810
6811     // Otherwise, expand into a number of unpckl*, start by extending each of
6812     // our (non-undef) elements to the full vector width with the element in the
6813     // bottom slot of the vector (which generates no code for SSE).
6814     for (unsigned i = 0; i < NumElems; ++i) {
6815       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6816         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6817       else
6818         V[i] = DAG.getUNDEF(VT);
6819     }
6820
6821     // Next, we iteratively mix elements, e.g. for v4f32:
6822     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6823     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6824     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6825     unsigned EltStride = NumElems >> 1;
6826     while (EltStride != 0) {
6827       for (unsigned i = 0; i < EltStride; ++i) {
6828         // If V[i+EltStride] is undef and this is the first round of mixing,
6829         // then it is safe to just drop this shuffle: V[i] is already in the
6830         // right place, the one element (since it's the first round) being
6831         // inserted as undef can be dropped.  This isn't safe for successive
6832         // rounds because they will permute elements within both vectors.
6833         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6834             EltStride == NumElems/2)
6835           continue;
6836
6837         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6838       }
6839       EltStride >>= 1;
6840     }
6841     return V[0];
6842   }
6843   return SDValue();
6844 }
6845
6846 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6847 // to create 256-bit vectors from two other 128-bit ones.
6848 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6849   SDLoc dl(Op);
6850   MVT ResVT = Op.getSimpleValueType();
6851
6852   assert((ResVT.is256BitVector() ||
6853           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6854
6855   SDValue V1 = Op.getOperand(0);
6856   SDValue V2 = Op.getOperand(1);
6857   unsigned NumElems = ResVT.getVectorNumElements();
6858   if(ResVT.is256BitVector())
6859     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6860
6861   if (Op.getNumOperands() == 4) {
6862     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6863                                 ResVT.getVectorNumElements()/2);
6864     SDValue V3 = Op.getOperand(2);
6865     SDValue V4 = Op.getOperand(3);
6866     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6867       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6868   }
6869   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6870 }
6871
6872 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6873   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6874   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6875          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6876           Op.getNumOperands() == 4)));
6877
6878   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6879   // from two other 128-bit ones.
6880
6881   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6882   return LowerAVXCONCAT_VECTORS(Op, DAG);
6883 }
6884
6885
6886 //===----------------------------------------------------------------------===//
6887 // Vector shuffle lowering
6888 //
6889 // This is an experimental code path for lowering vector shuffles on x86. It is
6890 // designed to handle arbitrary vector shuffles and blends, gracefully
6891 // degrading performance as necessary. It works hard to recognize idiomatic
6892 // shuffles and lower them to optimal instruction patterns without leaving
6893 // a framework that allows reasonably efficient handling of all vector shuffle
6894 // patterns.
6895 //===----------------------------------------------------------------------===//
6896
6897 /// \brief Tiny helper function to identify a no-op mask.
6898 ///
6899 /// This is a somewhat boring predicate function. It checks whether the mask
6900 /// array input, which is assumed to be a single-input shuffle mask of the kind
6901 /// used by the X86 shuffle instructions (not a fully general
6902 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6903 /// in-place shuffle are 'no-op's.
6904 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6905   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6906     if (Mask[i] != -1 && Mask[i] != i)
6907       return false;
6908   return true;
6909 }
6910
6911 /// \brief Helper function to classify a mask as a single-input mask.
6912 ///
6913 /// This isn't a generic single-input test because in the vector shuffle
6914 /// lowering we canonicalize single inputs to be the first input operand. This
6915 /// means we can more quickly test for a single input by only checking whether
6916 /// an input from the second operand exists. We also assume that the size of
6917 /// mask corresponds to the size of the input vectors which isn't true in the
6918 /// fully general case.
6919 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6920   for (int M : Mask)
6921     if (M >= (int)Mask.size())
6922       return false;
6923   return true;
6924 }
6925
6926 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6927 ///
6928 /// This helper function produces an 8-bit shuffle immediate corresponding to
6929 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6930 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6931 /// example.
6932 ///
6933 /// NB: We rely heavily on "undef" masks preserving the input lane.
6934 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6935                                           SelectionDAG &DAG) {
6936   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6937   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6938   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6939   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6940   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6941
6942   unsigned Imm = 0;
6943   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6944   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6945   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6946   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6947   return DAG.getConstant(Imm, MVT::i8);
6948 }
6949
6950 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6951 ///
6952 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6953 /// support for floating point shuffles but not integer shuffles. These
6954 /// instructions will incur a domain crossing penalty on some chips though so
6955 /// it is better to avoid lowering through this for integer vectors where
6956 /// possible.
6957 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6958                                        const X86Subtarget *Subtarget,
6959                                        SelectionDAG &DAG) {
6960   SDLoc DL(Op);
6961   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6962   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6963   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6965   ArrayRef<int> Mask = SVOp->getMask();
6966   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6967
6968   if (isSingleInputShuffleMask(Mask)) {
6969     // Straight shuffle of a single input vector. Simulate this by using the
6970     // single input as both of the "inputs" to this instruction..
6971     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6972     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6973                        DAG.getConstant(SHUFPDMask, MVT::i8));
6974   }
6975   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6976   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6977
6978   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6979   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6980                      DAG.getConstant(SHUFPDMask, MVT::i8));
6981 }
6982
6983 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6984 ///
6985 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6986 /// the integer unit to minimize domain crossing penalties. However, for blends
6987 /// it falls back to the floating point shuffle operation with appropriate bit
6988 /// casting.
6989 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6990                                        const X86Subtarget *Subtarget,
6991                                        SelectionDAG &DAG) {
6992   SDLoc DL(Op);
6993   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6994   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6995   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6997   ArrayRef<int> Mask = SVOp->getMask();
6998   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6999
7000   if (isSingleInputShuffleMask(Mask)) {
7001     // Straight shuffle of a single input vector. For everything from SSE2
7002     // onward this has a single fast instruction with no scary immediates.
7003     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7004     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7005     int WidenedMask[4] = {
7006         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7007         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7008     return DAG.getNode(
7009         ISD::BITCAST, DL, MVT::v2i64,
7010         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7011                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7012   }
7013
7014   // We implement this with SHUFPD which is pretty lame because it will likely
7015   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7016   // However, all the alternatives are still more cycles and newer chips don't
7017   // have this problem. It would be really nice if x86 had better shuffles here.
7018   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7019   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7020   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7021                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7022 }
7023
7024 /// \brief Lower 4-lane 32-bit floating point shuffles.
7025 ///
7026 /// Uses instructions exclusively from the floating point unit to minimize
7027 /// domain crossing penalties, as these are sufficient to implement all v4f32
7028 /// shuffles.
7029 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7030                                        const X86Subtarget *Subtarget,
7031                                        SelectionDAG &DAG) {
7032   SDLoc DL(Op);
7033   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7034   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7035   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7037   ArrayRef<int> Mask = SVOp->getMask();
7038   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7039
7040   SDValue LowV = V1, HighV = V2;
7041   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7042
7043   int NumV2Elements =
7044       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7045
7046   if (NumV2Elements == 0)
7047     // Straight shuffle of a single input vector. We pass the input vector to
7048     // both operands to simulate this with a SHUFPS.
7049     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7050                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7051
7052   if (NumV2Elements == 1) {
7053     int V2Index =
7054         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7055         Mask.begin();
7056     // Compute the index adjacent to V2Index and in the same half by toggling
7057     // the low bit.
7058     int V2AdjIndex = V2Index ^ 1;
7059
7060     if (Mask[V2AdjIndex] == -1) {
7061       // Handles all the cases where we have a single V2 element and an undef.
7062       // This will only ever happen in the high lanes because we commute the
7063       // vector otherwise.
7064       if (V2Index < 2)
7065         std::swap(LowV, HighV);
7066       NewMask[V2Index] -= 4;
7067     } else {
7068       // Handle the case where the V2 element ends up adjacent to a V1 element.
7069       // To make this work, blend them together as the first step.
7070       int V1Index = V2AdjIndex;
7071       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7072       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7073                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7074
7075       // Now proceed to reconstruct the final blend as we have the necessary
7076       // high or low half formed.
7077       if (V2Index < 2) {
7078         LowV = V2;
7079         HighV = V1;
7080       } else {
7081         HighV = V2;
7082       }
7083       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7084       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7085     }
7086   } else if (NumV2Elements == 2) {
7087     if (Mask[0] < 4 && Mask[1] < 4) {
7088       // Handle the easy case where we have V1 in the low lanes and V2 in the
7089       // high lanes. We never see this reversed because we sort the shuffle.
7090       NewMask[2] -= 4;
7091       NewMask[3] -= 4;
7092     } else {
7093       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7094       // trying to place elements directly, just blend them and set up the final
7095       // shuffle to place them.
7096
7097       // The first two blend mask elements are for V1, the second two are for
7098       // V2.
7099       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7100                           Mask[2] < 4 ? Mask[2] : Mask[3],
7101                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7102                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7103       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7104                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7105
7106       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7107       // a blend.
7108       LowV = HighV = V1;
7109       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7110       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7111       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7112       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7113     }
7114   }
7115   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7116                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7117 }
7118
7119 /// \brief Lower 4-lane i32 vector shuffles.
7120 ///
7121 /// We try to handle these with integer-domain shuffles where we can, but for
7122 /// blends we use the floating point domain blend instructions.
7123 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7124                                        const X86Subtarget *Subtarget,
7125                                        SelectionDAG &DAG) {
7126   SDLoc DL(Op);
7127   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7128   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7129   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131   ArrayRef<int> Mask = SVOp->getMask();
7132   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7133
7134   if (isSingleInputShuffleMask(Mask))
7135     // Straight shuffle of a single input vector. For everything from SSE2
7136     // onward this has a single fast instruction with no scary immediates.
7137     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7138                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7139
7140   // We implement this with SHUFPS because it can blend from two vectors.
7141   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7142   // up the inputs, bypassing domain shift penalties that we would encur if we
7143   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7144   // relevant.
7145   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7146                      DAG.getVectorShuffle(
7147                          MVT::v4f32, DL,
7148                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7149                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7150 }
7151
7152 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7153 /// shuffle lowering, and the most complex part.
7154 ///
7155 /// The lowering strategy is to try to form pairs of input lanes which are
7156 /// targeted at the same half of the final vector, and then use a dword shuffle
7157 /// to place them onto the right half, and finally unpack the paired lanes into
7158 /// their final position.
7159 ///
7160 /// The exact breakdown of how to form these dword pairs and align them on the
7161 /// correct sides is really tricky. See the comments within the function for
7162 /// more of the details.
7163 static SDValue lowerV8I16SingleInputVectorShuffle(
7164     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7165     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7166   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7167   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7168   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7169
7170   SmallVector<int, 4> LoInputs;
7171   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7172                [](int M) { return M >= 0; });
7173   std::sort(LoInputs.begin(), LoInputs.end());
7174   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7175   SmallVector<int, 4> HiInputs;
7176   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7177                [](int M) { return M >= 0; });
7178   std::sort(HiInputs.begin(), HiInputs.end());
7179   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7180   int NumLToL =
7181       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7182   int NumHToL = LoInputs.size() - NumLToL;
7183   int NumLToH =
7184       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7185   int NumHToH = HiInputs.size() - NumLToH;
7186   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7187   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7188   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7189   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7190
7191   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7192   // such inputs we can swap two of the dwords across the half mark and end up
7193   // with <=2 inputs to each half in each half. Once there, we can fall through
7194   // to the generic code below. For example:
7195   //
7196   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7197   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7198   //
7199   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7200   // and 2-2.
7201   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7202                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7203     // Compute the index of dword with only one word among the three inputs in
7204     // a half by taking the sum of the half with three inputs and subtracting
7205     // the sum of the actual three inputs. The difference is the remaining
7206     // slot.
7207     int DWordA = (ThreeInputHalfSum -
7208                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7209                  2;
7210     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7211
7212     int PSHUFDMask[] = {0, 1, 2, 3};
7213     PSHUFDMask[DWordA] = DWordB;
7214     PSHUFDMask[DWordB] = DWordA;
7215     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7216                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7217                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7218                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7219
7220     // Adjust the mask to match the new locations of A and B.
7221     for (int &M : Mask)
7222       if (M != -1 && M/2 == DWordA)
7223         M = 2 * DWordB + M % 2;
7224       else if (M != -1 && M/2 == DWordB)
7225         M = 2 * DWordA + M % 2;
7226
7227     // Recurse back into this routine to re-compute state now that this isn't
7228     // a 3 and 1 problem.
7229     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7230                                 Mask);
7231   };
7232   if (NumLToL == 3 && NumHToL == 1)
7233     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7234   else if (NumLToL == 1 && NumHToL == 3)
7235     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7236   else if (NumLToH == 1 && NumHToH == 3)
7237     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7238   else if (NumLToH == 3 && NumHToH == 1)
7239     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7240
7241   // At this point there are at most two inputs to the low and high halves from
7242   // each half. That means the inputs can always be grouped into dwords and
7243   // those dwords can then be moved to the correct half with a dword shuffle.
7244   // We use at most one low and one high word shuffle to collect these paired
7245   // inputs into dwords, and finally a dword shuffle to place them.
7246   int PSHUFLMask[4] = {-1, -1, -1, -1};
7247   int PSHUFHMask[4] = {-1, -1, -1, -1};
7248   int PSHUFDMask[4] = {-1, -1, -1, -1};
7249
7250   // First fix the masks for all the inputs that are staying in their
7251   // original halves. This will then dictate the targets of the cross-half
7252   // shuffles.
7253   auto fixInPlaceInputs = [&PSHUFDMask](
7254       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7255       MutableArrayRef<int> HalfMask, int HalfOffset) {
7256     if (InPlaceInputs.empty())
7257       return;
7258     if (InPlaceInputs.size() == 1) {
7259       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7260           InPlaceInputs[0] - HalfOffset;
7261       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7262       return;
7263     }
7264
7265     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7266     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7267         InPlaceInputs[0] - HalfOffset;
7268     // Put the second input next to the first so that they are packed into
7269     // a dword. We find the adjacent index by toggling the low bit.
7270     int AdjIndex = InPlaceInputs[0] ^ 1;
7271     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7272     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7273     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7274   };
7275   if (!HToLInputs.empty())
7276     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7277   if (!LToHInputs.empty())
7278     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7279
7280   // Now gather the cross-half inputs and place them into a free dword of
7281   // their target half.
7282   // FIXME: This operation could almost certainly be simplified dramatically to
7283   // look more like the 3-1 fixing operation.
7284   auto moveInputsToRightHalf = [&PSHUFDMask](
7285       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7286       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7287       int SourceOffset, int DestOffset) {
7288     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7289       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7290     };
7291     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7292                                                int Word) {
7293       int LowWord = Word & ~1;
7294       int HighWord = Word | 1;
7295       return isWordClobbered(SourceHalfMask, LowWord) ||
7296              isWordClobbered(SourceHalfMask, HighWord);
7297     };
7298
7299     if (IncomingInputs.empty())
7300       return;
7301
7302     if (ExistingInputs.empty()) {
7303       // Map any dwords with inputs from them into the right half.
7304       for (int Input : IncomingInputs) {
7305         // If the source half mask maps over the inputs, turn those into
7306         // swaps and use the swapped lane.
7307         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7308           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7309             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7310                 Input - SourceOffset;
7311             // We have to swap the uses in our half mask in one sweep.
7312             for (int &M : HalfMask)
7313               if (M == SourceHalfMask[Input - SourceOffset])
7314                 M = Input;
7315               else if (M == Input)
7316                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7317           } else {
7318             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7319                        Input - SourceOffset &&
7320                    "Previous placement doesn't match!");
7321           }
7322           // Note that this correctly re-maps both when we do a swap and when
7323           // we observe the other side of the swap above. We rely on that to
7324           // avoid swapping the members of the input list directly.
7325           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7326         }
7327
7328         // Map the input's dword into the correct half.
7329         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7330           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7331         else
7332           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7333                      Input / 2 &&
7334                  "Previous placement doesn't match!");
7335       }
7336
7337       // And just directly shift any other-half mask elements to be same-half
7338       // as we will have mirrored the dword containing the element into the
7339       // same position within that half.
7340       for (int &M : HalfMask)
7341         if (M >= SourceOffset && M < SourceOffset + 4) {
7342           M = M - SourceOffset + DestOffset;
7343           assert(M >= 0 && "This should never wrap below zero!");
7344         }
7345       return;
7346     }
7347
7348     // Ensure we have the input in a viable dword of its current half. This
7349     // is particularly tricky because the original position may be clobbered
7350     // by inputs being moved and *staying* in that half.
7351     if (IncomingInputs.size() == 1) {
7352       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7353         int InputFixed = std::find(std::begin(SourceHalfMask),
7354                                    std::end(SourceHalfMask), -1) -
7355                          std::begin(SourceHalfMask) + SourceOffset;
7356         SourceHalfMask[InputFixed - SourceOffset] =
7357             IncomingInputs[0] - SourceOffset;
7358         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7359                      InputFixed);
7360         IncomingInputs[0] = InputFixed;
7361       }
7362     } else if (IncomingInputs.size() == 2) {
7363       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7364           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7365         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7366         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7367                "Not all dwords can be clobbered!");
7368         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7369         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7370         for (int &M : HalfMask)
7371           if (M == IncomingInputs[0])
7372             M = SourceDWordBase + SourceOffset;
7373           else if (M == IncomingInputs[1])
7374             M = SourceDWordBase + 1 + SourceOffset;
7375         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7376         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7377       }
7378     } else {
7379       llvm_unreachable("Unhandled input size!");
7380     }
7381
7382     // Now hoist the DWord down to the right half.
7383     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7384     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7385     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7386     for (int Input : IncomingInputs)
7387       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7388                    FreeDWord * 2 + Input % 2);
7389   };
7390   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7391                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7392   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7393                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7394
7395   // Now enact all the shuffles we've computed to move the inputs into their
7396   // target half.
7397   if (!isNoopShuffleMask(PSHUFLMask))
7398     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7399                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7400   if (!isNoopShuffleMask(PSHUFHMask))
7401     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7402                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7403   if (!isNoopShuffleMask(PSHUFDMask))
7404     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7405                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7406                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7407                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7408
7409   // At this point, each half should contain all its inputs, and we can then
7410   // just shuffle them into their final position.
7411   assert(std::count_if(LoMask.begin(), LoMask.end(),
7412                        [](int M) { return M >= 4; }) == 0 &&
7413          "Failed to lift all the high half inputs to the low mask!");
7414   assert(std::count_if(HiMask.begin(), HiMask.end(),
7415                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7416          "Failed to lift all the low half inputs to the high mask!");
7417
7418   // Do a half shuffle for the low mask.
7419   if (!isNoopShuffleMask(LoMask))
7420     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7421                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7422
7423   // Do a half shuffle with the high mask after shifting its values down.
7424   for (int &M : HiMask)
7425     if (M >= 0)
7426       M -= 4;
7427   if (!isNoopShuffleMask(HiMask))
7428     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7429                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7430
7431   return V;
7432 }
7433
7434 /// \brief Detect whether the mask pattern should be lowered through
7435 /// interleaving.
7436 ///
7437 /// This essentially tests whether viewing the mask as an interleaving of two
7438 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7439 /// lowering it through interleaving is a significantly better strategy.
7440 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7441   int NumEvenInputs[2] = {0, 0};
7442   int NumOddInputs[2] = {0, 0};
7443   int NumLoInputs[2] = {0, 0};
7444   int NumHiInputs[2] = {0, 0};
7445   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7446     if (Mask[i] < 0)
7447       continue;
7448
7449     int InputIdx = Mask[i] >= Size;
7450
7451     if (i < Size / 2)
7452       ++NumLoInputs[InputIdx];
7453     else
7454       ++NumHiInputs[InputIdx];
7455
7456     if ((i % 2) == 0)
7457       ++NumEvenInputs[InputIdx];
7458     else
7459       ++NumOddInputs[InputIdx];
7460   }
7461
7462   // The minimum number of cross-input results for both the interleaved and
7463   // split cases. If interleaving results in fewer cross-input results, return
7464   // true.
7465   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7466                                     NumEvenInputs[0] + NumOddInputs[1]);
7467   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7468                               NumLoInputs[0] + NumHiInputs[1]);
7469   return InterleavedCrosses < SplitCrosses;
7470 }
7471
7472 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7473 ///
7474 /// This strategy only works when the inputs from each vector fit into a single
7475 /// half of that vector, and generally there are not so many inputs as to leave
7476 /// the in-place shuffles required highly constrained (and thus expensive). It
7477 /// shifts all the inputs into a single side of both input vectors and then
7478 /// uses an unpack to interleave these inputs in a single vector. At that
7479 /// point, we will fall back on the generic single input shuffle lowering.
7480 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7481                                                  SDValue V2,
7482                                                  MutableArrayRef<int> Mask,
7483                                                  const X86Subtarget *Subtarget,
7484                                                  SelectionDAG &DAG) {
7485   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7486   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7488   for (int i = 0; i < 8; ++i)
7489     if (Mask[i] >= 0 && Mask[i] < 4)
7490       LoV1Inputs.push_back(i);
7491     else if (Mask[i] >= 4 && Mask[i] < 8)
7492       HiV1Inputs.push_back(i);
7493     else if (Mask[i] >= 8 && Mask[i] < 12)
7494       LoV2Inputs.push_back(i);
7495     else if (Mask[i] >= 12)
7496       HiV2Inputs.push_back(i);
7497
7498   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7499   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7500   (void)NumV1Inputs;
7501   (void)NumV2Inputs;
7502   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7503   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7504   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7505
7506   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7507                      HiV1Inputs.size() + HiV2Inputs.size();
7508
7509   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7510                               ArrayRef<int> HiInputs, bool MoveToLo,
7511                               int MaskOffset) {
7512     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7513     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7514     if (BadInputs.empty())
7515       return V;
7516
7517     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7518     int MoveOffset = MoveToLo ? 0 : 4;
7519
7520     if (GoodInputs.empty()) {
7521       for (int BadInput : BadInputs) {
7522         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7523         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7524       }
7525     } else {
7526       if (GoodInputs.size() == 2) {
7527         // If the low inputs are spread across two dwords, pack them into
7528         // a single dword.
7529         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7530             Mask[GoodInputs[0]] - MaskOffset;
7531         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7532             Mask[GoodInputs[1]] - MaskOffset;
7533         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7534         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7535       } else {
7536         // Otherwise pin the low inputs.
7537         for (int GoodInput : GoodInputs)
7538           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7539       }
7540
7541       int MoveMaskIdx =
7542           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7543           std::begin(MoveMask);
7544       assert(MoveMaskIdx >= MoveOffset && "Established above");
7545
7546       if (BadInputs.size() == 2) {
7547         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7548         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7549         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7550             Mask[BadInputs[0]] - MaskOffset;
7551         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7552             Mask[BadInputs[1]] - MaskOffset;
7553         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7554         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7555       } else {
7556         assert(BadInputs.size() == 1 && "All sizes handled");
7557         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7558         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7559       }
7560     }
7561
7562     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7563                                 MoveMask);
7564   };
7565   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7566                         /*MaskOffset*/ 0);
7567   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7568                         /*MaskOffset*/ 8);
7569
7570   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7571   // cross-half traffic in the final shuffle.
7572
7573   // Munge the mask to be a single-input mask after the unpack merges the
7574   // results.
7575   for (int &M : Mask)
7576     if (M != -1)
7577       M = 2 * (M % 4) + (M / 8);
7578
7579   return DAG.getVectorShuffle(
7580       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7581                                   DL, MVT::v8i16, V1, V2),
7582       DAG.getUNDEF(MVT::v8i16), Mask);
7583 }
7584
7585 /// \brief Generic lowering of 8-lane i16 shuffles.
7586 ///
7587 /// This handles both single-input shuffles and combined shuffle/blends with
7588 /// two inputs. The single input shuffles are immediately delegated to
7589 /// a dedicated lowering routine.
7590 ///
7591 /// The blends are lowered in one of three fundamental ways. If there are few
7592 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7593 /// of the input is significantly cheaper when lowered as an interleaving of
7594 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7595 /// halves of the inputs separately (making them have relatively few inputs)
7596 /// and then concatenate them.
7597 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7598                                        const X86Subtarget *Subtarget,
7599                                        SelectionDAG &DAG) {
7600   SDLoc DL(Op);
7601   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7602   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7603   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7605   ArrayRef<int> OrigMask = SVOp->getMask();
7606   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7607                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7608   MutableArrayRef<int> Mask(MaskStorage);
7609
7610   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7611
7612   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7613   auto isV2 = [](int M) { return M >= 8; };
7614
7615   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7616   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7617
7618   if (NumV2Inputs == 0)
7619     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7620
7621   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7622                             "to be V1-input shuffles.");
7623
7624   if (NumV1Inputs + NumV2Inputs <= 4)
7625     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7626
7627   // Check whether an interleaving lowering is likely to be more efficient.
7628   // This isn't perfect but it is a strong heuristic that tends to work well on
7629   // the kinds of shuffles that show up in practice.
7630   //
7631   // FIXME: Handle 1x, 2x, and 4x interleaving.
7632   if (shouldLowerAsInterleaving(Mask)) {
7633     // FIXME: Figure out whether we should pack these into the low or high
7634     // halves.
7635
7636     int EMask[8], OMask[8];
7637     for (int i = 0; i < 4; ++i) {
7638       EMask[i] = Mask[2*i];
7639       OMask[i] = Mask[2*i + 1];
7640       EMask[i + 4] = -1;
7641       OMask[i + 4] = -1;
7642     }
7643
7644     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7645     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7646
7647     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7648   }
7649
7650   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7651   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7652
7653   for (int i = 0; i < 4; ++i) {
7654     LoBlendMask[i] = Mask[i];
7655     HiBlendMask[i] = Mask[i + 4];
7656   }
7657
7658   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7659   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7660   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7661   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7662
7663   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7664                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7665 }
7666
7667 /// \brief Generic lowering of v16i8 shuffles.
7668 ///
7669 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7670 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7671 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7672 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7673 /// back together.
7674 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7675                                        const X86Subtarget *Subtarget,
7676                                        SelectionDAG &DAG) {
7677   SDLoc DL(Op);
7678   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7679   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7680   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7681   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7682   ArrayRef<int> OrigMask = SVOp->getMask();
7683   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7684   int MaskStorage[16] = {
7685       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7686       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7687       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7688       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7689   MutableArrayRef<int> Mask(MaskStorage);
7690   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7691   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7692
7693   // For single-input shuffles, there are some nicer lowering tricks we can use.
7694   if (isSingleInputShuffleMask(Mask)) {
7695     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7696     // Notably, this handles splat and partial-splat shuffles more efficiently.
7697     //
7698     // FIXME: We should check for other patterns which can be widened into an
7699     // i16 shuffle as well.
7700     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7701       for (int i = 0; i < 16; i += 2) {
7702         if (Mask[i] != Mask[i + 1])
7703           return false;
7704       }
7705       return true;
7706     };
7707     if (canWidenViaDuplication(Mask)) {
7708       SmallVector<int, 4> LoInputs;
7709       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7710                    [](int M) { return M >= 0 && M < 8; });
7711       std::sort(LoInputs.begin(), LoInputs.end());
7712       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7713                      LoInputs.end());
7714       SmallVector<int, 4> HiInputs;
7715       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7716                    [](int M) { return M >= 8; });
7717       std::sort(HiInputs.begin(), HiInputs.end());
7718       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7719                      HiInputs.end());
7720
7721       bool TargetLo = LoInputs.size() >= HiInputs.size();
7722       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7723       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7724
7725       int ByteMask[16];
7726       SmallDenseMap<int, int, 8> LaneMap;
7727       for (int i = 0; i < 16; ++i)
7728         ByteMask[i] = -1;
7729       for (int I : InPlaceInputs) {
7730         ByteMask[I] = I;
7731         LaneMap[I] = I;
7732       }
7733       int FreeByteIdx = 0;
7734       int TargetOffset = TargetLo ? 0 : 8;
7735       for (int I : MovingInputs) {
7736         // Walk the free index into the byte mask until we find an unoccupied
7737         // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7738         // principle indicates that there *must* be a spot as we can only have
7739         // 8 duplicated inputs. We have to walk the index using modular
7740         // arithmetic to wrap around as necessary.
7741         // FIXME: We could do a much better job of picking an inexpensive slot
7742         // so this doesn't go through the worst case for the byte shuffle.
7743         for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7744              ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7745           ;
7746         assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7747                "Failed to find a free byte!");
7748         ByteMask[FreeByteIdx + TargetOffset] = I;
7749         LaneMap[I] = FreeByteIdx + TargetOffset;
7750       }
7751       V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7752                                 ByteMask);
7753       for (int &M : Mask)
7754         if (M != -1)
7755           M = LaneMap[M];
7756
7757       // Unpack the bytes to form the i16s that will be shuffled into place.
7758       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7759                        MVT::v16i8, V1, V1);
7760
7761       int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7762       for (int i = 0; i < 16; i += 2) {
7763         if (Mask[i] != -1)
7764           I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7765         assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7766       }
7767       return DAG.getVectorShuffle(MVT::v8i16, DL,
7768                                   DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7769                                   DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7770     }
7771   }
7772
7773   // Check whether an interleaving lowering is likely to be more efficient.
7774   // This isn't perfect but it is a strong heuristic that tends to work well on
7775   // the kinds of shuffles that show up in practice.
7776   //
7777   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7778   if (shouldLowerAsInterleaving(Mask)) {
7779     // FIXME: Figure out whether we should pack these into the low or high
7780     // halves.
7781
7782     int EMask[16], OMask[16];
7783     for (int i = 0; i < 8; ++i) {
7784       EMask[i] = Mask[2*i];
7785       OMask[i] = Mask[2*i + 1];
7786       EMask[i + 8] = -1;
7787       OMask[i + 8] = -1;
7788     }
7789
7790     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7791     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7792
7793     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7794   }
7795   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7796   SDValue LoV1 =
7797       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7798                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7799   SDValue HiV1 =
7800       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7801                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7802   SDValue LoV2 =
7803       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7804                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7805   SDValue HiV2 =
7806       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7807                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7808
7809   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7810   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7811   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7812   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7813
7814   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7815                             MutableArrayRef<int> V1HalfBlendMask,
7816                             MutableArrayRef<int> V2HalfBlendMask) {
7817     for (int i = 0; i < 8; ++i)
7818       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7819         V1HalfBlendMask[i] = HalfMask[i];
7820         HalfMask[i] = i;
7821       } else if (HalfMask[i] >= 16) {
7822         V2HalfBlendMask[i] = HalfMask[i] - 16;
7823         HalfMask[i] = i + 8;
7824       }
7825   };
7826   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7827   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7828
7829   SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7830   SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7831   SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7832   SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7833
7834   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7835   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7836
7837   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7838 }
7839
7840 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7841 ///
7842 /// This routine breaks down the specific type of 128-bit shuffle and
7843 /// dispatches to the lowering routines accordingly.
7844 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7845                                         MVT VT, const X86Subtarget *Subtarget,
7846                                         SelectionDAG &DAG) {
7847   switch (VT.SimpleTy) {
7848   case MVT::v2i64:
7849     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7850   case MVT::v2f64:
7851     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7852   case MVT::v4i32:
7853     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7854   case MVT::v4f32:
7855     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7856   case MVT::v8i16:
7857     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7858   case MVT::v16i8:
7859     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7860
7861   default:
7862     llvm_unreachable("Unimplemented!");
7863   }
7864 }
7865
7866 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7867 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7868   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7869     if (Mask[i] + 1 != Mask[i+1])
7870       return false;
7871
7872   return true;
7873 }
7874
7875 /// \brief Top-level lowering for x86 vector shuffles.
7876 ///
7877 /// This handles decomposition, canonicalization, and lowering of all x86
7878 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7879 /// above in helper routines. The canonicalization attempts to widen shuffles
7880 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7881 /// s.t. only one of the two inputs needs to be tested, etc.
7882 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7883                                   SelectionDAG &DAG) {
7884   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7885   ArrayRef<int> Mask = SVOp->getMask();
7886   SDValue V1 = Op.getOperand(0);
7887   SDValue V2 = Op.getOperand(1);
7888   MVT VT = Op.getSimpleValueType();
7889   int NumElements = VT.getVectorNumElements();
7890   SDLoc dl(Op);
7891
7892   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7893
7894   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7895   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7896   if (V1IsUndef && V2IsUndef)
7897     return DAG.getUNDEF(VT);
7898
7899   // When we create a shuffle node we put the UNDEF node to second operand,
7900   // but in some cases the first operand may be transformed to UNDEF.
7901   // In this case we should just commute the node.
7902   if (V1IsUndef)
7903     return CommuteVectorShuffle(SVOp, DAG);
7904
7905   // Check for non-undef masks pointing at an undef vector and make the masks
7906   // undef as well. This makes it easier to match the shuffle based solely on
7907   // the mask.
7908   if (V2IsUndef)
7909     for (int M : Mask)
7910       if (M >= NumElements) {
7911         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7912         for (int &M : NewMask)
7913           if (M >= NumElements)
7914             M = -1;
7915         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7916       }
7917
7918   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7919   // lanes but wider integers. We cap this to not form integers larger than i64
7920   // but it might be interesting to form i128 integers to handle flipping the
7921   // low and high halves of AVX 256-bit vectors.
7922   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7923       areAdjacentMasksSequential(Mask)) {
7924     SmallVector<int, 8> NewMask;
7925     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7926       NewMask.push_back(Mask[i] / 2);
7927     MVT NewVT =
7928         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7929                          VT.getVectorNumElements() / 2);
7930     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7931     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7932     return DAG.getNode(ISD::BITCAST, dl, VT,
7933                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7934   }
7935
7936   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7937   for (int M : SVOp->getMask())
7938     if (M < 0)
7939       ++NumUndefElements;
7940     else if (M < NumElements)
7941       ++NumV1Elements;
7942     else
7943       ++NumV2Elements;
7944
7945   // Commute the shuffle as needed such that more elements come from V1 than
7946   // V2. This allows us to match the shuffle pattern strictly on how many
7947   // elements come from V1 without handling the symmetric cases.
7948   if (NumV2Elements > NumV1Elements)
7949     return CommuteVectorShuffle(SVOp, DAG);
7950
7951   // When the number of V1 and V2 elements are the same, try to minimize the
7952   // number of uses of V2 in the low half of the vector.
7953   if (NumV1Elements == NumV2Elements) {
7954     int LowV1Elements = 0, LowV2Elements = 0;
7955     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7956       if (M >= NumElements)
7957         ++LowV2Elements;
7958       else if (M >= 0)
7959         ++LowV1Elements;
7960     if (LowV2Elements > LowV1Elements)
7961       return CommuteVectorShuffle(SVOp, DAG);
7962   }
7963
7964   // For each vector width, delegate to a specialized lowering routine.
7965   if (VT.getSizeInBits() == 128)
7966     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7967
7968   llvm_unreachable("Unimplemented!");
7969 }
7970
7971
7972 //===----------------------------------------------------------------------===//
7973 // Legacy vector shuffle lowering
7974 //
7975 // This code is the legacy code handling vector shuffles until the above
7976 // replaces its functionality and performance.
7977 //===----------------------------------------------------------------------===//
7978
7979 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7980                         bool hasInt256, unsigned *MaskOut = nullptr) {
7981   MVT EltVT = VT.getVectorElementType();
7982
7983   // There is no blend with immediate in AVX-512.
7984   if (VT.is512BitVector())
7985     return false;
7986
7987   if (!hasSSE41 || EltVT == MVT::i8)
7988     return false;
7989   if (!hasInt256 && VT == MVT::v16i16)
7990     return false;
7991
7992   unsigned MaskValue = 0;
7993   unsigned NumElems = VT.getVectorNumElements();
7994   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7995   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7996   unsigned NumElemsInLane = NumElems / NumLanes;
7997
7998   // Blend for v16i16 should be symetric for the both lanes.
7999   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8000
8001     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8002     int EltIdx = MaskVals[i];
8003
8004     if ((EltIdx < 0 || EltIdx == (int)i) &&
8005         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8006       continue;
8007
8008     if (((unsigned)EltIdx == (i + NumElems)) &&
8009         (SndLaneEltIdx < 0 ||
8010          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8011       MaskValue |= (1 << i);
8012     else
8013       return false;
8014   }
8015
8016   if (MaskOut)
8017     *MaskOut = MaskValue;
8018   return true;
8019 }
8020
8021 // Try to lower a shuffle node into a simple blend instruction.
8022 // This function assumes isBlendMask returns true for this
8023 // SuffleVectorSDNode
8024 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8025                                           unsigned MaskValue,
8026                                           const X86Subtarget *Subtarget,
8027                                           SelectionDAG &DAG) {
8028   MVT VT = SVOp->getSimpleValueType(0);
8029   MVT EltVT = VT.getVectorElementType();
8030   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8031                      Subtarget->hasInt256() && "Trying to lower a "
8032                                                "VECTOR_SHUFFLE to a Blend but "
8033                                                "with the wrong mask"));
8034   SDValue V1 = SVOp->getOperand(0);
8035   SDValue V2 = SVOp->getOperand(1);
8036   SDLoc dl(SVOp);
8037   unsigned NumElems = VT.getVectorNumElements();
8038
8039   // Convert i32 vectors to floating point if it is not AVX2.
8040   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8041   MVT BlendVT = VT;
8042   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8043     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8044                                NumElems);
8045     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8046     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8047   }
8048
8049   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8050                             DAG.getConstant(MaskValue, MVT::i32));
8051   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8052 }
8053
8054 /// In vector type \p VT, return true if the element at index \p InputIdx
8055 /// falls on a different 128-bit lane than \p OutputIdx.
8056 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8057                                      unsigned OutputIdx) {
8058   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8059   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8060 }
8061
8062 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8063 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8064 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8065 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8066 /// zero.
8067 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8068                          SelectionDAG &DAG) {
8069   MVT VT = V1.getSimpleValueType();
8070   assert(VT.is128BitVector() || VT.is256BitVector());
8071
8072   MVT EltVT = VT.getVectorElementType();
8073   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8074   unsigned NumElts = VT.getVectorNumElements();
8075
8076   SmallVector<SDValue, 32> PshufbMask;
8077   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8078     int InputIdx = MaskVals[OutputIdx];
8079     unsigned InputByteIdx;
8080
8081     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8082       InputByteIdx = 0x80;
8083     else {
8084       // Cross lane is not allowed.
8085       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8086         return SDValue();
8087       InputByteIdx = InputIdx * EltSizeInBytes;
8088       // Index is an byte offset within the 128-bit lane.
8089       InputByteIdx &= 0xf;
8090     }
8091
8092     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8093       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8094       if (InputByteIdx != 0x80)
8095         ++InputByteIdx;
8096     }
8097   }
8098
8099   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8100   if (ShufVT != VT)
8101     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8102   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8103                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8104 }
8105
8106 // v8i16 shuffles - Prefer shuffles in the following order:
8107 // 1. [all]   pshuflw, pshufhw, optional move
8108 // 2. [ssse3] 1 x pshufb
8109 // 3. [ssse3] 2 x pshufb + 1 x por
8110 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8111 static SDValue
8112 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8113                          SelectionDAG &DAG) {
8114   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8115   SDValue V1 = SVOp->getOperand(0);
8116   SDValue V2 = SVOp->getOperand(1);
8117   SDLoc dl(SVOp);
8118   SmallVector<int, 8> MaskVals;
8119
8120   // Determine if more than 1 of the words in each of the low and high quadwords
8121   // of the result come from the same quadword of one of the two inputs.  Undef
8122   // mask values count as coming from any quadword, for better codegen.
8123   //
8124   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8125   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8126   unsigned LoQuad[] = { 0, 0, 0, 0 };
8127   unsigned HiQuad[] = { 0, 0, 0, 0 };
8128   // Indices of quads used.
8129   std::bitset<4> InputQuads;
8130   for (unsigned i = 0; i < 8; ++i) {
8131     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8132     int EltIdx = SVOp->getMaskElt(i);
8133     MaskVals.push_back(EltIdx);
8134     if (EltIdx < 0) {
8135       ++Quad[0];
8136       ++Quad[1];
8137       ++Quad[2];
8138       ++Quad[3];
8139       continue;
8140     }
8141     ++Quad[EltIdx / 4];
8142     InputQuads.set(EltIdx / 4);
8143   }
8144
8145   int BestLoQuad = -1;
8146   unsigned MaxQuad = 1;
8147   for (unsigned i = 0; i < 4; ++i) {
8148     if (LoQuad[i] > MaxQuad) {
8149       BestLoQuad = i;
8150       MaxQuad = LoQuad[i];
8151     }
8152   }
8153
8154   int BestHiQuad = -1;
8155   MaxQuad = 1;
8156   for (unsigned i = 0; i < 4; ++i) {
8157     if (HiQuad[i] > MaxQuad) {
8158       BestHiQuad = i;
8159       MaxQuad = HiQuad[i];
8160     }
8161   }
8162
8163   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8164   // of the two input vectors, shuffle them into one input vector so only a
8165   // single pshufb instruction is necessary. If there are more than 2 input
8166   // quads, disable the next transformation since it does not help SSSE3.
8167   bool V1Used = InputQuads[0] || InputQuads[1];
8168   bool V2Used = InputQuads[2] || InputQuads[3];
8169   if (Subtarget->hasSSSE3()) {
8170     if (InputQuads.count() == 2 && V1Used && V2Used) {
8171       BestLoQuad = InputQuads[0] ? 0 : 1;
8172       BestHiQuad = InputQuads[2] ? 2 : 3;
8173     }
8174     if (InputQuads.count() > 2) {
8175       BestLoQuad = -1;
8176       BestHiQuad = -1;
8177     }
8178   }
8179
8180   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8181   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8182   // words from all 4 input quadwords.
8183   SDValue NewV;
8184   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8185     int MaskV[] = {
8186       BestLoQuad < 0 ? 0 : BestLoQuad,
8187       BestHiQuad < 0 ? 1 : BestHiQuad
8188     };
8189     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8190                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8191                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8192     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8193
8194     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8195     // source words for the shuffle, to aid later transformations.
8196     bool AllWordsInNewV = true;
8197     bool InOrder[2] = { true, true };
8198     for (unsigned i = 0; i != 8; ++i) {
8199       int idx = MaskVals[i];
8200       if (idx != (int)i)
8201         InOrder[i/4] = false;
8202       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8203         continue;
8204       AllWordsInNewV = false;
8205       break;
8206     }
8207
8208     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8209     if (AllWordsInNewV) {
8210       for (int i = 0; i != 8; ++i) {
8211         int idx = MaskVals[i];
8212         if (idx < 0)
8213           continue;
8214         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8215         if ((idx != i) && idx < 4)
8216           pshufhw = false;
8217         if ((idx != i) && idx > 3)
8218           pshuflw = false;
8219       }
8220       V1 = NewV;
8221       V2Used = false;
8222       BestLoQuad = 0;
8223       BestHiQuad = 1;
8224     }
8225
8226     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8227     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8228     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8229       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8230       unsigned TargetMask = 0;
8231       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8232                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8233       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8234       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8235                              getShufflePSHUFLWImmediate(SVOp);
8236       V1 = NewV.getOperand(0);
8237       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8238     }
8239   }
8240
8241   // Promote splats to a larger type which usually leads to more efficient code.
8242   // FIXME: Is this true if pshufb is available?
8243   if (SVOp->isSplat())
8244     return PromoteSplat(SVOp, DAG);
8245
8246   // If we have SSSE3, and all words of the result are from 1 input vector,
8247   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8248   // is present, fall back to case 4.
8249   if (Subtarget->hasSSSE3()) {
8250     SmallVector<SDValue,16> pshufbMask;
8251
8252     // If we have elements from both input vectors, set the high bit of the
8253     // shuffle mask element to zero out elements that come from V2 in the V1
8254     // mask, and elements that come from V1 in the V2 mask, so that the two
8255     // results can be OR'd together.
8256     bool TwoInputs = V1Used && V2Used;
8257     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8258     if (!TwoInputs)
8259       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8260
8261     // Calculate the shuffle mask for the second input, shuffle it, and
8262     // OR it with the first shuffled input.
8263     CommuteVectorShuffleMask(MaskVals, 8);
8264     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8265     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8266     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8267   }
8268
8269   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8270   // and update MaskVals with new element order.
8271   std::bitset<8> InOrder;
8272   if (BestLoQuad >= 0) {
8273     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8274     for (int i = 0; i != 4; ++i) {
8275       int idx = MaskVals[i];
8276       if (idx < 0) {
8277         InOrder.set(i);
8278       } else if ((idx / 4) == BestLoQuad) {
8279         MaskV[i] = idx & 3;
8280         InOrder.set(i);
8281       }
8282     }
8283     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8284                                 &MaskV[0]);
8285
8286     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8287       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8288       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8289                                   NewV.getOperand(0),
8290                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8291     }
8292   }
8293
8294   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8295   // and update MaskVals with the new element order.
8296   if (BestHiQuad >= 0) {
8297     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8298     for (unsigned i = 4; i != 8; ++i) {
8299       int idx = MaskVals[i];
8300       if (idx < 0) {
8301         InOrder.set(i);
8302       } else if ((idx / 4) == BestHiQuad) {
8303         MaskV[i] = (idx & 3) + 4;
8304         InOrder.set(i);
8305       }
8306     }
8307     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8308                                 &MaskV[0]);
8309
8310     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8311       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8312       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8313                                   NewV.getOperand(0),
8314                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8315     }
8316   }
8317
8318   // In case BestHi & BestLo were both -1, which means each quadword has a word
8319   // from each of the four input quadwords, calculate the InOrder bitvector now
8320   // before falling through to the insert/extract cleanup.
8321   if (BestLoQuad == -1 && BestHiQuad == -1) {
8322     NewV = V1;
8323     for (int i = 0; i != 8; ++i)
8324       if (MaskVals[i] < 0 || MaskVals[i] == i)
8325         InOrder.set(i);
8326   }
8327
8328   // The other elements are put in the right place using pextrw and pinsrw.
8329   for (unsigned i = 0; i != 8; ++i) {
8330     if (InOrder[i])
8331       continue;
8332     int EltIdx = MaskVals[i];
8333     if (EltIdx < 0)
8334       continue;
8335     SDValue ExtOp = (EltIdx < 8) ?
8336       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8337                   DAG.getIntPtrConstant(EltIdx)) :
8338       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8339                   DAG.getIntPtrConstant(EltIdx - 8));
8340     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8341                        DAG.getIntPtrConstant(i));
8342   }
8343   return NewV;
8344 }
8345
8346 /// \brief v16i16 shuffles
8347 ///
8348 /// FIXME: We only support generation of a single pshufb currently.  We can
8349 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8350 /// well (e.g 2 x pshufb + 1 x por).
8351 static SDValue
8352 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8353   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8354   SDValue V1 = SVOp->getOperand(0);
8355   SDValue V2 = SVOp->getOperand(1);
8356   SDLoc dl(SVOp);
8357
8358   if (V2.getOpcode() != ISD::UNDEF)
8359     return SDValue();
8360
8361   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8362   return getPSHUFB(MaskVals, V1, dl, DAG);
8363 }
8364
8365 // v16i8 shuffles - Prefer shuffles in the following order:
8366 // 1. [ssse3] 1 x pshufb
8367 // 2. [ssse3] 2 x pshufb + 1 x por
8368 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8369 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8370                                         const X86Subtarget* Subtarget,
8371                                         SelectionDAG &DAG) {
8372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8373   SDValue V1 = SVOp->getOperand(0);
8374   SDValue V2 = SVOp->getOperand(1);
8375   SDLoc dl(SVOp);
8376   ArrayRef<int> MaskVals = SVOp->getMask();
8377
8378   // Promote splats to a larger type which usually leads to more efficient code.
8379   // FIXME: Is this true if pshufb is available?
8380   if (SVOp->isSplat())
8381     return PromoteSplat(SVOp, DAG);
8382
8383   // If we have SSSE3, case 1 is generated when all result bytes come from
8384   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8385   // present, fall back to case 3.
8386
8387   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8388   if (Subtarget->hasSSSE3()) {
8389     SmallVector<SDValue,16> pshufbMask;
8390
8391     // If all result elements are from one input vector, then only translate
8392     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8393     //
8394     // Otherwise, we have elements from both input vectors, and must zero out
8395     // elements that come from V2 in the first mask, and V1 in the second mask
8396     // so that we can OR them together.
8397     for (unsigned i = 0; i != 16; ++i) {
8398       int EltIdx = MaskVals[i];
8399       if (EltIdx < 0 || EltIdx >= 16)
8400         EltIdx = 0x80;
8401       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8402     }
8403     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8404                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8405                                  MVT::v16i8, pshufbMask));
8406
8407     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8408     // the 2nd operand if it's undefined or zero.
8409     if (V2.getOpcode() == ISD::UNDEF ||
8410         ISD::isBuildVectorAllZeros(V2.getNode()))
8411       return V1;
8412
8413     // Calculate the shuffle mask for the second input, shuffle it, and
8414     // OR it with the first shuffled input.
8415     pshufbMask.clear();
8416     for (unsigned i = 0; i != 16; ++i) {
8417       int EltIdx = MaskVals[i];
8418       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8419       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8420     }
8421     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8422                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8423                                  MVT::v16i8, pshufbMask));
8424     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8425   }
8426
8427   // No SSSE3 - Calculate in place words and then fix all out of place words
8428   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8429   // the 16 different words that comprise the two doublequadword input vectors.
8430   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8431   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8432   SDValue NewV = V1;
8433   for (int i = 0; i != 8; ++i) {
8434     int Elt0 = MaskVals[i*2];
8435     int Elt1 = MaskVals[i*2+1];
8436
8437     // This word of the result is all undef, skip it.
8438     if (Elt0 < 0 && Elt1 < 0)
8439       continue;
8440
8441     // This word of the result is already in the correct place, skip it.
8442     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8443       continue;
8444
8445     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8446     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8447     SDValue InsElt;
8448
8449     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8450     // using a single extract together, load it and store it.
8451     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8452       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8453                            DAG.getIntPtrConstant(Elt1 / 2));
8454       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8455                         DAG.getIntPtrConstant(i));
8456       continue;
8457     }
8458
8459     // If Elt1 is defined, extract it from the appropriate source.  If the
8460     // source byte is not also odd, shift the extracted word left 8 bits
8461     // otherwise clear the bottom 8 bits if we need to do an or.
8462     if (Elt1 >= 0) {
8463       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8464                            DAG.getIntPtrConstant(Elt1 / 2));
8465       if ((Elt1 & 1) == 0)
8466         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8467                              DAG.getConstant(8,
8468                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8469       else if (Elt0 >= 0)
8470         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8471                              DAG.getConstant(0xFF00, MVT::i16));
8472     }
8473     // If Elt0 is defined, extract it from the appropriate source.  If the
8474     // source byte is not also even, shift the extracted word right 8 bits. If
8475     // Elt1 was also defined, OR the extracted values together before
8476     // inserting them in the result.
8477     if (Elt0 >= 0) {
8478       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8479                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8480       if ((Elt0 & 1) != 0)
8481         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8482                               DAG.getConstant(8,
8483                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8484       else if (Elt1 >= 0)
8485         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8486                              DAG.getConstant(0x00FF, MVT::i16));
8487       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8488                          : InsElt0;
8489     }
8490     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8491                        DAG.getIntPtrConstant(i));
8492   }
8493   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8494 }
8495
8496 // v32i8 shuffles - Translate to VPSHUFB if possible.
8497 static
8498 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8499                                  const X86Subtarget *Subtarget,
8500                                  SelectionDAG &DAG) {
8501   MVT VT = SVOp->getSimpleValueType(0);
8502   SDValue V1 = SVOp->getOperand(0);
8503   SDValue V2 = SVOp->getOperand(1);
8504   SDLoc dl(SVOp);
8505   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8506
8507   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8508   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8509   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8510
8511   // VPSHUFB may be generated if
8512   // (1) one of input vector is undefined or zeroinitializer.
8513   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8514   // And (2) the mask indexes don't cross the 128-bit lane.
8515   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8516       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8517     return SDValue();
8518
8519   if (V1IsAllZero && !V2IsAllZero) {
8520     CommuteVectorShuffleMask(MaskVals, 32);
8521     V1 = V2;
8522   }
8523   return getPSHUFB(MaskVals, V1, dl, DAG);
8524 }
8525
8526 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8527 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8528 /// done when every pair / quad of shuffle mask elements point to elements in
8529 /// the right sequence. e.g.
8530 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8531 static
8532 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8533                                  SelectionDAG &DAG) {
8534   MVT VT = SVOp->getSimpleValueType(0);
8535   SDLoc dl(SVOp);
8536   unsigned NumElems = VT.getVectorNumElements();
8537   MVT NewVT;
8538   unsigned Scale;
8539   switch (VT.SimpleTy) {
8540   default: llvm_unreachable("Unexpected!");
8541   case MVT::v2i64:
8542   case MVT::v2f64:
8543            return SDValue(SVOp, 0);
8544   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8545   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8546   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8547   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8548   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8549   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8550   }
8551
8552   SmallVector<int, 8> MaskVec;
8553   for (unsigned i = 0; i != NumElems; i += Scale) {
8554     int StartIdx = -1;
8555     for (unsigned j = 0; j != Scale; ++j) {
8556       int EltIdx = SVOp->getMaskElt(i+j);
8557       if (EltIdx < 0)
8558         continue;
8559       if (StartIdx < 0)
8560         StartIdx = (EltIdx / Scale);
8561       if (EltIdx != (int)(StartIdx*Scale + j))
8562         return SDValue();
8563     }
8564     MaskVec.push_back(StartIdx);
8565   }
8566
8567   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8568   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8569   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8570 }
8571
8572 /// getVZextMovL - Return a zero-extending vector move low node.
8573 ///
8574 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8575                             SDValue SrcOp, SelectionDAG &DAG,
8576                             const X86Subtarget *Subtarget, SDLoc dl) {
8577   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8578     LoadSDNode *LD = nullptr;
8579     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8580       LD = dyn_cast<LoadSDNode>(SrcOp);
8581     if (!LD) {
8582       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8583       // instead.
8584       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8585       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8586           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8587           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8588           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8589         // PR2108
8590         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8591         return DAG.getNode(ISD::BITCAST, dl, VT,
8592                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8593                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8594                                                    OpVT,
8595                                                    SrcOp.getOperand(0)
8596                                                           .getOperand(0))));
8597       }
8598     }
8599   }
8600
8601   return DAG.getNode(ISD::BITCAST, dl, VT,
8602                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8603                                  DAG.getNode(ISD::BITCAST, dl,
8604                                              OpVT, SrcOp)));
8605 }
8606
8607 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8608 /// which could not be matched by any known target speficic shuffle
8609 static SDValue
8610 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8611
8612   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8613   if (NewOp.getNode())
8614     return NewOp;
8615
8616   MVT VT = SVOp->getSimpleValueType(0);
8617
8618   unsigned NumElems = VT.getVectorNumElements();
8619   unsigned NumLaneElems = NumElems / 2;
8620
8621   SDLoc dl(SVOp);
8622   MVT EltVT = VT.getVectorElementType();
8623   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8624   SDValue Output[2];
8625
8626   SmallVector<int, 16> Mask;
8627   for (unsigned l = 0; l < 2; ++l) {
8628     // Build a shuffle mask for the output, discovering on the fly which
8629     // input vectors to use as shuffle operands (recorded in InputUsed).
8630     // If building a suitable shuffle vector proves too hard, then bail
8631     // out with UseBuildVector set.
8632     bool UseBuildVector = false;
8633     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8634     unsigned LaneStart = l * NumLaneElems;
8635     for (unsigned i = 0; i != NumLaneElems; ++i) {
8636       // The mask element.  This indexes into the input.
8637       int Idx = SVOp->getMaskElt(i+LaneStart);
8638       if (Idx < 0) {
8639         // the mask element does not index into any input vector.
8640         Mask.push_back(-1);
8641         continue;
8642       }
8643
8644       // The input vector this mask element indexes into.
8645       int Input = Idx / NumLaneElems;
8646
8647       // Turn the index into an offset from the start of the input vector.
8648       Idx -= Input * NumLaneElems;
8649
8650       // Find or create a shuffle vector operand to hold this input.
8651       unsigned OpNo;
8652       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8653         if (InputUsed[OpNo] == Input)
8654           // This input vector is already an operand.
8655           break;
8656         if (InputUsed[OpNo] < 0) {
8657           // Create a new operand for this input vector.
8658           InputUsed[OpNo] = Input;
8659           break;
8660         }
8661       }
8662
8663       if (OpNo >= array_lengthof(InputUsed)) {
8664         // More than two input vectors used!  Give up on trying to create a
8665         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8666         UseBuildVector = true;
8667         break;
8668       }
8669
8670       // Add the mask index for the new shuffle vector.
8671       Mask.push_back(Idx + OpNo * NumLaneElems);
8672     }
8673
8674     if (UseBuildVector) {
8675       SmallVector<SDValue, 16> SVOps;
8676       for (unsigned i = 0; i != NumLaneElems; ++i) {
8677         // The mask element.  This indexes into the input.
8678         int Idx = SVOp->getMaskElt(i+LaneStart);
8679         if (Idx < 0) {
8680           SVOps.push_back(DAG.getUNDEF(EltVT));
8681           continue;
8682         }
8683
8684         // The input vector this mask element indexes into.
8685         int Input = Idx / NumElems;
8686
8687         // Turn the index into an offset from the start of the input vector.
8688         Idx -= Input * NumElems;
8689
8690         // Extract the vector element by hand.
8691         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8692                                     SVOp->getOperand(Input),
8693                                     DAG.getIntPtrConstant(Idx)));
8694       }
8695
8696       // Construct the output using a BUILD_VECTOR.
8697       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8698     } else if (InputUsed[0] < 0) {
8699       // No input vectors were used! The result is undefined.
8700       Output[l] = DAG.getUNDEF(NVT);
8701     } else {
8702       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8703                                         (InputUsed[0] % 2) * NumLaneElems,
8704                                         DAG, dl);
8705       // If only one input was used, use an undefined vector for the other.
8706       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8707         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8708                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8709       // At least one input vector was used. Create a new shuffle vector.
8710       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8711     }
8712
8713     Mask.clear();
8714   }
8715
8716   // Concatenate the result back
8717   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8718 }
8719
8720 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8721 /// 4 elements, and match them with several different shuffle types.
8722 static SDValue
8723 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8724   SDValue V1 = SVOp->getOperand(0);
8725   SDValue V2 = SVOp->getOperand(1);
8726   SDLoc dl(SVOp);
8727   MVT VT = SVOp->getSimpleValueType(0);
8728
8729   assert(VT.is128BitVector() && "Unsupported vector size");
8730
8731   std::pair<int, int> Locs[4];
8732   int Mask1[] = { -1, -1, -1, -1 };
8733   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8734
8735   unsigned NumHi = 0;
8736   unsigned NumLo = 0;
8737   for (unsigned i = 0; i != 4; ++i) {
8738     int Idx = PermMask[i];
8739     if (Idx < 0) {
8740       Locs[i] = std::make_pair(-1, -1);
8741     } else {
8742       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8743       if (Idx < 4) {
8744         Locs[i] = std::make_pair(0, NumLo);
8745         Mask1[NumLo] = Idx;
8746         NumLo++;
8747       } else {
8748         Locs[i] = std::make_pair(1, NumHi);
8749         if (2+NumHi < 4)
8750           Mask1[2+NumHi] = Idx;
8751         NumHi++;
8752       }
8753     }
8754   }
8755
8756   if (NumLo <= 2 && NumHi <= 2) {
8757     // If no more than two elements come from either vector. This can be
8758     // implemented with two shuffles. First shuffle gather the elements.
8759     // The second shuffle, which takes the first shuffle as both of its
8760     // vector operands, put the elements into the right order.
8761     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8762
8763     int Mask2[] = { -1, -1, -1, -1 };
8764
8765     for (unsigned i = 0; i != 4; ++i)
8766       if (Locs[i].first != -1) {
8767         unsigned Idx = (i < 2) ? 0 : 4;
8768         Idx += Locs[i].first * 2 + Locs[i].second;
8769         Mask2[i] = Idx;
8770       }
8771
8772     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8773   }
8774
8775   if (NumLo == 3 || NumHi == 3) {
8776     // Otherwise, we must have three elements from one vector, call it X, and
8777     // one element from the other, call it Y.  First, use a shufps to build an
8778     // intermediate vector with the one element from Y and the element from X
8779     // that will be in the same half in the final destination (the indexes don't
8780     // matter). Then, use a shufps to build the final vector, taking the half
8781     // containing the element from Y from the intermediate, and the other half
8782     // from X.
8783     if (NumHi == 3) {
8784       // Normalize it so the 3 elements come from V1.
8785       CommuteVectorShuffleMask(PermMask, 4);
8786       std::swap(V1, V2);
8787     }
8788
8789     // Find the element from V2.
8790     unsigned HiIndex;
8791     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8792       int Val = PermMask[HiIndex];
8793       if (Val < 0)
8794         continue;
8795       if (Val >= 4)
8796         break;
8797     }
8798
8799     Mask1[0] = PermMask[HiIndex];
8800     Mask1[1] = -1;
8801     Mask1[2] = PermMask[HiIndex^1];
8802     Mask1[3] = -1;
8803     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8804
8805     if (HiIndex >= 2) {
8806       Mask1[0] = PermMask[0];
8807       Mask1[1] = PermMask[1];
8808       Mask1[2] = HiIndex & 1 ? 6 : 4;
8809       Mask1[3] = HiIndex & 1 ? 4 : 6;
8810       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8811     }
8812
8813     Mask1[0] = HiIndex & 1 ? 2 : 0;
8814     Mask1[1] = HiIndex & 1 ? 0 : 2;
8815     Mask1[2] = PermMask[2];
8816     Mask1[3] = PermMask[3];
8817     if (Mask1[2] >= 0)
8818       Mask1[2] += 4;
8819     if (Mask1[3] >= 0)
8820       Mask1[3] += 4;
8821     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8822   }
8823
8824   // Break it into (shuffle shuffle_hi, shuffle_lo).
8825   int LoMask[] = { -1, -1, -1, -1 };
8826   int HiMask[] = { -1, -1, -1, -1 };
8827
8828   int *MaskPtr = LoMask;
8829   unsigned MaskIdx = 0;
8830   unsigned LoIdx = 0;
8831   unsigned HiIdx = 2;
8832   for (unsigned i = 0; i != 4; ++i) {
8833     if (i == 2) {
8834       MaskPtr = HiMask;
8835       MaskIdx = 1;
8836       LoIdx = 0;
8837       HiIdx = 2;
8838     }
8839     int Idx = PermMask[i];
8840     if (Idx < 0) {
8841       Locs[i] = std::make_pair(-1, -1);
8842     } else if (Idx < 4) {
8843       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8844       MaskPtr[LoIdx] = Idx;
8845       LoIdx++;
8846     } else {
8847       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8848       MaskPtr[HiIdx] = Idx;
8849       HiIdx++;
8850     }
8851   }
8852
8853   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8854   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8855   int MaskOps[] = { -1, -1, -1, -1 };
8856   for (unsigned i = 0; i != 4; ++i)
8857     if (Locs[i].first != -1)
8858       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8859   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8860 }
8861
8862 static bool MayFoldVectorLoad(SDValue V) {
8863   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8864     V = V.getOperand(0);
8865
8866   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8867     V = V.getOperand(0);
8868   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8869       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8870     // BUILD_VECTOR (load), undef
8871     V = V.getOperand(0);
8872
8873   return MayFoldLoad(V);
8874 }
8875
8876 static
8877 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8878   MVT VT = Op.getSimpleValueType();
8879
8880   // Canonizalize to v2f64.
8881   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8882   return DAG.getNode(ISD::BITCAST, dl, VT,
8883                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8884                                           V1, DAG));
8885 }
8886
8887 static
8888 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8889                         bool HasSSE2) {
8890   SDValue V1 = Op.getOperand(0);
8891   SDValue V2 = Op.getOperand(1);
8892   MVT VT = Op.getSimpleValueType();
8893
8894   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8895
8896   if (HasSSE2 && VT == MVT::v2f64)
8897     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8898
8899   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8900   return DAG.getNode(ISD::BITCAST, dl, VT,
8901                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8902                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8903                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8904 }
8905
8906 static
8907 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8908   SDValue V1 = Op.getOperand(0);
8909   SDValue V2 = Op.getOperand(1);
8910   MVT VT = Op.getSimpleValueType();
8911
8912   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8913          "unsupported shuffle type");
8914
8915   if (V2.getOpcode() == ISD::UNDEF)
8916     V2 = V1;
8917
8918   // v4i32 or v4f32
8919   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8920 }
8921
8922 static
8923 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8924   SDValue V1 = Op.getOperand(0);
8925   SDValue V2 = Op.getOperand(1);
8926   MVT VT = Op.getSimpleValueType();
8927   unsigned NumElems = VT.getVectorNumElements();
8928
8929   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8930   // operand of these instructions is only memory, so check if there's a
8931   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8932   // same masks.
8933   bool CanFoldLoad = false;
8934
8935   // Trivial case, when V2 comes from a load.
8936   if (MayFoldVectorLoad(V2))
8937     CanFoldLoad = true;
8938
8939   // When V1 is a load, it can be folded later into a store in isel, example:
8940   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8941   //    turns into:
8942   //  (MOVLPSmr addr:$src1, VR128:$src2)
8943   // So, recognize this potential and also use MOVLPS or MOVLPD
8944   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8945     CanFoldLoad = true;
8946
8947   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8948   if (CanFoldLoad) {
8949     if (HasSSE2 && NumElems == 2)
8950       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8951
8952     if (NumElems == 4)
8953       // If we don't care about the second element, proceed to use movss.
8954       if (SVOp->getMaskElt(1) != -1)
8955         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8956   }
8957
8958   // movl and movlp will both match v2i64, but v2i64 is never matched by
8959   // movl earlier because we make it strict to avoid messing with the movlp load
8960   // folding logic (see the code above getMOVLP call). Match it here then,
8961   // this is horrible, but will stay like this until we move all shuffle
8962   // matching to x86 specific nodes. Note that for the 1st condition all
8963   // types are matched with movsd.
8964   if (HasSSE2) {
8965     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8966     // as to remove this logic from here, as much as possible
8967     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8968       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8969     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8970   }
8971
8972   assert(VT != MVT::v4i32 && "unsupported shuffle type");
8973
8974   // Invert the operand order and use SHUFPS to match it.
8975   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8976                               getShuffleSHUFImmediate(SVOp), DAG);
8977 }
8978
8979 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8980                                          SelectionDAG &DAG) {
8981   SDLoc dl(Load);
8982   MVT VT = Load->getSimpleValueType(0);
8983   MVT EVT = VT.getVectorElementType();
8984   SDValue Addr = Load->getOperand(1);
8985   SDValue NewAddr = DAG.getNode(
8986       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8987       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8988
8989   SDValue NewLoad =
8990       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8991                   DAG.getMachineFunction().getMachineMemOperand(
8992                       Load->getMemOperand(), 0, EVT.getStoreSize()));
8993   return NewLoad;
8994 }
8995
8996 // It is only safe to call this function if isINSERTPSMask is true for
8997 // this shufflevector mask.
8998 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
8999                            SelectionDAG &DAG) {
9000   // Generate an insertps instruction when inserting an f32 from memory onto a
9001   // v4f32 or when copying a member from one v4f32 to another.
9002   // We also use it for transferring i32 from one register to another,
9003   // since it simply copies the same bits.
9004   // If we're transferring an i32 from memory to a specific element in a
9005   // register, we output a generic DAG that will match the PINSRD
9006   // instruction.
9007   MVT VT = SVOp->getSimpleValueType(0);
9008   MVT EVT = VT.getVectorElementType();
9009   SDValue V1 = SVOp->getOperand(0);
9010   SDValue V2 = SVOp->getOperand(1);
9011   auto Mask = SVOp->getMask();
9012   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9013          "unsupported vector type for insertps/pinsrd");
9014
9015   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9016   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9017   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9018
9019   SDValue From;
9020   SDValue To;
9021   unsigned DestIndex;
9022   if (FromV1 == 1) {
9023     From = V1;
9024     To = V2;
9025     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9026                 Mask.begin();
9027   } else {
9028     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9029            "More than one element from V1 and from V2, or no elements from one "
9030            "of the vectors. This case should not have returned true from "
9031            "isINSERTPSMask");
9032     From = V2;
9033     To = V1;
9034     DestIndex =
9035         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9036   }
9037
9038   unsigned SrcIndex = Mask[DestIndex] % 4;
9039   if (MayFoldLoad(From)) {
9040     // Trivial case, when From comes from a load and is only used by the
9041     // shuffle. Make it use insertps from the vector that we need from that
9042     // load.
9043     SDValue NewLoad =
9044         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9045     if (!NewLoad.getNode())
9046       return SDValue();
9047
9048     if (EVT == MVT::f32) {
9049       // Create this as a scalar to vector to match the instruction pattern.
9050       SDValue LoadScalarToVector =
9051           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9052       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9053       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9054                          InsertpsMask);
9055     } else { // EVT == MVT::i32
9056       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9057       // instruction, to match the PINSRD instruction, which loads an i32 to a
9058       // certain vector element.
9059       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9060                          DAG.getConstant(DestIndex, MVT::i32));
9061     }
9062   }
9063
9064   // Vector-element-to-vector
9065   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9066   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9067 }
9068
9069 // Reduce a vector shuffle to zext.
9070 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9071                                     SelectionDAG &DAG) {
9072   // PMOVZX is only available from SSE41.
9073   if (!Subtarget->hasSSE41())
9074     return SDValue();
9075
9076   MVT VT = Op.getSimpleValueType();
9077
9078   // Only AVX2 support 256-bit vector integer extending.
9079   if (!Subtarget->hasInt256() && VT.is256BitVector())
9080     return SDValue();
9081
9082   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9083   SDLoc DL(Op);
9084   SDValue V1 = Op.getOperand(0);
9085   SDValue V2 = Op.getOperand(1);
9086   unsigned NumElems = VT.getVectorNumElements();
9087
9088   // Extending is an unary operation and the element type of the source vector
9089   // won't be equal to or larger than i64.
9090   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9091       VT.getVectorElementType() == MVT::i64)
9092     return SDValue();
9093
9094   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9095   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9096   while ((1U << Shift) < NumElems) {
9097     if (SVOp->getMaskElt(1U << Shift) == 1)
9098       break;
9099     Shift += 1;
9100     // The maximal ratio is 8, i.e. from i8 to i64.
9101     if (Shift > 3)
9102       return SDValue();
9103   }
9104
9105   // Check the shuffle mask.
9106   unsigned Mask = (1U << Shift) - 1;
9107   for (unsigned i = 0; i != NumElems; ++i) {
9108     int EltIdx = SVOp->getMaskElt(i);
9109     if ((i & Mask) != 0 && EltIdx != -1)
9110       return SDValue();
9111     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9112       return SDValue();
9113   }
9114
9115   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9116   MVT NeVT = MVT::getIntegerVT(NBits);
9117   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9118
9119   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9120     return SDValue();
9121
9122   // Simplify the operand as it's prepared to be fed into shuffle.
9123   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9124   if (V1.getOpcode() == ISD::BITCAST &&
9125       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9126       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9127       V1.getOperand(0).getOperand(0)
9128         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9129     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9130     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9131     ConstantSDNode *CIdx =
9132       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9133     // If it's foldable, i.e. normal load with single use, we will let code
9134     // selection to fold it. Otherwise, we will short the conversion sequence.
9135     if (CIdx && CIdx->getZExtValue() == 0 &&
9136         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9137       MVT FullVT = V.getSimpleValueType();
9138       MVT V1VT = V1.getSimpleValueType();
9139       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9140         // The "ext_vec_elt" node is wider than the result node.
9141         // In this case we should extract subvector from V.
9142         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9143         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9144         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9145                                         FullVT.getVectorNumElements()/Ratio);
9146         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9147                         DAG.getIntPtrConstant(0));
9148       }
9149       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9150     }
9151   }
9152
9153   return DAG.getNode(ISD::BITCAST, DL, VT,
9154                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9155 }
9156
9157 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9158                                       SelectionDAG &DAG) {
9159   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9160   MVT VT = Op.getSimpleValueType();
9161   SDLoc dl(Op);
9162   SDValue V1 = Op.getOperand(0);
9163   SDValue V2 = Op.getOperand(1);
9164
9165   if (isZeroShuffle(SVOp))
9166     return getZeroVector(VT, Subtarget, DAG, dl);
9167
9168   // Handle splat operations
9169   if (SVOp->isSplat()) {
9170     // Use vbroadcast whenever the splat comes from a foldable load
9171     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9172     if (Broadcast.getNode())
9173       return Broadcast;
9174   }
9175
9176   // Check integer expanding shuffles.
9177   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9178   if (NewOp.getNode())
9179     return NewOp;
9180
9181   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9182   // do it!
9183   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9184       VT == MVT::v32i8) {
9185     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9186     if (NewOp.getNode())
9187       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9188   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9189     // FIXME: Figure out a cleaner way to do this.
9190     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9191       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9192       if (NewOp.getNode()) {
9193         MVT NewVT = NewOp.getSimpleValueType();
9194         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9195                                NewVT, true, false))
9196           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9197                               dl);
9198       }
9199     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9200       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9201       if (NewOp.getNode()) {
9202         MVT NewVT = NewOp.getSimpleValueType();
9203         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9204           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9205                               dl);
9206       }
9207     }
9208   }
9209   return SDValue();
9210 }
9211
9212 SDValue
9213 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9215   SDValue V1 = Op.getOperand(0);
9216   SDValue V2 = Op.getOperand(1);
9217   MVT VT = Op.getSimpleValueType();
9218   SDLoc dl(Op);
9219   unsigned NumElems = VT.getVectorNumElements();
9220   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9221   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9222   bool V1IsSplat = false;
9223   bool V2IsSplat = false;
9224   bool HasSSE2 = Subtarget->hasSSE2();
9225   bool HasFp256    = Subtarget->hasFp256();
9226   bool HasInt256   = Subtarget->hasInt256();
9227   MachineFunction &MF = DAG.getMachineFunction();
9228   bool OptForSize = MF.getFunction()->getAttributes().
9229     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9230
9231   // Check if we should use the experimental vector shuffle lowering. If so,
9232   // delegate completely to that code path.
9233   if (ExperimentalVectorShuffleLowering)
9234     return lowerVectorShuffle(Op, Subtarget, DAG);
9235
9236   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9237
9238   if (V1IsUndef && V2IsUndef)
9239     return DAG.getUNDEF(VT);
9240
9241   // When we create a shuffle node we put the UNDEF node to second operand,
9242   // but in some cases the first operand may be transformed to UNDEF.
9243   // In this case we should just commute the node.
9244   if (V1IsUndef)
9245     return CommuteVectorShuffle(SVOp, DAG);
9246
9247   // Vector shuffle lowering takes 3 steps:
9248   //
9249   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9250   //    narrowing and commutation of operands should be handled.
9251   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9252   //    shuffle nodes.
9253   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9254   //    so the shuffle can be broken into other shuffles and the legalizer can
9255   //    try the lowering again.
9256   //
9257   // The general idea is that no vector_shuffle operation should be left to
9258   // be matched during isel, all of them must be converted to a target specific
9259   // node here.
9260
9261   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9262   // narrowing and commutation of operands should be handled. The actual code
9263   // doesn't include all of those, work in progress...
9264   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9265   if (NewOp.getNode())
9266     return NewOp;
9267
9268   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9269
9270   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9271   // unpckh_undef). Only use pshufd if speed is more important than size.
9272   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9273     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9274   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9275     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9276
9277   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9278       V2IsUndef && MayFoldVectorLoad(V1))
9279     return getMOVDDup(Op, dl, V1, DAG);
9280
9281   if (isMOVHLPS_v_undef_Mask(M, VT))
9282     return getMOVHighToLow(Op, dl, DAG);
9283
9284   // Use to match splats
9285   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9286       (VT == MVT::v2f64 || VT == MVT::v2i64))
9287     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9288
9289   if (isPSHUFDMask(M, VT)) {
9290     // The actual implementation will match the mask in the if above and then
9291     // during isel it can match several different instructions, not only pshufd
9292     // as its name says, sad but true, emulate the behavior for now...
9293     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9294       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9295
9296     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9297
9298     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9299       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9300
9301     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9302       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9303                                   DAG);
9304
9305     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9306                                 TargetMask, DAG);
9307   }
9308
9309   if (isPALIGNRMask(M, VT, Subtarget))
9310     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9311                                 getShufflePALIGNRImmediate(SVOp),
9312                                 DAG);
9313
9314   // Check if this can be converted into a logical shift.
9315   bool isLeft = false;
9316   unsigned ShAmt = 0;
9317   SDValue ShVal;
9318   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9319   if (isShift && ShVal.hasOneUse()) {
9320     // If the shifted value has multiple uses, it may be cheaper to use
9321     // v_set0 + movlhps or movhlps, etc.
9322     MVT EltVT = VT.getVectorElementType();
9323     ShAmt *= EltVT.getSizeInBits();
9324     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9325   }
9326
9327   if (isMOVLMask(M, VT)) {
9328     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9329       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9330     if (!isMOVLPMask(M, VT)) {
9331       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9332         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9333
9334       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9335         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9336     }
9337   }
9338
9339   // FIXME: fold these into legal mask.
9340   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9341     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9342
9343   if (isMOVHLPSMask(M, VT))
9344     return getMOVHighToLow(Op, dl, DAG);
9345
9346   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9347     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9348
9349   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9350     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9351
9352   if (isMOVLPMask(M, VT))
9353     return getMOVLP(Op, dl, DAG, HasSSE2);
9354
9355   if (ShouldXformToMOVHLPS(M, VT) ||
9356       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9357     return CommuteVectorShuffle(SVOp, DAG);
9358
9359   if (isShift) {
9360     // No better options. Use a vshldq / vsrldq.
9361     MVT EltVT = VT.getVectorElementType();
9362     ShAmt *= EltVT.getSizeInBits();
9363     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9364   }
9365
9366   bool Commuted = false;
9367   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9368   // 1,1,1,1 -> v8i16 though.
9369   V1IsSplat = isSplatVector(V1.getNode());
9370   V2IsSplat = isSplatVector(V2.getNode());
9371
9372   // Canonicalize the splat or undef, if present, to be on the RHS.
9373   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9374     CommuteVectorShuffleMask(M, NumElems);
9375     std::swap(V1, V2);
9376     std::swap(V1IsSplat, V2IsSplat);
9377     Commuted = true;
9378   }
9379
9380   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9381     // Shuffling low element of v1 into undef, just return v1.
9382     if (V2IsUndef)
9383       return V1;
9384     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9385     // the instruction selector will not match, so get a canonical MOVL with
9386     // swapped operands to undo the commute.
9387     return getMOVL(DAG, dl, VT, V2, V1);
9388   }
9389
9390   if (isUNPCKLMask(M, VT, HasInt256))
9391     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9392
9393   if (isUNPCKHMask(M, VT, HasInt256))
9394     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9395
9396   if (V2IsSplat) {
9397     // Normalize mask so all entries that point to V2 points to its first
9398     // element then try to match unpck{h|l} again. If match, return a
9399     // new vector_shuffle with the corrected mask.p
9400     SmallVector<int, 8> NewMask(M.begin(), M.end());
9401     NormalizeMask(NewMask, NumElems);
9402     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9403       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9404     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9405       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9406   }
9407
9408   if (Commuted) {
9409     // Commute is back and try unpck* again.
9410     // FIXME: this seems wrong.
9411     CommuteVectorShuffleMask(M, NumElems);
9412     std::swap(V1, V2);
9413     std::swap(V1IsSplat, V2IsSplat);
9414
9415     if (isUNPCKLMask(M, VT, HasInt256))
9416       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9417
9418     if (isUNPCKHMask(M, VT, HasInt256))
9419       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9420   }
9421
9422   // Normalize the node to match x86 shuffle ops if needed
9423   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9424     return CommuteVectorShuffle(SVOp, DAG);
9425
9426   // The checks below are all present in isShuffleMaskLegal, but they are
9427   // inlined here right now to enable us to directly emit target specific
9428   // nodes, and remove one by one until they don't return Op anymore.
9429
9430   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9431       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9432     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9433       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9434   }
9435
9436   if (isPSHUFHWMask(M, VT, HasInt256))
9437     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9438                                 getShufflePSHUFHWImmediate(SVOp),
9439                                 DAG);
9440
9441   if (isPSHUFLWMask(M, VT, HasInt256))
9442     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9443                                 getShufflePSHUFLWImmediate(SVOp),
9444                                 DAG);
9445
9446   unsigned MaskValue;
9447   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9448                   &MaskValue))
9449     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9450
9451   if (isSHUFPMask(M, VT))
9452     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9453                                 getShuffleSHUFImmediate(SVOp), DAG);
9454
9455   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9456     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9457   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9458     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9459
9460   //===--------------------------------------------------------------------===//
9461   // Generate target specific nodes for 128 or 256-bit shuffles only
9462   // supported in the AVX instruction set.
9463   //
9464
9465   // Handle VMOVDDUPY permutations
9466   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9467     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9468
9469   // Handle VPERMILPS/D* permutations
9470   if (isVPERMILPMask(M, VT)) {
9471     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9472       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9473                                   getShuffleSHUFImmediate(SVOp), DAG);
9474     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9475                                 getShuffleSHUFImmediate(SVOp), DAG);
9476   }
9477
9478   unsigned Idx;
9479   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9480     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9481                               Idx*(NumElems/2), DAG, dl);
9482
9483   // Handle VPERM2F128/VPERM2I128 permutations
9484   if (isVPERM2X128Mask(M, VT, HasFp256))
9485     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9486                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9487
9488   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9489     return getINSERTPS(SVOp, dl, DAG);
9490
9491   unsigned Imm8;
9492   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9493     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9494
9495   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9496       VT.is512BitVector()) {
9497     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9498     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9499     SmallVector<SDValue, 16> permclMask;
9500     for (unsigned i = 0; i != NumElems; ++i) {
9501       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9502     }
9503
9504     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9505     if (V2IsUndef)
9506       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9507       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9508                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9509     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9510                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9511   }
9512
9513   //===--------------------------------------------------------------------===//
9514   // Since no target specific shuffle was selected for this generic one,
9515   // lower it into other known shuffles. FIXME: this isn't true yet, but
9516   // this is the plan.
9517   //
9518
9519   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9520   if (VT == MVT::v8i16) {
9521     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9522     if (NewOp.getNode())
9523       return NewOp;
9524   }
9525
9526   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9527     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9528     if (NewOp.getNode())
9529       return NewOp;
9530   }
9531
9532   if (VT == MVT::v16i8) {
9533     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9534     if (NewOp.getNode())
9535       return NewOp;
9536   }
9537
9538   if (VT == MVT::v32i8) {
9539     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9540     if (NewOp.getNode())
9541       return NewOp;
9542   }
9543
9544   // Handle all 128-bit wide vectors with 4 elements, and match them with
9545   // several different shuffle types.
9546   if (NumElems == 4 && VT.is128BitVector())
9547     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9548
9549   // Handle general 256-bit shuffles
9550   if (VT.is256BitVector())
9551     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9552
9553   return SDValue();
9554 }
9555
9556 // This function assumes its argument is a BUILD_VECTOR of constants or
9557 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9558 // true.
9559 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9560                                     unsigned &MaskValue) {
9561   MaskValue = 0;
9562   unsigned NumElems = BuildVector->getNumOperands();
9563   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9564   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9565   unsigned NumElemsInLane = NumElems / NumLanes;
9566
9567   // Blend for v16i16 should be symetric for the both lanes.
9568   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9569     SDValue EltCond = BuildVector->getOperand(i);
9570     SDValue SndLaneEltCond =
9571         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9572
9573     int Lane1Cond = -1, Lane2Cond = -1;
9574     if (isa<ConstantSDNode>(EltCond))
9575       Lane1Cond = !isZero(EltCond);
9576     if (isa<ConstantSDNode>(SndLaneEltCond))
9577       Lane2Cond = !isZero(SndLaneEltCond);
9578
9579     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9580       // Lane1Cond != 0, means we want the first argument.
9581       // Lane1Cond == 0, means we want the second argument.
9582       // The encoding of this argument is 0 for the first argument, 1
9583       // for the second. Therefore, invert the condition.
9584       MaskValue |= !Lane1Cond << i;
9585     else if (Lane1Cond < 0)
9586       MaskValue |= !Lane2Cond << i;
9587     else
9588       return false;
9589   }
9590   return true;
9591 }
9592
9593 // Try to lower a vselect node into a simple blend instruction.
9594 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9595                                    SelectionDAG &DAG) {
9596   SDValue Cond = Op.getOperand(0);
9597   SDValue LHS = Op.getOperand(1);
9598   SDValue RHS = Op.getOperand(2);
9599   SDLoc dl(Op);
9600   MVT VT = Op.getSimpleValueType();
9601   MVT EltVT = VT.getVectorElementType();
9602   unsigned NumElems = VT.getVectorNumElements();
9603
9604   // There is no blend with immediate in AVX-512.
9605   if (VT.is512BitVector())
9606     return SDValue();
9607
9608   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9609     return SDValue();
9610   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9611     return SDValue();
9612
9613   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9614     return SDValue();
9615
9616   // Check the mask for BLEND and build the value.
9617   unsigned MaskValue = 0;
9618   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9619     return SDValue();
9620
9621   // Convert i32 vectors to floating point if it is not AVX2.
9622   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9623   MVT BlendVT = VT;
9624   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9625     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9626                                NumElems);
9627     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9628     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9629   }
9630
9631   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9632                             DAG.getConstant(MaskValue, MVT::i32));
9633   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9634 }
9635
9636 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9637   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9638   if (BlendOp.getNode())
9639     return BlendOp;
9640
9641   // Some types for vselect were previously set to Expand, not Legal or
9642   // Custom. Return an empty SDValue so we fall-through to Expand, after
9643   // the Custom lowering phase.
9644   MVT VT = Op.getSimpleValueType();
9645   switch (VT.SimpleTy) {
9646   default:
9647     break;
9648   case MVT::v8i16:
9649   case MVT::v16i16:
9650     return SDValue();
9651   }
9652
9653   // We couldn't create a "Blend with immediate" node.
9654   // This node should still be legal, but we'll have to emit a blendv*
9655   // instruction.
9656   return Op;
9657 }
9658
9659 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9660   MVT VT = Op.getSimpleValueType();
9661   SDLoc dl(Op);
9662
9663   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9664     return SDValue();
9665
9666   if (VT.getSizeInBits() == 8) {
9667     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9668                                   Op.getOperand(0), Op.getOperand(1));
9669     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9670                                   DAG.getValueType(VT));
9671     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9672   }
9673
9674   if (VT.getSizeInBits() == 16) {
9675     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9676     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9677     if (Idx == 0)
9678       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9679                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9680                                      DAG.getNode(ISD::BITCAST, dl,
9681                                                  MVT::v4i32,
9682                                                  Op.getOperand(0)),
9683                                      Op.getOperand(1)));
9684     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9685                                   Op.getOperand(0), Op.getOperand(1));
9686     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9687                                   DAG.getValueType(VT));
9688     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9689   }
9690
9691   if (VT == MVT::f32) {
9692     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9693     // the result back to FR32 register. It's only worth matching if the
9694     // result has a single use which is a store or a bitcast to i32.  And in
9695     // the case of a store, it's not worth it if the index is a constant 0,
9696     // because a MOVSSmr can be used instead, which is smaller and faster.
9697     if (!Op.hasOneUse())
9698       return SDValue();
9699     SDNode *User = *Op.getNode()->use_begin();
9700     if ((User->getOpcode() != ISD::STORE ||
9701          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9702           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9703         (User->getOpcode() != ISD::BITCAST ||
9704          User->getValueType(0) != MVT::i32))
9705       return SDValue();
9706     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9707                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9708                                               Op.getOperand(0)),
9709                                               Op.getOperand(1));
9710     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9711   }
9712
9713   if (VT == MVT::i32 || VT == MVT::i64) {
9714     // ExtractPS/pextrq works with constant index.
9715     if (isa<ConstantSDNode>(Op.getOperand(1)))
9716       return Op;
9717   }
9718   return SDValue();
9719 }
9720
9721 /// Extract one bit from mask vector, like v16i1 or v8i1.
9722 /// AVX-512 feature.
9723 SDValue
9724 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9725   SDValue Vec = Op.getOperand(0);
9726   SDLoc dl(Vec);
9727   MVT VecVT = Vec.getSimpleValueType();
9728   SDValue Idx = Op.getOperand(1);
9729   MVT EltVT = Op.getSimpleValueType();
9730
9731   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9732
9733   // variable index can't be handled in mask registers,
9734   // extend vector to VR512
9735   if (!isa<ConstantSDNode>(Idx)) {
9736     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9737     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9738     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9739                               ExtVT.getVectorElementType(), Ext, Idx);
9740     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9741   }
9742
9743   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9744   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9745   unsigned MaxSift = rc->getSize()*8 - 1;
9746   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9747                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9748   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9749                     DAG.getConstant(MaxSift, MVT::i8));
9750   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9751                        DAG.getIntPtrConstant(0));
9752 }
9753
9754 SDValue
9755 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9756                                            SelectionDAG &DAG) const {
9757   SDLoc dl(Op);
9758   SDValue Vec = Op.getOperand(0);
9759   MVT VecVT = Vec.getSimpleValueType();
9760   SDValue Idx = Op.getOperand(1);
9761
9762   if (Op.getSimpleValueType() == MVT::i1)
9763     return ExtractBitFromMaskVector(Op, DAG);
9764
9765   if (!isa<ConstantSDNode>(Idx)) {
9766     if (VecVT.is512BitVector() ||
9767         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9768          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9769
9770       MVT MaskEltVT =
9771         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9772       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9773                                     MaskEltVT.getSizeInBits());
9774
9775       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9776       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9777                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9778                                 Idx, DAG.getConstant(0, getPointerTy()));
9779       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9780       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9781                         Perm, DAG.getConstant(0, getPointerTy()));
9782     }
9783     return SDValue();
9784   }
9785
9786   // If this is a 256-bit vector result, first extract the 128-bit vector and
9787   // then extract the element from the 128-bit vector.
9788   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9789
9790     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9791     // Get the 128-bit vector.
9792     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9793     MVT EltVT = VecVT.getVectorElementType();
9794
9795     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9796
9797     //if (IdxVal >= NumElems/2)
9798     //  IdxVal -= NumElems/2;
9799     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9800     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9801                        DAG.getConstant(IdxVal, MVT::i32));
9802   }
9803
9804   assert(VecVT.is128BitVector() && "Unexpected vector length");
9805
9806   if (Subtarget->hasSSE41()) {
9807     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9808     if (Res.getNode())
9809       return Res;
9810   }
9811
9812   MVT VT = Op.getSimpleValueType();
9813   // TODO: handle v16i8.
9814   if (VT.getSizeInBits() == 16) {
9815     SDValue Vec = Op.getOperand(0);
9816     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9817     if (Idx == 0)
9818       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9819                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9820                                      DAG.getNode(ISD::BITCAST, dl,
9821                                                  MVT::v4i32, Vec),
9822                                      Op.getOperand(1)));
9823     // Transform it so it match pextrw which produces a 32-bit result.
9824     MVT EltVT = MVT::i32;
9825     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9826                                   Op.getOperand(0), Op.getOperand(1));
9827     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9828                                   DAG.getValueType(VT));
9829     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9830   }
9831
9832   if (VT.getSizeInBits() == 32) {
9833     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9834     if (Idx == 0)
9835       return Op;
9836
9837     // SHUFPS the element to the lowest double word, then movss.
9838     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9839     MVT VVT = Op.getOperand(0).getSimpleValueType();
9840     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9841                                        DAG.getUNDEF(VVT), Mask);
9842     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9843                        DAG.getIntPtrConstant(0));
9844   }
9845
9846   if (VT.getSizeInBits() == 64) {
9847     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9848     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9849     //        to match extract_elt for f64.
9850     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9851     if (Idx == 0)
9852       return Op;
9853
9854     // UNPCKHPD the element to the lowest double word, then movsd.
9855     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9856     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9857     int Mask[2] = { 1, -1 };
9858     MVT VVT = Op.getOperand(0).getSimpleValueType();
9859     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9860                                        DAG.getUNDEF(VVT), Mask);
9861     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9862                        DAG.getIntPtrConstant(0));
9863   }
9864
9865   return SDValue();
9866 }
9867
9868 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9869   MVT VT = Op.getSimpleValueType();
9870   MVT EltVT = VT.getVectorElementType();
9871   SDLoc dl(Op);
9872
9873   SDValue N0 = Op.getOperand(0);
9874   SDValue N1 = Op.getOperand(1);
9875   SDValue N2 = Op.getOperand(2);
9876
9877   if (!VT.is128BitVector())
9878     return SDValue();
9879
9880   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9881       isa<ConstantSDNode>(N2)) {
9882     unsigned Opc;
9883     if (VT == MVT::v8i16)
9884       Opc = X86ISD::PINSRW;
9885     else if (VT == MVT::v16i8)
9886       Opc = X86ISD::PINSRB;
9887     else
9888       Opc = X86ISD::PINSRB;
9889
9890     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9891     // argument.
9892     if (N1.getValueType() != MVT::i32)
9893       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9894     if (N2.getValueType() != MVT::i32)
9895       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9896     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9897   }
9898
9899   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9900     // Bits [7:6] of the constant are the source select.  This will always be
9901     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9902     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9903     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9904     // Bits [5:4] of the constant are the destination select.  This is the
9905     //  value of the incoming immediate.
9906     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9907     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9908     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9909     // Create this as a scalar to vector..
9910     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9911     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9912   }
9913
9914   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9915     // PINSR* works with constant index.
9916     return Op;
9917   }
9918   return SDValue();
9919 }
9920
9921 /// Insert one bit to mask vector, like v16i1 or v8i1.
9922 /// AVX-512 feature.
9923 SDValue 
9924 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9925   SDLoc dl(Op);
9926   SDValue Vec = Op.getOperand(0);
9927   SDValue Elt = Op.getOperand(1);
9928   SDValue Idx = Op.getOperand(2);
9929   MVT VecVT = Vec.getSimpleValueType();
9930
9931   if (!isa<ConstantSDNode>(Idx)) {
9932     // Non constant index. Extend source and destination,
9933     // insert element and then truncate the result.
9934     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9935     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9936     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9937       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9938       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9939     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9940   }
9941
9942   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9943   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9944   if (Vec.getOpcode() == ISD::UNDEF)
9945     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9946                        DAG.getConstant(IdxVal, MVT::i8));
9947   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9948   unsigned MaxSift = rc->getSize()*8 - 1;
9949   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9950                     DAG.getConstant(MaxSift, MVT::i8));
9951   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9952                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9953   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9954 }
9955 SDValue
9956 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9957   MVT VT = Op.getSimpleValueType();
9958   MVT EltVT = VT.getVectorElementType();
9959   
9960   if (EltVT == MVT::i1)
9961     return InsertBitToMaskVector(Op, DAG);
9962
9963   SDLoc dl(Op);
9964   SDValue N0 = Op.getOperand(0);
9965   SDValue N1 = Op.getOperand(1);
9966   SDValue N2 = Op.getOperand(2);
9967
9968   // If this is a 256-bit vector result, first extract the 128-bit vector,
9969   // insert the element into the extracted half and then place it back.
9970   if (VT.is256BitVector() || VT.is512BitVector()) {
9971     if (!isa<ConstantSDNode>(N2))
9972       return SDValue();
9973
9974     // Get the desired 128-bit vector half.
9975     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9976     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9977
9978     // Insert the element into the desired half.
9979     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9980     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9981
9982     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9983                     DAG.getConstant(IdxIn128, MVT::i32));
9984
9985     // Insert the changed part back to the 256-bit vector
9986     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9987   }
9988
9989   if (Subtarget->hasSSE41())
9990     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9991
9992   if (EltVT == MVT::i8)
9993     return SDValue();
9994
9995   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9996     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9997     // as its second argument.
9998     if (N1.getValueType() != MVT::i32)
9999       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10000     if (N2.getValueType() != MVT::i32)
10001       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10002     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10003   }
10004   return SDValue();
10005 }
10006
10007 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10008   SDLoc dl(Op);
10009   MVT OpVT = Op.getSimpleValueType();
10010
10011   // If this is a 256-bit vector result, first insert into a 128-bit
10012   // vector and then insert into the 256-bit vector.
10013   if (!OpVT.is128BitVector()) {
10014     // Insert into a 128-bit vector.
10015     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10016     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10017                                  OpVT.getVectorNumElements() / SizeFactor);
10018
10019     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10020
10021     // Insert the 128-bit vector.
10022     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10023   }
10024
10025   if (OpVT == MVT::v1i64 &&
10026       Op.getOperand(0).getValueType() == MVT::i64)
10027     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10028
10029   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10030   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10031   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10032                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10033 }
10034
10035 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10036 // a simple subregister reference or explicit instructions to grab
10037 // upper bits of a vector.
10038 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10039                                       SelectionDAG &DAG) {
10040   SDLoc dl(Op);
10041   SDValue In =  Op.getOperand(0);
10042   SDValue Idx = Op.getOperand(1);
10043   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10044   MVT ResVT   = Op.getSimpleValueType();
10045   MVT InVT    = In.getSimpleValueType();
10046
10047   if (Subtarget->hasFp256()) {
10048     if (ResVT.is128BitVector() &&
10049         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10050         isa<ConstantSDNode>(Idx)) {
10051       return Extract128BitVector(In, IdxVal, DAG, dl);
10052     }
10053     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10054         isa<ConstantSDNode>(Idx)) {
10055       return Extract256BitVector(In, IdxVal, DAG, dl);
10056     }
10057   }
10058   return SDValue();
10059 }
10060
10061 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10062 // simple superregister reference or explicit instructions to insert
10063 // the upper bits of a vector.
10064 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10065                                      SelectionDAG &DAG) {
10066   if (Subtarget->hasFp256()) {
10067     SDLoc dl(Op.getNode());
10068     SDValue Vec = Op.getNode()->getOperand(0);
10069     SDValue SubVec = Op.getNode()->getOperand(1);
10070     SDValue Idx = Op.getNode()->getOperand(2);
10071
10072     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10073          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10074         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10075         isa<ConstantSDNode>(Idx)) {
10076       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10077       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10078     }
10079
10080     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10081         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10082         isa<ConstantSDNode>(Idx)) {
10083       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10084       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10085     }
10086   }
10087   return SDValue();
10088 }
10089
10090 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10091 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10092 // one of the above mentioned nodes. It has to be wrapped because otherwise
10093 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10094 // be used to form addressing mode. These wrapped nodes will be selected
10095 // into MOV32ri.
10096 SDValue
10097 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10098   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10099
10100   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10101   // global base reg.
10102   unsigned char OpFlag = 0;
10103   unsigned WrapperKind = X86ISD::Wrapper;
10104   CodeModel::Model M = DAG.getTarget().getCodeModel();
10105
10106   if (Subtarget->isPICStyleRIPRel() &&
10107       (M == CodeModel::Small || M == CodeModel::Kernel))
10108     WrapperKind = X86ISD::WrapperRIP;
10109   else if (Subtarget->isPICStyleGOT())
10110     OpFlag = X86II::MO_GOTOFF;
10111   else if (Subtarget->isPICStyleStubPIC())
10112     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10113
10114   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10115                                              CP->getAlignment(),
10116                                              CP->getOffset(), OpFlag);
10117   SDLoc DL(CP);
10118   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10119   // With PIC, the address is actually $g + Offset.
10120   if (OpFlag) {
10121     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10122                          DAG.getNode(X86ISD::GlobalBaseReg,
10123                                      SDLoc(), getPointerTy()),
10124                          Result);
10125   }
10126
10127   return Result;
10128 }
10129
10130 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10131   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10132
10133   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10134   // global base reg.
10135   unsigned char OpFlag = 0;
10136   unsigned WrapperKind = X86ISD::Wrapper;
10137   CodeModel::Model M = DAG.getTarget().getCodeModel();
10138
10139   if (Subtarget->isPICStyleRIPRel() &&
10140       (M == CodeModel::Small || M == CodeModel::Kernel))
10141     WrapperKind = X86ISD::WrapperRIP;
10142   else if (Subtarget->isPICStyleGOT())
10143     OpFlag = X86II::MO_GOTOFF;
10144   else if (Subtarget->isPICStyleStubPIC())
10145     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10146
10147   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10148                                           OpFlag);
10149   SDLoc DL(JT);
10150   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10151
10152   // With PIC, the address is actually $g + Offset.
10153   if (OpFlag)
10154     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10155                          DAG.getNode(X86ISD::GlobalBaseReg,
10156                                      SDLoc(), getPointerTy()),
10157                          Result);
10158
10159   return Result;
10160 }
10161
10162 SDValue
10163 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10164   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10165
10166   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10167   // global base reg.
10168   unsigned char OpFlag = 0;
10169   unsigned WrapperKind = X86ISD::Wrapper;
10170   CodeModel::Model M = DAG.getTarget().getCodeModel();
10171
10172   if (Subtarget->isPICStyleRIPRel() &&
10173       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10174     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10175       OpFlag = X86II::MO_GOTPCREL;
10176     WrapperKind = X86ISD::WrapperRIP;
10177   } else if (Subtarget->isPICStyleGOT()) {
10178     OpFlag = X86II::MO_GOT;
10179   } else if (Subtarget->isPICStyleStubPIC()) {
10180     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10181   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10182     OpFlag = X86II::MO_DARWIN_NONLAZY;
10183   }
10184
10185   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10186
10187   SDLoc DL(Op);
10188   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10189
10190   // With PIC, the address is actually $g + Offset.
10191   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10192       !Subtarget->is64Bit()) {
10193     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10194                          DAG.getNode(X86ISD::GlobalBaseReg,
10195                                      SDLoc(), getPointerTy()),
10196                          Result);
10197   }
10198
10199   // For symbols that require a load from a stub to get the address, emit the
10200   // load.
10201   if (isGlobalStubReference(OpFlag))
10202     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10203                          MachinePointerInfo::getGOT(), false, false, false, 0);
10204
10205   return Result;
10206 }
10207
10208 SDValue
10209 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10210   // Create the TargetBlockAddressAddress node.
10211   unsigned char OpFlags =
10212     Subtarget->ClassifyBlockAddressReference();
10213   CodeModel::Model M = DAG.getTarget().getCodeModel();
10214   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10215   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10216   SDLoc dl(Op);
10217   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10218                                              OpFlags);
10219
10220   if (Subtarget->isPICStyleRIPRel() &&
10221       (M == CodeModel::Small || M == CodeModel::Kernel))
10222     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10223   else
10224     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10225
10226   // With PIC, the address is actually $g + Offset.
10227   if (isGlobalRelativeToPICBase(OpFlags)) {
10228     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10229                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10230                          Result);
10231   }
10232
10233   return Result;
10234 }
10235
10236 SDValue
10237 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10238                                       int64_t Offset, SelectionDAG &DAG) const {
10239   // Create the TargetGlobalAddress node, folding in the constant
10240   // offset if it is legal.
10241   unsigned char OpFlags =
10242       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10243   CodeModel::Model M = DAG.getTarget().getCodeModel();
10244   SDValue Result;
10245   if (OpFlags == X86II::MO_NO_FLAG &&
10246       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10247     // A direct static reference to a global.
10248     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10249     Offset = 0;
10250   } else {
10251     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10252   }
10253
10254   if (Subtarget->isPICStyleRIPRel() &&
10255       (M == CodeModel::Small || M == CodeModel::Kernel))
10256     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10257   else
10258     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10259
10260   // With PIC, the address is actually $g + Offset.
10261   if (isGlobalRelativeToPICBase(OpFlags)) {
10262     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10263                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10264                          Result);
10265   }
10266
10267   // For globals that require a load from a stub to get the address, emit the
10268   // load.
10269   if (isGlobalStubReference(OpFlags))
10270     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10271                          MachinePointerInfo::getGOT(), false, false, false, 0);
10272
10273   // If there was a non-zero offset that we didn't fold, create an explicit
10274   // addition for it.
10275   if (Offset != 0)
10276     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10277                          DAG.getConstant(Offset, getPointerTy()));
10278
10279   return Result;
10280 }
10281
10282 SDValue
10283 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10284   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10285   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10286   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10287 }
10288
10289 static SDValue
10290 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10291            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10292            unsigned char OperandFlags, bool LocalDynamic = false) {
10293   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10294   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10295   SDLoc dl(GA);
10296   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10297                                            GA->getValueType(0),
10298                                            GA->getOffset(),
10299                                            OperandFlags);
10300
10301   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10302                                            : X86ISD::TLSADDR;
10303
10304   if (InFlag) {
10305     SDValue Ops[] = { Chain,  TGA, *InFlag };
10306     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10307   } else {
10308     SDValue Ops[]  = { Chain, TGA };
10309     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10310   }
10311
10312   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10313   MFI->setAdjustsStack(true);
10314
10315   SDValue Flag = Chain.getValue(1);
10316   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10317 }
10318
10319 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10320 static SDValue
10321 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10322                                 const EVT PtrVT) {
10323   SDValue InFlag;
10324   SDLoc dl(GA);  // ? function entry point might be better
10325   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10326                                    DAG.getNode(X86ISD::GlobalBaseReg,
10327                                                SDLoc(), PtrVT), InFlag);
10328   InFlag = Chain.getValue(1);
10329
10330   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10331 }
10332
10333 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10334 static SDValue
10335 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10336                                 const EVT PtrVT) {
10337   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10338                     X86::RAX, X86II::MO_TLSGD);
10339 }
10340
10341 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10342                                            SelectionDAG &DAG,
10343                                            const EVT PtrVT,
10344                                            bool is64Bit) {
10345   SDLoc dl(GA);
10346
10347   // Get the start address of the TLS block for this module.
10348   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10349       .getInfo<X86MachineFunctionInfo>();
10350   MFI->incNumLocalDynamicTLSAccesses();
10351
10352   SDValue Base;
10353   if (is64Bit) {
10354     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10355                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10356   } else {
10357     SDValue InFlag;
10358     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10359         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10360     InFlag = Chain.getValue(1);
10361     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10362                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10363   }
10364
10365   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10366   // of Base.
10367
10368   // Build x@dtpoff.
10369   unsigned char OperandFlags = X86II::MO_DTPOFF;
10370   unsigned WrapperKind = X86ISD::Wrapper;
10371   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10372                                            GA->getValueType(0),
10373                                            GA->getOffset(), OperandFlags);
10374   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10375
10376   // Add x@dtpoff with the base.
10377   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10378 }
10379
10380 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10381 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10382                                    const EVT PtrVT, TLSModel::Model model,
10383                                    bool is64Bit, bool isPIC) {
10384   SDLoc dl(GA);
10385
10386   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10387   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10388                                                          is64Bit ? 257 : 256));
10389
10390   SDValue ThreadPointer =
10391       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10392                   MachinePointerInfo(Ptr), false, false, false, 0);
10393
10394   unsigned char OperandFlags = 0;
10395   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10396   // initialexec.
10397   unsigned WrapperKind = X86ISD::Wrapper;
10398   if (model == TLSModel::LocalExec) {
10399     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10400   } else if (model == TLSModel::InitialExec) {
10401     if (is64Bit) {
10402       OperandFlags = X86II::MO_GOTTPOFF;
10403       WrapperKind = X86ISD::WrapperRIP;
10404     } else {
10405       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10406     }
10407   } else {
10408     llvm_unreachable("Unexpected model");
10409   }
10410
10411   // emit "addl x@ntpoff,%eax" (local exec)
10412   // or "addl x@indntpoff,%eax" (initial exec)
10413   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10414   SDValue TGA =
10415       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10416                                  GA->getOffset(), OperandFlags);
10417   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10418
10419   if (model == TLSModel::InitialExec) {
10420     if (isPIC && !is64Bit) {
10421       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10422                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10423                            Offset);
10424     }
10425
10426     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10427                          MachinePointerInfo::getGOT(), false, false, false, 0);
10428   }
10429
10430   // The address of the thread local variable is the add of the thread
10431   // pointer with the offset of the variable.
10432   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10433 }
10434
10435 SDValue
10436 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10437
10438   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10439   const GlobalValue *GV = GA->getGlobal();
10440
10441   if (Subtarget->isTargetELF()) {
10442     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10443
10444     switch (model) {
10445       case TLSModel::GeneralDynamic:
10446         if (Subtarget->is64Bit())
10447           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10448         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10449       case TLSModel::LocalDynamic:
10450         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10451                                            Subtarget->is64Bit());
10452       case TLSModel::InitialExec:
10453       case TLSModel::LocalExec:
10454         return LowerToTLSExecModel(
10455             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10456             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10457     }
10458     llvm_unreachable("Unknown TLS model.");
10459   }
10460
10461   if (Subtarget->isTargetDarwin()) {
10462     // Darwin only has one model of TLS.  Lower to that.
10463     unsigned char OpFlag = 0;
10464     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10465                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10466
10467     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10468     // global base reg.
10469     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10470                  !Subtarget->is64Bit();
10471     if (PIC32)
10472       OpFlag = X86II::MO_TLVP_PIC_BASE;
10473     else
10474       OpFlag = X86II::MO_TLVP;
10475     SDLoc DL(Op);
10476     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10477                                                 GA->getValueType(0),
10478                                                 GA->getOffset(), OpFlag);
10479     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10480
10481     // With PIC32, the address is actually $g + Offset.
10482     if (PIC32)
10483       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10484                            DAG.getNode(X86ISD::GlobalBaseReg,
10485                                        SDLoc(), getPointerTy()),
10486                            Offset);
10487
10488     // Lowering the machine isd will make sure everything is in the right
10489     // location.
10490     SDValue Chain = DAG.getEntryNode();
10491     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10492     SDValue Args[] = { Chain, Offset };
10493     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10494
10495     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10496     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10497     MFI->setAdjustsStack(true);
10498
10499     // And our return value (tls address) is in the standard call return value
10500     // location.
10501     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10502     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10503                               Chain.getValue(1));
10504   }
10505
10506   if (Subtarget->isTargetKnownWindowsMSVC() ||
10507       Subtarget->isTargetWindowsGNU()) {
10508     // Just use the implicit TLS architecture
10509     // Need to generate someting similar to:
10510     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10511     //                                  ; from TEB
10512     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10513     //   mov     rcx, qword [rdx+rcx*8]
10514     //   mov     eax, .tls$:tlsvar
10515     //   [rax+rcx] contains the address
10516     // Windows 64bit: gs:0x58
10517     // Windows 32bit: fs:__tls_array
10518
10519     SDLoc dl(GA);
10520     SDValue Chain = DAG.getEntryNode();
10521
10522     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10523     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10524     // use its literal value of 0x2C.
10525     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10526                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10527                                                              256)
10528                                         : Type::getInt32PtrTy(*DAG.getContext(),
10529                                                               257));
10530
10531     SDValue TlsArray =
10532         Subtarget->is64Bit()
10533             ? DAG.getIntPtrConstant(0x58)
10534             : (Subtarget->isTargetWindowsGNU()
10535                    ? DAG.getIntPtrConstant(0x2C)
10536                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10537
10538     SDValue ThreadPointer =
10539         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10540                     MachinePointerInfo(Ptr), false, false, false, 0);
10541
10542     // Load the _tls_index variable
10543     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10544     if (Subtarget->is64Bit())
10545       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10546                            IDX, MachinePointerInfo(), MVT::i32,
10547                            false, false, 0);
10548     else
10549       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10550                         false, false, false, 0);
10551
10552     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10553                                     getPointerTy());
10554     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10555
10556     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10557     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10558                       false, false, false, 0);
10559
10560     // Get the offset of start of .tls section
10561     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10562                                              GA->getValueType(0),
10563                                              GA->getOffset(), X86II::MO_SECREL);
10564     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10565
10566     // The address of the thread local variable is the add of the thread
10567     // pointer with the offset of the variable.
10568     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10569   }
10570
10571   llvm_unreachable("TLS not implemented for this target.");
10572 }
10573
10574 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10575 /// and take a 2 x i32 value to shift plus a shift amount.
10576 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10577   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10578   MVT VT = Op.getSimpleValueType();
10579   unsigned VTBits = VT.getSizeInBits();
10580   SDLoc dl(Op);
10581   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10582   SDValue ShOpLo = Op.getOperand(0);
10583   SDValue ShOpHi = Op.getOperand(1);
10584   SDValue ShAmt  = Op.getOperand(2);
10585   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10586   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10587   // during isel.
10588   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10589                                   DAG.getConstant(VTBits - 1, MVT::i8));
10590   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10591                                      DAG.getConstant(VTBits - 1, MVT::i8))
10592                        : DAG.getConstant(0, VT);
10593
10594   SDValue Tmp2, Tmp3;
10595   if (Op.getOpcode() == ISD::SHL_PARTS) {
10596     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10597     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10598   } else {
10599     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10600     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10601   }
10602
10603   // If the shift amount is larger or equal than the width of a part we can't
10604   // rely on the results of shld/shrd. Insert a test and select the appropriate
10605   // values for large shift amounts.
10606   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10607                                 DAG.getConstant(VTBits, MVT::i8));
10608   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10609                              AndNode, DAG.getConstant(0, MVT::i8));
10610
10611   SDValue Hi, Lo;
10612   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10613   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10614   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10615
10616   if (Op.getOpcode() == ISD::SHL_PARTS) {
10617     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10618     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10619   } else {
10620     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10621     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10622   }
10623
10624   SDValue Ops[2] = { Lo, Hi };
10625   return DAG.getMergeValues(Ops, dl);
10626 }
10627
10628 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10629                                            SelectionDAG &DAG) const {
10630   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10631
10632   if (SrcVT.isVector())
10633     return SDValue();
10634
10635   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10636          "Unknown SINT_TO_FP to lower!");
10637
10638   // These are really Legal; return the operand so the caller accepts it as
10639   // Legal.
10640   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10641     return Op;
10642   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10643       Subtarget->is64Bit()) {
10644     return Op;
10645   }
10646
10647   SDLoc dl(Op);
10648   unsigned Size = SrcVT.getSizeInBits()/8;
10649   MachineFunction &MF = DAG.getMachineFunction();
10650   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10651   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10652   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10653                                StackSlot,
10654                                MachinePointerInfo::getFixedStack(SSFI),
10655                                false, false, 0);
10656   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10657 }
10658
10659 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10660                                      SDValue StackSlot,
10661                                      SelectionDAG &DAG) const {
10662   // Build the FILD
10663   SDLoc DL(Op);
10664   SDVTList Tys;
10665   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10666   if (useSSE)
10667     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10668   else
10669     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10670
10671   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10672
10673   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10674   MachineMemOperand *MMO;
10675   if (FI) {
10676     int SSFI = FI->getIndex();
10677     MMO =
10678       DAG.getMachineFunction()
10679       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10680                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10681   } else {
10682     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10683     StackSlot = StackSlot.getOperand(1);
10684   }
10685   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10686   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10687                                            X86ISD::FILD, DL,
10688                                            Tys, Ops, SrcVT, MMO);
10689
10690   if (useSSE) {
10691     Chain = Result.getValue(1);
10692     SDValue InFlag = Result.getValue(2);
10693
10694     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10695     // shouldn't be necessary except that RFP cannot be live across
10696     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10697     MachineFunction &MF = DAG.getMachineFunction();
10698     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10699     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10700     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10701     Tys = DAG.getVTList(MVT::Other);
10702     SDValue Ops[] = {
10703       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10704     };
10705     MachineMemOperand *MMO =
10706       DAG.getMachineFunction()
10707       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10708                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10709
10710     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10711                                     Ops, Op.getValueType(), MMO);
10712     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10713                          MachinePointerInfo::getFixedStack(SSFI),
10714                          false, false, false, 0);
10715   }
10716
10717   return Result;
10718 }
10719
10720 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10721 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10722                                                SelectionDAG &DAG) const {
10723   // This algorithm is not obvious. Here it is what we're trying to output:
10724   /*
10725      movq       %rax,  %xmm0
10726      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10727      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10728      #ifdef __SSE3__
10729        haddpd   %xmm0, %xmm0
10730      #else
10731        pshufd   $0x4e, %xmm0, %xmm1
10732        addpd    %xmm1, %xmm0
10733      #endif
10734   */
10735
10736   SDLoc dl(Op);
10737   LLVMContext *Context = DAG.getContext();
10738
10739   // Build some magic constants.
10740   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10741   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10742   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10743
10744   SmallVector<Constant*,2> CV1;
10745   CV1.push_back(
10746     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10747                                       APInt(64, 0x4330000000000000ULL))));
10748   CV1.push_back(
10749     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10750                                       APInt(64, 0x4530000000000000ULL))));
10751   Constant *C1 = ConstantVector::get(CV1);
10752   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10753
10754   // Load the 64-bit value into an XMM register.
10755   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10756                             Op.getOperand(0));
10757   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10758                               MachinePointerInfo::getConstantPool(),
10759                               false, false, false, 16);
10760   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10761                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10762                               CLod0);
10763
10764   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10765                               MachinePointerInfo::getConstantPool(),
10766                               false, false, false, 16);
10767   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10768   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10769   SDValue Result;
10770
10771   if (Subtarget->hasSSE3()) {
10772     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10773     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10774   } else {
10775     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10776     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10777                                            S2F, 0x4E, DAG);
10778     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10779                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10780                          Sub);
10781   }
10782
10783   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10784                      DAG.getIntPtrConstant(0));
10785 }
10786
10787 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10788 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10789                                                SelectionDAG &DAG) const {
10790   SDLoc dl(Op);
10791   // FP constant to bias correct the final result.
10792   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10793                                    MVT::f64);
10794
10795   // Load the 32-bit value into an XMM register.
10796   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10797                              Op.getOperand(0));
10798
10799   // Zero out the upper parts of the register.
10800   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10801
10802   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10803                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10804                      DAG.getIntPtrConstant(0));
10805
10806   // Or the load with the bias.
10807   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10808                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10809                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10810                                                    MVT::v2f64, Load)),
10811                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10812                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10813                                                    MVT::v2f64, Bias)));
10814   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10815                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10816                    DAG.getIntPtrConstant(0));
10817
10818   // Subtract the bias.
10819   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10820
10821   // Handle final rounding.
10822   EVT DestVT = Op.getValueType();
10823
10824   if (DestVT.bitsLT(MVT::f64))
10825     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10826                        DAG.getIntPtrConstant(0));
10827   if (DestVT.bitsGT(MVT::f64))
10828     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10829
10830   // Handle final rounding.
10831   return Sub;
10832 }
10833
10834 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10835                                                SelectionDAG &DAG) const {
10836   SDValue N0 = Op.getOperand(0);
10837   MVT SVT = N0.getSimpleValueType();
10838   SDLoc dl(Op);
10839
10840   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10841           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10842          "Custom UINT_TO_FP is not supported!");
10843
10844   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10845   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10846                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10847 }
10848
10849 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10850                                            SelectionDAG &DAG) const {
10851   SDValue N0 = Op.getOperand(0);
10852   SDLoc dl(Op);
10853
10854   if (Op.getValueType().isVector())
10855     return lowerUINT_TO_FP_vec(Op, DAG);
10856
10857   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10858   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10859   // the optimization here.
10860   if (DAG.SignBitIsZero(N0))
10861     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10862
10863   MVT SrcVT = N0.getSimpleValueType();
10864   MVT DstVT = Op.getSimpleValueType();
10865   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10866     return LowerUINT_TO_FP_i64(Op, DAG);
10867   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10868     return LowerUINT_TO_FP_i32(Op, DAG);
10869   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10870     return SDValue();
10871
10872   // Make a 64-bit buffer, and use it to build an FILD.
10873   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10874   if (SrcVT == MVT::i32) {
10875     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10876     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10877                                      getPointerTy(), StackSlot, WordOff);
10878     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10879                                   StackSlot, MachinePointerInfo(),
10880                                   false, false, 0);
10881     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10882                                   OffsetSlot, MachinePointerInfo(),
10883                                   false, false, 0);
10884     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10885     return Fild;
10886   }
10887
10888   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10889   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10890                                StackSlot, MachinePointerInfo(),
10891                                false, false, 0);
10892   // For i64 source, we need to add the appropriate power of 2 if the input
10893   // was negative.  This is the same as the optimization in
10894   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10895   // we must be careful to do the computation in x87 extended precision, not
10896   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10897   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10898   MachineMemOperand *MMO =
10899     DAG.getMachineFunction()
10900     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10901                           MachineMemOperand::MOLoad, 8, 8);
10902
10903   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10904   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10905   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10906                                          MVT::i64, MMO);
10907
10908   APInt FF(32, 0x5F800000ULL);
10909
10910   // Check whether the sign bit is set.
10911   SDValue SignSet = DAG.getSetCC(dl,
10912                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10913                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10914                                  ISD::SETLT);
10915
10916   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10917   SDValue FudgePtr = DAG.getConstantPool(
10918                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10919                                          getPointerTy());
10920
10921   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10922   SDValue Zero = DAG.getIntPtrConstant(0);
10923   SDValue Four = DAG.getIntPtrConstant(4);
10924   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10925                                Zero, Four);
10926   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10927
10928   // Load the value out, extending it from f32 to f80.
10929   // FIXME: Avoid the extend by constructing the right constant pool?
10930   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10931                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10932                                  MVT::f32, false, false, 4);
10933   // Extend everything to 80 bits to force it to be done on x87.
10934   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10935   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10936 }
10937
10938 std::pair<SDValue,SDValue>
10939 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10940                                     bool IsSigned, bool IsReplace) const {
10941   SDLoc DL(Op);
10942
10943   EVT DstTy = Op.getValueType();
10944
10945   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10946     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10947     DstTy = MVT::i64;
10948   }
10949
10950   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10951          DstTy.getSimpleVT() >= MVT::i16 &&
10952          "Unknown FP_TO_INT to lower!");
10953
10954   // These are really Legal.
10955   if (DstTy == MVT::i32 &&
10956       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10957     return std::make_pair(SDValue(), SDValue());
10958   if (Subtarget->is64Bit() &&
10959       DstTy == MVT::i64 &&
10960       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10961     return std::make_pair(SDValue(), SDValue());
10962
10963   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10964   // stack slot, or into the FTOL runtime function.
10965   MachineFunction &MF = DAG.getMachineFunction();
10966   unsigned MemSize = DstTy.getSizeInBits()/8;
10967   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10968   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10969
10970   unsigned Opc;
10971   if (!IsSigned && isIntegerTypeFTOL(DstTy))
10972     Opc = X86ISD::WIN_FTOL;
10973   else
10974     switch (DstTy.getSimpleVT().SimpleTy) {
10975     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10976     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10977     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10978     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10979     }
10980
10981   SDValue Chain = DAG.getEntryNode();
10982   SDValue Value = Op.getOperand(0);
10983   EVT TheVT = Op.getOperand(0).getValueType();
10984   // FIXME This causes a redundant load/store if the SSE-class value is already
10985   // in memory, such as if it is on the callstack.
10986   if (isScalarFPTypeInSSEReg(TheVT)) {
10987     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10988     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10989                          MachinePointerInfo::getFixedStack(SSFI),
10990                          false, false, 0);
10991     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10992     SDValue Ops[] = {
10993       Chain, StackSlot, DAG.getValueType(TheVT)
10994     };
10995
10996     MachineMemOperand *MMO =
10997       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10998                               MachineMemOperand::MOLoad, MemSize, MemSize);
10999     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11000     Chain = Value.getValue(1);
11001     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11002     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11003   }
11004
11005   MachineMemOperand *MMO =
11006     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11007                             MachineMemOperand::MOStore, MemSize, MemSize);
11008
11009   if (Opc != X86ISD::WIN_FTOL) {
11010     // Build the FP_TO_INT*_IN_MEM
11011     SDValue Ops[] = { Chain, Value, StackSlot };
11012     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11013                                            Ops, DstTy, MMO);
11014     return std::make_pair(FIST, StackSlot);
11015   } else {
11016     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11017       DAG.getVTList(MVT::Other, MVT::Glue),
11018       Chain, Value);
11019     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11020       MVT::i32, ftol.getValue(1));
11021     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11022       MVT::i32, eax.getValue(2));
11023     SDValue Ops[] = { eax, edx };
11024     SDValue pair = IsReplace
11025       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11026       : DAG.getMergeValues(Ops, DL);
11027     return std::make_pair(pair, SDValue());
11028   }
11029 }
11030
11031 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11032                               const X86Subtarget *Subtarget) {
11033   MVT VT = Op->getSimpleValueType(0);
11034   SDValue In = Op->getOperand(0);
11035   MVT InVT = In.getSimpleValueType();
11036   SDLoc dl(Op);
11037
11038   // Optimize vectors in AVX mode:
11039   //
11040   //   v8i16 -> v8i32
11041   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11042   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11043   //   Concat upper and lower parts.
11044   //
11045   //   v4i32 -> v4i64
11046   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11047   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11048   //   Concat upper and lower parts.
11049   //
11050
11051   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11052       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11053       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11054     return SDValue();
11055
11056   if (Subtarget->hasInt256())
11057     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11058
11059   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11060   SDValue Undef = DAG.getUNDEF(InVT);
11061   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11062   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11063   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11064
11065   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11066                              VT.getVectorNumElements()/2);
11067
11068   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11069   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11070
11071   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11072 }
11073
11074 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11075                                         SelectionDAG &DAG) {
11076   MVT VT = Op->getSimpleValueType(0);
11077   SDValue In = Op->getOperand(0);
11078   MVT InVT = In.getSimpleValueType();
11079   SDLoc DL(Op);
11080   unsigned int NumElts = VT.getVectorNumElements();
11081   if (NumElts != 8 && NumElts != 16)
11082     return SDValue();
11083
11084   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11085     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11086
11087   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11089   // Now we have only mask extension
11090   assert(InVT.getVectorElementType() == MVT::i1);
11091   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11092   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11093   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11094   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11095   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11096                            MachinePointerInfo::getConstantPool(),
11097                            false, false, false, Alignment);
11098
11099   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11100   if (VT.is512BitVector())
11101     return Brcst;
11102   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11103 }
11104
11105 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11106                                SelectionDAG &DAG) {
11107   if (Subtarget->hasFp256()) {
11108     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11109     if (Res.getNode())
11110       return Res;
11111   }
11112
11113   return SDValue();
11114 }
11115
11116 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11117                                 SelectionDAG &DAG) {
11118   SDLoc DL(Op);
11119   MVT VT = Op.getSimpleValueType();
11120   SDValue In = Op.getOperand(0);
11121   MVT SVT = In.getSimpleValueType();
11122
11123   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11124     return LowerZERO_EXTEND_AVX512(Op, DAG);
11125
11126   if (Subtarget->hasFp256()) {
11127     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11128     if (Res.getNode())
11129       return Res;
11130   }
11131
11132   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11133          VT.getVectorNumElements() != SVT.getVectorNumElements());
11134   return SDValue();
11135 }
11136
11137 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11138   SDLoc DL(Op);
11139   MVT VT = Op.getSimpleValueType();
11140   SDValue In = Op.getOperand(0);
11141   MVT InVT = In.getSimpleValueType();
11142
11143   if (VT == MVT::i1) {
11144     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11145            "Invalid scalar TRUNCATE operation");
11146     if (InVT == MVT::i32)
11147       return SDValue();
11148     if (InVT.getSizeInBits() == 64)
11149       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11150     else if (InVT.getSizeInBits() < 32)
11151       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11152     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11153   }
11154   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11155          "Invalid TRUNCATE operation");
11156
11157   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11158     if (VT.getVectorElementType().getSizeInBits() >=8)
11159       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11160
11161     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11162     unsigned NumElts = InVT.getVectorNumElements();
11163     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11164     if (InVT.getSizeInBits() < 512) {
11165       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11166       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11167       InVT = ExtVT;
11168     }
11169     
11170     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11171     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11172     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11173     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11174     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11175                            MachinePointerInfo::getConstantPool(),
11176                            false, false, false, Alignment);
11177     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11178     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11179     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11180   }
11181
11182   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11183     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11184     if (Subtarget->hasInt256()) {
11185       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11186       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11187       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11188                                 ShufMask);
11189       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11190                          DAG.getIntPtrConstant(0));
11191     }
11192
11193     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11194                                DAG.getIntPtrConstant(0));
11195     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11196                                DAG.getIntPtrConstant(2));
11197     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11198     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11199     static const int ShufMask[] = {0, 2, 4, 6};
11200     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11201   }
11202
11203   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11204     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11205     if (Subtarget->hasInt256()) {
11206       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11207
11208       SmallVector<SDValue,32> pshufbMask;
11209       for (unsigned i = 0; i < 2; ++i) {
11210         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11211         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11212         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11213         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11214         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11215         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11216         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11217         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11218         for (unsigned j = 0; j < 8; ++j)
11219           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11220       }
11221       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11222       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11223       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11224
11225       static const int ShufMask[] = {0,  2,  -1,  -1};
11226       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11227                                 &ShufMask[0]);
11228       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11229                        DAG.getIntPtrConstant(0));
11230       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11231     }
11232
11233     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11234                                DAG.getIntPtrConstant(0));
11235
11236     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11237                                DAG.getIntPtrConstant(4));
11238
11239     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11240     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11241
11242     // The PSHUFB mask:
11243     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11244                                    -1, -1, -1, -1, -1, -1, -1, -1};
11245
11246     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11247     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11248     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11249
11250     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11251     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11252
11253     // The MOVLHPS Mask:
11254     static const int ShufMask2[] = {0, 1, 4, 5};
11255     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11256     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11257   }
11258
11259   // Handle truncation of V256 to V128 using shuffles.
11260   if (!VT.is128BitVector() || !InVT.is256BitVector())
11261     return SDValue();
11262
11263   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11264
11265   unsigned NumElems = VT.getVectorNumElements();
11266   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11267
11268   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11269   // Prepare truncation shuffle mask
11270   for (unsigned i = 0; i != NumElems; ++i)
11271     MaskVec[i] = i * 2;
11272   SDValue V = DAG.getVectorShuffle(NVT, DL,
11273                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11274                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11275   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11276                      DAG.getIntPtrConstant(0));
11277 }
11278
11279 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11280                                            SelectionDAG &DAG) const {
11281   assert(!Op.getSimpleValueType().isVector());
11282
11283   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11284     /*IsSigned=*/ true, /*IsReplace=*/ false);
11285   SDValue FIST = Vals.first, StackSlot = Vals.second;
11286   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11287   if (!FIST.getNode()) return Op;
11288
11289   if (StackSlot.getNode())
11290     // Load the result.
11291     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11292                        FIST, StackSlot, MachinePointerInfo(),
11293                        false, false, false, 0);
11294
11295   // The node is the result.
11296   return FIST;
11297 }
11298
11299 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11300                                            SelectionDAG &DAG) const {
11301   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11302     /*IsSigned=*/ false, /*IsReplace=*/ false);
11303   SDValue FIST = Vals.first, StackSlot = Vals.second;
11304   assert(FIST.getNode() && "Unexpected failure");
11305
11306   if (StackSlot.getNode())
11307     // Load the result.
11308     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11309                        FIST, StackSlot, MachinePointerInfo(),
11310                        false, false, false, 0);
11311
11312   // The node is the result.
11313   return FIST;
11314 }
11315
11316 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11317   SDLoc DL(Op);
11318   MVT VT = Op.getSimpleValueType();
11319   SDValue In = Op.getOperand(0);
11320   MVT SVT = In.getSimpleValueType();
11321
11322   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11323
11324   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11325                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11326                                  In, DAG.getUNDEF(SVT)));
11327 }
11328
11329 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11330   LLVMContext *Context = DAG.getContext();
11331   SDLoc dl(Op);
11332   MVT VT = Op.getSimpleValueType();
11333   MVT EltVT = VT;
11334   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11335   if (VT.isVector()) {
11336     EltVT = VT.getVectorElementType();
11337     NumElts = VT.getVectorNumElements();
11338   }
11339   Constant *C;
11340   if (EltVT == MVT::f64)
11341     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11342                                           APInt(64, ~(1ULL << 63))));
11343   else
11344     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11345                                           APInt(32, ~(1U << 31))));
11346   C = ConstantVector::getSplat(NumElts, C);
11347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11348   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11349   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11350   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11351                              MachinePointerInfo::getConstantPool(),
11352                              false, false, false, Alignment);
11353   if (VT.isVector()) {
11354     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11355     return DAG.getNode(ISD::BITCAST, dl, VT,
11356                        DAG.getNode(ISD::AND, dl, ANDVT,
11357                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11358                                                Op.getOperand(0)),
11359                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11360   }
11361   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11362 }
11363
11364 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11365   LLVMContext *Context = DAG.getContext();
11366   SDLoc dl(Op);
11367   MVT VT = Op.getSimpleValueType();
11368   MVT EltVT = VT;
11369   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11370   if (VT.isVector()) {
11371     EltVT = VT.getVectorElementType();
11372     NumElts = VT.getVectorNumElements();
11373   }
11374   Constant *C;
11375   if (EltVT == MVT::f64)
11376     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11377                                           APInt(64, 1ULL << 63)));
11378   else
11379     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11380                                           APInt(32, 1U << 31)));
11381   C = ConstantVector::getSplat(NumElts, C);
11382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11383   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11384   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11385   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11386                              MachinePointerInfo::getConstantPool(),
11387                              false, false, false, Alignment);
11388   if (VT.isVector()) {
11389     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11390     return DAG.getNode(ISD::BITCAST, dl, VT,
11391                        DAG.getNode(ISD::XOR, dl, XORVT,
11392                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11393                                                Op.getOperand(0)),
11394                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11395   }
11396
11397   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11398 }
11399
11400 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11402   LLVMContext *Context = DAG.getContext();
11403   SDValue Op0 = Op.getOperand(0);
11404   SDValue Op1 = Op.getOperand(1);
11405   SDLoc dl(Op);
11406   MVT VT = Op.getSimpleValueType();
11407   MVT SrcVT = Op1.getSimpleValueType();
11408
11409   // If second operand is smaller, extend it first.
11410   if (SrcVT.bitsLT(VT)) {
11411     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11412     SrcVT = VT;
11413   }
11414   // And if it is bigger, shrink it first.
11415   if (SrcVT.bitsGT(VT)) {
11416     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11417     SrcVT = VT;
11418   }
11419
11420   // At this point the operands and the result should have the same
11421   // type, and that won't be f80 since that is not custom lowered.
11422
11423   // First get the sign bit of second operand.
11424   SmallVector<Constant*,4> CV;
11425   if (SrcVT == MVT::f64) {
11426     const fltSemantics &Sem = APFloat::IEEEdouble;
11427     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11428     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11429   } else {
11430     const fltSemantics &Sem = APFloat::IEEEsingle;
11431     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11432     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11433     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11434     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11435   }
11436   Constant *C = ConstantVector::get(CV);
11437   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11438   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11439                               MachinePointerInfo::getConstantPool(),
11440                               false, false, false, 16);
11441   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11442
11443   // Shift sign bit right or left if the two operands have different types.
11444   if (SrcVT.bitsGT(VT)) {
11445     // Op0 is MVT::f32, Op1 is MVT::f64.
11446     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11447     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11448                           DAG.getConstant(32, MVT::i32));
11449     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11450     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11451                           DAG.getIntPtrConstant(0));
11452   }
11453
11454   // Clear first operand sign bit.
11455   CV.clear();
11456   if (VT == MVT::f64) {
11457     const fltSemantics &Sem = APFloat::IEEEdouble;
11458     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11459                                                    APInt(64, ~(1ULL << 63)))));
11460     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11461   } else {
11462     const fltSemantics &Sem = APFloat::IEEEsingle;
11463     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11464                                                    APInt(32, ~(1U << 31)))));
11465     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11466     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11467     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11468   }
11469   C = ConstantVector::get(CV);
11470   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11471   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11472                               MachinePointerInfo::getConstantPool(),
11473                               false, false, false, 16);
11474   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11475
11476   // Or the value with the sign bit.
11477   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11478 }
11479
11480 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11481   SDValue N0 = Op.getOperand(0);
11482   SDLoc dl(Op);
11483   MVT VT = Op.getSimpleValueType();
11484
11485   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11486   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11487                                   DAG.getConstant(1, VT));
11488   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11489 }
11490
11491 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11492 //
11493 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11494                                       SelectionDAG &DAG) {
11495   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11496
11497   if (!Subtarget->hasSSE41())
11498     return SDValue();
11499
11500   if (!Op->hasOneUse())
11501     return SDValue();
11502
11503   SDNode *N = Op.getNode();
11504   SDLoc DL(N);
11505
11506   SmallVector<SDValue, 8> Opnds;
11507   DenseMap<SDValue, unsigned> VecInMap;
11508   SmallVector<SDValue, 8> VecIns;
11509   EVT VT = MVT::Other;
11510
11511   // Recognize a special case where a vector is casted into wide integer to
11512   // test all 0s.
11513   Opnds.push_back(N->getOperand(0));
11514   Opnds.push_back(N->getOperand(1));
11515
11516   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11517     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11518     // BFS traverse all OR'd operands.
11519     if (I->getOpcode() == ISD::OR) {
11520       Opnds.push_back(I->getOperand(0));
11521       Opnds.push_back(I->getOperand(1));
11522       // Re-evaluate the number of nodes to be traversed.
11523       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11524       continue;
11525     }
11526
11527     // Quit if a non-EXTRACT_VECTOR_ELT
11528     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11529       return SDValue();
11530
11531     // Quit if without a constant index.
11532     SDValue Idx = I->getOperand(1);
11533     if (!isa<ConstantSDNode>(Idx))
11534       return SDValue();
11535
11536     SDValue ExtractedFromVec = I->getOperand(0);
11537     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11538     if (M == VecInMap.end()) {
11539       VT = ExtractedFromVec.getValueType();
11540       // Quit if not 128/256-bit vector.
11541       if (!VT.is128BitVector() && !VT.is256BitVector())
11542         return SDValue();
11543       // Quit if not the same type.
11544       if (VecInMap.begin() != VecInMap.end() &&
11545           VT != VecInMap.begin()->first.getValueType())
11546         return SDValue();
11547       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11548       VecIns.push_back(ExtractedFromVec);
11549     }
11550     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11551   }
11552
11553   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11554          "Not extracted from 128-/256-bit vector.");
11555
11556   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11557
11558   for (DenseMap<SDValue, unsigned>::const_iterator
11559         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11560     // Quit if not all elements are used.
11561     if (I->second != FullMask)
11562       return SDValue();
11563   }
11564
11565   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11566
11567   // Cast all vectors into TestVT for PTEST.
11568   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11569     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11570
11571   // If more than one full vectors are evaluated, OR them first before PTEST.
11572   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11573     // Each iteration will OR 2 nodes and append the result until there is only
11574     // 1 node left, i.e. the final OR'd value of all vectors.
11575     SDValue LHS = VecIns[Slot];
11576     SDValue RHS = VecIns[Slot + 1];
11577     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11578   }
11579
11580   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11581                      VecIns.back(), VecIns.back());
11582 }
11583
11584 /// \brief return true if \c Op has a use that doesn't just read flags.
11585 static bool hasNonFlagsUse(SDValue Op) {
11586   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11587        ++UI) {
11588     SDNode *User = *UI;
11589     unsigned UOpNo = UI.getOperandNo();
11590     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11591       // Look pass truncate.
11592       UOpNo = User->use_begin().getOperandNo();
11593       User = *User->use_begin();
11594     }
11595
11596     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11597         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11598       return true;
11599   }
11600   return false;
11601 }
11602
11603 /// Emit nodes that will be selected as "test Op0,Op0", or something
11604 /// equivalent.
11605 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11606                                     SelectionDAG &DAG) const {
11607   if (Op.getValueType() == MVT::i1)
11608     // KORTEST instruction should be selected
11609     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11610                        DAG.getConstant(0, Op.getValueType()));
11611
11612   // CF and OF aren't always set the way we want. Determine which
11613   // of these we need.
11614   bool NeedCF = false;
11615   bool NeedOF = false;
11616   switch (X86CC) {
11617   default: break;
11618   case X86::COND_A: case X86::COND_AE:
11619   case X86::COND_B: case X86::COND_BE:
11620     NeedCF = true;
11621     break;
11622   case X86::COND_G: case X86::COND_GE:
11623   case X86::COND_L: case X86::COND_LE:
11624   case X86::COND_O: case X86::COND_NO: {
11625     // Check if we really need to set the
11626     // Overflow flag. If NoSignedWrap is present
11627     // that is not actually needed.
11628     switch (Op->getOpcode()) {
11629     case ISD::ADD:
11630     case ISD::SUB:
11631     case ISD::MUL:
11632     case ISD::SHL: {
11633       const BinaryWithFlagsSDNode *BinNode =
11634           cast<BinaryWithFlagsSDNode>(Op.getNode());
11635       if (BinNode->hasNoSignedWrap())
11636         break;
11637     }
11638     default:
11639       NeedOF = true;
11640       break;
11641     }
11642     break;
11643   }
11644   }
11645   // See if we can use the EFLAGS value from the operand instead of
11646   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11647   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11648   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11649     // Emit a CMP with 0, which is the TEST pattern.
11650     //if (Op.getValueType() == MVT::i1)
11651     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11652     //                     DAG.getConstant(0, MVT::i1));
11653     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11654                        DAG.getConstant(0, Op.getValueType()));
11655   }
11656   unsigned Opcode = 0;
11657   unsigned NumOperands = 0;
11658
11659   // Truncate operations may prevent the merge of the SETCC instruction
11660   // and the arithmetic instruction before it. Attempt to truncate the operands
11661   // of the arithmetic instruction and use a reduced bit-width instruction.
11662   bool NeedTruncation = false;
11663   SDValue ArithOp = Op;
11664   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11665     SDValue Arith = Op->getOperand(0);
11666     // Both the trunc and the arithmetic op need to have one user each.
11667     if (Arith->hasOneUse())
11668       switch (Arith.getOpcode()) {
11669         default: break;
11670         case ISD::ADD:
11671         case ISD::SUB:
11672         case ISD::AND:
11673         case ISD::OR:
11674         case ISD::XOR: {
11675           NeedTruncation = true;
11676           ArithOp = Arith;
11677         }
11678       }
11679   }
11680
11681   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11682   // which may be the result of a CAST.  We use the variable 'Op', which is the
11683   // non-casted variable when we check for possible users.
11684   switch (ArithOp.getOpcode()) {
11685   case ISD::ADD:
11686     // Due to an isel shortcoming, be conservative if this add is likely to be
11687     // selected as part of a load-modify-store instruction. When the root node
11688     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11689     // uses of other nodes in the match, such as the ADD in this case. This
11690     // leads to the ADD being left around and reselected, with the result being
11691     // two adds in the output.  Alas, even if none our users are stores, that
11692     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11693     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11694     // climbing the DAG back to the root, and it doesn't seem to be worth the
11695     // effort.
11696     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11697          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11698       if (UI->getOpcode() != ISD::CopyToReg &&
11699           UI->getOpcode() != ISD::SETCC &&
11700           UI->getOpcode() != ISD::STORE)
11701         goto default_case;
11702
11703     if (ConstantSDNode *C =
11704         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11705       // An add of one will be selected as an INC.
11706       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11707         Opcode = X86ISD::INC;
11708         NumOperands = 1;
11709         break;
11710       }
11711
11712       // An add of negative one (subtract of one) will be selected as a DEC.
11713       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11714         Opcode = X86ISD::DEC;
11715         NumOperands = 1;
11716         break;
11717       }
11718     }
11719
11720     // Otherwise use a regular EFLAGS-setting add.
11721     Opcode = X86ISD::ADD;
11722     NumOperands = 2;
11723     break;
11724   case ISD::SHL:
11725   case ISD::SRL:
11726     // If we have a constant logical shift that's only used in a comparison
11727     // against zero turn it into an equivalent AND. This allows turning it into
11728     // a TEST instruction later.
11729     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11730         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11731       EVT VT = Op.getValueType();
11732       unsigned BitWidth = VT.getSizeInBits();
11733       unsigned ShAmt = Op->getConstantOperandVal(1);
11734       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11735         break;
11736       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11737                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11738                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11739       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11740         break;
11741       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11742                                 DAG.getConstant(Mask, VT));
11743       DAG.ReplaceAllUsesWith(Op, New);
11744       Op = New;
11745     }
11746     break;
11747
11748   case ISD::AND:
11749     // If the primary and result isn't used, don't bother using X86ISD::AND,
11750     // because a TEST instruction will be better.
11751     if (!hasNonFlagsUse(Op))
11752       break;
11753     // FALL THROUGH
11754   case ISD::SUB:
11755   case ISD::OR:
11756   case ISD::XOR:
11757     // Due to the ISEL shortcoming noted above, be conservative if this op is
11758     // likely to be selected as part of a load-modify-store instruction.
11759     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11760            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11761       if (UI->getOpcode() == ISD::STORE)
11762         goto default_case;
11763
11764     // Otherwise use a regular EFLAGS-setting instruction.
11765     switch (ArithOp.getOpcode()) {
11766     default: llvm_unreachable("unexpected operator!");
11767     case ISD::SUB: Opcode = X86ISD::SUB; break;
11768     case ISD::XOR: Opcode = X86ISD::XOR; break;
11769     case ISD::AND: Opcode = X86ISD::AND; break;
11770     case ISD::OR: {
11771       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11772         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11773         if (EFLAGS.getNode())
11774           return EFLAGS;
11775       }
11776       Opcode = X86ISD::OR;
11777       break;
11778     }
11779     }
11780
11781     NumOperands = 2;
11782     break;
11783   case X86ISD::ADD:
11784   case X86ISD::SUB:
11785   case X86ISD::INC:
11786   case X86ISD::DEC:
11787   case X86ISD::OR:
11788   case X86ISD::XOR:
11789   case X86ISD::AND:
11790     return SDValue(Op.getNode(), 1);
11791   default:
11792   default_case:
11793     break;
11794   }
11795
11796   // If we found that truncation is beneficial, perform the truncation and
11797   // update 'Op'.
11798   if (NeedTruncation) {
11799     EVT VT = Op.getValueType();
11800     SDValue WideVal = Op->getOperand(0);
11801     EVT WideVT = WideVal.getValueType();
11802     unsigned ConvertedOp = 0;
11803     // Use a target machine opcode to prevent further DAGCombine
11804     // optimizations that may separate the arithmetic operations
11805     // from the setcc node.
11806     switch (WideVal.getOpcode()) {
11807       default: break;
11808       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11809       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11810       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11811       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11812       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11813     }
11814
11815     if (ConvertedOp) {
11816       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11817       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11818         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11819         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11820         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11821       }
11822     }
11823   }
11824
11825   if (Opcode == 0)
11826     // Emit a CMP with 0, which is the TEST pattern.
11827     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11828                        DAG.getConstant(0, Op.getValueType()));
11829
11830   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11831   SmallVector<SDValue, 4> Ops;
11832   for (unsigned i = 0; i != NumOperands; ++i)
11833     Ops.push_back(Op.getOperand(i));
11834
11835   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11836   DAG.ReplaceAllUsesWith(Op, New);
11837   return SDValue(New.getNode(), 1);
11838 }
11839
11840 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11841 /// equivalent.
11842 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11843                                    SDLoc dl, SelectionDAG &DAG) const {
11844   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11845     if (C->getAPIntValue() == 0)
11846       return EmitTest(Op0, X86CC, dl, DAG);
11847
11848      if (Op0.getValueType() == MVT::i1)
11849        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11850   }
11851  
11852   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11853        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11854     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11855     // This avoids subregister aliasing issues. Keep the smaller reference 
11856     // if we're optimizing for size, however, as that'll allow better folding 
11857     // of memory operations.
11858     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11859         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11860              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11861         !Subtarget->isAtom()) {
11862       unsigned ExtendOp =
11863           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11864       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11865       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11866     }
11867     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11868     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11869     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11870                               Op0, Op1);
11871     return SDValue(Sub.getNode(), 1);
11872   }
11873   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11874 }
11875
11876 /// Convert a comparison if required by the subtarget.
11877 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11878                                                  SelectionDAG &DAG) const {
11879   // If the subtarget does not support the FUCOMI instruction, floating-point
11880   // comparisons have to be converted.
11881   if (Subtarget->hasCMov() ||
11882       Cmp.getOpcode() != X86ISD::CMP ||
11883       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11884       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11885     return Cmp;
11886
11887   // The instruction selector will select an FUCOM instruction instead of
11888   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11889   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11890   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11891   SDLoc dl(Cmp);
11892   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11893   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11894   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11895                             DAG.getConstant(8, MVT::i8));
11896   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11897   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11898 }
11899
11900 static bool isAllOnes(SDValue V) {
11901   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11902   return C && C->isAllOnesValue();
11903 }
11904
11905 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11906 /// if it's possible.
11907 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11908                                      SDLoc dl, SelectionDAG &DAG) const {
11909   SDValue Op0 = And.getOperand(0);
11910   SDValue Op1 = And.getOperand(1);
11911   if (Op0.getOpcode() == ISD::TRUNCATE)
11912     Op0 = Op0.getOperand(0);
11913   if (Op1.getOpcode() == ISD::TRUNCATE)
11914     Op1 = Op1.getOperand(0);
11915
11916   SDValue LHS, RHS;
11917   if (Op1.getOpcode() == ISD::SHL)
11918     std::swap(Op0, Op1);
11919   if (Op0.getOpcode() == ISD::SHL) {
11920     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11921       if (And00C->getZExtValue() == 1) {
11922         // If we looked past a truncate, check that it's only truncating away
11923         // known zeros.
11924         unsigned BitWidth = Op0.getValueSizeInBits();
11925         unsigned AndBitWidth = And.getValueSizeInBits();
11926         if (BitWidth > AndBitWidth) {
11927           APInt Zeros, Ones;
11928           DAG.computeKnownBits(Op0, Zeros, Ones);
11929           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11930             return SDValue();
11931         }
11932         LHS = Op1;
11933         RHS = Op0.getOperand(1);
11934       }
11935   } else if (Op1.getOpcode() == ISD::Constant) {
11936     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11937     uint64_t AndRHSVal = AndRHS->getZExtValue();
11938     SDValue AndLHS = Op0;
11939
11940     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11941       LHS = AndLHS.getOperand(0);
11942       RHS = AndLHS.getOperand(1);
11943     }
11944
11945     // Use BT if the immediate can't be encoded in a TEST instruction.
11946     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11947       LHS = AndLHS;
11948       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11949     }
11950   }
11951
11952   if (LHS.getNode()) {
11953     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
11954     // instruction.  Since the shift amount is in-range-or-undefined, we know
11955     // that doing a bittest on the i32 value is ok.  We extend to i32 because
11956     // the encoding for the i16 version is larger than the i32 version.
11957     // Also promote i16 to i32 for performance / code size reason.
11958     if (LHS.getValueType() == MVT::i8 ||
11959         LHS.getValueType() == MVT::i16)
11960       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11961
11962     // If the operand types disagree, extend the shift amount to match.  Since
11963     // BT ignores high bits (like shifts) we can use anyextend.
11964     if (LHS.getValueType() != RHS.getValueType())
11965       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11966
11967     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11968     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11969     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11970                        DAG.getConstant(Cond, MVT::i8), BT);
11971   }
11972
11973   return SDValue();
11974 }
11975
11976 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11977 /// mask CMPs.
11978 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11979                               SDValue &Op1) {
11980   unsigned SSECC;
11981   bool Swap = false;
11982
11983   // SSE Condition code mapping:
11984   //  0 - EQ
11985   //  1 - LT
11986   //  2 - LE
11987   //  3 - UNORD
11988   //  4 - NEQ
11989   //  5 - NLT
11990   //  6 - NLE
11991   //  7 - ORD
11992   switch (SetCCOpcode) {
11993   default: llvm_unreachable("Unexpected SETCC condition");
11994   case ISD::SETOEQ:
11995   case ISD::SETEQ:  SSECC = 0; break;
11996   case ISD::SETOGT:
11997   case ISD::SETGT:  Swap = true; // Fallthrough
11998   case ISD::SETLT:
11999   case ISD::SETOLT: SSECC = 1; break;
12000   case ISD::SETOGE:
12001   case ISD::SETGE:  Swap = true; // Fallthrough
12002   case ISD::SETLE:
12003   case ISD::SETOLE: SSECC = 2; break;
12004   case ISD::SETUO:  SSECC = 3; break;
12005   case ISD::SETUNE:
12006   case ISD::SETNE:  SSECC = 4; break;
12007   case ISD::SETULE: Swap = true; // Fallthrough
12008   case ISD::SETUGE: SSECC = 5; break;
12009   case ISD::SETULT: Swap = true; // Fallthrough
12010   case ISD::SETUGT: SSECC = 6; break;
12011   case ISD::SETO:   SSECC = 7; break;
12012   case ISD::SETUEQ:
12013   case ISD::SETONE: SSECC = 8; break;
12014   }
12015   if (Swap)
12016     std::swap(Op0, Op1);
12017
12018   return SSECC;
12019 }
12020
12021 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12022 // ones, and then concatenate the result back.
12023 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12024   MVT VT = Op.getSimpleValueType();
12025
12026   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12027          "Unsupported value type for operation");
12028
12029   unsigned NumElems = VT.getVectorNumElements();
12030   SDLoc dl(Op);
12031   SDValue CC = Op.getOperand(2);
12032
12033   // Extract the LHS vectors
12034   SDValue LHS = Op.getOperand(0);
12035   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12036   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12037
12038   // Extract the RHS vectors
12039   SDValue RHS = Op.getOperand(1);
12040   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12041   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12042
12043   // Issue the operation on the smaller types and concatenate the result back
12044   MVT EltVT = VT.getVectorElementType();
12045   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12046   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12047                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12048                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12049 }
12050
12051 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12052                                      const X86Subtarget *Subtarget) {
12053   SDValue Op0 = Op.getOperand(0);
12054   SDValue Op1 = Op.getOperand(1);
12055   SDValue CC = Op.getOperand(2);
12056   MVT VT = Op.getSimpleValueType();
12057   SDLoc dl(Op);
12058
12059   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12060          Op.getValueType().getScalarType() == MVT::i1 &&
12061          "Cannot set masked compare for this operation");
12062
12063   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12064   unsigned  Opc = 0;
12065   bool Unsigned = false;
12066   bool Swap = false;
12067   unsigned SSECC;
12068   switch (SetCCOpcode) {
12069   default: llvm_unreachable("Unexpected SETCC condition");
12070   case ISD::SETNE:  SSECC = 4; break;
12071   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12072   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12073   case ISD::SETLT:  Swap = true; //fall-through
12074   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12075   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12076   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12077   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12078   case ISD::SETULE: Unsigned = true; //fall-through
12079   case ISD::SETLE:  SSECC = 2; break;
12080   }
12081
12082   if (Swap)
12083     std::swap(Op0, Op1);
12084   if (Opc)
12085     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12086   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12087   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12088                      DAG.getConstant(SSECC, MVT::i8));
12089 }
12090
12091 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12092 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12093 /// return an empty value.
12094 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12095 {
12096   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12097   if (!BV)
12098     return SDValue();
12099
12100   MVT VT = Op1.getSimpleValueType();
12101   MVT EVT = VT.getVectorElementType();
12102   unsigned n = VT.getVectorNumElements();
12103   SmallVector<SDValue, 8> ULTOp1;
12104
12105   for (unsigned i = 0; i < n; ++i) {
12106     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12107     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12108       return SDValue();
12109
12110     // Avoid underflow.
12111     APInt Val = Elt->getAPIntValue();
12112     if (Val == 0)
12113       return SDValue();
12114
12115     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12116   }
12117
12118   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12119 }
12120
12121 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12122                            SelectionDAG &DAG) {
12123   SDValue Op0 = Op.getOperand(0);
12124   SDValue Op1 = Op.getOperand(1);
12125   SDValue CC = Op.getOperand(2);
12126   MVT VT = Op.getSimpleValueType();
12127   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12128   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12129   SDLoc dl(Op);
12130
12131   if (isFP) {
12132 #ifndef NDEBUG
12133     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12134     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12135 #endif
12136
12137     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12138     unsigned Opc = X86ISD::CMPP;
12139     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12140       assert(VT.getVectorNumElements() <= 16);
12141       Opc = X86ISD::CMPM;
12142     }
12143     // In the two special cases we can't handle, emit two comparisons.
12144     if (SSECC == 8) {
12145       unsigned CC0, CC1;
12146       unsigned CombineOpc;
12147       if (SetCCOpcode == ISD::SETUEQ) {
12148         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12149       } else {
12150         assert(SetCCOpcode == ISD::SETONE);
12151         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12152       }
12153
12154       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12155                                  DAG.getConstant(CC0, MVT::i8));
12156       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12157                                  DAG.getConstant(CC1, MVT::i8));
12158       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12159     }
12160     // Handle all other FP comparisons here.
12161     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12162                        DAG.getConstant(SSECC, MVT::i8));
12163   }
12164
12165   // Break 256-bit integer vector compare into smaller ones.
12166   if (VT.is256BitVector() && !Subtarget->hasInt256())
12167     return Lower256IntVSETCC(Op, DAG);
12168
12169   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12170   EVT OpVT = Op1.getValueType();
12171   if (Subtarget->hasAVX512()) {
12172     if (Op1.getValueType().is512BitVector() ||
12173         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12174       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12175
12176     // In AVX-512 architecture setcc returns mask with i1 elements,
12177     // But there is no compare instruction for i8 and i16 elements.
12178     // We are not talking about 512-bit operands in this case, these
12179     // types are illegal.
12180     if (MaskResult &&
12181         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12182          OpVT.getVectorElementType().getSizeInBits() >= 8))
12183       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12184                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12185   }
12186
12187   // We are handling one of the integer comparisons here.  Since SSE only has
12188   // GT and EQ comparisons for integer, swapping operands and multiple
12189   // operations may be required for some comparisons.
12190   unsigned Opc;
12191   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12192   bool Subus = false;
12193
12194   switch (SetCCOpcode) {
12195   default: llvm_unreachable("Unexpected SETCC condition");
12196   case ISD::SETNE:  Invert = true;
12197   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12198   case ISD::SETLT:  Swap = true;
12199   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12200   case ISD::SETGE:  Swap = true;
12201   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12202                     Invert = true; break;
12203   case ISD::SETULT: Swap = true;
12204   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12205                     FlipSigns = true; break;
12206   case ISD::SETUGE: Swap = true;
12207   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12208                     FlipSigns = true; Invert = true; break;
12209   }
12210
12211   // Special case: Use min/max operations for SETULE/SETUGE
12212   MVT VET = VT.getVectorElementType();
12213   bool hasMinMax =
12214        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12215     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12216
12217   if (hasMinMax) {
12218     switch (SetCCOpcode) {
12219     default: break;
12220     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12221     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12222     }
12223
12224     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12225   }
12226
12227   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12228   if (!MinMax && hasSubus) {
12229     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12230     // Op0 u<= Op1:
12231     //   t = psubus Op0, Op1
12232     //   pcmpeq t, <0..0>
12233     switch (SetCCOpcode) {
12234     default: break;
12235     case ISD::SETULT: {
12236       // If the comparison is against a constant we can turn this into a
12237       // setule.  With psubus, setule does not require a swap.  This is
12238       // beneficial because the constant in the register is no longer
12239       // destructed as the destination so it can be hoisted out of a loop.
12240       // Only do this pre-AVX since vpcmp* is no longer destructive.
12241       if (Subtarget->hasAVX())
12242         break;
12243       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12244       if (ULEOp1.getNode()) {
12245         Op1 = ULEOp1;
12246         Subus = true; Invert = false; Swap = false;
12247       }
12248       break;
12249     }
12250     // Psubus is better than flip-sign because it requires no inversion.
12251     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12252     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12253     }
12254
12255     if (Subus) {
12256       Opc = X86ISD::SUBUS;
12257       FlipSigns = false;
12258     }
12259   }
12260
12261   if (Swap)
12262     std::swap(Op0, Op1);
12263
12264   // Check that the operation in question is available (most are plain SSE2,
12265   // but PCMPGTQ and PCMPEQQ have different requirements).
12266   if (VT == MVT::v2i64) {
12267     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12268       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12269
12270       // First cast everything to the right type.
12271       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12272       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12273
12274       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12275       // bits of the inputs before performing those operations. The lower
12276       // compare is always unsigned.
12277       SDValue SB;
12278       if (FlipSigns) {
12279         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12280       } else {
12281         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12282         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12283         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12284                          Sign, Zero, Sign, Zero);
12285       }
12286       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12287       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12288
12289       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12290       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12291       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12292
12293       // Create masks for only the low parts/high parts of the 64 bit integers.
12294       static const int MaskHi[] = { 1, 1, 3, 3 };
12295       static const int MaskLo[] = { 0, 0, 2, 2 };
12296       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12297       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12298       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12299
12300       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12301       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12302
12303       if (Invert)
12304         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12305
12306       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12307     }
12308
12309     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12310       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12311       // pcmpeqd + pshufd + pand.
12312       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12313
12314       // First cast everything to the right type.
12315       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12316       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12317
12318       // Do the compare.
12319       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12320
12321       // Make sure the lower and upper halves are both all-ones.
12322       static const int Mask[] = { 1, 0, 3, 2 };
12323       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12324       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12325
12326       if (Invert)
12327         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12328
12329       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12330     }
12331   }
12332
12333   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12334   // bits of the inputs before performing those operations.
12335   if (FlipSigns) {
12336     EVT EltVT = VT.getVectorElementType();
12337     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12338     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12339     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12340   }
12341
12342   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12343
12344   // If the logical-not of the result is required, perform that now.
12345   if (Invert)
12346     Result = DAG.getNOT(dl, Result, VT);
12347
12348   if (MinMax)
12349     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12350
12351   if (Subus)
12352     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12353                          getZeroVector(VT, Subtarget, DAG, dl));
12354
12355   return Result;
12356 }
12357
12358 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12359
12360   MVT VT = Op.getSimpleValueType();
12361
12362   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12363
12364   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12365          && "SetCC type must be 8-bit or 1-bit integer");
12366   SDValue Op0 = Op.getOperand(0);
12367   SDValue Op1 = Op.getOperand(1);
12368   SDLoc dl(Op);
12369   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12370
12371   // Optimize to BT if possible.
12372   // Lower (X & (1 << N)) == 0 to BT(X, N).
12373   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12374   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12375   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12376       Op1.getOpcode() == ISD::Constant &&
12377       cast<ConstantSDNode>(Op1)->isNullValue() &&
12378       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12379     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12380     if (NewSetCC.getNode())
12381       return NewSetCC;
12382   }
12383
12384   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12385   // these.
12386   if (Op1.getOpcode() == ISD::Constant &&
12387       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12388        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12389       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12390
12391     // If the input is a setcc, then reuse the input setcc or use a new one with
12392     // the inverted condition.
12393     if (Op0.getOpcode() == X86ISD::SETCC) {
12394       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12395       bool Invert = (CC == ISD::SETNE) ^
12396         cast<ConstantSDNode>(Op1)->isNullValue();
12397       if (!Invert)
12398         return Op0;
12399
12400       CCode = X86::GetOppositeBranchCondition(CCode);
12401       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12402                                   DAG.getConstant(CCode, MVT::i8),
12403                                   Op0.getOperand(1));
12404       if (VT == MVT::i1)
12405         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12406       return SetCC;
12407     }
12408   }
12409   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12410       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12411       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12412
12413     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12414     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12415   }
12416
12417   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12418   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12419   if (X86CC == X86::COND_INVALID)
12420     return SDValue();
12421
12422   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12423   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12424   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12425                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12426   if (VT == MVT::i1)
12427     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12428   return SetCC;
12429 }
12430
12431 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12432 static bool isX86LogicalCmp(SDValue Op) {
12433   unsigned Opc = Op.getNode()->getOpcode();
12434   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12435       Opc == X86ISD::SAHF)
12436     return true;
12437   if (Op.getResNo() == 1 &&
12438       (Opc == X86ISD::ADD ||
12439        Opc == X86ISD::SUB ||
12440        Opc == X86ISD::ADC ||
12441        Opc == X86ISD::SBB ||
12442        Opc == X86ISD::SMUL ||
12443        Opc == X86ISD::UMUL ||
12444        Opc == X86ISD::INC ||
12445        Opc == X86ISD::DEC ||
12446        Opc == X86ISD::OR ||
12447        Opc == X86ISD::XOR ||
12448        Opc == X86ISD::AND))
12449     return true;
12450
12451   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12452     return true;
12453
12454   return false;
12455 }
12456
12457 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12458   if (V.getOpcode() != ISD::TRUNCATE)
12459     return false;
12460
12461   SDValue VOp0 = V.getOperand(0);
12462   unsigned InBits = VOp0.getValueSizeInBits();
12463   unsigned Bits = V.getValueSizeInBits();
12464   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12465 }
12466
12467 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12468   bool addTest = true;
12469   SDValue Cond  = Op.getOperand(0);
12470   SDValue Op1 = Op.getOperand(1);
12471   SDValue Op2 = Op.getOperand(2);
12472   SDLoc DL(Op);
12473   EVT VT = Op1.getValueType();
12474   SDValue CC;
12475
12476   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12477   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12478   // sequence later on.
12479   if (Cond.getOpcode() == ISD::SETCC &&
12480       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12481        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12482       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12483     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12484     int SSECC = translateX86FSETCC(
12485         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12486
12487     if (SSECC != 8) {
12488       if (Subtarget->hasAVX512()) {
12489         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12490                                   DAG.getConstant(SSECC, MVT::i8));
12491         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12492       }
12493       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12494                                 DAG.getConstant(SSECC, MVT::i8));
12495       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12496       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12497       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12498     }
12499   }
12500
12501   if (Cond.getOpcode() == ISD::SETCC) {
12502     SDValue NewCond = LowerSETCC(Cond, DAG);
12503     if (NewCond.getNode())
12504       Cond = NewCond;
12505   }
12506
12507   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12508   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12509   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12510   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12511   if (Cond.getOpcode() == X86ISD::SETCC &&
12512       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12513       isZero(Cond.getOperand(1).getOperand(1))) {
12514     SDValue Cmp = Cond.getOperand(1);
12515
12516     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12517
12518     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12519         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12520       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12521
12522       SDValue CmpOp0 = Cmp.getOperand(0);
12523       // Apply further optimizations for special cases
12524       // (select (x != 0), -1, 0) -> neg & sbb
12525       // (select (x == 0), 0, -1) -> neg & sbb
12526       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12527         if (YC->isNullValue() &&
12528             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12529           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12530           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12531                                     DAG.getConstant(0, CmpOp0.getValueType()),
12532                                     CmpOp0);
12533           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12534                                     DAG.getConstant(X86::COND_B, MVT::i8),
12535                                     SDValue(Neg.getNode(), 1));
12536           return Res;
12537         }
12538
12539       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12540                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12541       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12542
12543       SDValue Res =   // Res = 0 or -1.
12544         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12545                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12546
12547       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12548         Res = DAG.getNOT(DL, Res, Res.getValueType());
12549
12550       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12551       if (!N2C || !N2C->isNullValue())
12552         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12553       return Res;
12554     }
12555   }
12556
12557   // Look past (and (setcc_carry (cmp ...)), 1).
12558   if (Cond.getOpcode() == ISD::AND &&
12559       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12560     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12561     if (C && C->getAPIntValue() == 1)
12562       Cond = Cond.getOperand(0);
12563   }
12564
12565   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12566   // setting operand in place of the X86ISD::SETCC.
12567   unsigned CondOpcode = Cond.getOpcode();
12568   if (CondOpcode == X86ISD::SETCC ||
12569       CondOpcode == X86ISD::SETCC_CARRY) {
12570     CC = Cond.getOperand(0);
12571
12572     SDValue Cmp = Cond.getOperand(1);
12573     unsigned Opc = Cmp.getOpcode();
12574     MVT VT = Op.getSimpleValueType();
12575
12576     bool IllegalFPCMov = false;
12577     if (VT.isFloatingPoint() && !VT.isVector() &&
12578         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12579       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12580
12581     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12582         Opc == X86ISD::BT) { // FIXME
12583       Cond = Cmp;
12584       addTest = false;
12585     }
12586   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12587              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12588              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12589               Cond.getOperand(0).getValueType() != MVT::i8)) {
12590     SDValue LHS = Cond.getOperand(0);
12591     SDValue RHS = Cond.getOperand(1);
12592     unsigned X86Opcode;
12593     unsigned X86Cond;
12594     SDVTList VTs;
12595     switch (CondOpcode) {
12596     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12597     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12598     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12599     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12600     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12601     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12602     default: llvm_unreachable("unexpected overflowing operator");
12603     }
12604     if (CondOpcode == ISD::UMULO)
12605       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12606                           MVT::i32);
12607     else
12608       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12609
12610     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12611
12612     if (CondOpcode == ISD::UMULO)
12613       Cond = X86Op.getValue(2);
12614     else
12615       Cond = X86Op.getValue(1);
12616
12617     CC = DAG.getConstant(X86Cond, MVT::i8);
12618     addTest = false;
12619   }
12620
12621   if (addTest) {
12622     // Look pass the truncate if the high bits are known zero.
12623     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12624         Cond = Cond.getOperand(0);
12625
12626     // We know the result of AND is compared against zero. Try to match
12627     // it to BT.
12628     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12629       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12630       if (NewSetCC.getNode()) {
12631         CC = NewSetCC.getOperand(0);
12632         Cond = NewSetCC.getOperand(1);
12633         addTest = false;
12634       }
12635     }
12636   }
12637
12638   if (addTest) {
12639     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12640     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12641   }
12642
12643   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12644   // a <  b ?  0 : -1 -> RES = setcc_carry
12645   // a >= b ? -1 :  0 -> RES = setcc_carry
12646   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12647   if (Cond.getOpcode() == X86ISD::SUB) {
12648     Cond = ConvertCmpIfNecessary(Cond, DAG);
12649     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12650
12651     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12652         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12653       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12654                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12655       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12656         return DAG.getNOT(DL, Res, Res.getValueType());
12657       return Res;
12658     }
12659   }
12660
12661   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12662   // widen the cmov and push the truncate through. This avoids introducing a new
12663   // branch during isel and doesn't add any extensions.
12664   if (Op.getValueType() == MVT::i8 &&
12665       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12666     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12667     if (T1.getValueType() == T2.getValueType() &&
12668         // Blacklist CopyFromReg to avoid partial register stalls.
12669         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12670       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12671       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12672       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12673     }
12674   }
12675
12676   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12677   // condition is true.
12678   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12679   SDValue Ops[] = { Op2, Op1, CC, Cond };
12680   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12681 }
12682
12683 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12684   MVT VT = Op->getSimpleValueType(0);
12685   SDValue In = Op->getOperand(0);
12686   MVT InVT = In.getSimpleValueType();
12687   SDLoc dl(Op);
12688
12689   unsigned int NumElts = VT.getVectorNumElements();
12690   if (NumElts != 8 && NumElts != 16)
12691     return SDValue();
12692
12693   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12694     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12695
12696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12697   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12698
12699   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12700   Constant *C = ConstantInt::get(*DAG.getContext(),
12701     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12702
12703   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12704   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12705   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12706                           MachinePointerInfo::getConstantPool(),
12707                           false, false, false, Alignment);
12708   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12709   if (VT.is512BitVector())
12710     return Brcst;
12711   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12712 }
12713
12714 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12715                                 SelectionDAG &DAG) {
12716   MVT VT = Op->getSimpleValueType(0);
12717   SDValue In = Op->getOperand(0);
12718   MVT InVT = In.getSimpleValueType();
12719   SDLoc dl(Op);
12720
12721   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12722     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12723
12724   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12725       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12726       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12727     return SDValue();
12728
12729   if (Subtarget->hasInt256())
12730     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12731
12732   // Optimize vectors in AVX mode
12733   // Sign extend  v8i16 to v8i32 and
12734   //              v4i32 to v4i64
12735   //
12736   // Divide input vector into two parts
12737   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12738   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12739   // concat the vectors to original VT
12740
12741   unsigned NumElems = InVT.getVectorNumElements();
12742   SDValue Undef = DAG.getUNDEF(InVT);
12743
12744   SmallVector<int,8> ShufMask1(NumElems, -1);
12745   for (unsigned i = 0; i != NumElems/2; ++i)
12746     ShufMask1[i] = i;
12747
12748   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12749
12750   SmallVector<int,8> ShufMask2(NumElems, -1);
12751   for (unsigned i = 0; i != NumElems/2; ++i)
12752     ShufMask2[i] = i + NumElems/2;
12753
12754   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12755
12756   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12757                                 VT.getVectorNumElements()/2);
12758
12759   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12760   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12761
12762   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12763 }
12764
12765 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12766 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12767 // from the AND / OR.
12768 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12769   Opc = Op.getOpcode();
12770   if (Opc != ISD::OR && Opc != ISD::AND)
12771     return false;
12772   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12773           Op.getOperand(0).hasOneUse() &&
12774           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12775           Op.getOperand(1).hasOneUse());
12776 }
12777
12778 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12779 // 1 and that the SETCC node has a single use.
12780 static bool isXor1OfSetCC(SDValue Op) {
12781   if (Op.getOpcode() != ISD::XOR)
12782     return false;
12783   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12784   if (N1C && N1C->getAPIntValue() == 1) {
12785     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12786       Op.getOperand(0).hasOneUse();
12787   }
12788   return false;
12789 }
12790
12791 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12792   bool addTest = true;
12793   SDValue Chain = Op.getOperand(0);
12794   SDValue Cond  = Op.getOperand(1);
12795   SDValue Dest  = Op.getOperand(2);
12796   SDLoc dl(Op);
12797   SDValue CC;
12798   bool Inverted = false;
12799
12800   if (Cond.getOpcode() == ISD::SETCC) {
12801     // Check for setcc([su]{add,sub,mul}o == 0).
12802     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12803         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12804         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12805         Cond.getOperand(0).getResNo() == 1 &&
12806         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12807          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12808          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12809          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12810          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12811          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12812       Inverted = true;
12813       Cond = Cond.getOperand(0);
12814     } else {
12815       SDValue NewCond = LowerSETCC(Cond, DAG);
12816       if (NewCond.getNode())
12817         Cond = NewCond;
12818     }
12819   }
12820 #if 0
12821   // FIXME: LowerXALUO doesn't handle these!!
12822   else if (Cond.getOpcode() == X86ISD::ADD  ||
12823            Cond.getOpcode() == X86ISD::SUB  ||
12824            Cond.getOpcode() == X86ISD::SMUL ||
12825            Cond.getOpcode() == X86ISD::UMUL)
12826     Cond = LowerXALUO(Cond, DAG);
12827 #endif
12828
12829   // Look pass (and (setcc_carry (cmp ...)), 1).
12830   if (Cond.getOpcode() == ISD::AND &&
12831       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12832     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12833     if (C && C->getAPIntValue() == 1)
12834       Cond = Cond.getOperand(0);
12835   }
12836
12837   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12838   // setting operand in place of the X86ISD::SETCC.
12839   unsigned CondOpcode = Cond.getOpcode();
12840   if (CondOpcode == X86ISD::SETCC ||
12841       CondOpcode == X86ISD::SETCC_CARRY) {
12842     CC = Cond.getOperand(0);
12843
12844     SDValue Cmp = Cond.getOperand(1);
12845     unsigned Opc = Cmp.getOpcode();
12846     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12847     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12848       Cond = Cmp;
12849       addTest = false;
12850     } else {
12851       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12852       default: break;
12853       case X86::COND_O:
12854       case X86::COND_B:
12855         // These can only come from an arithmetic instruction with overflow,
12856         // e.g. SADDO, UADDO.
12857         Cond = Cond.getNode()->getOperand(1);
12858         addTest = false;
12859         break;
12860       }
12861     }
12862   }
12863   CondOpcode = Cond.getOpcode();
12864   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12865       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12866       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12867        Cond.getOperand(0).getValueType() != MVT::i8)) {
12868     SDValue LHS = Cond.getOperand(0);
12869     SDValue RHS = Cond.getOperand(1);
12870     unsigned X86Opcode;
12871     unsigned X86Cond;
12872     SDVTList VTs;
12873     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12874     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12875     // X86ISD::INC).
12876     switch (CondOpcode) {
12877     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12878     case ISD::SADDO:
12879       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12880         if (C->isOne()) {
12881           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12882           break;
12883         }
12884       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12885     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12886     case ISD::SSUBO:
12887       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12888         if (C->isOne()) {
12889           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12890           break;
12891         }
12892       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12893     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12894     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12895     default: llvm_unreachable("unexpected overflowing operator");
12896     }
12897     if (Inverted)
12898       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12899     if (CondOpcode == ISD::UMULO)
12900       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12901                           MVT::i32);
12902     else
12903       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12904
12905     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12906
12907     if (CondOpcode == ISD::UMULO)
12908       Cond = X86Op.getValue(2);
12909     else
12910       Cond = X86Op.getValue(1);
12911
12912     CC = DAG.getConstant(X86Cond, MVT::i8);
12913     addTest = false;
12914   } else {
12915     unsigned CondOpc;
12916     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12917       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12918       if (CondOpc == ISD::OR) {
12919         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12920         // two branches instead of an explicit OR instruction with a
12921         // separate test.
12922         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12923             isX86LogicalCmp(Cmp)) {
12924           CC = Cond.getOperand(0).getOperand(0);
12925           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12926                               Chain, Dest, CC, Cmp);
12927           CC = Cond.getOperand(1).getOperand(0);
12928           Cond = Cmp;
12929           addTest = false;
12930         }
12931       } else { // ISD::AND
12932         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12933         // two branches instead of an explicit AND instruction with a
12934         // separate test. However, we only do this if this block doesn't
12935         // have a fall-through edge, because this requires an explicit
12936         // jmp when the condition is false.
12937         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12938             isX86LogicalCmp(Cmp) &&
12939             Op.getNode()->hasOneUse()) {
12940           X86::CondCode CCode =
12941             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12942           CCode = X86::GetOppositeBranchCondition(CCode);
12943           CC = DAG.getConstant(CCode, MVT::i8);
12944           SDNode *User = *Op.getNode()->use_begin();
12945           // Look for an unconditional branch following this conditional branch.
12946           // We need this because we need to reverse the successors in order
12947           // to implement FCMP_OEQ.
12948           if (User->getOpcode() == ISD::BR) {
12949             SDValue FalseBB = User->getOperand(1);
12950             SDNode *NewBR =
12951               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12952             assert(NewBR == User);
12953             (void)NewBR;
12954             Dest = FalseBB;
12955
12956             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12957                                 Chain, Dest, CC, Cmp);
12958             X86::CondCode CCode =
12959               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12960             CCode = X86::GetOppositeBranchCondition(CCode);
12961             CC = DAG.getConstant(CCode, MVT::i8);
12962             Cond = Cmp;
12963             addTest = false;
12964           }
12965         }
12966       }
12967     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12968       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12969       // It should be transformed during dag combiner except when the condition
12970       // is set by a arithmetics with overflow node.
12971       X86::CondCode CCode =
12972         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12973       CCode = X86::GetOppositeBranchCondition(CCode);
12974       CC = DAG.getConstant(CCode, MVT::i8);
12975       Cond = Cond.getOperand(0).getOperand(1);
12976       addTest = false;
12977     } else if (Cond.getOpcode() == ISD::SETCC &&
12978                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12979       // For FCMP_OEQ, we can emit
12980       // two branches instead of an explicit AND instruction with a
12981       // separate test. However, we only do this if this block doesn't
12982       // have a fall-through edge, because this requires an explicit
12983       // jmp when the condition is false.
12984       if (Op.getNode()->hasOneUse()) {
12985         SDNode *User = *Op.getNode()->use_begin();
12986         // Look for an unconditional branch following this conditional branch.
12987         // We need this because we need to reverse the successors in order
12988         // to implement FCMP_OEQ.
12989         if (User->getOpcode() == ISD::BR) {
12990           SDValue FalseBB = User->getOperand(1);
12991           SDNode *NewBR =
12992             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12993           assert(NewBR == User);
12994           (void)NewBR;
12995           Dest = FalseBB;
12996
12997           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12998                                     Cond.getOperand(0), Cond.getOperand(1));
12999           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13000           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13001           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13002                               Chain, Dest, CC, Cmp);
13003           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13004           Cond = Cmp;
13005           addTest = false;
13006         }
13007       }
13008     } else if (Cond.getOpcode() == ISD::SETCC &&
13009                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13010       // For FCMP_UNE, we can emit
13011       // two branches instead of an explicit AND instruction with a
13012       // separate test. However, we only do this if this block doesn't
13013       // have a fall-through edge, because this requires an explicit
13014       // jmp when the condition is false.
13015       if (Op.getNode()->hasOneUse()) {
13016         SDNode *User = *Op.getNode()->use_begin();
13017         // Look for an unconditional branch following this conditional branch.
13018         // We need this because we need to reverse the successors in order
13019         // to implement FCMP_UNE.
13020         if (User->getOpcode() == ISD::BR) {
13021           SDValue FalseBB = User->getOperand(1);
13022           SDNode *NewBR =
13023             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13024           assert(NewBR == User);
13025           (void)NewBR;
13026
13027           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13028                                     Cond.getOperand(0), Cond.getOperand(1));
13029           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13030           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13031           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13032                               Chain, Dest, CC, Cmp);
13033           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13034           Cond = Cmp;
13035           addTest = false;
13036           Dest = FalseBB;
13037         }
13038       }
13039     }
13040   }
13041
13042   if (addTest) {
13043     // Look pass the truncate if the high bits are known zero.
13044     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13045         Cond = Cond.getOperand(0);
13046
13047     // We know the result of AND is compared against zero. Try to match
13048     // it to BT.
13049     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13050       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13051       if (NewSetCC.getNode()) {
13052         CC = NewSetCC.getOperand(0);
13053         Cond = NewSetCC.getOperand(1);
13054         addTest = false;
13055       }
13056     }
13057   }
13058
13059   if (addTest) {
13060     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13061     CC = DAG.getConstant(X86Cond, MVT::i8);
13062     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13063   }
13064   Cond = ConvertCmpIfNecessary(Cond, DAG);
13065   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13066                      Chain, Dest, CC, Cond);
13067 }
13068
13069 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13070 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13071 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13072 // that the guard pages used by the OS virtual memory manager are allocated in
13073 // correct sequence.
13074 SDValue
13075 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13076                                            SelectionDAG &DAG) const {
13077   MachineFunction &MF = DAG.getMachineFunction();
13078   bool SplitStack = MF.shouldSplitStack();
13079   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13080                SplitStack;
13081   SDLoc dl(Op);
13082
13083   if (!Lower) {
13084     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13085     SDNode* Node = Op.getNode();
13086
13087     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13088     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13089         " not tell us which reg is the stack pointer!");
13090     EVT VT = Node->getValueType(0);
13091     SDValue Tmp1 = SDValue(Node, 0);
13092     SDValue Tmp2 = SDValue(Node, 1);
13093     SDValue Tmp3 = Node->getOperand(2);
13094     SDValue Chain = Tmp1.getOperand(0);
13095
13096     // Chain the dynamic stack allocation so that it doesn't modify the stack
13097     // pointer when other instructions are using the stack.
13098     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13099         SDLoc(Node));
13100
13101     SDValue Size = Tmp2.getOperand(1);
13102     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13103     Chain = SP.getValue(1);
13104     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13105     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13106     unsigned StackAlign = TFI.getStackAlignment();
13107     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13108     if (Align > StackAlign)
13109       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13110           DAG.getConstant(-(uint64_t)Align, VT));
13111     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13112
13113     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13114         DAG.getIntPtrConstant(0, true), SDValue(),
13115         SDLoc(Node));
13116
13117     SDValue Ops[2] = { Tmp1, Tmp2 };
13118     return DAG.getMergeValues(Ops, dl);
13119   }
13120
13121   // Get the inputs.
13122   SDValue Chain = Op.getOperand(0);
13123   SDValue Size  = Op.getOperand(1);
13124   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13125   EVT VT = Op.getNode()->getValueType(0);
13126
13127   bool Is64Bit = Subtarget->is64Bit();
13128   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13129
13130   if (SplitStack) {
13131     MachineRegisterInfo &MRI = MF.getRegInfo();
13132
13133     if (Is64Bit) {
13134       // The 64 bit implementation of segmented stacks needs to clobber both r10
13135       // r11. This makes it impossible to use it along with nested parameters.
13136       const Function *F = MF.getFunction();
13137
13138       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13139            I != E; ++I)
13140         if (I->hasNestAttr())
13141           report_fatal_error("Cannot use segmented stacks with functions that "
13142                              "have nested arguments.");
13143     }
13144
13145     const TargetRegisterClass *AddrRegClass =
13146       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13147     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13148     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13149     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13150                                 DAG.getRegister(Vreg, SPTy));
13151     SDValue Ops1[2] = { Value, Chain };
13152     return DAG.getMergeValues(Ops1, dl);
13153   } else {
13154     SDValue Flag;
13155     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13156
13157     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13158     Flag = Chain.getValue(1);
13159     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13160
13161     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13162
13163     const X86RegisterInfo *RegInfo =
13164       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13165     unsigned SPReg = RegInfo->getStackRegister();
13166     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13167     Chain = SP.getValue(1);
13168
13169     if (Align) {
13170       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13171                        DAG.getConstant(-(uint64_t)Align, VT));
13172       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13173     }
13174
13175     SDValue Ops1[2] = { SP, Chain };
13176     return DAG.getMergeValues(Ops1, dl);
13177   }
13178 }
13179
13180 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13181   MachineFunction &MF = DAG.getMachineFunction();
13182   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13183
13184   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13185   SDLoc DL(Op);
13186
13187   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13188     // vastart just stores the address of the VarArgsFrameIndex slot into the
13189     // memory location argument.
13190     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13191                                    getPointerTy());
13192     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13193                         MachinePointerInfo(SV), false, false, 0);
13194   }
13195
13196   // __va_list_tag:
13197   //   gp_offset         (0 - 6 * 8)
13198   //   fp_offset         (48 - 48 + 8 * 16)
13199   //   overflow_arg_area (point to parameters coming in memory).
13200   //   reg_save_area
13201   SmallVector<SDValue, 8> MemOps;
13202   SDValue FIN = Op.getOperand(1);
13203   // Store gp_offset
13204   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13205                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13206                                                MVT::i32),
13207                                FIN, MachinePointerInfo(SV), false, false, 0);
13208   MemOps.push_back(Store);
13209
13210   // Store fp_offset
13211   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13212                     FIN, DAG.getIntPtrConstant(4));
13213   Store = DAG.getStore(Op.getOperand(0), DL,
13214                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13215                                        MVT::i32),
13216                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13217   MemOps.push_back(Store);
13218
13219   // Store ptr to overflow_arg_area
13220   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13221                     FIN, DAG.getIntPtrConstant(4));
13222   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13223                                     getPointerTy());
13224   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13225                        MachinePointerInfo(SV, 8),
13226                        false, false, 0);
13227   MemOps.push_back(Store);
13228
13229   // Store ptr to reg_save_area.
13230   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13231                     FIN, DAG.getIntPtrConstant(8));
13232   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13233                                     getPointerTy());
13234   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13235                        MachinePointerInfo(SV, 16), false, false, 0);
13236   MemOps.push_back(Store);
13237   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13238 }
13239
13240 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13241   assert(Subtarget->is64Bit() &&
13242          "LowerVAARG only handles 64-bit va_arg!");
13243   assert((Subtarget->isTargetLinux() ||
13244           Subtarget->isTargetDarwin()) &&
13245           "Unhandled target in LowerVAARG");
13246   assert(Op.getNode()->getNumOperands() == 4);
13247   SDValue Chain = Op.getOperand(0);
13248   SDValue SrcPtr = Op.getOperand(1);
13249   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13250   unsigned Align = Op.getConstantOperandVal(3);
13251   SDLoc dl(Op);
13252
13253   EVT ArgVT = Op.getNode()->getValueType(0);
13254   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13255   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13256   uint8_t ArgMode;
13257
13258   // Decide which area this value should be read from.
13259   // TODO: Implement the AMD64 ABI in its entirety. This simple
13260   // selection mechanism works only for the basic types.
13261   if (ArgVT == MVT::f80) {
13262     llvm_unreachable("va_arg for f80 not yet implemented");
13263   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13264     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13265   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13266     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13267   } else {
13268     llvm_unreachable("Unhandled argument type in LowerVAARG");
13269   }
13270
13271   if (ArgMode == 2) {
13272     // Sanity Check: Make sure using fp_offset makes sense.
13273     assert(!DAG.getTarget().Options.UseSoftFloat &&
13274            !(DAG.getMachineFunction()
13275                 .getFunction()->getAttributes()
13276                 .hasAttribute(AttributeSet::FunctionIndex,
13277                               Attribute::NoImplicitFloat)) &&
13278            Subtarget->hasSSE1());
13279   }
13280
13281   // Insert VAARG_64 node into the DAG
13282   // VAARG_64 returns two values: Variable Argument Address, Chain
13283   SmallVector<SDValue, 11> InstOps;
13284   InstOps.push_back(Chain);
13285   InstOps.push_back(SrcPtr);
13286   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13287   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13288   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13289   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13290   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13291                                           VTs, InstOps, MVT::i64,
13292                                           MachinePointerInfo(SV),
13293                                           /*Align=*/0,
13294                                           /*Volatile=*/false,
13295                                           /*ReadMem=*/true,
13296                                           /*WriteMem=*/true);
13297   Chain = VAARG.getValue(1);
13298
13299   // Load the next argument and return it
13300   return DAG.getLoad(ArgVT, dl,
13301                      Chain,
13302                      VAARG,
13303                      MachinePointerInfo(),
13304                      false, false, false, 0);
13305 }
13306
13307 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13308                            SelectionDAG &DAG) {
13309   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13310   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13311   SDValue Chain = Op.getOperand(0);
13312   SDValue DstPtr = Op.getOperand(1);
13313   SDValue SrcPtr = Op.getOperand(2);
13314   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13315   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13316   SDLoc DL(Op);
13317
13318   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13319                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13320                        false,
13321                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13322 }
13323
13324 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13325 // amount is a constant. Takes immediate version of shift as input.
13326 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13327                                           SDValue SrcOp, uint64_t ShiftAmt,
13328                                           SelectionDAG &DAG) {
13329   MVT ElementType = VT.getVectorElementType();
13330
13331   // Fold this packed shift into its first operand if ShiftAmt is 0.
13332   if (ShiftAmt == 0)
13333     return SrcOp;
13334
13335   // Check for ShiftAmt >= element width
13336   if (ShiftAmt >= ElementType.getSizeInBits()) {
13337     if (Opc == X86ISD::VSRAI)
13338       ShiftAmt = ElementType.getSizeInBits() - 1;
13339     else
13340       return DAG.getConstant(0, VT);
13341   }
13342
13343   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13344          && "Unknown target vector shift-by-constant node");
13345
13346   // Fold this packed vector shift into a build vector if SrcOp is a
13347   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13348   if (VT == SrcOp.getSimpleValueType() &&
13349       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13350     SmallVector<SDValue, 8> Elts;
13351     unsigned NumElts = SrcOp->getNumOperands();
13352     ConstantSDNode *ND;
13353
13354     switch(Opc) {
13355     default: llvm_unreachable(nullptr);
13356     case X86ISD::VSHLI:
13357       for (unsigned i=0; i!=NumElts; ++i) {
13358         SDValue CurrentOp = SrcOp->getOperand(i);
13359         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13360           Elts.push_back(CurrentOp);
13361           continue;
13362         }
13363         ND = cast<ConstantSDNode>(CurrentOp);
13364         const APInt &C = ND->getAPIntValue();
13365         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13366       }
13367       break;
13368     case X86ISD::VSRLI:
13369       for (unsigned i=0; i!=NumElts; ++i) {
13370         SDValue CurrentOp = SrcOp->getOperand(i);
13371         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13372           Elts.push_back(CurrentOp);
13373           continue;
13374         }
13375         ND = cast<ConstantSDNode>(CurrentOp);
13376         const APInt &C = ND->getAPIntValue();
13377         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13378       }
13379       break;
13380     case X86ISD::VSRAI:
13381       for (unsigned i=0; i!=NumElts; ++i) {
13382         SDValue CurrentOp = SrcOp->getOperand(i);
13383         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13384           Elts.push_back(CurrentOp);
13385           continue;
13386         }
13387         ND = cast<ConstantSDNode>(CurrentOp);
13388         const APInt &C = ND->getAPIntValue();
13389         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13390       }
13391       break;
13392     }
13393
13394     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13395   }
13396
13397   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13398 }
13399
13400 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13401 // may or may not be a constant. Takes immediate version of shift as input.
13402 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13403                                    SDValue SrcOp, SDValue ShAmt,
13404                                    SelectionDAG &DAG) {
13405   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13406
13407   // Catch shift-by-constant.
13408   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13409     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13410                                       CShAmt->getZExtValue(), DAG);
13411
13412   // Change opcode to non-immediate version
13413   switch (Opc) {
13414     default: llvm_unreachable("Unknown target vector shift node");
13415     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13416     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13417     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13418   }
13419
13420   // Need to build a vector containing shift amount
13421   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13422   SDValue ShOps[4];
13423   ShOps[0] = ShAmt;
13424   ShOps[1] = DAG.getConstant(0, MVT::i32);
13425   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13426   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13427
13428   // The return type has to be a 128-bit type with the same element
13429   // type as the input type.
13430   MVT EltVT = VT.getVectorElementType();
13431   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13432
13433   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13434   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13435 }
13436
13437 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13438   SDLoc dl(Op);
13439   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13440   switch (IntNo) {
13441   default: return SDValue();    // Don't custom lower most intrinsics.
13442   // Comparison intrinsics.
13443   case Intrinsic::x86_sse_comieq_ss:
13444   case Intrinsic::x86_sse_comilt_ss:
13445   case Intrinsic::x86_sse_comile_ss:
13446   case Intrinsic::x86_sse_comigt_ss:
13447   case Intrinsic::x86_sse_comige_ss:
13448   case Intrinsic::x86_sse_comineq_ss:
13449   case Intrinsic::x86_sse_ucomieq_ss:
13450   case Intrinsic::x86_sse_ucomilt_ss:
13451   case Intrinsic::x86_sse_ucomile_ss:
13452   case Intrinsic::x86_sse_ucomigt_ss:
13453   case Intrinsic::x86_sse_ucomige_ss:
13454   case Intrinsic::x86_sse_ucomineq_ss:
13455   case Intrinsic::x86_sse2_comieq_sd:
13456   case Intrinsic::x86_sse2_comilt_sd:
13457   case Intrinsic::x86_sse2_comile_sd:
13458   case Intrinsic::x86_sse2_comigt_sd:
13459   case Intrinsic::x86_sse2_comige_sd:
13460   case Intrinsic::x86_sse2_comineq_sd:
13461   case Intrinsic::x86_sse2_ucomieq_sd:
13462   case Intrinsic::x86_sse2_ucomilt_sd:
13463   case Intrinsic::x86_sse2_ucomile_sd:
13464   case Intrinsic::x86_sse2_ucomigt_sd:
13465   case Intrinsic::x86_sse2_ucomige_sd:
13466   case Intrinsic::x86_sse2_ucomineq_sd: {
13467     unsigned Opc;
13468     ISD::CondCode CC;
13469     switch (IntNo) {
13470     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13471     case Intrinsic::x86_sse_comieq_ss:
13472     case Intrinsic::x86_sse2_comieq_sd:
13473       Opc = X86ISD::COMI;
13474       CC = ISD::SETEQ;
13475       break;
13476     case Intrinsic::x86_sse_comilt_ss:
13477     case Intrinsic::x86_sse2_comilt_sd:
13478       Opc = X86ISD::COMI;
13479       CC = ISD::SETLT;
13480       break;
13481     case Intrinsic::x86_sse_comile_ss:
13482     case Intrinsic::x86_sse2_comile_sd:
13483       Opc = X86ISD::COMI;
13484       CC = ISD::SETLE;
13485       break;
13486     case Intrinsic::x86_sse_comigt_ss:
13487     case Intrinsic::x86_sse2_comigt_sd:
13488       Opc = X86ISD::COMI;
13489       CC = ISD::SETGT;
13490       break;
13491     case Intrinsic::x86_sse_comige_ss:
13492     case Intrinsic::x86_sse2_comige_sd:
13493       Opc = X86ISD::COMI;
13494       CC = ISD::SETGE;
13495       break;
13496     case Intrinsic::x86_sse_comineq_ss:
13497     case Intrinsic::x86_sse2_comineq_sd:
13498       Opc = X86ISD::COMI;
13499       CC = ISD::SETNE;
13500       break;
13501     case Intrinsic::x86_sse_ucomieq_ss:
13502     case Intrinsic::x86_sse2_ucomieq_sd:
13503       Opc = X86ISD::UCOMI;
13504       CC = ISD::SETEQ;
13505       break;
13506     case Intrinsic::x86_sse_ucomilt_ss:
13507     case Intrinsic::x86_sse2_ucomilt_sd:
13508       Opc = X86ISD::UCOMI;
13509       CC = ISD::SETLT;
13510       break;
13511     case Intrinsic::x86_sse_ucomile_ss:
13512     case Intrinsic::x86_sse2_ucomile_sd:
13513       Opc = X86ISD::UCOMI;
13514       CC = ISD::SETLE;
13515       break;
13516     case Intrinsic::x86_sse_ucomigt_ss:
13517     case Intrinsic::x86_sse2_ucomigt_sd:
13518       Opc = X86ISD::UCOMI;
13519       CC = ISD::SETGT;
13520       break;
13521     case Intrinsic::x86_sse_ucomige_ss:
13522     case Intrinsic::x86_sse2_ucomige_sd:
13523       Opc = X86ISD::UCOMI;
13524       CC = ISD::SETGE;
13525       break;
13526     case Intrinsic::x86_sse_ucomineq_ss:
13527     case Intrinsic::x86_sse2_ucomineq_sd:
13528       Opc = X86ISD::UCOMI;
13529       CC = ISD::SETNE;
13530       break;
13531     }
13532
13533     SDValue LHS = Op.getOperand(1);
13534     SDValue RHS = Op.getOperand(2);
13535     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13536     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13537     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13538     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13539                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13540     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13541   }
13542
13543   // Arithmetic intrinsics.
13544   case Intrinsic::x86_sse2_pmulu_dq:
13545   case Intrinsic::x86_avx2_pmulu_dq:
13546     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13547                        Op.getOperand(1), Op.getOperand(2));
13548
13549   case Intrinsic::x86_sse41_pmuldq:
13550   case Intrinsic::x86_avx2_pmul_dq:
13551     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13552                        Op.getOperand(1), Op.getOperand(2));
13553
13554   case Intrinsic::x86_sse2_pmulhu_w:
13555   case Intrinsic::x86_avx2_pmulhu_w:
13556     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13557                        Op.getOperand(1), Op.getOperand(2));
13558
13559   case Intrinsic::x86_sse2_pmulh_w:
13560   case Intrinsic::x86_avx2_pmulh_w:
13561     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13562                        Op.getOperand(1), Op.getOperand(2));
13563
13564   // SSE2/AVX2 sub with unsigned saturation intrinsics
13565   case Intrinsic::x86_sse2_psubus_b:
13566   case Intrinsic::x86_sse2_psubus_w:
13567   case Intrinsic::x86_avx2_psubus_b:
13568   case Intrinsic::x86_avx2_psubus_w:
13569     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13570                        Op.getOperand(1), Op.getOperand(2));
13571
13572   // SSE3/AVX horizontal add/sub intrinsics
13573   case Intrinsic::x86_sse3_hadd_ps:
13574   case Intrinsic::x86_sse3_hadd_pd:
13575   case Intrinsic::x86_avx_hadd_ps_256:
13576   case Intrinsic::x86_avx_hadd_pd_256:
13577   case Intrinsic::x86_sse3_hsub_ps:
13578   case Intrinsic::x86_sse3_hsub_pd:
13579   case Intrinsic::x86_avx_hsub_ps_256:
13580   case Intrinsic::x86_avx_hsub_pd_256:
13581   case Intrinsic::x86_ssse3_phadd_w_128:
13582   case Intrinsic::x86_ssse3_phadd_d_128:
13583   case Intrinsic::x86_avx2_phadd_w:
13584   case Intrinsic::x86_avx2_phadd_d:
13585   case Intrinsic::x86_ssse3_phsub_w_128:
13586   case Intrinsic::x86_ssse3_phsub_d_128:
13587   case Intrinsic::x86_avx2_phsub_w:
13588   case Intrinsic::x86_avx2_phsub_d: {
13589     unsigned Opcode;
13590     switch (IntNo) {
13591     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13592     case Intrinsic::x86_sse3_hadd_ps:
13593     case Intrinsic::x86_sse3_hadd_pd:
13594     case Intrinsic::x86_avx_hadd_ps_256:
13595     case Intrinsic::x86_avx_hadd_pd_256:
13596       Opcode = X86ISD::FHADD;
13597       break;
13598     case Intrinsic::x86_sse3_hsub_ps:
13599     case Intrinsic::x86_sse3_hsub_pd:
13600     case Intrinsic::x86_avx_hsub_ps_256:
13601     case Intrinsic::x86_avx_hsub_pd_256:
13602       Opcode = X86ISD::FHSUB;
13603       break;
13604     case Intrinsic::x86_ssse3_phadd_w_128:
13605     case Intrinsic::x86_ssse3_phadd_d_128:
13606     case Intrinsic::x86_avx2_phadd_w:
13607     case Intrinsic::x86_avx2_phadd_d:
13608       Opcode = X86ISD::HADD;
13609       break;
13610     case Intrinsic::x86_ssse3_phsub_w_128:
13611     case Intrinsic::x86_ssse3_phsub_d_128:
13612     case Intrinsic::x86_avx2_phsub_w:
13613     case Intrinsic::x86_avx2_phsub_d:
13614       Opcode = X86ISD::HSUB;
13615       break;
13616     }
13617     return DAG.getNode(Opcode, dl, Op.getValueType(),
13618                        Op.getOperand(1), Op.getOperand(2));
13619   }
13620
13621   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13622   case Intrinsic::x86_sse2_pmaxu_b:
13623   case Intrinsic::x86_sse41_pmaxuw:
13624   case Intrinsic::x86_sse41_pmaxud:
13625   case Intrinsic::x86_avx2_pmaxu_b:
13626   case Intrinsic::x86_avx2_pmaxu_w:
13627   case Intrinsic::x86_avx2_pmaxu_d:
13628   case Intrinsic::x86_sse2_pminu_b:
13629   case Intrinsic::x86_sse41_pminuw:
13630   case Intrinsic::x86_sse41_pminud:
13631   case Intrinsic::x86_avx2_pminu_b:
13632   case Intrinsic::x86_avx2_pminu_w:
13633   case Intrinsic::x86_avx2_pminu_d:
13634   case Intrinsic::x86_sse41_pmaxsb:
13635   case Intrinsic::x86_sse2_pmaxs_w:
13636   case Intrinsic::x86_sse41_pmaxsd:
13637   case Intrinsic::x86_avx2_pmaxs_b:
13638   case Intrinsic::x86_avx2_pmaxs_w:
13639   case Intrinsic::x86_avx2_pmaxs_d:
13640   case Intrinsic::x86_sse41_pminsb:
13641   case Intrinsic::x86_sse2_pmins_w:
13642   case Intrinsic::x86_sse41_pminsd:
13643   case Intrinsic::x86_avx2_pmins_b:
13644   case Intrinsic::x86_avx2_pmins_w:
13645   case Intrinsic::x86_avx2_pmins_d: {
13646     unsigned Opcode;
13647     switch (IntNo) {
13648     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13649     case Intrinsic::x86_sse2_pmaxu_b:
13650     case Intrinsic::x86_sse41_pmaxuw:
13651     case Intrinsic::x86_sse41_pmaxud:
13652     case Intrinsic::x86_avx2_pmaxu_b:
13653     case Intrinsic::x86_avx2_pmaxu_w:
13654     case Intrinsic::x86_avx2_pmaxu_d:
13655       Opcode = X86ISD::UMAX;
13656       break;
13657     case Intrinsic::x86_sse2_pminu_b:
13658     case Intrinsic::x86_sse41_pminuw:
13659     case Intrinsic::x86_sse41_pminud:
13660     case Intrinsic::x86_avx2_pminu_b:
13661     case Intrinsic::x86_avx2_pminu_w:
13662     case Intrinsic::x86_avx2_pminu_d:
13663       Opcode = X86ISD::UMIN;
13664       break;
13665     case Intrinsic::x86_sse41_pmaxsb:
13666     case Intrinsic::x86_sse2_pmaxs_w:
13667     case Intrinsic::x86_sse41_pmaxsd:
13668     case Intrinsic::x86_avx2_pmaxs_b:
13669     case Intrinsic::x86_avx2_pmaxs_w:
13670     case Intrinsic::x86_avx2_pmaxs_d:
13671       Opcode = X86ISD::SMAX;
13672       break;
13673     case Intrinsic::x86_sse41_pminsb:
13674     case Intrinsic::x86_sse2_pmins_w:
13675     case Intrinsic::x86_sse41_pminsd:
13676     case Intrinsic::x86_avx2_pmins_b:
13677     case Intrinsic::x86_avx2_pmins_w:
13678     case Intrinsic::x86_avx2_pmins_d:
13679       Opcode = X86ISD::SMIN;
13680       break;
13681     }
13682     return DAG.getNode(Opcode, dl, Op.getValueType(),
13683                        Op.getOperand(1), Op.getOperand(2));
13684   }
13685
13686   // SSE/SSE2/AVX floating point max/min intrinsics.
13687   case Intrinsic::x86_sse_max_ps:
13688   case Intrinsic::x86_sse2_max_pd:
13689   case Intrinsic::x86_avx_max_ps_256:
13690   case Intrinsic::x86_avx_max_pd_256:
13691   case Intrinsic::x86_sse_min_ps:
13692   case Intrinsic::x86_sse2_min_pd:
13693   case Intrinsic::x86_avx_min_ps_256:
13694   case Intrinsic::x86_avx_min_pd_256: {
13695     unsigned Opcode;
13696     switch (IntNo) {
13697     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13698     case Intrinsic::x86_sse_max_ps:
13699     case Intrinsic::x86_sse2_max_pd:
13700     case Intrinsic::x86_avx_max_ps_256:
13701     case Intrinsic::x86_avx_max_pd_256:
13702       Opcode = X86ISD::FMAX;
13703       break;
13704     case Intrinsic::x86_sse_min_ps:
13705     case Intrinsic::x86_sse2_min_pd:
13706     case Intrinsic::x86_avx_min_ps_256:
13707     case Intrinsic::x86_avx_min_pd_256:
13708       Opcode = X86ISD::FMIN;
13709       break;
13710     }
13711     return DAG.getNode(Opcode, dl, Op.getValueType(),
13712                        Op.getOperand(1), Op.getOperand(2));
13713   }
13714
13715   // AVX2 variable shift intrinsics
13716   case Intrinsic::x86_avx2_psllv_d:
13717   case Intrinsic::x86_avx2_psllv_q:
13718   case Intrinsic::x86_avx2_psllv_d_256:
13719   case Intrinsic::x86_avx2_psllv_q_256:
13720   case Intrinsic::x86_avx2_psrlv_d:
13721   case Intrinsic::x86_avx2_psrlv_q:
13722   case Intrinsic::x86_avx2_psrlv_d_256:
13723   case Intrinsic::x86_avx2_psrlv_q_256:
13724   case Intrinsic::x86_avx2_psrav_d:
13725   case Intrinsic::x86_avx2_psrav_d_256: {
13726     unsigned Opcode;
13727     switch (IntNo) {
13728     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13729     case Intrinsic::x86_avx2_psllv_d:
13730     case Intrinsic::x86_avx2_psllv_q:
13731     case Intrinsic::x86_avx2_psllv_d_256:
13732     case Intrinsic::x86_avx2_psllv_q_256:
13733       Opcode = ISD::SHL;
13734       break;
13735     case Intrinsic::x86_avx2_psrlv_d:
13736     case Intrinsic::x86_avx2_psrlv_q:
13737     case Intrinsic::x86_avx2_psrlv_d_256:
13738     case Intrinsic::x86_avx2_psrlv_q_256:
13739       Opcode = ISD::SRL;
13740       break;
13741     case Intrinsic::x86_avx2_psrav_d:
13742     case Intrinsic::x86_avx2_psrav_d_256:
13743       Opcode = ISD::SRA;
13744       break;
13745     }
13746     return DAG.getNode(Opcode, dl, Op.getValueType(),
13747                        Op.getOperand(1), Op.getOperand(2));
13748   }
13749
13750   case Intrinsic::x86_sse2_packssdw_128:
13751   case Intrinsic::x86_sse2_packsswb_128:
13752   case Intrinsic::x86_avx2_packssdw:
13753   case Intrinsic::x86_avx2_packsswb:
13754     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13755                        Op.getOperand(1), Op.getOperand(2));
13756
13757   case Intrinsic::x86_sse2_packuswb_128:
13758   case Intrinsic::x86_sse41_packusdw:
13759   case Intrinsic::x86_avx2_packuswb:
13760   case Intrinsic::x86_avx2_packusdw:
13761     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13762                        Op.getOperand(1), Op.getOperand(2));
13763
13764   case Intrinsic::x86_ssse3_pshuf_b_128:
13765   case Intrinsic::x86_avx2_pshuf_b:
13766     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13767                        Op.getOperand(1), Op.getOperand(2));
13768
13769   case Intrinsic::x86_sse2_pshuf_d:
13770     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13771                        Op.getOperand(1), Op.getOperand(2));
13772
13773   case Intrinsic::x86_sse2_pshufl_w:
13774     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13775                        Op.getOperand(1), Op.getOperand(2));
13776
13777   case Intrinsic::x86_sse2_pshufh_w:
13778     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13779                        Op.getOperand(1), Op.getOperand(2));
13780
13781   case Intrinsic::x86_ssse3_psign_b_128:
13782   case Intrinsic::x86_ssse3_psign_w_128:
13783   case Intrinsic::x86_ssse3_psign_d_128:
13784   case Intrinsic::x86_avx2_psign_b:
13785   case Intrinsic::x86_avx2_psign_w:
13786   case Intrinsic::x86_avx2_psign_d:
13787     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13788                        Op.getOperand(1), Op.getOperand(2));
13789
13790   case Intrinsic::x86_sse41_insertps:
13791     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13792                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13793
13794   case Intrinsic::x86_avx_vperm2f128_ps_256:
13795   case Intrinsic::x86_avx_vperm2f128_pd_256:
13796   case Intrinsic::x86_avx_vperm2f128_si_256:
13797   case Intrinsic::x86_avx2_vperm2i128:
13798     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13799                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13800
13801   case Intrinsic::x86_avx2_permd:
13802   case Intrinsic::x86_avx2_permps:
13803     // Operands intentionally swapped. Mask is last operand to intrinsic,
13804     // but second operand for node/instruction.
13805     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13806                        Op.getOperand(2), Op.getOperand(1));
13807
13808   case Intrinsic::x86_sse_sqrt_ps:
13809   case Intrinsic::x86_sse2_sqrt_pd:
13810   case Intrinsic::x86_avx_sqrt_ps_256:
13811   case Intrinsic::x86_avx_sqrt_pd_256:
13812     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13813
13814   // ptest and testp intrinsics. The intrinsic these come from are designed to
13815   // return an integer value, not just an instruction so lower it to the ptest
13816   // or testp pattern and a setcc for the result.
13817   case Intrinsic::x86_sse41_ptestz:
13818   case Intrinsic::x86_sse41_ptestc:
13819   case Intrinsic::x86_sse41_ptestnzc:
13820   case Intrinsic::x86_avx_ptestz_256:
13821   case Intrinsic::x86_avx_ptestc_256:
13822   case Intrinsic::x86_avx_ptestnzc_256:
13823   case Intrinsic::x86_avx_vtestz_ps:
13824   case Intrinsic::x86_avx_vtestc_ps:
13825   case Intrinsic::x86_avx_vtestnzc_ps:
13826   case Intrinsic::x86_avx_vtestz_pd:
13827   case Intrinsic::x86_avx_vtestc_pd:
13828   case Intrinsic::x86_avx_vtestnzc_pd:
13829   case Intrinsic::x86_avx_vtestz_ps_256:
13830   case Intrinsic::x86_avx_vtestc_ps_256:
13831   case Intrinsic::x86_avx_vtestnzc_ps_256:
13832   case Intrinsic::x86_avx_vtestz_pd_256:
13833   case Intrinsic::x86_avx_vtestc_pd_256:
13834   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13835     bool IsTestPacked = false;
13836     unsigned X86CC;
13837     switch (IntNo) {
13838     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13839     case Intrinsic::x86_avx_vtestz_ps:
13840     case Intrinsic::x86_avx_vtestz_pd:
13841     case Intrinsic::x86_avx_vtestz_ps_256:
13842     case Intrinsic::x86_avx_vtestz_pd_256:
13843       IsTestPacked = true; // Fallthrough
13844     case Intrinsic::x86_sse41_ptestz:
13845     case Intrinsic::x86_avx_ptestz_256:
13846       // ZF = 1
13847       X86CC = X86::COND_E;
13848       break;
13849     case Intrinsic::x86_avx_vtestc_ps:
13850     case Intrinsic::x86_avx_vtestc_pd:
13851     case Intrinsic::x86_avx_vtestc_ps_256:
13852     case Intrinsic::x86_avx_vtestc_pd_256:
13853       IsTestPacked = true; // Fallthrough
13854     case Intrinsic::x86_sse41_ptestc:
13855     case Intrinsic::x86_avx_ptestc_256:
13856       // CF = 1
13857       X86CC = X86::COND_B;
13858       break;
13859     case Intrinsic::x86_avx_vtestnzc_ps:
13860     case Intrinsic::x86_avx_vtestnzc_pd:
13861     case Intrinsic::x86_avx_vtestnzc_ps_256:
13862     case Intrinsic::x86_avx_vtestnzc_pd_256:
13863       IsTestPacked = true; // Fallthrough
13864     case Intrinsic::x86_sse41_ptestnzc:
13865     case Intrinsic::x86_avx_ptestnzc_256:
13866       // ZF and CF = 0
13867       X86CC = X86::COND_A;
13868       break;
13869     }
13870
13871     SDValue LHS = Op.getOperand(1);
13872     SDValue RHS = Op.getOperand(2);
13873     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13874     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13875     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13876     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13877     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13878   }
13879   case Intrinsic::x86_avx512_kortestz_w:
13880   case Intrinsic::x86_avx512_kortestc_w: {
13881     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13882     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13883     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13884     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13885     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13886     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13887     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13888   }
13889
13890   // SSE/AVX shift intrinsics
13891   case Intrinsic::x86_sse2_psll_w:
13892   case Intrinsic::x86_sse2_psll_d:
13893   case Intrinsic::x86_sse2_psll_q:
13894   case Intrinsic::x86_avx2_psll_w:
13895   case Intrinsic::x86_avx2_psll_d:
13896   case Intrinsic::x86_avx2_psll_q:
13897   case Intrinsic::x86_sse2_psrl_w:
13898   case Intrinsic::x86_sse2_psrl_d:
13899   case Intrinsic::x86_sse2_psrl_q:
13900   case Intrinsic::x86_avx2_psrl_w:
13901   case Intrinsic::x86_avx2_psrl_d:
13902   case Intrinsic::x86_avx2_psrl_q:
13903   case Intrinsic::x86_sse2_psra_w:
13904   case Intrinsic::x86_sse2_psra_d:
13905   case Intrinsic::x86_avx2_psra_w:
13906   case Intrinsic::x86_avx2_psra_d: {
13907     unsigned Opcode;
13908     switch (IntNo) {
13909     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13910     case Intrinsic::x86_sse2_psll_w:
13911     case Intrinsic::x86_sse2_psll_d:
13912     case Intrinsic::x86_sse2_psll_q:
13913     case Intrinsic::x86_avx2_psll_w:
13914     case Intrinsic::x86_avx2_psll_d:
13915     case Intrinsic::x86_avx2_psll_q:
13916       Opcode = X86ISD::VSHL;
13917       break;
13918     case Intrinsic::x86_sse2_psrl_w:
13919     case Intrinsic::x86_sse2_psrl_d:
13920     case Intrinsic::x86_sse2_psrl_q:
13921     case Intrinsic::x86_avx2_psrl_w:
13922     case Intrinsic::x86_avx2_psrl_d:
13923     case Intrinsic::x86_avx2_psrl_q:
13924       Opcode = X86ISD::VSRL;
13925       break;
13926     case Intrinsic::x86_sse2_psra_w:
13927     case Intrinsic::x86_sse2_psra_d:
13928     case Intrinsic::x86_avx2_psra_w:
13929     case Intrinsic::x86_avx2_psra_d:
13930       Opcode = X86ISD::VSRA;
13931       break;
13932     }
13933     return DAG.getNode(Opcode, dl, Op.getValueType(),
13934                        Op.getOperand(1), Op.getOperand(2));
13935   }
13936
13937   // SSE/AVX immediate shift intrinsics
13938   case Intrinsic::x86_sse2_pslli_w:
13939   case Intrinsic::x86_sse2_pslli_d:
13940   case Intrinsic::x86_sse2_pslli_q:
13941   case Intrinsic::x86_avx2_pslli_w:
13942   case Intrinsic::x86_avx2_pslli_d:
13943   case Intrinsic::x86_avx2_pslli_q:
13944   case Intrinsic::x86_sse2_psrli_w:
13945   case Intrinsic::x86_sse2_psrli_d:
13946   case Intrinsic::x86_sse2_psrli_q:
13947   case Intrinsic::x86_avx2_psrli_w:
13948   case Intrinsic::x86_avx2_psrli_d:
13949   case Intrinsic::x86_avx2_psrli_q:
13950   case Intrinsic::x86_sse2_psrai_w:
13951   case Intrinsic::x86_sse2_psrai_d:
13952   case Intrinsic::x86_avx2_psrai_w:
13953   case Intrinsic::x86_avx2_psrai_d: {
13954     unsigned Opcode;
13955     switch (IntNo) {
13956     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13957     case Intrinsic::x86_sse2_pslli_w:
13958     case Intrinsic::x86_sse2_pslli_d:
13959     case Intrinsic::x86_sse2_pslli_q:
13960     case Intrinsic::x86_avx2_pslli_w:
13961     case Intrinsic::x86_avx2_pslli_d:
13962     case Intrinsic::x86_avx2_pslli_q:
13963       Opcode = X86ISD::VSHLI;
13964       break;
13965     case Intrinsic::x86_sse2_psrli_w:
13966     case Intrinsic::x86_sse2_psrli_d:
13967     case Intrinsic::x86_sse2_psrli_q:
13968     case Intrinsic::x86_avx2_psrli_w:
13969     case Intrinsic::x86_avx2_psrli_d:
13970     case Intrinsic::x86_avx2_psrli_q:
13971       Opcode = X86ISD::VSRLI;
13972       break;
13973     case Intrinsic::x86_sse2_psrai_w:
13974     case Intrinsic::x86_sse2_psrai_d:
13975     case Intrinsic::x86_avx2_psrai_w:
13976     case Intrinsic::x86_avx2_psrai_d:
13977       Opcode = X86ISD::VSRAI;
13978       break;
13979     }
13980     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13981                                Op.getOperand(1), Op.getOperand(2), DAG);
13982   }
13983
13984   case Intrinsic::x86_sse42_pcmpistria128:
13985   case Intrinsic::x86_sse42_pcmpestria128:
13986   case Intrinsic::x86_sse42_pcmpistric128:
13987   case Intrinsic::x86_sse42_pcmpestric128:
13988   case Intrinsic::x86_sse42_pcmpistrio128:
13989   case Intrinsic::x86_sse42_pcmpestrio128:
13990   case Intrinsic::x86_sse42_pcmpistris128:
13991   case Intrinsic::x86_sse42_pcmpestris128:
13992   case Intrinsic::x86_sse42_pcmpistriz128:
13993   case Intrinsic::x86_sse42_pcmpestriz128: {
13994     unsigned Opcode;
13995     unsigned X86CC;
13996     switch (IntNo) {
13997     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13998     case Intrinsic::x86_sse42_pcmpistria128:
13999       Opcode = X86ISD::PCMPISTRI;
14000       X86CC = X86::COND_A;
14001       break;
14002     case Intrinsic::x86_sse42_pcmpestria128:
14003       Opcode = X86ISD::PCMPESTRI;
14004       X86CC = X86::COND_A;
14005       break;
14006     case Intrinsic::x86_sse42_pcmpistric128:
14007       Opcode = X86ISD::PCMPISTRI;
14008       X86CC = X86::COND_B;
14009       break;
14010     case Intrinsic::x86_sse42_pcmpestric128:
14011       Opcode = X86ISD::PCMPESTRI;
14012       X86CC = X86::COND_B;
14013       break;
14014     case Intrinsic::x86_sse42_pcmpistrio128:
14015       Opcode = X86ISD::PCMPISTRI;
14016       X86CC = X86::COND_O;
14017       break;
14018     case Intrinsic::x86_sse42_pcmpestrio128:
14019       Opcode = X86ISD::PCMPESTRI;
14020       X86CC = X86::COND_O;
14021       break;
14022     case Intrinsic::x86_sse42_pcmpistris128:
14023       Opcode = X86ISD::PCMPISTRI;
14024       X86CC = X86::COND_S;
14025       break;
14026     case Intrinsic::x86_sse42_pcmpestris128:
14027       Opcode = X86ISD::PCMPESTRI;
14028       X86CC = X86::COND_S;
14029       break;
14030     case Intrinsic::x86_sse42_pcmpistriz128:
14031       Opcode = X86ISD::PCMPISTRI;
14032       X86CC = X86::COND_E;
14033       break;
14034     case Intrinsic::x86_sse42_pcmpestriz128:
14035       Opcode = X86ISD::PCMPESTRI;
14036       X86CC = X86::COND_E;
14037       break;
14038     }
14039     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14040     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14041     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14042     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14043                                 DAG.getConstant(X86CC, MVT::i8),
14044                                 SDValue(PCMP.getNode(), 1));
14045     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14046   }
14047
14048   case Intrinsic::x86_sse42_pcmpistri128:
14049   case Intrinsic::x86_sse42_pcmpestri128: {
14050     unsigned Opcode;
14051     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14052       Opcode = X86ISD::PCMPISTRI;
14053     else
14054       Opcode = X86ISD::PCMPESTRI;
14055
14056     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14057     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14058     return DAG.getNode(Opcode, dl, VTs, NewOps);
14059   }
14060   case Intrinsic::x86_fma_vfmadd_ps:
14061   case Intrinsic::x86_fma_vfmadd_pd:
14062   case Intrinsic::x86_fma_vfmsub_ps:
14063   case Intrinsic::x86_fma_vfmsub_pd:
14064   case Intrinsic::x86_fma_vfnmadd_ps:
14065   case Intrinsic::x86_fma_vfnmadd_pd:
14066   case Intrinsic::x86_fma_vfnmsub_ps:
14067   case Intrinsic::x86_fma_vfnmsub_pd:
14068   case Intrinsic::x86_fma_vfmaddsub_ps:
14069   case Intrinsic::x86_fma_vfmaddsub_pd:
14070   case Intrinsic::x86_fma_vfmsubadd_ps:
14071   case Intrinsic::x86_fma_vfmsubadd_pd:
14072   case Intrinsic::x86_fma_vfmadd_ps_256:
14073   case Intrinsic::x86_fma_vfmadd_pd_256:
14074   case Intrinsic::x86_fma_vfmsub_ps_256:
14075   case Intrinsic::x86_fma_vfmsub_pd_256:
14076   case Intrinsic::x86_fma_vfnmadd_ps_256:
14077   case Intrinsic::x86_fma_vfnmadd_pd_256:
14078   case Intrinsic::x86_fma_vfnmsub_ps_256:
14079   case Intrinsic::x86_fma_vfnmsub_pd_256:
14080   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14081   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14082   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14083   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14084   case Intrinsic::x86_fma_vfmadd_ps_512:
14085   case Intrinsic::x86_fma_vfmadd_pd_512:
14086   case Intrinsic::x86_fma_vfmsub_ps_512:
14087   case Intrinsic::x86_fma_vfmsub_pd_512:
14088   case Intrinsic::x86_fma_vfnmadd_ps_512:
14089   case Intrinsic::x86_fma_vfnmadd_pd_512:
14090   case Intrinsic::x86_fma_vfnmsub_ps_512:
14091   case Intrinsic::x86_fma_vfnmsub_pd_512:
14092   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14093   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14094   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14095   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14096     unsigned Opc;
14097     switch (IntNo) {
14098     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14099     case Intrinsic::x86_fma_vfmadd_ps:
14100     case Intrinsic::x86_fma_vfmadd_pd:
14101     case Intrinsic::x86_fma_vfmadd_ps_256:
14102     case Intrinsic::x86_fma_vfmadd_pd_256:
14103     case Intrinsic::x86_fma_vfmadd_ps_512:
14104     case Intrinsic::x86_fma_vfmadd_pd_512:
14105       Opc = X86ISD::FMADD;
14106       break;
14107     case Intrinsic::x86_fma_vfmsub_ps:
14108     case Intrinsic::x86_fma_vfmsub_pd:
14109     case Intrinsic::x86_fma_vfmsub_ps_256:
14110     case Intrinsic::x86_fma_vfmsub_pd_256:
14111     case Intrinsic::x86_fma_vfmsub_ps_512:
14112     case Intrinsic::x86_fma_vfmsub_pd_512:
14113       Opc = X86ISD::FMSUB;
14114       break;
14115     case Intrinsic::x86_fma_vfnmadd_ps:
14116     case Intrinsic::x86_fma_vfnmadd_pd:
14117     case Intrinsic::x86_fma_vfnmadd_ps_256:
14118     case Intrinsic::x86_fma_vfnmadd_pd_256:
14119     case Intrinsic::x86_fma_vfnmadd_ps_512:
14120     case Intrinsic::x86_fma_vfnmadd_pd_512:
14121       Opc = X86ISD::FNMADD;
14122       break;
14123     case Intrinsic::x86_fma_vfnmsub_ps:
14124     case Intrinsic::x86_fma_vfnmsub_pd:
14125     case Intrinsic::x86_fma_vfnmsub_ps_256:
14126     case Intrinsic::x86_fma_vfnmsub_pd_256:
14127     case Intrinsic::x86_fma_vfnmsub_ps_512:
14128     case Intrinsic::x86_fma_vfnmsub_pd_512:
14129       Opc = X86ISD::FNMSUB;
14130       break;
14131     case Intrinsic::x86_fma_vfmaddsub_ps:
14132     case Intrinsic::x86_fma_vfmaddsub_pd:
14133     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14134     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14135     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14136     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14137       Opc = X86ISD::FMADDSUB;
14138       break;
14139     case Intrinsic::x86_fma_vfmsubadd_ps:
14140     case Intrinsic::x86_fma_vfmsubadd_pd:
14141     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14142     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14143     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14144     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14145       Opc = X86ISD::FMSUBADD;
14146       break;
14147     }
14148
14149     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14150                        Op.getOperand(2), Op.getOperand(3));
14151   }
14152   }
14153 }
14154
14155 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14156                               SDValue Src, SDValue Mask, SDValue Base,
14157                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14158                               const X86Subtarget * Subtarget) {
14159   SDLoc dl(Op);
14160   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14161   assert(C && "Invalid scale type");
14162   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14163   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14164                              Index.getSimpleValueType().getVectorNumElements());
14165   SDValue MaskInReg;
14166   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14167   if (MaskC)
14168     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14169   else
14170     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14171   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14172   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14173   SDValue Segment = DAG.getRegister(0, MVT::i32);
14174   if (Src.getOpcode() == ISD::UNDEF)
14175     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14176   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14177   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14178   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14179   return DAG.getMergeValues(RetOps, dl);
14180 }
14181
14182 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14183                                SDValue Src, SDValue Mask, SDValue Base,
14184                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14185   SDLoc dl(Op);
14186   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14187   assert(C && "Invalid scale type");
14188   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14189   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14190   SDValue Segment = DAG.getRegister(0, MVT::i32);
14191   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14192                              Index.getSimpleValueType().getVectorNumElements());
14193   SDValue MaskInReg;
14194   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14195   if (MaskC)
14196     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14197   else
14198     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14199   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14200   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14201   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14202   return SDValue(Res, 1);
14203 }
14204
14205 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14206                                SDValue Mask, SDValue Base, SDValue Index,
14207                                SDValue ScaleOp, SDValue Chain) {
14208   SDLoc dl(Op);
14209   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14210   assert(C && "Invalid scale type");
14211   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14212   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14213   SDValue Segment = DAG.getRegister(0, MVT::i32);
14214   EVT MaskVT =
14215     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14216   SDValue MaskInReg;
14217   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14218   if (MaskC)
14219     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14220   else
14221     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14222   //SDVTList VTs = DAG.getVTList(MVT::Other);
14223   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14224   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14225   return SDValue(Res, 0);
14226 }
14227
14228 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14229 // read performance monitor counters (x86_rdpmc).
14230 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14231                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14232                               SmallVectorImpl<SDValue> &Results) {
14233   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14234   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14235   SDValue LO, HI;
14236
14237   // The ECX register is used to select the index of the performance counter
14238   // to read.
14239   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14240                                    N->getOperand(2));
14241   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14242
14243   // Reads the content of a 64-bit performance counter and returns it in the
14244   // registers EDX:EAX.
14245   if (Subtarget->is64Bit()) {
14246     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14247     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14248                             LO.getValue(2));
14249   } else {
14250     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14251     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14252                             LO.getValue(2));
14253   }
14254   Chain = HI.getValue(1);
14255
14256   if (Subtarget->is64Bit()) {
14257     // The EAX register is loaded with the low-order 32 bits. The EDX register
14258     // is loaded with the supported high-order bits of the counter.
14259     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14260                               DAG.getConstant(32, MVT::i8));
14261     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14262     Results.push_back(Chain);
14263     return;
14264   }
14265
14266   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14267   SDValue Ops[] = { LO, HI };
14268   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14269   Results.push_back(Pair);
14270   Results.push_back(Chain);
14271 }
14272
14273 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14274 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14275 // also used to custom lower READCYCLECOUNTER nodes.
14276 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14277                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14278                               SmallVectorImpl<SDValue> &Results) {
14279   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14280   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14281   SDValue LO, HI;
14282
14283   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14284   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14285   // and the EAX register is loaded with the low-order 32 bits.
14286   if (Subtarget->is64Bit()) {
14287     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14288     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14289                             LO.getValue(2));
14290   } else {
14291     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14292     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14293                             LO.getValue(2));
14294   }
14295   SDValue Chain = HI.getValue(1);
14296
14297   if (Opcode == X86ISD::RDTSCP_DAG) {
14298     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14299
14300     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14301     // the ECX register. Add 'ecx' explicitly to the chain.
14302     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14303                                      HI.getValue(2));
14304     // Explicitly store the content of ECX at the location passed in input
14305     // to the 'rdtscp' intrinsic.
14306     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14307                          MachinePointerInfo(), false, false, 0);
14308   }
14309
14310   if (Subtarget->is64Bit()) {
14311     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14312     // the EAX register is loaded with the low-order 32 bits.
14313     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14314                               DAG.getConstant(32, MVT::i8));
14315     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14316     Results.push_back(Chain);
14317     return;
14318   }
14319
14320   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14321   SDValue Ops[] = { LO, HI };
14322   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14323   Results.push_back(Pair);
14324   Results.push_back(Chain);
14325 }
14326
14327 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14328                                      SelectionDAG &DAG) {
14329   SmallVector<SDValue, 2> Results;
14330   SDLoc DL(Op);
14331   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14332                           Results);
14333   return DAG.getMergeValues(Results, DL);
14334 }
14335
14336 enum IntrinsicType {
14337   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14338 };
14339
14340 struct IntrinsicData {
14341   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14342     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14343   IntrinsicType Type;
14344   unsigned      Opc0;
14345   unsigned      Opc1;
14346 };
14347
14348 std::map < unsigned, IntrinsicData> IntrMap;
14349 static void InitIntinsicsMap() {
14350   static bool Initialized = false;
14351   if (Initialized) 
14352     return;
14353   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14354                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14355   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14356                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14357   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14358                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14359   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14360                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14361   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14362                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14363   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14364                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14365   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14366                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14367   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14368                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14369   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14370                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14371
14372   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14373                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14374   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14375                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14376   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14377                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14378   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14379                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14380   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14381                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14382   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14383                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14384   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14385                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14386   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14387                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14388    
14389   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14390                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14391                                                         X86::VGATHERPF1QPSm)));
14392   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14393                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14394                                                         X86::VGATHERPF1QPDm)));
14395   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14396                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14397                                                         X86::VGATHERPF1DPDm)));
14398   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14399                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14400                                                         X86::VGATHERPF1DPSm)));
14401   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14402                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14403                                                         X86::VSCATTERPF1QPSm)));
14404   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14405                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14406                                                         X86::VSCATTERPF1QPDm)));
14407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14408                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14409                                                         X86::VSCATTERPF1DPDm)));
14410   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14411                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14412                                                         X86::VSCATTERPF1DPSm)));
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14414                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14415   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14416                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14417   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14418                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14419   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14420                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14421   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14422                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14423   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14424                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14425   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14426                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14427   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14428                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14429   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14430                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14431   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14432                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14433   Initialized = true;
14434 }
14435
14436 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14437                                       SelectionDAG &DAG) {
14438   InitIntinsicsMap();
14439   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14440   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14441   if (itr == IntrMap.end())
14442     return SDValue();
14443
14444   SDLoc dl(Op);
14445   IntrinsicData Intr = itr->second;
14446   switch(Intr.Type) {
14447   case RDSEED:
14448   case RDRAND: {
14449     // Emit the node with the right value type.
14450     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14451     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14452
14453     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14454     // Otherwise return the value from Rand, which is always 0, casted to i32.
14455     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14456                       DAG.getConstant(1, Op->getValueType(1)),
14457                       DAG.getConstant(X86::COND_B, MVT::i32),
14458                       SDValue(Result.getNode(), 1) };
14459     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14460                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14461                                   Ops);
14462
14463     // Return { result, isValid, chain }.
14464     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14465                        SDValue(Result.getNode(), 2));
14466   }
14467   case GATHER: {
14468   //gather(v1, mask, index, base, scale);
14469     SDValue Chain = Op.getOperand(0);
14470     SDValue Src   = Op.getOperand(2);
14471     SDValue Base  = Op.getOperand(3);
14472     SDValue Index = Op.getOperand(4);
14473     SDValue Mask  = Op.getOperand(5);
14474     SDValue Scale = Op.getOperand(6);
14475     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14476                           Subtarget);
14477   }
14478   case SCATTER: {
14479   //scatter(base, mask, index, v1, scale);
14480     SDValue Chain = Op.getOperand(0);
14481     SDValue Base  = Op.getOperand(2);
14482     SDValue Mask  = Op.getOperand(3);
14483     SDValue Index = Op.getOperand(4);
14484     SDValue Src   = Op.getOperand(5);
14485     SDValue Scale = Op.getOperand(6);
14486     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14487   }
14488   case PREFETCH: {
14489     SDValue Hint = Op.getOperand(6);
14490     unsigned HintVal;
14491     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14492         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14493       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14494     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14495     SDValue Chain = Op.getOperand(0);
14496     SDValue Mask  = Op.getOperand(2);
14497     SDValue Index = Op.getOperand(3);
14498     SDValue Base  = Op.getOperand(4);
14499     SDValue Scale = Op.getOperand(5);
14500     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14501   }
14502   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14503   case RDTSC: {
14504     SmallVector<SDValue, 2> Results;
14505     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14506     return DAG.getMergeValues(Results, dl);
14507   }
14508   // Read Performance Monitoring Counters.
14509   case RDPMC: {
14510     SmallVector<SDValue, 2> Results;
14511     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14512     return DAG.getMergeValues(Results, dl);
14513   }
14514   // XTEST intrinsics.
14515   case XTEST: {
14516     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14517     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14518     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14519                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14520                                 InTrans);
14521     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14522     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14523                        Ret, SDValue(InTrans.getNode(), 1));
14524   }
14525   }
14526   llvm_unreachable("Unknown Intrinsic Type");
14527 }
14528
14529 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14530                                            SelectionDAG &DAG) const {
14531   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14532   MFI->setReturnAddressIsTaken(true);
14533
14534   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14535     return SDValue();
14536
14537   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14538   SDLoc dl(Op);
14539   EVT PtrVT = getPointerTy();
14540
14541   if (Depth > 0) {
14542     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14543     const X86RegisterInfo *RegInfo =
14544       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14545     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14546     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14547                        DAG.getNode(ISD::ADD, dl, PtrVT,
14548                                    FrameAddr, Offset),
14549                        MachinePointerInfo(), false, false, false, 0);
14550   }
14551
14552   // Just load the return address.
14553   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14554   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14555                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14556 }
14557
14558 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14559   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14560   MFI->setFrameAddressIsTaken(true);
14561
14562   EVT VT = Op.getValueType();
14563   SDLoc dl(Op);  // FIXME probably not meaningful
14564   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14565   const X86RegisterInfo *RegInfo =
14566     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14567   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14568   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14569           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14570          "Invalid Frame Register!");
14571   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14572   while (Depth--)
14573     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14574                             MachinePointerInfo(),
14575                             false, false, false, 0);
14576   return FrameAddr;
14577 }
14578
14579 // FIXME? Maybe this could be a TableGen attribute on some registers and
14580 // this table could be generated automatically from RegInfo.
14581 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14582                                               EVT VT) const {
14583   unsigned Reg = StringSwitch<unsigned>(RegName)
14584                        .Case("esp", X86::ESP)
14585                        .Case("rsp", X86::RSP)
14586                        .Default(0);
14587   if (Reg)
14588     return Reg;
14589   report_fatal_error("Invalid register name global variable");
14590 }
14591
14592 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14593                                                      SelectionDAG &DAG) const {
14594   const X86RegisterInfo *RegInfo =
14595     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14596   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14597 }
14598
14599 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14600   SDValue Chain     = Op.getOperand(0);
14601   SDValue Offset    = Op.getOperand(1);
14602   SDValue Handler   = Op.getOperand(2);
14603   SDLoc dl      (Op);
14604
14605   EVT PtrVT = getPointerTy();
14606   const X86RegisterInfo *RegInfo =
14607     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14608   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14609   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14610           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14611          "Invalid Frame Register!");
14612   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14613   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14614
14615   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14616                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14617   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14618   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14619                        false, false, 0);
14620   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14621
14622   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14623                      DAG.getRegister(StoreAddrReg, PtrVT));
14624 }
14625
14626 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14627                                                SelectionDAG &DAG) const {
14628   SDLoc DL(Op);
14629   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14630                      DAG.getVTList(MVT::i32, MVT::Other),
14631                      Op.getOperand(0), Op.getOperand(1));
14632 }
14633
14634 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14635                                                 SelectionDAG &DAG) const {
14636   SDLoc DL(Op);
14637   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14638                      Op.getOperand(0), Op.getOperand(1));
14639 }
14640
14641 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14642   return Op.getOperand(0);
14643 }
14644
14645 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14646                                                 SelectionDAG &DAG) const {
14647   SDValue Root = Op.getOperand(0);
14648   SDValue Trmp = Op.getOperand(1); // trampoline
14649   SDValue FPtr = Op.getOperand(2); // nested function
14650   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14651   SDLoc dl (Op);
14652
14653   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14654   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14655
14656   if (Subtarget->is64Bit()) {
14657     SDValue OutChains[6];
14658
14659     // Large code-model.
14660     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14661     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14662
14663     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14664     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14665
14666     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14667
14668     // Load the pointer to the nested function into R11.
14669     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14670     SDValue Addr = Trmp;
14671     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14672                                 Addr, MachinePointerInfo(TrmpAddr),
14673                                 false, false, 0);
14674
14675     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14676                        DAG.getConstant(2, MVT::i64));
14677     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14678                                 MachinePointerInfo(TrmpAddr, 2),
14679                                 false, false, 2);
14680
14681     // Load the 'nest' parameter value into R10.
14682     // R10 is specified in X86CallingConv.td
14683     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14684     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14685                        DAG.getConstant(10, MVT::i64));
14686     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14687                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14688                                 false, false, 0);
14689
14690     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14691                        DAG.getConstant(12, MVT::i64));
14692     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14693                                 MachinePointerInfo(TrmpAddr, 12),
14694                                 false, false, 2);
14695
14696     // Jump to the nested function.
14697     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14698     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14699                        DAG.getConstant(20, MVT::i64));
14700     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14701                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14702                                 false, false, 0);
14703
14704     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14705     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14706                        DAG.getConstant(22, MVT::i64));
14707     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14708                                 MachinePointerInfo(TrmpAddr, 22),
14709                                 false, false, 0);
14710
14711     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14712   } else {
14713     const Function *Func =
14714       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14715     CallingConv::ID CC = Func->getCallingConv();
14716     unsigned NestReg;
14717
14718     switch (CC) {
14719     default:
14720       llvm_unreachable("Unsupported calling convention");
14721     case CallingConv::C:
14722     case CallingConv::X86_StdCall: {
14723       // Pass 'nest' parameter in ECX.
14724       // Must be kept in sync with X86CallingConv.td
14725       NestReg = X86::ECX;
14726
14727       // Check that ECX wasn't needed by an 'inreg' parameter.
14728       FunctionType *FTy = Func->getFunctionType();
14729       const AttributeSet &Attrs = Func->getAttributes();
14730
14731       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14732         unsigned InRegCount = 0;
14733         unsigned Idx = 1;
14734
14735         for (FunctionType::param_iterator I = FTy->param_begin(),
14736              E = FTy->param_end(); I != E; ++I, ++Idx)
14737           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14738             // FIXME: should only count parameters that are lowered to integers.
14739             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14740
14741         if (InRegCount > 2) {
14742           report_fatal_error("Nest register in use - reduce number of inreg"
14743                              " parameters!");
14744         }
14745       }
14746       break;
14747     }
14748     case CallingConv::X86_FastCall:
14749     case CallingConv::X86_ThisCall:
14750     case CallingConv::Fast:
14751       // Pass 'nest' parameter in EAX.
14752       // Must be kept in sync with X86CallingConv.td
14753       NestReg = X86::EAX;
14754       break;
14755     }
14756
14757     SDValue OutChains[4];
14758     SDValue Addr, Disp;
14759
14760     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14761                        DAG.getConstant(10, MVT::i32));
14762     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14763
14764     // This is storing the opcode for MOV32ri.
14765     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14766     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14767     OutChains[0] = DAG.getStore(Root, dl,
14768                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14769                                 Trmp, MachinePointerInfo(TrmpAddr),
14770                                 false, false, 0);
14771
14772     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14773                        DAG.getConstant(1, MVT::i32));
14774     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14775                                 MachinePointerInfo(TrmpAddr, 1),
14776                                 false, false, 1);
14777
14778     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14779     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14780                        DAG.getConstant(5, MVT::i32));
14781     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14782                                 MachinePointerInfo(TrmpAddr, 5),
14783                                 false, false, 1);
14784
14785     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14786                        DAG.getConstant(6, MVT::i32));
14787     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14788                                 MachinePointerInfo(TrmpAddr, 6),
14789                                 false, false, 1);
14790
14791     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14792   }
14793 }
14794
14795 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14796                                             SelectionDAG &DAG) const {
14797   /*
14798    The rounding mode is in bits 11:10 of FPSR, and has the following
14799    settings:
14800      00 Round to nearest
14801      01 Round to -inf
14802      10 Round to +inf
14803      11 Round to 0
14804
14805   FLT_ROUNDS, on the other hand, expects the following:
14806     -1 Undefined
14807      0 Round to 0
14808      1 Round to nearest
14809      2 Round to +inf
14810      3 Round to -inf
14811
14812   To perform the conversion, we do:
14813     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14814   */
14815
14816   MachineFunction &MF = DAG.getMachineFunction();
14817   const TargetMachine &TM = MF.getTarget();
14818   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14819   unsigned StackAlignment = TFI.getStackAlignment();
14820   MVT VT = Op.getSimpleValueType();
14821   SDLoc DL(Op);
14822
14823   // Save FP Control Word to stack slot
14824   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14825   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14826
14827   MachineMemOperand *MMO =
14828    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14829                            MachineMemOperand::MOStore, 2, 2);
14830
14831   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14832   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14833                                           DAG.getVTList(MVT::Other),
14834                                           Ops, MVT::i16, MMO);
14835
14836   // Load FP Control Word from stack slot
14837   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14838                             MachinePointerInfo(), false, false, false, 0);
14839
14840   // Transform as necessary
14841   SDValue CWD1 =
14842     DAG.getNode(ISD::SRL, DL, MVT::i16,
14843                 DAG.getNode(ISD::AND, DL, MVT::i16,
14844                             CWD, DAG.getConstant(0x800, MVT::i16)),
14845                 DAG.getConstant(11, MVT::i8));
14846   SDValue CWD2 =
14847     DAG.getNode(ISD::SRL, DL, MVT::i16,
14848                 DAG.getNode(ISD::AND, DL, MVT::i16,
14849                             CWD, DAG.getConstant(0x400, MVT::i16)),
14850                 DAG.getConstant(9, MVT::i8));
14851
14852   SDValue RetVal =
14853     DAG.getNode(ISD::AND, DL, MVT::i16,
14854                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14855                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14856                             DAG.getConstant(1, MVT::i16)),
14857                 DAG.getConstant(3, MVT::i16));
14858
14859   return DAG.getNode((VT.getSizeInBits() < 16 ?
14860                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14861 }
14862
14863 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14864   MVT VT = Op.getSimpleValueType();
14865   EVT OpVT = VT;
14866   unsigned NumBits = VT.getSizeInBits();
14867   SDLoc dl(Op);
14868
14869   Op = Op.getOperand(0);
14870   if (VT == MVT::i8) {
14871     // Zero extend to i32 since there is not an i8 bsr.
14872     OpVT = MVT::i32;
14873     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14874   }
14875
14876   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14877   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14878   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14879
14880   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14881   SDValue Ops[] = {
14882     Op,
14883     DAG.getConstant(NumBits+NumBits-1, OpVT),
14884     DAG.getConstant(X86::COND_E, MVT::i8),
14885     Op.getValue(1)
14886   };
14887   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14888
14889   // Finally xor with NumBits-1.
14890   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14891
14892   if (VT == MVT::i8)
14893     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14894   return Op;
14895 }
14896
14897 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14898   MVT VT = Op.getSimpleValueType();
14899   EVT OpVT = VT;
14900   unsigned NumBits = VT.getSizeInBits();
14901   SDLoc dl(Op);
14902
14903   Op = Op.getOperand(0);
14904   if (VT == MVT::i8) {
14905     // Zero extend to i32 since there is not an i8 bsr.
14906     OpVT = MVT::i32;
14907     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14908   }
14909
14910   // Issue a bsr (scan bits in reverse).
14911   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14912   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14913
14914   // And xor with NumBits-1.
14915   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14916
14917   if (VT == MVT::i8)
14918     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14919   return Op;
14920 }
14921
14922 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14923   MVT VT = Op.getSimpleValueType();
14924   unsigned NumBits = VT.getSizeInBits();
14925   SDLoc dl(Op);
14926   Op = Op.getOperand(0);
14927
14928   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14929   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14930   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14931
14932   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14933   SDValue Ops[] = {
14934     Op,
14935     DAG.getConstant(NumBits, VT),
14936     DAG.getConstant(X86::COND_E, MVT::i8),
14937     Op.getValue(1)
14938   };
14939   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14940 }
14941
14942 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14943 // ones, and then concatenate the result back.
14944 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14945   MVT VT = Op.getSimpleValueType();
14946
14947   assert(VT.is256BitVector() && VT.isInteger() &&
14948          "Unsupported value type for operation");
14949
14950   unsigned NumElems = VT.getVectorNumElements();
14951   SDLoc dl(Op);
14952
14953   // Extract the LHS vectors
14954   SDValue LHS = Op.getOperand(0);
14955   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14956   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14957
14958   // Extract the RHS vectors
14959   SDValue RHS = Op.getOperand(1);
14960   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14961   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14962
14963   MVT EltVT = VT.getVectorElementType();
14964   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14965
14966   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14967                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14968                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14969 }
14970
14971 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14972   assert(Op.getSimpleValueType().is256BitVector() &&
14973          Op.getSimpleValueType().isInteger() &&
14974          "Only handle AVX 256-bit vector integer operation");
14975   return Lower256IntArith(Op, DAG);
14976 }
14977
14978 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14979   assert(Op.getSimpleValueType().is256BitVector() &&
14980          Op.getSimpleValueType().isInteger() &&
14981          "Only handle AVX 256-bit vector integer operation");
14982   return Lower256IntArith(Op, DAG);
14983 }
14984
14985 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14986                         SelectionDAG &DAG) {
14987   SDLoc dl(Op);
14988   MVT VT = Op.getSimpleValueType();
14989
14990   // Decompose 256-bit ops into smaller 128-bit ops.
14991   if (VT.is256BitVector() && !Subtarget->hasInt256())
14992     return Lower256IntArith(Op, DAG);
14993
14994   SDValue A = Op.getOperand(0);
14995   SDValue B = Op.getOperand(1);
14996
14997   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14998   if (VT == MVT::v4i32) {
14999     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15000            "Should not custom lower when pmuldq is available!");
15001
15002     // Extract the odd parts.
15003     static const int UnpackMask[] = { 1, -1, 3, -1 };
15004     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15005     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15006
15007     // Multiply the even parts.
15008     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15009     // Now multiply odd parts.
15010     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15011
15012     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15013     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15014
15015     // Merge the two vectors back together with a shuffle. This expands into 2
15016     // shuffles.
15017     static const int ShufMask[] = { 0, 4, 2, 6 };
15018     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15019   }
15020
15021   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15022          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15023
15024   //  Ahi = psrlqi(a, 32);
15025   //  Bhi = psrlqi(b, 32);
15026   //
15027   //  AloBlo = pmuludq(a, b);
15028   //  AloBhi = pmuludq(a, Bhi);
15029   //  AhiBlo = pmuludq(Ahi, b);
15030
15031   //  AloBhi = psllqi(AloBhi, 32);
15032   //  AhiBlo = psllqi(AhiBlo, 32);
15033   //  return AloBlo + AloBhi + AhiBlo;
15034
15035   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15036   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15037
15038   // Bit cast to 32-bit vectors for MULUDQ
15039   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15040                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15041   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15042   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15043   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15044   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15045
15046   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15047   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15048   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15049
15050   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15051   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15052
15053   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15054   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15055 }
15056
15057 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15058   assert(Subtarget->isTargetWin64() && "Unexpected target");
15059   EVT VT = Op.getValueType();
15060   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15061          "Unexpected return type for lowering");
15062
15063   RTLIB::Libcall LC;
15064   bool isSigned;
15065   switch (Op->getOpcode()) {
15066   default: llvm_unreachable("Unexpected request for libcall!");
15067   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15068   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15069   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15070   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15071   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15072   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15073   }
15074
15075   SDLoc dl(Op);
15076   SDValue InChain = DAG.getEntryNode();
15077
15078   TargetLowering::ArgListTy Args;
15079   TargetLowering::ArgListEntry Entry;
15080   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15081     EVT ArgVT = Op->getOperand(i).getValueType();
15082     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15083            "Unexpected argument type for lowering");
15084     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15085     Entry.Node = StackPtr;
15086     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15087                            false, false, 16);
15088     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15089     Entry.Ty = PointerType::get(ArgTy,0);
15090     Entry.isSExt = false;
15091     Entry.isZExt = false;
15092     Args.push_back(Entry);
15093   }
15094
15095   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15096                                          getPointerTy());
15097
15098   TargetLowering::CallLoweringInfo CLI(DAG);
15099   CLI.setDebugLoc(dl).setChain(InChain)
15100     .setCallee(getLibcallCallingConv(LC),
15101                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15102                Callee, &Args, 0)
15103     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15104
15105   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15106   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15107 }
15108
15109 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15110                              SelectionDAG &DAG) {
15111   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15112   EVT VT = Op0.getValueType();
15113   SDLoc dl(Op);
15114
15115   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15116          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15117
15118   // Get the high parts.
15119   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15120   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15121   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15122
15123   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15124   // ints.
15125   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15126   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15127   unsigned Opcode =
15128       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15129   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15130                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15131   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15132                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15133
15134   // Shuffle it back into the right order.
15135   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15136   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15137   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15138   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15139
15140   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15141   // unsigned multiply.
15142   if (IsSigned && !Subtarget->hasSSE41()) {
15143     SDValue ShAmt =
15144         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15145     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15146                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15147     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15148                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15149
15150     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15151     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15152   }
15153
15154   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15155 }
15156
15157 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15158                                          const X86Subtarget *Subtarget) {
15159   MVT VT = Op.getSimpleValueType();
15160   SDLoc dl(Op);
15161   SDValue R = Op.getOperand(0);
15162   SDValue Amt = Op.getOperand(1);
15163
15164   // Optimize shl/srl/sra with constant shift amount.
15165   if (isSplatVector(Amt.getNode())) {
15166     SDValue SclrAmt = Amt->getOperand(0);
15167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15168       uint64_t ShiftAmt = C->getZExtValue();
15169
15170       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15171           (Subtarget->hasInt256() &&
15172            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15173           (Subtarget->hasAVX512() &&
15174            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15175         if (Op.getOpcode() == ISD::SHL)
15176           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15177                                             DAG);
15178         if (Op.getOpcode() == ISD::SRL)
15179           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15180                                             DAG);
15181         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15182           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15183                                             DAG);
15184       }
15185
15186       if (VT == MVT::v16i8) {
15187         if (Op.getOpcode() == ISD::SHL) {
15188           // Make a large shift.
15189           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15190                                                    MVT::v8i16, R, ShiftAmt,
15191                                                    DAG);
15192           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15193           // Zero out the rightmost bits.
15194           SmallVector<SDValue, 16> V(16,
15195                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15196                                                      MVT::i8));
15197           return DAG.getNode(ISD::AND, dl, VT, SHL,
15198                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15199         }
15200         if (Op.getOpcode() == ISD::SRL) {
15201           // Make a large shift.
15202           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15203                                                    MVT::v8i16, R, ShiftAmt,
15204                                                    DAG);
15205           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15206           // Zero out the leftmost bits.
15207           SmallVector<SDValue, 16> V(16,
15208                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15209                                                      MVT::i8));
15210           return DAG.getNode(ISD::AND, dl, VT, SRL,
15211                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15212         }
15213         if (Op.getOpcode() == ISD::SRA) {
15214           if (ShiftAmt == 7) {
15215             // R s>> 7  ===  R s< 0
15216             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15217             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15218           }
15219
15220           // R s>> a === ((R u>> a) ^ m) - m
15221           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15222           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15223                                                          MVT::i8));
15224           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15225           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15226           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15227           return Res;
15228         }
15229         llvm_unreachable("Unknown shift opcode.");
15230       }
15231
15232       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15233         if (Op.getOpcode() == ISD::SHL) {
15234           // Make a large shift.
15235           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15236                                                    MVT::v16i16, R, ShiftAmt,
15237                                                    DAG);
15238           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15239           // Zero out the rightmost bits.
15240           SmallVector<SDValue, 32> V(32,
15241                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15242                                                      MVT::i8));
15243           return DAG.getNode(ISD::AND, dl, VT, SHL,
15244                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15245         }
15246         if (Op.getOpcode() == ISD::SRL) {
15247           // Make a large shift.
15248           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15249                                                    MVT::v16i16, R, ShiftAmt,
15250                                                    DAG);
15251           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15252           // Zero out the leftmost bits.
15253           SmallVector<SDValue, 32> V(32,
15254                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15255                                                      MVT::i8));
15256           return DAG.getNode(ISD::AND, dl, VT, SRL,
15257                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15258         }
15259         if (Op.getOpcode() == ISD::SRA) {
15260           if (ShiftAmt == 7) {
15261             // R s>> 7  ===  R s< 0
15262             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15263             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15264           }
15265
15266           // R s>> a === ((R u>> a) ^ m) - m
15267           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15268           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15269                                                          MVT::i8));
15270           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15271           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15272           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15273           return Res;
15274         }
15275         llvm_unreachable("Unknown shift opcode.");
15276       }
15277     }
15278   }
15279
15280   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15281   if (!Subtarget->is64Bit() &&
15282       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15283       Amt.getOpcode() == ISD::BITCAST &&
15284       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15285     Amt = Amt.getOperand(0);
15286     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15287                      VT.getVectorNumElements();
15288     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15289     uint64_t ShiftAmt = 0;
15290     for (unsigned i = 0; i != Ratio; ++i) {
15291       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15292       if (!C)
15293         return SDValue();
15294       // 6 == Log2(64)
15295       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15296     }
15297     // Check remaining shift amounts.
15298     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15299       uint64_t ShAmt = 0;
15300       for (unsigned j = 0; j != Ratio; ++j) {
15301         ConstantSDNode *C =
15302           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15303         if (!C)
15304           return SDValue();
15305         // 6 == Log2(64)
15306         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15307       }
15308       if (ShAmt != ShiftAmt)
15309         return SDValue();
15310     }
15311     switch (Op.getOpcode()) {
15312     default:
15313       llvm_unreachable("Unknown shift opcode!");
15314     case ISD::SHL:
15315       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15316                                         DAG);
15317     case ISD::SRL:
15318       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15319                                         DAG);
15320     case ISD::SRA:
15321       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15322                                         DAG);
15323     }
15324   }
15325
15326   return SDValue();
15327 }
15328
15329 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15330                                         const X86Subtarget* Subtarget) {
15331   MVT VT = Op.getSimpleValueType();
15332   SDLoc dl(Op);
15333   SDValue R = Op.getOperand(0);
15334   SDValue Amt = Op.getOperand(1);
15335
15336   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15337       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15338       (Subtarget->hasInt256() &&
15339        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15340         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15341        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15342     SDValue BaseShAmt;
15343     EVT EltVT = VT.getVectorElementType();
15344
15345     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15346       unsigned NumElts = VT.getVectorNumElements();
15347       unsigned i, j;
15348       for (i = 0; i != NumElts; ++i) {
15349         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15350           continue;
15351         break;
15352       }
15353       for (j = i; j != NumElts; ++j) {
15354         SDValue Arg = Amt.getOperand(j);
15355         if (Arg.getOpcode() == ISD::UNDEF) continue;
15356         if (Arg != Amt.getOperand(i))
15357           break;
15358       }
15359       if (i != NumElts && j == NumElts)
15360         BaseShAmt = Amt.getOperand(i);
15361     } else {
15362       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15363         Amt = Amt.getOperand(0);
15364       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15365                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15366         SDValue InVec = Amt.getOperand(0);
15367         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15368           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15369           unsigned i = 0;
15370           for (; i != NumElts; ++i) {
15371             SDValue Arg = InVec.getOperand(i);
15372             if (Arg.getOpcode() == ISD::UNDEF) continue;
15373             BaseShAmt = Arg;
15374             break;
15375           }
15376         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15377            if (ConstantSDNode *C =
15378                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15379              unsigned SplatIdx =
15380                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15381              if (C->getZExtValue() == SplatIdx)
15382                BaseShAmt = InVec.getOperand(1);
15383            }
15384         }
15385         if (!BaseShAmt.getNode())
15386           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15387                                   DAG.getIntPtrConstant(0));
15388       }
15389     }
15390
15391     if (BaseShAmt.getNode()) {
15392       if (EltVT.bitsGT(MVT::i32))
15393         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15394       else if (EltVT.bitsLT(MVT::i32))
15395         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15396
15397       switch (Op.getOpcode()) {
15398       default:
15399         llvm_unreachable("Unknown shift opcode!");
15400       case ISD::SHL:
15401         switch (VT.SimpleTy) {
15402         default: return SDValue();
15403         case MVT::v2i64:
15404         case MVT::v4i32:
15405         case MVT::v8i16:
15406         case MVT::v4i64:
15407         case MVT::v8i32:
15408         case MVT::v16i16:
15409         case MVT::v16i32:
15410         case MVT::v8i64:
15411           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15412         }
15413       case ISD::SRA:
15414         switch (VT.SimpleTy) {
15415         default: return SDValue();
15416         case MVT::v4i32:
15417         case MVT::v8i16:
15418         case MVT::v8i32:
15419         case MVT::v16i16:
15420         case MVT::v16i32:
15421         case MVT::v8i64:
15422           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15423         }
15424       case ISD::SRL:
15425         switch (VT.SimpleTy) {
15426         default: return SDValue();
15427         case MVT::v2i64:
15428         case MVT::v4i32:
15429         case MVT::v8i16:
15430         case MVT::v4i64:
15431         case MVT::v8i32:
15432         case MVT::v16i16:
15433         case MVT::v16i32:
15434         case MVT::v8i64:
15435           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15436         }
15437       }
15438     }
15439   }
15440
15441   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15442   if (!Subtarget->is64Bit() &&
15443       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15444       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15445       Amt.getOpcode() == ISD::BITCAST &&
15446       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15447     Amt = Amt.getOperand(0);
15448     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15449                      VT.getVectorNumElements();
15450     std::vector<SDValue> Vals(Ratio);
15451     for (unsigned i = 0; i != Ratio; ++i)
15452       Vals[i] = Amt.getOperand(i);
15453     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15454       for (unsigned j = 0; j != Ratio; ++j)
15455         if (Vals[j] != Amt.getOperand(i + j))
15456           return SDValue();
15457     }
15458     switch (Op.getOpcode()) {
15459     default:
15460       llvm_unreachable("Unknown shift opcode!");
15461     case ISD::SHL:
15462       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15463     case ISD::SRL:
15464       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15465     case ISD::SRA:
15466       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15467     }
15468   }
15469
15470   return SDValue();
15471 }
15472
15473 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15474                           SelectionDAG &DAG) {
15475
15476   MVT VT = Op.getSimpleValueType();
15477   SDLoc dl(Op);
15478   SDValue R = Op.getOperand(0);
15479   SDValue Amt = Op.getOperand(1);
15480   SDValue V;
15481
15482   if (!Subtarget->hasSSE2())
15483     return SDValue();
15484
15485   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15486   if (V.getNode())
15487     return V;
15488
15489   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15490   if (V.getNode())
15491       return V;
15492
15493   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15494     return Op;
15495   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15496   if (Subtarget->hasInt256()) {
15497     if (Op.getOpcode() == ISD::SRL &&
15498         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15499          VT == MVT::v4i64 || VT == MVT::v8i32))
15500       return Op;
15501     if (Op.getOpcode() == ISD::SHL &&
15502         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15503          VT == MVT::v4i64 || VT == MVT::v8i32))
15504       return Op;
15505     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15506       return Op;
15507   }
15508
15509   // If possible, lower this packed shift into a vector multiply instead of
15510   // expanding it into a sequence of scalar shifts.
15511   // Do this only if the vector shift count is a constant build_vector.
15512   if (Op.getOpcode() == ISD::SHL && 
15513       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15514        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15515       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15516     SmallVector<SDValue, 8> Elts;
15517     EVT SVT = VT.getScalarType();
15518     unsigned SVTBits = SVT.getSizeInBits();
15519     const APInt &One = APInt(SVTBits, 1);
15520     unsigned NumElems = VT.getVectorNumElements();
15521
15522     for (unsigned i=0; i !=NumElems; ++i) {
15523       SDValue Op = Amt->getOperand(i);
15524       if (Op->getOpcode() == ISD::UNDEF) {
15525         Elts.push_back(Op);
15526         continue;
15527       }
15528
15529       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15530       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15531       uint64_t ShAmt = C.getZExtValue();
15532       if (ShAmt >= SVTBits) {
15533         Elts.push_back(DAG.getUNDEF(SVT));
15534         continue;
15535       }
15536       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15537     }
15538     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15539     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15540   }
15541
15542   // Lower SHL with variable shift amount.
15543   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15544     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15545
15546     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15547     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15548     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15549     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15550   }
15551
15552   // If possible, lower this shift as a sequence of two shifts by
15553   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15554   // Example:
15555   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15556   //
15557   // Could be rewritten as:
15558   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15559   //
15560   // The advantage is that the two shifts from the example would be
15561   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15562   // the vector shift into four scalar shifts plus four pairs of vector
15563   // insert/extract.
15564   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15565       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15566     unsigned TargetOpcode = X86ISD::MOVSS;
15567     bool CanBeSimplified;
15568     // The splat value for the first packed shift (the 'X' from the example).
15569     SDValue Amt1 = Amt->getOperand(0);
15570     // The splat value for the second packed shift (the 'Y' from the example).
15571     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15572                                         Amt->getOperand(2);
15573
15574     // See if it is possible to replace this node with a sequence of
15575     // two shifts followed by a MOVSS/MOVSD
15576     if (VT == MVT::v4i32) {
15577       // Check if it is legal to use a MOVSS.
15578       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15579                         Amt2 == Amt->getOperand(3);
15580       if (!CanBeSimplified) {
15581         // Otherwise, check if we can still simplify this node using a MOVSD.
15582         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15583                           Amt->getOperand(2) == Amt->getOperand(3);
15584         TargetOpcode = X86ISD::MOVSD;
15585         Amt2 = Amt->getOperand(2);
15586       }
15587     } else {
15588       // Do similar checks for the case where the machine value type
15589       // is MVT::v8i16.
15590       CanBeSimplified = Amt1 == Amt->getOperand(1);
15591       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15592         CanBeSimplified = Amt2 == Amt->getOperand(i);
15593
15594       if (!CanBeSimplified) {
15595         TargetOpcode = X86ISD::MOVSD;
15596         CanBeSimplified = true;
15597         Amt2 = Amt->getOperand(4);
15598         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15599           CanBeSimplified = Amt1 == Amt->getOperand(i);
15600         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15601           CanBeSimplified = Amt2 == Amt->getOperand(j);
15602       }
15603     }
15604     
15605     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15606         isa<ConstantSDNode>(Amt2)) {
15607       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15608       EVT CastVT = MVT::v4i32;
15609       SDValue Splat1 = 
15610         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15611       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15612       SDValue Splat2 = 
15613         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15614       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15615       if (TargetOpcode == X86ISD::MOVSD)
15616         CastVT = MVT::v2i64;
15617       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15618       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15619       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15620                                             BitCast1, DAG);
15621       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15622     }
15623   }
15624
15625   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15626     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15627
15628     // a = a << 5;
15629     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15630     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15631
15632     // Turn 'a' into a mask suitable for VSELECT
15633     SDValue VSelM = DAG.getConstant(0x80, VT);
15634     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15635     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15636
15637     SDValue CM1 = DAG.getConstant(0x0f, VT);
15638     SDValue CM2 = DAG.getConstant(0x3f, VT);
15639
15640     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15641     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15642     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15643     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15644     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15645
15646     // a += a
15647     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15648     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15649     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15650
15651     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15652     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15653     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15654     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15655     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15656
15657     // a += a
15658     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15659     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15660     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15661
15662     // return VSELECT(r, r+r, a);
15663     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15664                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15665     return R;
15666   }
15667
15668   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15669   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15670   // solution better.
15671   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15672     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15673     unsigned ExtOpc =
15674         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15675     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15676     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15677     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15678                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15679     }
15680
15681   // Decompose 256-bit shifts into smaller 128-bit shifts.
15682   if (VT.is256BitVector()) {
15683     unsigned NumElems = VT.getVectorNumElements();
15684     MVT EltVT = VT.getVectorElementType();
15685     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15686
15687     // Extract the two vectors
15688     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15689     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15690
15691     // Recreate the shift amount vectors
15692     SDValue Amt1, Amt2;
15693     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15694       // Constant shift amount
15695       SmallVector<SDValue, 4> Amt1Csts;
15696       SmallVector<SDValue, 4> Amt2Csts;
15697       for (unsigned i = 0; i != NumElems/2; ++i)
15698         Amt1Csts.push_back(Amt->getOperand(i));
15699       for (unsigned i = NumElems/2; i != NumElems; ++i)
15700         Amt2Csts.push_back(Amt->getOperand(i));
15701
15702       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15703       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15704     } else {
15705       // Variable shift amount
15706       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15707       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15708     }
15709
15710     // Issue new vector shifts for the smaller types
15711     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15712     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15713
15714     // Concatenate the result back
15715     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15716   }
15717
15718   return SDValue();
15719 }
15720
15721 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15722   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15723   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15724   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15725   // has only one use.
15726   SDNode *N = Op.getNode();
15727   SDValue LHS = N->getOperand(0);
15728   SDValue RHS = N->getOperand(1);
15729   unsigned BaseOp = 0;
15730   unsigned Cond = 0;
15731   SDLoc DL(Op);
15732   switch (Op.getOpcode()) {
15733   default: llvm_unreachable("Unknown ovf instruction!");
15734   case ISD::SADDO:
15735     // A subtract of one will be selected as a INC. Note that INC doesn't
15736     // set CF, so we can't do this for UADDO.
15737     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15738       if (C->isOne()) {
15739         BaseOp = X86ISD::INC;
15740         Cond = X86::COND_O;
15741         break;
15742       }
15743     BaseOp = X86ISD::ADD;
15744     Cond = X86::COND_O;
15745     break;
15746   case ISD::UADDO:
15747     BaseOp = X86ISD::ADD;
15748     Cond = X86::COND_B;
15749     break;
15750   case ISD::SSUBO:
15751     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15752     // set CF, so we can't do this for USUBO.
15753     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15754       if (C->isOne()) {
15755         BaseOp = X86ISD::DEC;
15756         Cond = X86::COND_O;
15757         break;
15758       }
15759     BaseOp = X86ISD::SUB;
15760     Cond = X86::COND_O;
15761     break;
15762   case ISD::USUBO:
15763     BaseOp = X86ISD::SUB;
15764     Cond = X86::COND_B;
15765     break;
15766   case ISD::SMULO:
15767     BaseOp = X86ISD::SMUL;
15768     Cond = X86::COND_O;
15769     break;
15770   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15771     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15772                                  MVT::i32);
15773     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15774
15775     SDValue SetCC =
15776       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15777                   DAG.getConstant(X86::COND_O, MVT::i32),
15778                   SDValue(Sum.getNode(), 2));
15779
15780     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15781   }
15782   }
15783
15784   // Also sets EFLAGS.
15785   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15786   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15787
15788   SDValue SetCC =
15789     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15790                 DAG.getConstant(Cond, MVT::i32),
15791                 SDValue(Sum.getNode(), 1));
15792
15793   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15794 }
15795
15796 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15797                                                   SelectionDAG &DAG) const {
15798   SDLoc dl(Op);
15799   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15800   MVT VT = Op.getSimpleValueType();
15801
15802   if (!Subtarget->hasSSE2() || !VT.isVector())
15803     return SDValue();
15804
15805   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15806                       ExtraVT.getScalarType().getSizeInBits();
15807
15808   switch (VT.SimpleTy) {
15809     default: return SDValue();
15810     case MVT::v8i32:
15811     case MVT::v16i16:
15812       if (!Subtarget->hasFp256())
15813         return SDValue();
15814       if (!Subtarget->hasInt256()) {
15815         // needs to be split
15816         unsigned NumElems = VT.getVectorNumElements();
15817
15818         // Extract the LHS vectors
15819         SDValue LHS = Op.getOperand(0);
15820         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15821         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15822
15823         MVT EltVT = VT.getVectorElementType();
15824         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15825
15826         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15827         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15828         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15829                                    ExtraNumElems/2);
15830         SDValue Extra = DAG.getValueType(ExtraVT);
15831
15832         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15833         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15834
15835         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15836       }
15837       // fall through
15838     case MVT::v4i32:
15839     case MVT::v8i16: {
15840       SDValue Op0 = Op.getOperand(0);
15841       SDValue Op00 = Op0.getOperand(0);
15842       SDValue Tmp1;
15843       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15844       if (Op0.getOpcode() == ISD::BITCAST &&
15845           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15846         // (sext (vzext x)) -> (vsext x)
15847         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15848         if (Tmp1.getNode()) {
15849           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15850           // This folding is only valid when the in-reg type is a vector of i8,
15851           // i16, or i32.
15852           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15853               ExtraEltVT == MVT::i32) {
15854             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15855             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15856                    "This optimization is invalid without a VZEXT.");
15857             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15858           }
15859           Op0 = Tmp1;
15860         }
15861       }
15862
15863       // If the above didn't work, then just use Shift-Left + Shift-Right.
15864       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15865                                         DAG);
15866       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15867                                         DAG);
15868     }
15869   }
15870 }
15871
15872 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15873                                  SelectionDAG &DAG) {
15874   SDLoc dl(Op);
15875   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15876     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15877   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15878     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15879
15880   // The only fence that needs an instruction is a sequentially-consistent
15881   // cross-thread fence.
15882   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15883     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15884     // no-sse2). There isn't any reason to disable it if the target processor
15885     // supports it.
15886     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15887       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15888
15889     SDValue Chain = Op.getOperand(0);
15890     SDValue Zero = DAG.getConstant(0, MVT::i32);
15891     SDValue Ops[] = {
15892       DAG.getRegister(X86::ESP, MVT::i32), // Base
15893       DAG.getTargetConstant(1, MVT::i8),   // Scale
15894       DAG.getRegister(0, MVT::i32),        // Index
15895       DAG.getTargetConstant(0, MVT::i32),  // Disp
15896       DAG.getRegister(0, MVT::i32),        // Segment.
15897       Zero,
15898       Chain
15899     };
15900     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15901     return SDValue(Res, 0);
15902   }
15903
15904   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15905   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15906 }
15907
15908 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15909                              SelectionDAG &DAG) {
15910   MVT T = Op.getSimpleValueType();
15911   SDLoc DL(Op);
15912   unsigned Reg = 0;
15913   unsigned size = 0;
15914   switch(T.SimpleTy) {
15915   default: llvm_unreachable("Invalid value type!");
15916   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15917   case MVT::i16: Reg = X86::AX;  size = 2; break;
15918   case MVT::i32: Reg = X86::EAX; size = 4; break;
15919   case MVT::i64:
15920     assert(Subtarget->is64Bit() && "Node not type legal!");
15921     Reg = X86::RAX; size = 8;
15922     break;
15923   }
15924   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15925                                   Op.getOperand(2), SDValue());
15926   SDValue Ops[] = { cpIn.getValue(0),
15927                     Op.getOperand(1),
15928                     Op.getOperand(3),
15929                     DAG.getTargetConstant(size, MVT::i8),
15930                     cpIn.getValue(1) };
15931   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15932   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15933   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15934                                            Ops, T, MMO);
15935
15936   SDValue cpOut =
15937     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15938   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15939                                       MVT::i32, cpOut.getValue(2));
15940   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15941                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15942
15943   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15944   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15945   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15946   return SDValue();
15947 }
15948
15949 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15950                             SelectionDAG &DAG) {
15951   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15952   MVT DstVT = Op.getSimpleValueType();
15953
15954   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15955     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15956     if (DstVT != MVT::f64)
15957       // This conversion needs to be expanded.
15958       return SDValue();
15959
15960     SDValue InVec = Op->getOperand(0);
15961     SDLoc dl(Op);
15962     unsigned NumElts = SrcVT.getVectorNumElements();
15963     EVT SVT = SrcVT.getVectorElementType();
15964
15965     // Widen the vector in input in the case of MVT::v2i32.
15966     // Example: from MVT::v2i32 to MVT::v4i32.
15967     SmallVector<SDValue, 16> Elts;
15968     for (unsigned i = 0, e = NumElts; i != e; ++i)
15969       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15970                                  DAG.getIntPtrConstant(i)));
15971
15972     // Explicitly mark the extra elements as Undef.
15973     SDValue Undef = DAG.getUNDEF(SVT);
15974     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15975       Elts.push_back(Undef);
15976
15977     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15978     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15979     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15980     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15981                        DAG.getIntPtrConstant(0));
15982   }
15983
15984   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15985          Subtarget->hasMMX() && "Unexpected custom BITCAST");
15986   assert((DstVT == MVT::i64 ||
15987           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15988          "Unexpected custom BITCAST");
15989   // i64 <=> MMX conversions are Legal.
15990   if (SrcVT==MVT::i64 && DstVT.isVector())
15991     return Op;
15992   if (DstVT==MVT::i64 && SrcVT.isVector())
15993     return Op;
15994   // MMX <=> MMX conversions are Legal.
15995   if (SrcVT.isVector() && DstVT.isVector())
15996     return Op;
15997   // All other conversions need to be expanded.
15998   return SDValue();
15999 }
16000
16001 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16002   SDNode *Node = Op.getNode();
16003   SDLoc dl(Node);
16004   EVT T = Node->getValueType(0);
16005   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16006                               DAG.getConstant(0, T), Node->getOperand(2));
16007   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16008                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16009                        Node->getOperand(0),
16010                        Node->getOperand(1), negOp,
16011                        cast<AtomicSDNode>(Node)->getMemOperand(),
16012                        cast<AtomicSDNode>(Node)->getOrdering(),
16013                        cast<AtomicSDNode>(Node)->getSynchScope());
16014 }
16015
16016 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16017   SDNode *Node = Op.getNode();
16018   SDLoc dl(Node);
16019   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16020
16021   // Convert seq_cst store -> xchg
16022   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16023   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16024   //        (The only way to get a 16-byte store is cmpxchg16b)
16025   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16026   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16027       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16028     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16029                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16030                                  Node->getOperand(0),
16031                                  Node->getOperand(1), Node->getOperand(2),
16032                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16033                                  cast<AtomicSDNode>(Node)->getOrdering(),
16034                                  cast<AtomicSDNode>(Node)->getSynchScope());
16035     return Swap.getValue(1);
16036   }
16037   // Other atomic stores have a simple pattern.
16038   return Op;
16039 }
16040
16041 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16042   EVT VT = Op.getNode()->getSimpleValueType(0);
16043
16044   // Let legalize expand this if it isn't a legal type yet.
16045   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16046     return SDValue();
16047
16048   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16049
16050   unsigned Opc;
16051   bool ExtraOp = false;
16052   switch (Op.getOpcode()) {
16053   default: llvm_unreachable("Invalid code");
16054   case ISD::ADDC: Opc = X86ISD::ADD; break;
16055   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16056   case ISD::SUBC: Opc = X86ISD::SUB; break;
16057   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16058   }
16059
16060   if (!ExtraOp)
16061     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16062                        Op.getOperand(1));
16063   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16064                      Op.getOperand(1), Op.getOperand(2));
16065 }
16066
16067 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16068                             SelectionDAG &DAG) {
16069   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16070
16071   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16072   // which returns the values as { float, float } (in XMM0) or
16073   // { double, double } (which is returned in XMM0, XMM1).
16074   SDLoc dl(Op);
16075   SDValue Arg = Op.getOperand(0);
16076   EVT ArgVT = Arg.getValueType();
16077   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16078
16079   TargetLowering::ArgListTy Args;
16080   TargetLowering::ArgListEntry Entry;
16081
16082   Entry.Node = Arg;
16083   Entry.Ty = ArgTy;
16084   Entry.isSExt = false;
16085   Entry.isZExt = false;
16086   Args.push_back(Entry);
16087
16088   bool isF64 = ArgVT == MVT::f64;
16089   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16090   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16091   // the results are returned via SRet in memory.
16092   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16094   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16095
16096   Type *RetTy = isF64
16097     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16098     : (Type*)VectorType::get(ArgTy, 4);
16099
16100   TargetLowering::CallLoweringInfo CLI(DAG);
16101   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16102     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
16103
16104   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16105
16106   if (isF64)
16107     // Returned in xmm0 and xmm1.
16108     return CallResult.first;
16109
16110   // Returned in bits 0:31 and 32:64 xmm0.
16111   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16112                                CallResult.first, DAG.getIntPtrConstant(0));
16113   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16114                                CallResult.first, DAG.getIntPtrConstant(1));
16115   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16116   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16117 }
16118
16119 /// LowerOperation - Provide custom lowering hooks for some operations.
16120 ///
16121 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16122   switch (Op.getOpcode()) {
16123   default: llvm_unreachable("Should not custom lower this!");
16124   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16125   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16126   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16127     return LowerCMP_SWAP(Op, Subtarget, DAG);
16128   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16129   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16130   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16131   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16132   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16133   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16134   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16135   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16136   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16137   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16138   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16139   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16140   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16141   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16142   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16143   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16144   case ISD::SHL_PARTS:
16145   case ISD::SRA_PARTS:
16146   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16147   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16148   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16149   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16150   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16151   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16152   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16153   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16154   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16155   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16156   case ISD::FABS:               return LowerFABS(Op, DAG);
16157   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16158   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16159   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16160   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16161   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16162   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16163   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16164   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16165   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16166   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16167   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16168   case ISD::INTRINSIC_VOID:
16169   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16170   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16171   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16172   case ISD::FRAME_TO_ARGS_OFFSET:
16173                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16174   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16175   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16176   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16177   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16178   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16179   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16180   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16181   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16182   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16183   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16184   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16185   case ISD::UMUL_LOHI:
16186   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16187   case ISD::SRA:
16188   case ISD::SRL:
16189   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16190   case ISD::SADDO:
16191   case ISD::UADDO:
16192   case ISD::SSUBO:
16193   case ISD::USUBO:
16194   case ISD::SMULO:
16195   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16196   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16197   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16198   case ISD::ADDC:
16199   case ISD::ADDE:
16200   case ISD::SUBC:
16201   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16202   case ISD::ADD:                return LowerADD(Op, DAG);
16203   case ISD::SUB:                return LowerSUB(Op, DAG);
16204   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16205   }
16206 }
16207
16208 static void ReplaceATOMIC_LOAD(SDNode *Node,
16209                                SmallVectorImpl<SDValue> &Results,
16210                                SelectionDAG &DAG) {
16211   SDLoc dl(Node);
16212   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16213
16214   // Convert wide load -> cmpxchg8b/cmpxchg16b
16215   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16216   //        (The only way to get a 16-byte load is cmpxchg16b)
16217   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16218   SDValue Zero = DAG.getConstant(0, VT);
16219   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16220   SDValue Swap =
16221       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16222                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16223                            cast<AtomicSDNode>(Node)->getMemOperand(),
16224                            cast<AtomicSDNode>(Node)->getOrdering(),
16225                            cast<AtomicSDNode>(Node)->getOrdering(),
16226                            cast<AtomicSDNode>(Node)->getSynchScope());
16227   Results.push_back(Swap.getValue(0));
16228   Results.push_back(Swap.getValue(2));
16229 }
16230
16231 static void
16232 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
16233                         SelectionDAG &DAG, unsigned NewOp) {
16234   SDLoc dl(Node);
16235   assert (Node->getValueType(0) == MVT::i64 &&
16236           "Only know how to expand i64 atomics");
16237
16238   SDValue Chain = Node->getOperand(0);
16239   SDValue In1 = Node->getOperand(1);
16240   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16241                              Node->getOperand(2), DAG.getIntPtrConstant(0));
16242   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16243                              Node->getOperand(2), DAG.getIntPtrConstant(1));
16244   SDValue Ops[] = { Chain, In1, In2L, In2H };
16245   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
16246   SDValue Result =
16247     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
16248                             cast<MemSDNode>(Node)->getMemOperand());
16249   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
16250   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
16251   Results.push_back(Result.getValue(2));
16252 }
16253
16254 /// ReplaceNodeResults - Replace a node with an illegal result type
16255 /// with a new node built out of custom code.
16256 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16257                                            SmallVectorImpl<SDValue>&Results,
16258                                            SelectionDAG &DAG) const {
16259   SDLoc dl(N);
16260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16261   switch (N->getOpcode()) {
16262   default:
16263     llvm_unreachable("Do not know how to custom type legalize this operation!");
16264   case ISD::SIGN_EXTEND_INREG:
16265   case ISD::ADDC:
16266   case ISD::ADDE:
16267   case ISD::SUBC:
16268   case ISD::SUBE:
16269     // We don't want to expand or promote these.
16270     return;
16271   case ISD::SDIV:
16272   case ISD::UDIV:
16273   case ISD::SREM:
16274   case ISD::UREM:
16275   case ISD::SDIVREM:
16276   case ISD::UDIVREM: {
16277     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16278     Results.push_back(V);
16279     return;
16280   }
16281   case ISD::FP_TO_SINT:
16282   case ISD::FP_TO_UINT: {
16283     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16284
16285     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16286       return;
16287
16288     std::pair<SDValue,SDValue> Vals =
16289         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16290     SDValue FIST = Vals.first, StackSlot = Vals.second;
16291     if (FIST.getNode()) {
16292       EVT VT = N->getValueType(0);
16293       // Return a load from the stack slot.
16294       if (StackSlot.getNode())
16295         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16296                                       MachinePointerInfo(),
16297                                       false, false, false, 0));
16298       else
16299         Results.push_back(FIST);
16300     }
16301     return;
16302   }
16303   case ISD::UINT_TO_FP: {
16304     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16305     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16306         N->getValueType(0) != MVT::v2f32)
16307       return;
16308     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16309                                  N->getOperand(0));
16310     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16311                                      MVT::f64);
16312     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16313     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16314                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16315     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16316     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16317     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16318     return;
16319   }
16320   case ISD::FP_ROUND: {
16321     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16322         return;
16323     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16324     Results.push_back(V);
16325     return;
16326   }
16327   case ISD::INTRINSIC_W_CHAIN: {
16328     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16329     switch (IntNo) {
16330     default : llvm_unreachable("Do not know how to custom type "
16331                                "legalize this intrinsic operation!");
16332     case Intrinsic::x86_rdtsc:
16333       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16334                                      Results);
16335     case Intrinsic::x86_rdtscp:
16336       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16337                                      Results);
16338     case Intrinsic::x86_rdpmc:
16339       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16340     }
16341   }
16342   case ISD::READCYCLECOUNTER: {
16343     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16344                                    Results);
16345   }
16346   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16347     EVT T = N->getValueType(0);
16348     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16349     bool Regs64bit = T == MVT::i128;
16350     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16351     SDValue cpInL, cpInH;
16352     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16353                         DAG.getConstant(0, HalfT));
16354     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16355                         DAG.getConstant(1, HalfT));
16356     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16357                              Regs64bit ? X86::RAX : X86::EAX,
16358                              cpInL, SDValue());
16359     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16360                              Regs64bit ? X86::RDX : X86::EDX,
16361                              cpInH, cpInL.getValue(1));
16362     SDValue swapInL, swapInH;
16363     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16364                           DAG.getConstant(0, HalfT));
16365     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16366                           DAG.getConstant(1, HalfT));
16367     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16368                                Regs64bit ? X86::RBX : X86::EBX,
16369                                swapInL, cpInH.getValue(1));
16370     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16371                                Regs64bit ? X86::RCX : X86::ECX,
16372                                swapInH, swapInL.getValue(1));
16373     SDValue Ops[] = { swapInH.getValue(0),
16374                       N->getOperand(1),
16375                       swapInH.getValue(1) };
16376     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16377     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16378     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16379                                   X86ISD::LCMPXCHG8_DAG;
16380     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16381     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16382                                         Regs64bit ? X86::RAX : X86::EAX,
16383                                         HalfT, Result.getValue(1));
16384     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16385                                         Regs64bit ? X86::RDX : X86::EDX,
16386                                         HalfT, cpOutL.getValue(2));
16387     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16388
16389     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16390                                         MVT::i32, cpOutH.getValue(2));
16391     SDValue Success =
16392         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16393                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16394     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16395
16396     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16397     Results.push_back(Success);
16398     Results.push_back(EFLAGS.getValue(1));
16399     return;
16400   }
16401   case ISD::ATOMIC_LOAD_ADD:
16402   case ISD::ATOMIC_LOAD_AND:
16403   case ISD::ATOMIC_LOAD_NAND:
16404   case ISD::ATOMIC_LOAD_OR:
16405   case ISD::ATOMIC_LOAD_SUB:
16406   case ISD::ATOMIC_LOAD_XOR:
16407   case ISD::ATOMIC_LOAD_MAX:
16408   case ISD::ATOMIC_LOAD_MIN:
16409   case ISD::ATOMIC_LOAD_UMAX:
16410   case ISD::ATOMIC_LOAD_UMIN:
16411   case ISD::ATOMIC_SWAP: {
16412     unsigned Opc;
16413     switch (N->getOpcode()) {
16414     default: llvm_unreachable("Unexpected opcode");
16415     case ISD::ATOMIC_LOAD_ADD:
16416       Opc = X86ISD::ATOMADD64_DAG;
16417       break;
16418     case ISD::ATOMIC_LOAD_AND:
16419       Opc = X86ISD::ATOMAND64_DAG;
16420       break;
16421     case ISD::ATOMIC_LOAD_NAND:
16422       Opc = X86ISD::ATOMNAND64_DAG;
16423       break;
16424     case ISD::ATOMIC_LOAD_OR:
16425       Opc = X86ISD::ATOMOR64_DAG;
16426       break;
16427     case ISD::ATOMIC_LOAD_SUB:
16428       Opc = X86ISD::ATOMSUB64_DAG;
16429       break;
16430     case ISD::ATOMIC_LOAD_XOR:
16431       Opc = X86ISD::ATOMXOR64_DAG;
16432       break;
16433     case ISD::ATOMIC_LOAD_MAX:
16434       Opc = X86ISD::ATOMMAX64_DAG;
16435       break;
16436     case ISD::ATOMIC_LOAD_MIN:
16437       Opc = X86ISD::ATOMMIN64_DAG;
16438       break;
16439     case ISD::ATOMIC_LOAD_UMAX:
16440       Opc = X86ISD::ATOMUMAX64_DAG;
16441       break;
16442     case ISD::ATOMIC_LOAD_UMIN:
16443       Opc = X86ISD::ATOMUMIN64_DAG;
16444       break;
16445     case ISD::ATOMIC_SWAP:
16446       Opc = X86ISD::ATOMSWAP64_DAG;
16447       break;
16448     }
16449     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
16450     return;
16451   }
16452   case ISD::ATOMIC_LOAD: {
16453     ReplaceATOMIC_LOAD(N, Results, DAG);
16454     return;
16455   }
16456   case ISD::BITCAST: {
16457     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16458     EVT DstVT = N->getValueType(0);
16459     EVT SrcVT = N->getOperand(0)->getValueType(0);
16460
16461     if (SrcVT != MVT::f64 ||
16462         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16463       return;
16464
16465     unsigned NumElts = DstVT.getVectorNumElements();
16466     EVT SVT = DstVT.getVectorElementType();
16467     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16468     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16469                                    MVT::v2f64, N->getOperand(0));
16470     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16471
16472     SmallVector<SDValue, 8> Elts;
16473     for (unsigned i = 0, e = NumElts; i != e; ++i)
16474       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16475                                    ToVecInt, DAG.getIntPtrConstant(i)));
16476
16477     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16478   }
16479   }
16480 }
16481
16482 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16483   switch (Opcode) {
16484   default: return nullptr;
16485   case X86ISD::BSF:                return "X86ISD::BSF";
16486   case X86ISD::BSR:                return "X86ISD::BSR";
16487   case X86ISD::SHLD:               return "X86ISD::SHLD";
16488   case X86ISD::SHRD:               return "X86ISD::SHRD";
16489   case X86ISD::FAND:               return "X86ISD::FAND";
16490   case X86ISD::FANDN:              return "X86ISD::FANDN";
16491   case X86ISD::FOR:                return "X86ISD::FOR";
16492   case X86ISD::FXOR:               return "X86ISD::FXOR";
16493   case X86ISD::FSRL:               return "X86ISD::FSRL";
16494   case X86ISD::FILD:               return "X86ISD::FILD";
16495   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16496   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16497   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16498   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16499   case X86ISD::FLD:                return "X86ISD::FLD";
16500   case X86ISD::FST:                return "X86ISD::FST";
16501   case X86ISD::CALL:               return "X86ISD::CALL";
16502   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16503   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16504   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16505   case X86ISD::BT:                 return "X86ISD::BT";
16506   case X86ISD::CMP:                return "X86ISD::CMP";
16507   case X86ISD::COMI:               return "X86ISD::COMI";
16508   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16509   case X86ISD::CMPM:               return "X86ISD::CMPM";
16510   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16511   case X86ISD::SETCC:              return "X86ISD::SETCC";
16512   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16513   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16514   case X86ISD::CMOV:               return "X86ISD::CMOV";
16515   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16516   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16517   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16518   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16519   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16520   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16521   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16522   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16523   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16524   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16525   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16526   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16527   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16528   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16529   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16530   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16531   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16532   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16533   case X86ISD::HADD:               return "X86ISD::HADD";
16534   case X86ISD::HSUB:               return "X86ISD::HSUB";
16535   case X86ISD::FHADD:              return "X86ISD::FHADD";
16536   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16537   case X86ISD::UMAX:               return "X86ISD::UMAX";
16538   case X86ISD::UMIN:               return "X86ISD::UMIN";
16539   case X86ISD::SMAX:               return "X86ISD::SMAX";
16540   case X86ISD::SMIN:               return "X86ISD::SMIN";
16541   case X86ISD::FMAX:               return "X86ISD::FMAX";
16542   case X86ISD::FMIN:               return "X86ISD::FMIN";
16543   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16544   case X86ISD::FMINC:              return "X86ISD::FMINC";
16545   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16546   case X86ISD::FRCP:               return "X86ISD::FRCP";
16547   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16548   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16549   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16550   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16551   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16552   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16553   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16554   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16555   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16556   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16557   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16558   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16559   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
16560   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
16561   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
16562   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
16563   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
16564   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
16565   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16566   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16567   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16568   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16569   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16570   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16571   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16572   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16573   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16574   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16575   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16576   case X86ISD::VSHL:               return "X86ISD::VSHL";
16577   case X86ISD::VSRL:               return "X86ISD::VSRL";
16578   case X86ISD::VSRA:               return "X86ISD::VSRA";
16579   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16580   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16581   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16582   case X86ISD::CMPP:               return "X86ISD::CMPP";
16583   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16584   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16585   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16586   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16587   case X86ISD::ADD:                return "X86ISD::ADD";
16588   case X86ISD::SUB:                return "X86ISD::SUB";
16589   case X86ISD::ADC:                return "X86ISD::ADC";
16590   case X86ISD::SBB:                return "X86ISD::SBB";
16591   case X86ISD::SMUL:               return "X86ISD::SMUL";
16592   case X86ISD::UMUL:               return "X86ISD::UMUL";
16593   case X86ISD::INC:                return "X86ISD::INC";
16594   case X86ISD::DEC:                return "X86ISD::DEC";
16595   case X86ISD::OR:                 return "X86ISD::OR";
16596   case X86ISD::XOR:                return "X86ISD::XOR";
16597   case X86ISD::AND:                return "X86ISD::AND";
16598   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16599   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16600   case X86ISD::PTEST:              return "X86ISD::PTEST";
16601   case X86ISD::TESTP:              return "X86ISD::TESTP";
16602   case X86ISD::TESTM:              return "X86ISD::TESTM";
16603   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16604   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16605   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16606   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16607   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16608   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16609   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16610   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16611   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16612   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16613   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16614   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16615   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16616   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16617   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16618   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16619   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16620   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16621   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16622   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16623   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16624   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16625   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16626   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16627   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16628   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16629   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16630   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16631   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16632   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16633   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16634   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16635   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16636   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16637   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16638   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16639   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16640   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16641   case X86ISD::SAHF:               return "X86ISD::SAHF";
16642   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16643   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16644   case X86ISD::FMADD:              return "X86ISD::FMADD";
16645   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16646   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16647   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16648   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16649   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16650   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16651   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16652   case X86ISD::XTEST:              return "X86ISD::XTEST";
16653   }
16654 }
16655
16656 // isLegalAddressingMode - Return true if the addressing mode represented
16657 // by AM is legal for this target, for a load/store of the specified type.
16658 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16659                                               Type *Ty) const {
16660   // X86 supports extremely general addressing modes.
16661   CodeModel::Model M = getTargetMachine().getCodeModel();
16662   Reloc::Model R = getTargetMachine().getRelocationModel();
16663
16664   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16665   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16666     return false;
16667
16668   if (AM.BaseGV) {
16669     unsigned GVFlags =
16670       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16671
16672     // If a reference to this global requires an extra load, we can't fold it.
16673     if (isGlobalStubReference(GVFlags))
16674       return false;
16675
16676     // If BaseGV requires a register for the PIC base, we cannot also have a
16677     // BaseReg specified.
16678     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16679       return false;
16680
16681     // If lower 4G is not available, then we must use rip-relative addressing.
16682     if ((M != CodeModel::Small || R != Reloc::Static) &&
16683         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16684       return false;
16685   }
16686
16687   switch (AM.Scale) {
16688   case 0:
16689   case 1:
16690   case 2:
16691   case 4:
16692   case 8:
16693     // These scales always work.
16694     break;
16695   case 3:
16696   case 5:
16697   case 9:
16698     // These scales are formed with basereg+scalereg.  Only accept if there is
16699     // no basereg yet.
16700     if (AM.HasBaseReg)
16701       return false;
16702     break;
16703   default:  // Other stuff never works.
16704     return false;
16705   }
16706
16707   return true;
16708 }
16709
16710 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16711   unsigned Bits = Ty->getScalarSizeInBits();
16712
16713   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16714   // particularly cheaper than those without.
16715   if (Bits == 8)
16716     return false;
16717
16718   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16719   // variable shifts just as cheap as scalar ones.
16720   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16721     return false;
16722
16723   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16724   // fully general vector.
16725   return true;
16726 }
16727
16728 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16729   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16730     return false;
16731   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16732   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16733   return NumBits1 > NumBits2;
16734 }
16735
16736 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16737   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16738     return false;
16739
16740   if (!isTypeLegal(EVT::getEVT(Ty1)))
16741     return false;
16742
16743   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16744
16745   // Assuming the caller doesn't have a zeroext or signext return parameter,
16746   // truncation all the way down to i1 is valid.
16747   return true;
16748 }
16749
16750 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16751   return isInt<32>(Imm);
16752 }
16753
16754 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16755   // Can also use sub to handle negated immediates.
16756   return isInt<32>(Imm);
16757 }
16758
16759 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16760   if (!VT1.isInteger() || !VT2.isInteger())
16761     return false;
16762   unsigned NumBits1 = VT1.getSizeInBits();
16763   unsigned NumBits2 = VT2.getSizeInBits();
16764   return NumBits1 > NumBits2;
16765 }
16766
16767 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16768   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16769   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16770 }
16771
16772 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16773   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16774   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16775 }
16776
16777 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16778   EVT VT1 = Val.getValueType();
16779   if (isZExtFree(VT1, VT2))
16780     return true;
16781
16782   if (Val.getOpcode() != ISD::LOAD)
16783     return false;
16784
16785   if (!VT1.isSimple() || !VT1.isInteger() ||
16786       !VT2.isSimple() || !VT2.isInteger())
16787     return false;
16788
16789   switch (VT1.getSimpleVT().SimpleTy) {
16790   default: break;
16791   case MVT::i8:
16792   case MVT::i16:
16793   case MVT::i32:
16794     // X86 has 8, 16, and 32-bit zero-extending loads.
16795     return true;
16796   }
16797
16798   return false;
16799 }
16800
16801 bool
16802 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16803   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16804     return false;
16805
16806   VT = VT.getScalarType();
16807
16808   if (!VT.isSimple())
16809     return false;
16810
16811   switch (VT.getSimpleVT().SimpleTy) {
16812   case MVT::f32:
16813   case MVT::f64:
16814     return true;
16815   default:
16816     break;
16817   }
16818
16819   return false;
16820 }
16821
16822 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16823   // i16 instructions are longer (0x66 prefix) and potentially slower.
16824   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16825 }
16826
16827 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16828 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16829 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16830 /// are assumed to be legal.
16831 bool
16832 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16833                                       EVT VT) const {
16834   if (!VT.isSimple())
16835     return false;
16836
16837   MVT SVT = VT.getSimpleVT();
16838
16839   // Very little shuffling can be done for 64-bit vectors right now.
16840   if (VT.getSizeInBits() == 64)
16841     return false;
16842
16843   // If this is a single-input shuffle with no 128 bit lane crossings we can
16844   // lower it into pshufb.
16845   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16846       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16847     bool isLegal = true;
16848     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16849       if (M[I] >= (int)SVT.getVectorNumElements() ||
16850           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16851         isLegal = false;
16852         break;
16853       }
16854     }
16855     if (isLegal)
16856       return true;
16857   }
16858
16859   // FIXME: blends, shifts.
16860   return (SVT.getVectorNumElements() == 2 ||
16861           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16862           isMOVLMask(M, SVT) ||
16863           isSHUFPMask(M, SVT) ||
16864           isPSHUFDMask(M, SVT) ||
16865           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16866           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16867           isPALIGNRMask(M, SVT, Subtarget) ||
16868           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16869           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16870           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16871           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16872           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16873 }
16874
16875 bool
16876 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16877                                           EVT VT) const {
16878   if (!VT.isSimple())
16879     return false;
16880
16881   MVT SVT = VT.getSimpleVT();
16882   unsigned NumElts = SVT.getVectorNumElements();
16883   // FIXME: This collection of masks seems suspect.
16884   if (NumElts == 2)
16885     return true;
16886   if (NumElts == 4 && SVT.is128BitVector()) {
16887     return (isMOVLMask(Mask, SVT)  ||
16888             isCommutedMOVLMask(Mask, SVT, true) ||
16889             isSHUFPMask(Mask, SVT) ||
16890             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16891   }
16892   return false;
16893 }
16894
16895 //===----------------------------------------------------------------------===//
16896 //                           X86 Scheduler Hooks
16897 //===----------------------------------------------------------------------===//
16898
16899 /// Utility function to emit xbegin specifying the start of an RTM region.
16900 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16901                                      const TargetInstrInfo *TII) {
16902   DebugLoc DL = MI->getDebugLoc();
16903
16904   const BasicBlock *BB = MBB->getBasicBlock();
16905   MachineFunction::iterator I = MBB;
16906   ++I;
16907
16908   // For the v = xbegin(), we generate
16909   //
16910   // thisMBB:
16911   //  xbegin sinkMBB
16912   //
16913   // mainMBB:
16914   //  eax = -1
16915   //
16916   // sinkMBB:
16917   //  v = eax
16918
16919   MachineBasicBlock *thisMBB = MBB;
16920   MachineFunction *MF = MBB->getParent();
16921   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16922   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16923   MF->insert(I, mainMBB);
16924   MF->insert(I, sinkMBB);
16925
16926   // Transfer the remainder of BB and its successor edges to sinkMBB.
16927   sinkMBB->splice(sinkMBB->begin(), MBB,
16928                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16929   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16930
16931   // thisMBB:
16932   //  xbegin sinkMBB
16933   //  # fallthrough to mainMBB
16934   //  # abortion to sinkMBB
16935   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16936   thisMBB->addSuccessor(mainMBB);
16937   thisMBB->addSuccessor(sinkMBB);
16938
16939   // mainMBB:
16940   //  EAX = -1
16941   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16942   mainMBB->addSuccessor(sinkMBB);
16943
16944   // sinkMBB:
16945   // EAX is live into the sinkMBB
16946   sinkMBB->addLiveIn(X86::EAX);
16947   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16948           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16949     .addReg(X86::EAX);
16950
16951   MI->eraseFromParent();
16952   return sinkMBB;
16953 }
16954
16955 // Get CMPXCHG opcode for the specified data type.
16956 static unsigned getCmpXChgOpcode(EVT VT) {
16957   switch (VT.getSimpleVT().SimpleTy) {
16958   case MVT::i8:  return X86::LCMPXCHG8;
16959   case MVT::i16: return X86::LCMPXCHG16;
16960   case MVT::i32: return X86::LCMPXCHG32;
16961   case MVT::i64: return X86::LCMPXCHG64;
16962   default:
16963     break;
16964   }
16965   llvm_unreachable("Invalid operand size!");
16966 }
16967
16968 // Get LOAD opcode for the specified data type.
16969 static unsigned getLoadOpcode(EVT VT) {
16970   switch (VT.getSimpleVT().SimpleTy) {
16971   case MVT::i8:  return X86::MOV8rm;
16972   case MVT::i16: return X86::MOV16rm;
16973   case MVT::i32: return X86::MOV32rm;
16974   case MVT::i64: return X86::MOV64rm;
16975   default:
16976     break;
16977   }
16978   llvm_unreachable("Invalid operand size!");
16979 }
16980
16981 // Get opcode of the non-atomic one from the specified atomic instruction.
16982 static unsigned getNonAtomicOpcode(unsigned Opc) {
16983   switch (Opc) {
16984   case X86::ATOMAND8:  return X86::AND8rr;
16985   case X86::ATOMAND16: return X86::AND16rr;
16986   case X86::ATOMAND32: return X86::AND32rr;
16987   case X86::ATOMAND64: return X86::AND64rr;
16988   case X86::ATOMOR8:   return X86::OR8rr;
16989   case X86::ATOMOR16:  return X86::OR16rr;
16990   case X86::ATOMOR32:  return X86::OR32rr;
16991   case X86::ATOMOR64:  return X86::OR64rr;
16992   case X86::ATOMXOR8:  return X86::XOR8rr;
16993   case X86::ATOMXOR16: return X86::XOR16rr;
16994   case X86::ATOMXOR32: return X86::XOR32rr;
16995   case X86::ATOMXOR64: return X86::XOR64rr;
16996   }
16997   llvm_unreachable("Unhandled atomic-load-op opcode!");
16998 }
16999
17000 // Get opcode of the non-atomic one from the specified atomic instruction with
17001 // extra opcode.
17002 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
17003                                                unsigned &ExtraOpc) {
17004   switch (Opc) {
17005   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
17006   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
17007   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
17008   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
17009   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
17010   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
17011   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
17012   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
17013   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
17014   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
17015   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
17016   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
17017   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
17018   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
17019   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
17020   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
17021   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
17022   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
17023   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
17024   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
17025   }
17026   llvm_unreachable("Unhandled atomic-load-op opcode!");
17027 }
17028
17029 // Get opcode of the non-atomic one from the specified atomic instruction for
17030 // 64-bit data type on 32-bit target.
17031 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
17032   switch (Opc) {
17033   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
17034   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
17035   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
17036   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
17037   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
17038   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
17039   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
17040   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
17041   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
17042   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
17043   }
17044   llvm_unreachable("Unhandled atomic-load-op opcode!");
17045 }
17046
17047 // Get opcode of the non-atomic one from the specified atomic instruction for
17048 // 64-bit data type on 32-bit target with extra opcode.
17049 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
17050                                                    unsigned &HiOpc,
17051                                                    unsigned &ExtraOpc) {
17052   switch (Opc) {
17053   case X86::ATOMNAND6432:
17054     ExtraOpc = X86::NOT32r;
17055     HiOpc = X86::AND32rr;
17056     return X86::AND32rr;
17057   }
17058   llvm_unreachable("Unhandled atomic-load-op opcode!");
17059 }
17060
17061 // Get pseudo CMOV opcode from the specified data type.
17062 static unsigned getPseudoCMOVOpc(EVT VT) {
17063   switch (VT.getSimpleVT().SimpleTy) {
17064   case MVT::i8:  return X86::CMOV_GR8;
17065   case MVT::i16: return X86::CMOV_GR16;
17066   case MVT::i32: return X86::CMOV_GR32;
17067   default:
17068     break;
17069   }
17070   llvm_unreachable("Unknown CMOV opcode!");
17071 }
17072
17073 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
17074 // They will be translated into a spin-loop or compare-exchange loop from
17075 //
17076 //    ...
17077 //    dst = atomic-fetch-op MI.addr, MI.val
17078 //    ...
17079 //
17080 // to
17081 //
17082 //    ...
17083 //    t1 = LOAD MI.addr
17084 // loop:
17085 //    t4 = phi(t1, t3 / loop)
17086 //    t2 = OP MI.val, t4
17087 //    EAX = t4
17088 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
17089 //    t3 = EAX
17090 //    JNE loop
17091 // sink:
17092 //    dst = t3
17093 //    ...
17094 MachineBasicBlock *
17095 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
17096                                        MachineBasicBlock *MBB) const {
17097   MachineFunction *MF = MBB->getParent();
17098   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17099   DebugLoc DL = MI->getDebugLoc();
17100
17101   MachineRegisterInfo &MRI = MF->getRegInfo();
17102
17103   const BasicBlock *BB = MBB->getBasicBlock();
17104   MachineFunction::iterator I = MBB;
17105   ++I;
17106
17107   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
17108          "Unexpected number of operands");
17109
17110   assert(MI->hasOneMemOperand() &&
17111          "Expected atomic-load-op to have one memoperand");
17112
17113   // Memory Reference
17114   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17115   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17116
17117   unsigned DstReg, SrcReg;
17118   unsigned MemOpndSlot;
17119
17120   unsigned CurOp = 0;
17121
17122   DstReg = MI->getOperand(CurOp++).getReg();
17123   MemOpndSlot = CurOp;
17124   CurOp += X86::AddrNumOperands;
17125   SrcReg = MI->getOperand(CurOp++).getReg();
17126
17127   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17128   MVT::SimpleValueType VT = *RC->vt_begin();
17129   unsigned t1 = MRI.createVirtualRegister(RC);
17130   unsigned t2 = MRI.createVirtualRegister(RC);
17131   unsigned t3 = MRI.createVirtualRegister(RC);
17132   unsigned t4 = MRI.createVirtualRegister(RC);
17133   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
17134
17135   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
17136   unsigned LOADOpc = getLoadOpcode(VT);
17137
17138   // For the atomic load-arith operator, we generate
17139   //
17140   //  thisMBB:
17141   //    t1 = LOAD [MI.addr]
17142   //  mainMBB:
17143   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
17144   //    t1 = OP MI.val, EAX
17145   //    EAX = t4
17146   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
17147   //    t3 = EAX
17148   //    JNE mainMBB
17149   //  sinkMBB:
17150   //    dst = t3
17151
17152   MachineBasicBlock *thisMBB = MBB;
17153   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17154   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17155   MF->insert(I, mainMBB);
17156   MF->insert(I, sinkMBB);
17157
17158   MachineInstrBuilder MIB;
17159
17160   // Transfer the remainder of BB and its successor edges to sinkMBB.
17161   sinkMBB->splice(sinkMBB->begin(), MBB,
17162                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17163   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17164
17165   // thisMBB:
17166   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
17167   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17168     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17169     if (NewMO.isReg())
17170       NewMO.setIsKill(false);
17171     MIB.addOperand(NewMO);
17172   }
17173   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17174     unsigned flags = (*MMOI)->getFlags();
17175     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17176     MachineMemOperand *MMO =
17177       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17178                                (*MMOI)->getSize(),
17179                                (*MMOI)->getBaseAlignment(),
17180                                (*MMOI)->getTBAAInfo(),
17181                                (*MMOI)->getRanges());
17182     MIB.addMemOperand(MMO);
17183   }
17184
17185   thisMBB->addSuccessor(mainMBB);
17186
17187   // mainMBB:
17188   MachineBasicBlock *origMainMBB = mainMBB;
17189
17190   // Add a PHI.
17191   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
17192                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17193
17194   unsigned Opc = MI->getOpcode();
17195   switch (Opc) {
17196   default:
17197     llvm_unreachable("Unhandled atomic-load-op opcode!");
17198   case X86::ATOMAND8:
17199   case X86::ATOMAND16:
17200   case X86::ATOMAND32:
17201   case X86::ATOMAND64:
17202   case X86::ATOMOR8:
17203   case X86::ATOMOR16:
17204   case X86::ATOMOR32:
17205   case X86::ATOMOR64:
17206   case X86::ATOMXOR8:
17207   case X86::ATOMXOR16:
17208   case X86::ATOMXOR32:
17209   case X86::ATOMXOR64: {
17210     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
17211     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
17212       .addReg(t4);
17213     break;
17214   }
17215   case X86::ATOMNAND8:
17216   case X86::ATOMNAND16:
17217   case X86::ATOMNAND32:
17218   case X86::ATOMNAND64: {
17219     unsigned Tmp = MRI.createVirtualRegister(RC);
17220     unsigned NOTOpc;
17221     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
17222     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
17223       .addReg(t4);
17224     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
17225     break;
17226   }
17227   case X86::ATOMMAX8:
17228   case X86::ATOMMAX16:
17229   case X86::ATOMMAX32:
17230   case X86::ATOMMAX64:
17231   case X86::ATOMMIN8:
17232   case X86::ATOMMIN16:
17233   case X86::ATOMMIN32:
17234   case X86::ATOMMIN64:
17235   case X86::ATOMUMAX8:
17236   case X86::ATOMUMAX16:
17237   case X86::ATOMUMAX32:
17238   case X86::ATOMUMAX64:
17239   case X86::ATOMUMIN8:
17240   case X86::ATOMUMIN16:
17241   case X86::ATOMUMIN32:
17242   case X86::ATOMUMIN64: {
17243     unsigned CMPOpc;
17244     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
17245
17246     BuildMI(mainMBB, DL, TII->get(CMPOpc))
17247       .addReg(SrcReg)
17248       .addReg(t4);
17249
17250     if (Subtarget->hasCMov()) {
17251       if (VT != MVT::i8) {
17252         // Native support
17253         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
17254           .addReg(SrcReg)
17255           .addReg(t4);
17256       } else {
17257         // Promote i8 to i32 to use CMOV32
17258         const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
17259         const TargetRegisterClass *RC32 =
17260           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
17261         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
17262         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
17263         unsigned Tmp = MRI.createVirtualRegister(RC32);
17264
17265         unsigned Undef = MRI.createVirtualRegister(RC32);
17266         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
17267
17268         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
17269           .addReg(Undef)
17270           .addReg(SrcReg)
17271           .addImm(X86::sub_8bit);
17272         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
17273           .addReg(Undef)
17274           .addReg(t4)
17275           .addImm(X86::sub_8bit);
17276
17277         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
17278           .addReg(SrcReg32)
17279           .addReg(AccReg32);
17280
17281         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
17282           .addReg(Tmp, 0, X86::sub_8bit);
17283       }
17284     } else {
17285       // Use pseudo select and lower them.
17286       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
17287              "Invalid atomic-load-op transformation!");
17288       unsigned SelOpc = getPseudoCMOVOpc(VT);
17289       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
17290       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
17291       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
17292               .addReg(SrcReg).addReg(t4)
17293               .addImm(CC);
17294       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17295       // Replace the original PHI node as mainMBB is changed after CMOV
17296       // lowering.
17297       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
17298         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17299       Phi->eraseFromParent();
17300     }
17301     break;
17302   }
17303   }
17304
17305   // Copy PhyReg back from virtual register.
17306   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
17307     .addReg(t4);
17308
17309   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17310   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17311     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17312     if (NewMO.isReg())
17313       NewMO.setIsKill(false);
17314     MIB.addOperand(NewMO);
17315   }
17316   MIB.addReg(t2);
17317   MIB.setMemRefs(MMOBegin, MMOEnd);
17318
17319   // Copy PhyReg back to virtual register.
17320   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
17321     .addReg(PhyReg);
17322
17323   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17324
17325   mainMBB->addSuccessor(origMainMBB);
17326   mainMBB->addSuccessor(sinkMBB);
17327
17328   // sinkMBB:
17329   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17330           TII->get(TargetOpcode::COPY), DstReg)
17331     .addReg(t3);
17332
17333   MI->eraseFromParent();
17334   return sinkMBB;
17335 }
17336
17337 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
17338 // instructions. They will be translated into a spin-loop or compare-exchange
17339 // loop from
17340 //
17341 //    ...
17342 //    dst = atomic-fetch-op MI.addr, MI.val
17343 //    ...
17344 //
17345 // to
17346 //
17347 //    ...
17348 //    t1L = LOAD [MI.addr + 0]
17349 //    t1H = LOAD [MI.addr + 4]
17350 // loop:
17351 //    t4L = phi(t1L, t3L / loop)
17352 //    t4H = phi(t1H, t3H / loop)
17353 //    t2L = OP MI.val.lo, t4L
17354 //    t2H = OP MI.val.hi, t4H
17355 //    EAX = t4L
17356 //    EDX = t4H
17357 //    EBX = t2L
17358 //    ECX = t2H
17359 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17360 //    t3L = EAX
17361 //    t3H = EDX
17362 //    JNE loop
17363 // sink:
17364 //    dstL = t3L
17365 //    dstH = t3H
17366 //    ...
17367 MachineBasicBlock *
17368 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
17369                                            MachineBasicBlock *MBB) const {
17370   MachineFunction *MF = MBB->getParent();
17371   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17372   DebugLoc DL = MI->getDebugLoc();
17373
17374   MachineRegisterInfo &MRI = MF->getRegInfo();
17375
17376   const BasicBlock *BB = MBB->getBasicBlock();
17377   MachineFunction::iterator I = MBB;
17378   ++I;
17379
17380   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
17381          "Unexpected number of operands");
17382
17383   assert(MI->hasOneMemOperand() &&
17384          "Expected atomic-load-op32 to have one memoperand");
17385
17386   // Memory Reference
17387   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17388   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17389
17390   unsigned DstLoReg, DstHiReg;
17391   unsigned SrcLoReg, SrcHiReg;
17392   unsigned MemOpndSlot;
17393
17394   unsigned CurOp = 0;
17395
17396   DstLoReg = MI->getOperand(CurOp++).getReg();
17397   DstHiReg = MI->getOperand(CurOp++).getReg();
17398   MemOpndSlot = CurOp;
17399   CurOp += X86::AddrNumOperands;
17400   SrcLoReg = MI->getOperand(CurOp++).getReg();
17401   SrcHiReg = MI->getOperand(CurOp++).getReg();
17402
17403   const TargetRegisterClass *RC = &X86::GR32RegClass;
17404   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
17405
17406   unsigned t1L = MRI.createVirtualRegister(RC);
17407   unsigned t1H = MRI.createVirtualRegister(RC);
17408   unsigned t2L = MRI.createVirtualRegister(RC);
17409   unsigned t2H = MRI.createVirtualRegister(RC);
17410   unsigned t3L = MRI.createVirtualRegister(RC);
17411   unsigned t3H = MRI.createVirtualRegister(RC);
17412   unsigned t4L = MRI.createVirtualRegister(RC);
17413   unsigned t4H = MRI.createVirtualRegister(RC);
17414
17415   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
17416   unsigned LOADOpc = X86::MOV32rm;
17417
17418   // For the atomic load-arith operator, we generate
17419   //
17420   //  thisMBB:
17421   //    t1L = LOAD [MI.addr + 0]
17422   //    t1H = LOAD [MI.addr + 4]
17423   //  mainMBB:
17424   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
17425   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
17426   //    t2L = OP MI.val.lo, t4L
17427   //    t2H = OP MI.val.hi, t4H
17428   //    EBX = t2L
17429   //    ECX = t2H
17430   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17431   //    t3L = EAX
17432   //    t3H = EDX
17433   //    JNE loop
17434   //  sinkMBB:
17435   //    dstL = t3L
17436   //    dstH = t3H
17437
17438   MachineBasicBlock *thisMBB = MBB;
17439   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17440   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17441   MF->insert(I, mainMBB);
17442   MF->insert(I, sinkMBB);
17443
17444   MachineInstrBuilder MIB;
17445
17446   // Transfer the remainder of BB and its successor edges to sinkMBB.
17447   sinkMBB->splice(sinkMBB->begin(), MBB,
17448                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17449   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17450
17451   // thisMBB:
17452   // Lo
17453   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
17454   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17455     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17456     if (NewMO.isReg())
17457       NewMO.setIsKill(false);
17458     MIB.addOperand(NewMO);
17459   }
17460   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17461     unsigned flags = (*MMOI)->getFlags();
17462     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17463     MachineMemOperand *MMO =
17464       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17465                                (*MMOI)->getSize(),
17466                                (*MMOI)->getBaseAlignment(),
17467                                (*MMOI)->getTBAAInfo(),
17468                                (*MMOI)->getRanges());
17469     MIB.addMemOperand(MMO);
17470   };
17471   MachineInstr *LowMI = MIB;
17472
17473   // Hi
17474   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
17475   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17476     if (i == X86::AddrDisp) {
17477       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
17478     } else {
17479       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17480       if (NewMO.isReg())
17481         NewMO.setIsKill(false);
17482       MIB.addOperand(NewMO);
17483     }
17484   }
17485   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
17486
17487   thisMBB->addSuccessor(mainMBB);
17488
17489   // mainMBB:
17490   MachineBasicBlock *origMainMBB = mainMBB;
17491
17492   // Add PHIs.
17493   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
17494                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17495   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
17496                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17497
17498   unsigned Opc = MI->getOpcode();
17499   switch (Opc) {
17500   default:
17501     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
17502   case X86::ATOMAND6432:
17503   case X86::ATOMOR6432:
17504   case X86::ATOMXOR6432:
17505   case X86::ATOMADD6432:
17506   case X86::ATOMSUB6432: {
17507     unsigned HiOpc;
17508     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17509     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
17510       .addReg(SrcLoReg);
17511     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
17512       .addReg(SrcHiReg);
17513     break;
17514   }
17515   case X86::ATOMNAND6432: {
17516     unsigned HiOpc, NOTOpc;
17517     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
17518     unsigned TmpL = MRI.createVirtualRegister(RC);
17519     unsigned TmpH = MRI.createVirtualRegister(RC);
17520     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
17521       .addReg(t4L);
17522     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
17523       .addReg(t4H);
17524     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
17525     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
17526     break;
17527   }
17528   case X86::ATOMMAX6432:
17529   case X86::ATOMMIN6432:
17530   case X86::ATOMUMAX6432:
17531   case X86::ATOMUMIN6432: {
17532     unsigned HiOpc;
17533     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17534     unsigned cL = MRI.createVirtualRegister(RC8);
17535     unsigned cH = MRI.createVirtualRegister(RC8);
17536     unsigned cL32 = MRI.createVirtualRegister(RC);
17537     unsigned cH32 = MRI.createVirtualRegister(RC);
17538     unsigned cc = MRI.createVirtualRegister(RC);
17539     // cl := cmp src_lo, lo
17540     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17541       .addReg(SrcLoReg).addReg(t4L);
17542     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
17543     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
17544     // ch := cmp src_hi, hi
17545     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17546       .addReg(SrcHiReg).addReg(t4H);
17547     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
17548     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
17549     // cc := if (src_hi == hi) ? cl : ch;
17550     if (Subtarget->hasCMov()) {
17551       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
17552         .addReg(cH32).addReg(cL32);
17553     } else {
17554       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
17555               .addReg(cH32).addReg(cL32)
17556               .addImm(X86::COND_E);
17557       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17558     }
17559     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
17560     if (Subtarget->hasCMov()) {
17561       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
17562         .addReg(SrcLoReg).addReg(t4L);
17563       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
17564         .addReg(SrcHiReg).addReg(t4H);
17565     } else {
17566       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
17567               .addReg(SrcLoReg).addReg(t4L)
17568               .addImm(X86::COND_NE);
17569       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17570       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
17571       // 2nd CMOV lowering.
17572       mainMBB->addLiveIn(X86::EFLAGS);
17573       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
17574               .addReg(SrcHiReg).addReg(t4H)
17575               .addImm(X86::COND_NE);
17576       mainMBB = EmitLoweredSelect(MIB, mainMBB);
17577       // Replace the original PHI node as mainMBB is changed after CMOV
17578       // lowering.
17579       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
17580         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17581       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
17582         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17583       PhiL->eraseFromParent();
17584       PhiH->eraseFromParent();
17585     }
17586     break;
17587   }
17588   case X86::ATOMSWAP6432: {
17589     unsigned HiOpc;
17590     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17591     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
17592     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
17593     break;
17594   }
17595   }
17596
17597   // Copy EDX:EAX back from HiReg:LoReg
17598   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
17599   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
17600   // Copy ECX:EBX from t1H:t1L
17601   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
17602   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
17603
17604   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17605   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17606     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17607     if (NewMO.isReg())
17608       NewMO.setIsKill(false);
17609     MIB.addOperand(NewMO);
17610   }
17611   MIB.setMemRefs(MMOBegin, MMOEnd);
17612
17613   // Copy EDX:EAX back to t3H:t3L
17614   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
17615   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
17616
17617   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17618
17619   mainMBB->addSuccessor(origMainMBB);
17620   mainMBB->addSuccessor(sinkMBB);
17621
17622   // sinkMBB:
17623   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17624           TII->get(TargetOpcode::COPY), DstLoReg)
17625     .addReg(t3L);
17626   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17627           TII->get(TargetOpcode::COPY), DstHiReg)
17628     .addReg(t3H);
17629
17630   MI->eraseFromParent();
17631   return sinkMBB;
17632 }
17633
17634 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17635 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17636 // in the .td file.
17637 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17638                                        const TargetInstrInfo *TII) {
17639   unsigned Opc;
17640   switch (MI->getOpcode()) {
17641   default: llvm_unreachable("illegal opcode!");
17642   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17643   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17644   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17645   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17646   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17647   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17648   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17649   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17650   }
17651
17652   DebugLoc dl = MI->getDebugLoc();
17653   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17654
17655   unsigned NumArgs = MI->getNumOperands();
17656   for (unsigned i = 1; i < NumArgs; ++i) {
17657     MachineOperand &Op = MI->getOperand(i);
17658     if (!(Op.isReg() && Op.isImplicit()))
17659       MIB.addOperand(Op);
17660   }
17661   if (MI->hasOneMemOperand())
17662     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17663
17664   BuildMI(*BB, MI, dl,
17665     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17666     .addReg(X86::XMM0);
17667
17668   MI->eraseFromParent();
17669   return BB;
17670 }
17671
17672 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17673 // defs in an instruction pattern
17674 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17675                                        const TargetInstrInfo *TII) {
17676   unsigned Opc;
17677   switch (MI->getOpcode()) {
17678   default: llvm_unreachable("illegal opcode!");
17679   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17680   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17681   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17682   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17683   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17684   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17685   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17686   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17687   }
17688
17689   DebugLoc dl = MI->getDebugLoc();
17690   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17691
17692   unsigned NumArgs = MI->getNumOperands(); // remove the results
17693   for (unsigned i = 1; i < NumArgs; ++i) {
17694     MachineOperand &Op = MI->getOperand(i);
17695     if (!(Op.isReg() && Op.isImplicit()))
17696       MIB.addOperand(Op);
17697   }
17698   if (MI->hasOneMemOperand())
17699     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17700
17701   BuildMI(*BB, MI, dl,
17702     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17703     .addReg(X86::ECX);
17704
17705   MI->eraseFromParent();
17706   return BB;
17707 }
17708
17709 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17710                                        const TargetInstrInfo *TII,
17711                                        const X86Subtarget* Subtarget) {
17712   DebugLoc dl = MI->getDebugLoc();
17713
17714   // Address into RAX/EAX, other two args into ECX, EDX.
17715   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17716   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17717   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17718   for (int i = 0; i < X86::AddrNumOperands; ++i)
17719     MIB.addOperand(MI->getOperand(i));
17720
17721   unsigned ValOps = X86::AddrNumOperands;
17722   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17723     .addReg(MI->getOperand(ValOps).getReg());
17724   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17725     .addReg(MI->getOperand(ValOps+1).getReg());
17726
17727   // The instruction doesn't actually take any operands though.
17728   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17729
17730   MI->eraseFromParent(); // The pseudo is gone now.
17731   return BB;
17732 }
17733
17734 MachineBasicBlock *
17735 X86TargetLowering::EmitVAARG64WithCustomInserter(
17736                    MachineInstr *MI,
17737                    MachineBasicBlock *MBB) const {
17738   // Emit va_arg instruction on X86-64.
17739
17740   // Operands to this pseudo-instruction:
17741   // 0  ) Output        : destination address (reg)
17742   // 1-5) Input         : va_list address (addr, i64mem)
17743   // 6  ) ArgSize       : Size (in bytes) of vararg type
17744   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17745   // 8  ) Align         : Alignment of type
17746   // 9  ) EFLAGS (implicit-def)
17747
17748   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17749   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17750
17751   unsigned DestReg = MI->getOperand(0).getReg();
17752   MachineOperand &Base = MI->getOperand(1);
17753   MachineOperand &Scale = MI->getOperand(2);
17754   MachineOperand &Index = MI->getOperand(3);
17755   MachineOperand &Disp = MI->getOperand(4);
17756   MachineOperand &Segment = MI->getOperand(5);
17757   unsigned ArgSize = MI->getOperand(6).getImm();
17758   unsigned ArgMode = MI->getOperand(7).getImm();
17759   unsigned Align = MI->getOperand(8).getImm();
17760
17761   // Memory Reference
17762   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17763   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17764   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17765
17766   // Machine Information
17767   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17768   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17769   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17770   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17771   DebugLoc DL = MI->getDebugLoc();
17772
17773   // struct va_list {
17774   //   i32   gp_offset
17775   //   i32   fp_offset
17776   //   i64   overflow_area (address)
17777   //   i64   reg_save_area (address)
17778   // }
17779   // sizeof(va_list) = 24
17780   // alignment(va_list) = 8
17781
17782   unsigned TotalNumIntRegs = 6;
17783   unsigned TotalNumXMMRegs = 8;
17784   bool UseGPOffset = (ArgMode == 1);
17785   bool UseFPOffset = (ArgMode == 2);
17786   unsigned MaxOffset = TotalNumIntRegs * 8 +
17787                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17788
17789   /* Align ArgSize to a multiple of 8 */
17790   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17791   bool NeedsAlign = (Align > 8);
17792
17793   MachineBasicBlock *thisMBB = MBB;
17794   MachineBasicBlock *overflowMBB;
17795   MachineBasicBlock *offsetMBB;
17796   MachineBasicBlock *endMBB;
17797
17798   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17799   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17800   unsigned OffsetReg = 0;
17801
17802   if (!UseGPOffset && !UseFPOffset) {
17803     // If we only pull from the overflow region, we don't create a branch.
17804     // We don't need to alter control flow.
17805     OffsetDestReg = 0; // unused
17806     OverflowDestReg = DestReg;
17807
17808     offsetMBB = nullptr;
17809     overflowMBB = thisMBB;
17810     endMBB = thisMBB;
17811   } else {
17812     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17813     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17814     // If not, pull from overflow_area. (branch to overflowMBB)
17815     //
17816     //       thisMBB
17817     //         |     .
17818     //         |        .
17819     //     offsetMBB   overflowMBB
17820     //         |        .
17821     //         |     .
17822     //        endMBB
17823
17824     // Registers for the PHI in endMBB
17825     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17826     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17827
17828     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17829     MachineFunction *MF = MBB->getParent();
17830     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17831     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17832     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17833
17834     MachineFunction::iterator MBBIter = MBB;
17835     ++MBBIter;
17836
17837     // Insert the new basic blocks
17838     MF->insert(MBBIter, offsetMBB);
17839     MF->insert(MBBIter, overflowMBB);
17840     MF->insert(MBBIter, endMBB);
17841
17842     // Transfer the remainder of MBB and its successor edges to endMBB.
17843     endMBB->splice(endMBB->begin(), thisMBB,
17844                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17845     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17846
17847     // Make offsetMBB and overflowMBB successors of thisMBB
17848     thisMBB->addSuccessor(offsetMBB);
17849     thisMBB->addSuccessor(overflowMBB);
17850
17851     // endMBB is a successor of both offsetMBB and overflowMBB
17852     offsetMBB->addSuccessor(endMBB);
17853     overflowMBB->addSuccessor(endMBB);
17854
17855     // Load the offset value into a register
17856     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17857     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17858       .addOperand(Base)
17859       .addOperand(Scale)
17860       .addOperand(Index)
17861       .addDisp(Disp, UseFPOffset ? 4 : 0)
17862       .addOperand(Segment)
17863       .setMemRefs(MMOBegin, MMOEnd);
17864
17865     // Check if there is enough room left to pull this argument.
17866     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17867       .addReg(OffsetReg)
17868       .addImm(MaxOffset + 8 - ArgSizeA8);
17869
17870     // Branch to "overflowMBB" if offset >= max
17871     // Fall through to "offsetMBB" otherwise
17872     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17873       .addMBB(overflowMBB);
17874   }
17875
17876   // In offsetMBB, emit code to use the reg_save_area.
17877   if (offsetMBB) {
17878     assert(OffsetReg != 0);
17879
17880     // Read the reg_save_area address.
17881     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17882     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17883       .addOperand(Base)
17884       .addOperand(Scale)
17885       .addOperand(Index)
17886       .addDisp(Disp, 16)
17887       .addOperand(Segment)
17888       .setMemRefs(MMOBegin, MMOEnd);
17889
17890     // Zero-extend the offset
17891     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17892       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17893         .addImm(0)
17894         .addReg(OffsetReg)
17895         .addImm(X86::sub_32bit);
17896
17897     // Add the offset to the reg_save_area to get the final address.
17898     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17899       .addReg(OffsetReg64)
17900       .addReg(RegSaveReg);
17901
17902     // Compute the offset for the next argument
17903     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17904     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17905       .addReg(OffsetReg)
17906       .addImm(UseFPOffset ? 16 : 8);
17907
17908     // Store it back into the va_list.
17909     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17910       .addOperand(Base)
17911       .addOperand(Scale)
17912       .addOperand(Index)
17913       .addDisp(Disp, UseFPOffset ? 4 : 0)
17914       .addOperand(Segment)
17915       .addReg(NextOffsetReg)
17916       .setMemRefs(MMOBegin, MMOEnd);
17917
17918     // Jump to endMBB
17919     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17920       .addMBB(endMBB);
17921   }
17922
17923   //
17924   // Emit code to use overflow area
17925   //
17926
17927   // Load the overflow_area address into a register.
17928   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17929   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17930     .addOperand(Base)
17931     .addOperand(Scale)
17932     .addOperand(Index)
17933     .addDisp(Disp, 8)
17934     .addOperand(Segment)
17935     .setMemRefs(MMOBegin, MMOEnd);
17936
17937   // If we need to align it, do so. Otherwise, just copy the address
17938   // to OverflowDestReg.
17939   if (NeedsAlign) {
17940     // Align the overflow address
17941     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17942     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17943
17944     // aligned_addr = (addr + (align-1)) & ~(align-1)
17945     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17946       .addReg(OverflowAddrReg)
17947       .addImm(Align-1);
17948
17949     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17950       .addReg(TmpReg)
17951       .addImm(~(uint64_t)(Align-1));
17952   } else {
17953     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17954       .addReg(OverflowAddrReg);
17955   }
17956
17957   // Compute the next overflow address after this argument.
17958   // (the overflow address should be kept 8-byte aligned)
17959   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17960   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17961     .addReg(OverflowDestReg)
17962     .addImm(ArgSizeA8);
17963
17964   // Store the new overflow address.
17965   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17966     .addOperand(Base)
17967     .addOperand(Scale)
17968     .addOperand(Index)
17969     .addDisp(Disp, 8)
17970     .addOperand(Segment)
17971     .addReg(NextAddrReg)
17972     .setMemRefs(MMOBegin, MMOEnd);
17973
17974   // If we branched, emit the PHI to the front of endMBB.
17975   if (offsetMBB) {
17976     BuildMI(*endMBB, endMBB->begin(), DL,
17977             TII->get(X86::PHI), DestReg)
17978       .addReg(OffsetDestReg).addMBB(offsetMBB)
17979       .addReg(OverflowDestReg).addMBB(overflowMBB);
17980   }
17981
17982   // Erase the pseudo instruction
17983   MI->eraseFromParent();
17984
17985   return endMBB;
17986 }
17987
17988 MachineBasicBlock *
17989 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17990                                                  MachineInstr *MI,
17991                                                  MachineBasicBlock *MBB) const {
17992   // Emit code to save XMM registers to the stack. The ABI says that the
17993   // number of registers to save is given in %al, so it's theoretically
17994   // possible to do an indirect jump trick to avoid saving all of them,
17995   // however this code takes a simpler approach and just executes all
17996   // of the stores if %al is non-zero. It's less code, and it's probably
17997   // easier on the hardware branch predictor, and stores aren't all that
17998   // expensive anyway.
17999
18000   // Create the new basic blocks. One block contains all the XMM stores,
18001   // and one block is the final destination regardless of whether any
18002   // stores were performed.
18003   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18004   MachineFunction *F = MBB->getParent();
18005   MachineFunction::iterator MBBIter = MBB;
18006   ++MBBIter;
18007   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18008   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18009   F->insert(MBBIter, XMMSaveMBB);
18010   F->insert(MBBIter, EndMBB);
18011
18012   // Transfer the remainder of MBB and its successor edges to EndMBB.
18013   EndMBB->splice(EndMBB->begin(), MBB,
18014                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18015   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18016
18017   // The original block will now fall through to the XMM save block.
18018   MBB->addSuccessor(XMMSaveMBB);
18019   // The XMMSaveMBB will fall through to the end block.
18020   XMMSaveMBB->addSuccessor(EndMBB);
18021
18022   // Now add the instructions.
18023   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
18024   DebugLoc DL = MI->getDebugLoc();
18025
18026   unsigned CountReg = MI->getOperand(0).getReg();
18027   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18028   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18029
18030   if (!Subtarget->isTargetWin64()) {
18031     // If %al is 0, branch around the XMM save block.
18032     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18033     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18034     MBB->addSuccessor(EndMBB);
18035   }
18036
18037   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18038   // that was just emitted, but clearly shouldn't be "saved".
18039   assert((MI->getNumOperands() <= 3 ||
18040           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18041           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18042          && "Expected last argument to be EFLAGS");
18043   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18044   // In the XMM save block, save all the XMM argument registers.
18045   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18046     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18047     MachineMemOperand *MMO =
18048       F->getMachineMemOperand(
18049           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18050         MachineMemOperand::MOStore,
18051         /*Size=*/16, /*Align=*/16);
18052     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18053       .addFrameIndex(RegSaveFrameIndex)
18054       .addImm(/*Scale=*/1)
18055       .addReg(/*IndexReg=*/0)
18056       .addImm(/*Disp=*/Offset)
18057       .addReg(/*Segment=*/0)
18058       .addReg(MI->getOperand(i).getReg())
18059       .addMemOperand(MMO);
18060   }
18061
18062   MI->eraseFromParent();   // The pseudo instruction is gone now.
18063
18064   return EndMBB;
18065 }
18066
18067 // The EFLAGS operand of SelectItr might be missing a kill marker
18068 // because there were multiple uses of EFLAGS, and ISel didn't know
18069 // which to mark. Figure out whether SelectItr should have had a
18070 // kill marker, and set it if it should. Returns the correct kill
18071 // marker value.
18072 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18073                                      MachineBasicBlock* BB,
18074                                      const TargetRegisterInfo* TRI) {
18075   // Scan forward through BB for a use/def of EFLAGS.
18076   MachineBasicBlock::iterator miI(std::next(SelectItr));
18077   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18078     const MachineInstr& mi = *miI;
18079     if (mi.readsRegister(X86::EFLAGS))
18080       return false;
18081     if (mi.definesRegister(X86::EFLAGS))
18082       break; // Should have kill-flag - update below.
18083   }
18084
18085   // If we hit the end of the block, check whether EFLAGS is live into a
18086   // successor.
18087   if (miI == BB->end()) {
18088     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18089                                           sEnd = BB->succ_end();
18090          sItr != sEnd; ++sItr) {
18091       MachineBasicBlock* succ = *sItr;
18092       if (succ->isLiveIn(X86::EFLAGS))
18093         return false;
18094     }
18095   }
18096
18097   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18098   // out. SelectMI should have a kill flag on EFLAGS.
18099   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18100   return true;
18101 }
18102
18103 MachineBasicBlock *
18104 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18105                                      MachineBasicBlock *BB) const {
18106   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
18107   DebugLoc DL = MI->getDebugLoc();
18108
18109   // To "insert" a SELECT_CC instruction, we actually have to insert the
18110   // diamond control-flow pattern.  The incoming instruction knows the
18111   // destination vreg to set, the condition code register to branch on, the
18112   // true/false values to select between, and a branch opcode to use.
18113   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18114   MachineFunction::iterator It = BB;
18115   ++It;
18116
18117   //  thisMBB:
18118   //  ...
18119   //   TrueVal = ...
18120   //   cmpTY ccX, r1, r2
18121   //   bCC copy1MBB
18122   //   fallthrough --> copy0MBB
18123   MachineBasicBlock *thisMBB = BB;
18124   MachineFunction *F = BB->getParent();
18125   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18126   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18127   F->insert(It, copy0MBB);
18128   F->insert(It, sinkMBB);
18129
18130   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18131   // live into the sink and copy blocks.
18132   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
18133   if (!MI->killsRegister(X86::EFLAGS) &&
18134       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18135     copy0MBB->addLiveIn(X86::EFLAGS);
18136     sinkMBB->addLiveIn(X86::EFLAGS);
18137   }
18138
18139   // Transfer the remainder of BB and its successor edges to sinkMBB.
18140   sinkMBB->splice(sinkMBB->begin(), BB,
18141                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18142   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18143
18144   // Add the true and fallthrough blocks as its successors.
18145   BB->addSuccessor(copy0MBB);
18146   BB->addSuccessor(sinkMBB);
18147
18148   // Create the conditional branch instruction.
18149   unsigned Opc =
18150     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18151   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18152
18153   //  copy0MBB:
18154   //   %FalseValue = ...
18155   //   # fallthrough to sinkMBB
18156   copy0MBB->addSuccessor(sinkMBB);
18157
18158   //  sinkMBB:
18159   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18160   //  ...
18161   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18162           TII->get(X86::PHI), MI->getOperand(0).getReg())
18163     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18164     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18165
18166   MI->eraseFromParent();   // The pseudo instruction is gone now.
18167   return sinkMBB;
18168 }
18169
18170 MachineBasicBlock *
18171 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18172                                         bool Is64Bit) const {
18173   MachineFunction *MF = BB->getParent();
18174   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18175   DebugLoc DL = MI->getDebugLoc();
18176   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18177
18178   assert(MF->shouldSplitStack());
18179
18180   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18181   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18182
18183   // BB:
18184   //  ... [Till the alloca]
18185   // If stacklet is not large enough, jump to mallocMBB
18186   //
18187   // bumpMBB:
18188   //  Allocate by subtracting from RSP
18189   //  Jump to continueMBB
18190   //
18191   // mallocMBB:
18192   //  Allocate by call to runtime
18193   //
18194   // continueMBB:
18195   //  ...
18196   //  [rest of original BB]
18197   //
18198
18199   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18200   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18201   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18202
18203   MachineRegisterInfo &MRI = MF->getRegInfo();
18204   const TargetRegisterClass *AddrRegClass =
18205     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18206
18207   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18208     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18209     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18210     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18211     sizeVReg = MI->getOperand(1).getReg(),
18212     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18213
18214   MachineFunction::iterator MBBIter = BB;
18215   ++MBBIter;
18216
18217   MF->insert(MBBIter, bumpMBB);
18218   MF->insert(MBBIter, mallocMBB);
18219   MF->insert(MBBIter, continueMBB);
18220
18221   continueMBB->splice(continueMBB->begin(), BB,
18222                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18223   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18224
18225   // Add code to the main basic block to check if the stack limit has been hit,
18226   // and if so, jump to mallocMBB otherwise to bumpMBB.
18227   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18228   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18229     .addReg(tmpSPVReg).addReg(sizeVReg);
18230   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18231     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18232     .addReg(SPLimitVReg);
18233   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18234
18235   // bumpMBB simply decreases the stack pointer, since we know the current
18236   // stacklet has enough space.
18237   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18238     .addReg(SPLimitVReg);
18239   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18240     .addReg(SPLimitVReg);
18241   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18242
18243   // Calls into a routine in libgcc to allocate more space from the heap.
18244   const uint32_t *RegMask =
18245     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18246   if (Is64Bit) {
18247     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18248       .addReg(sizeVReg);
18249     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18250       .addExternalSymbol("__morestack_allocate_stack_space")
18251       .addRegMask(RegMask)
18252       .addReg(X86::RDI, RegState::Implicit)
18253       .addReg(X86::RAX, RegState::ImplicitDefine);
18254   } else {
18255     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18256       .addImm(12);
18257     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18258     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18259       .addExternalSymbol("__morestack_allocate_stack_space")
18260       .addRegMask(RegMask)
18261       .addReg(X86::EAX, RegState::ImplicitDefine);
18262   }
18263
18264   if (!Is64Bit)
18265     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18266       .addImm(16);
18267
18268   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18269     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18270   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18271
18272   // Set up the CFG correctly.
18273   BB->addSuccessor(bumpMBB);
18274   BB->addSuccessor(mallocMBB);
18275   mallocMBB->addSuccessor(continueMBB);
18276   bumpMBB->addSuccessor(continueMBB);
18277
18278   // Take care of the PHI nodes.
18279   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18280           MI->getOperand(0).getReg())
18281     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18282     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18283
18284   // Delete the original pseudo instruction.
18285   MI->eraseFromParent();
18286
18287   // And we're done.
18288   return continueMBB;
18289 }
18290
18291 MachineBasicBlock *
18292 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18293                                         MachineBasicBlock *BB) const {
18294   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
18295   DebugLoc DL = MI->getDebugLoc();
18296
18297   assert(!Subtarget->isTargetMacho());
18298
18299   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18300   // non-trivial part is impdef of ESP.
18301
18302   if (Subtarget->isTargetWin64()) {
18303     if (Subtarget->isTargetCygMing()) {
18304       // ___chkstk(Mingw64):
18305       // Clobbers R10, R11, RAX and EFLAGS.
18306       // Updates RSP.
18307       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18308         .addExternalSymbol("___chkstk")
18309         .addReg(X86::RAX, RegState::Implicit)
18310         .addReg(X86::RSP, RegState::Implicit)
18311         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18312         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18313         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18314     } else {
18315       // __chkstk(MSVCRT): does not update stack pointer.
18316       // Clobbers R10, R11 and EFLAGS.
18317       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18318         .addExternalSymbol("__chkstk")
18319         .addReg(X86::RAX, RegState::Implicit)
18320         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18321       // RAX has the offset to be subtracted from RSP.
18322       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18323         .addReg(X86::RSP)
18324         .addReg(X86::RAX);
18325     }
18326   } else {
18327     const char *StackProbeSymbol =
18328       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18329
18330     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18331       .addExternalSymbol(StackProbeSymbol)
18332       .addReg(X86::EAX, RegState::Implicit)
18333       .addReg(X86::ESP, RegState::Implicit)
18334       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18335       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18336       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18337   }
18338
18339   MI->eraseFromParent();   // The pseudo instruction is gone now.
18340   return BB;
18341 }
18342
18343 MachineBasicBlock *
18344 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18345                                       MachineBasicBlock *BB) const {
18346   // This is pretty easy.  We're taking the value that we received from
18347   // our load from the relocation, sticking it in either RDI (x86-64)
18348   // or EAX and doing an indirect call.  The return value will then
18349   // be in the normal return register.
18350   MachineFunction *F = BB->getParent();
18351   const X86InstrInfo *TII
18352     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
18353   DebugLoc DL = MI->getDebugLoc();
18354
18355   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18356   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18357
18358   // Get a register mask for the lowered call.
18359   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18360   // proper register mask.
18361   const uint32_t *RegMask =
18362     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18363   if (Subtarget->is64Bit()) {
18364     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18365                                       TII->get(X86::MOV64rm), X86::RDI)
18366     .addReg(X86::RIP)
18367     .addImm(0).addReg(0)
18368     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18369                       MI->getOperand(3).getTargetFlags())
18370     .addReg(0);
18371     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18372     addDirectMem(MIB, X86::RDI);
18373     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18374   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18375     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18376                                       TII->get(X86::MOV32rm), X86::EAX)
18377     .addReg(0)
18378     .addImm(0).addReg(0)
18379     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18380                       MI->getOperand(3).getTargetFlags())
18381     .addReg(0);
18382     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18383     addDirectMem(MIB, X86::EAX);
18384     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18385   } else {
18386     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18387                                       TII->get(X86::MOV32rm), X86::EAX)
18388     .addReg(TII->getGlobalBaseReg(F))
18389     .addImm(0).addReg(0)
18390     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18391                       MI->getOperand(3).getTargetFlags())
18392     .addReg(0);
18393     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18394     addDirectMem(MIB, X86::EAX);
18395     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18396   }
18397
18398   MI->eraseFromParent(); // The pseudo instruction is gone now.
18399   return BB;
18400 }
18401
18402 MachineBasicBlock *
18403 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18404                                     MachineBasicBlock *MBB) const {
18405   DebugLoc DL = MI->getDebugLoc();
18406   MachineFunction *MF = MBB->getParent();
18407   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18408   MachineRegisterInfo &MRI = MF->getRegInfo();
18409
18410   const BasicBlock *BB = MBB->getBasicBlock();
18411   MachineFunction::iterator I = MBB;
18412   ++I;
18413
18414   // Memory Reference
18415   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18416   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18417
18418   unsigned DstReg;
18419   unsigned MemOpndSlot = 0;
18420
18421   unsigned CurOp = 0;
18422
18423   DstReg = MI->getOperand(CurOp++).getReg();
18424   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18425   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18426   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18427   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18428
18429   MemOpndSlot = CurOp;
18430
18431   MVT PVT = getPointerTy();
18432   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18433          "Invalid Pointer Size!");
18434
18435   // For v = setjmp(buf), we generate
18436   //
18437   // thisMBB:
18438   //  buf[LabelOffset] = restoreMBB
18439   //  SjLjSetup restoreMBB
18440   //
18441   // mainMBB:
18442   //  v_main = 0
18443   //
18444   // sinkMBB:
18445   //  v = phi(main, restore)
18446   //
18447   // restoreMBB:
18448   //  v_restore = 1
18449
18450   MachineBasicBlock *thisMBB = MBB;
18451   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18452   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18453   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18454   MF->insert(I, mainMBB);
18455   MF->insert(I, sinkMBB);
18456   MF->push_back(restoreMBB);
18457
18458   MachineInstrBuilder MIB;
18459
18460   // Transfer the remainder of BB and its successor edges to sinkMBB.
18461   sinkMBB->splice(sinkMBB->begin(), MBB,
18462                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18463   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18464
18465   // thisMBB:
18466   unsigned PtrStoreOpc = 0;
18467   unsigned LabelReg = 0;
18468   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18469   Reloc::Model RM = MF->getTarget().getRelocationModel();
18470   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18471                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18472
18473   // Prepare IP either in reg or imm.
18474   if (!UseImmLabel) {
18475     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18476     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18477     LabelReg = MRI.createVirtualRegister(PtrRC);
18478     if (Subtarget->is64Bit()) {
18479       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18480               .addReg(X86::RIP)
18481               .addImm(0)
18482               .addReg(0)
18483               .addMBB(restoreMBB)
18484               .addReg(0);
18485     } else {
18486       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18487       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18488               .addReg(XII->getGlobalBaseReg(MF))
18489               .addImm(0)
18490               .addReg(0)
18491               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18492               .addReg(0);
18493     }
18494   } else
18495     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18496   // Store IP
18497   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18498   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18499     if (i == X86::AddrDisp)
18500       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18501     else
18502       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18503   }
18504   if (!UseImmLabel)
18505     MIB.addReg(LabelReg);
18506   else
18507     MIB.addMBB(restoreMBB);
18508   MIB.setMemRefs(MMOBegin, MMOEnd);
18509   // Setup
18510   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18511           .addMBB(restoreMBB);
18512
18513   const X86RegisterInfo *RegInfo =
18514     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18515   MIB.addRegMask(RegInfo->getNoPreservedMask());
18516   thisMBB->addSuccessor(mainMBB);
18517   thisMBB->addSuccessor(restoreMBB);
18518
18519   // mainMBB:
18520   //  EAX = 0
18521   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18522   mainMBB->addSuccessor(sinkMBB);
18523
18524   // sinkMBB:
18525   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18526           TII->get(X86::PHI), DstReg)
18527     .addReg(mainDstReg).addMBB(mainMBB)
18528     .addReg(restoreDstReg).addMBB(restoreMBB);
18529
18530   // restoreMBB:
18531   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18532   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18533   restoreMBB->addSuccessor(sinkMBB);
18534
18535   MI->eraseFromParent();
18536   return sinkMBB;
18537 }
18538
18539 MachineBasicBlock *
18540 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18541                                      MachineBasicBlock *MBB) const {
18542   DebugLoc DL = MI->getDebugLoc();
18543   MachineFunction *MF = MBB->getParent();
18544   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18545   MachineRegisterInfo &MRI = MF->getRegInfo();
18546
18547   // Memory Reference
18548   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18549   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18550
18551   MVT PVT = getPointerTy();
18552   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18553          "Invalid Pointer Size!");
18554
18555   const TargetRegisterClass *RC =
18556     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18557   unsigned Tmp = MRI.createVirtualRegister(RC);
18558   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18559   const X86RegisterInfo *RegInfo =
18560     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18561   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18562   unsigned SP = RegInfo->getStackRegister();
18563
18564   MachineInstrBuilder MIB;
18565
18566   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18567   const int64_t SPOffset = 2 * PVT.getStoreSize();
18568
18569   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18570   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18571
18572   // Reload FP
18573   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18574   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18575     MIB.addOperand(MI->getOperand(i));
18576   MIB.setMemRefs(MMOBegin, MMOEnd);
18577   // Reload IP
18578   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18579   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18580     if (i == X86::AddrDisp)
18581       MIB.addDisp(MI->getOperand(i), LabelOffset);
18582     else
18583       MIB.addOperand(MI->getOperand(i));
18584   }
18585   MIB.setMemRefs(MMOBegin, MMOEnd);
18586   // Reload SP
18587   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18588   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18589     if (i == X86::AddrDisp)
18590       MIB.addDisp(MI->getOperand(i), SPOffset);
18591     else
18592       MIB.addOperand(MI->getOperand(i));
18593   }
18594   MIB.setMemRefs(MMOBegin, MMOEnd);
18595   // Jump
18596   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18597
18598   MI->eraseFromParent();
18599   return MBB;
18600 }
18601
18602 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18603 // accumulator loops. Writing back to the accumulator allows the coalescer
18604 // to remove extra copies in the loop.   
18605 MachineBasicBlock *
18606 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18607                                  MachineBasicBlock *MBB) const {
18608   MachineOperand &AddendOp = MI->getOperand(3);
18609
18610   // Bail out early if the addend isn't a register - we can't switch these.
18611   if (!AddendOp.isReg())
18612     return MBB;
18613
18614   MachineFunction &MF = *MBB->getParent();
18615   MachineRegisterInfo &MRI = MF.getRegInfo();
18616
18617   // Check whether the addend is defined by a PHI:
18618   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18619   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18620   if (!AddendDef.isPHI())
18621     return MBB;
18622
18623   // Look for the following pattern:
18624   // loop:
18625   //   %addend = phi [%entry, 0], [%loop, %result]
18626   //   ...
18627   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18628
18629   // Replace with:
18630   //   loop:
18631   //   %addend = phi [%entry, 0], [%loop, %result]
18632   //   ...
18633   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18634
18635   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18636     assert(AddendDef.getOperand(i).isReg());
18637     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18638     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18639     if (&PHISrcInst == MI) {
18640       // Found a matching instruction.
18641       unsigned NewFMAOpc = 0;
18642       switch (MI->getOpcode()) {
18643         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18644         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18645         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18646         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18647         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18648         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18649         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18650         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18651         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18652         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18653         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18654         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18655         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18656         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18657         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18658         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18659         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18660         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18661         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18662         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18663         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18664         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18665         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18666         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18667         default: llvm_unreachable("Unrecognized FMA variant.");
18668       }
18669
18670       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18671       MachineInstrBuilder MIB =
18672         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18673         .addOperand(MI->getOperand(0))
18674         .addOperand(MI->getOperand(3))
18675         .addOperand(MI->getOperand(2))
18676         .addOperand(MI->getOperand(1));
18677       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18678       MI->eraseFromParent();
18679     }
18680   }
18681
18682   return MBB;
18683 }
18684
18685 MachineBasicBlock *
18686 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18687                                                MachineBasicBlock *BB) const {
18688   switch (MI->getOpcode()) {
18689   default: llvm_unreachable("Unexpected instr type to insert");
18690   case X86::TAILJMPd64:
18691   case X86::TAILJMPr64:
18692   case X86::TAILJMPm64:
18693     llvm_unreachable("TAILJMP64 would not be touched here.");
18694   case X86::TCRETURNdi64:
18695   case X86::TCRETURNri64:
18696   case X86::TCRETURNmi64:
18697     return BB;
18698   case X86::WIN_ALLOCA:
18699     return EmitLoweredWinAlloca(MI, BB);
18700   case X86::SEG_ALLOCA_32:
18701     return EmitLoweredSegAlloca(MI, BB, false);
18702   case X86::SEG_ALLOCA_64:
18703     return EmitLoweredSegAlloca(MI, BB, true);
18704   case X86::TLSCall_32:
18705   case X86::TLSCall_64:
18706     return EmitLoweredTLSCall(MI, BB);
18707   case X86::CMOV_GR8:
18708   case X86::CMOV_FR32:
18709   case X86::CMOV_FR64:
18710   case X86::CMOV_V4F32:
18711   case X86::CMOV_V2F64:
18712   case X86::CMOV_V2I64:
18713   case X86::CMOV_V8F32:
18714   case X86::CMOV_V4F64:
18715   case X86::CMOV_V4I64:
18716   case X86::CMOV_V16F32:
18717   case X86::CMOV_V8F64:
18718   case X86::CMOV_V8I64:
18719   case X86::CMOV_GR16:
18720   case X86::CMOV_GR32:
18721   case X86::CMOV_RFP32:
18722   case X86::CMOV_RFP64:
18723   case X86::CMOV_RFP80:
18724     return EmitLoweredSelect(MI, BB);
18725
18726   case X86::FP32_TO_INT16_IN_MEM:
18727   case X86::FP32_TO_INT32_IN_MEM:
18728   case X86::FP32_TO_INT64_IN_MEM:
18729   case X86::FP64_TO_INT16_IN_MEM:
18730   case X86::FP64_TO_INT32_IN_MEM:
18731   case X86::FP64_TO_INT64_IN_MEM:
18732   case X86::FP80_TO_INT16_IN_MEM:
18733   case X86::FP80_TO_INT32_IN_MEM:
18734   case X86::FP80_TO_INT64_IN_MEM: {
18735     MachineFunction *F = BB->getParent();
18736     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18737     DebugLoc DL = MI->getDebugLoc();
18738
18739     // Change the floating point control register to use "round towards zero"
18740     // mode when truncating to an integer value.
18741     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18742     addFrameReference(BuildMI(*BB, MI, DL,
18743                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18744
18745     // Load the old value of the high byte of the control word...
18746     unsigned OldCW =
18747       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18748     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18749                       CWFrameIdx);
18750
18751     // Set the high part to be round to zero...
18752     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18753       .addImm(0xC7F);
18754
18755     // Reload the modified control word now...
18756     addFrameReference(BuildMI(*BB, MI, DL,
18757                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18758
18759     // Restore the memory image of control word to original value
18760     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18761       .addReg(OldCW);
18762
18763     // Get the X86 opcode to use.
18764     unsigned Opc;
18765     switch (MI->getOpcode()) {
18766     default: llvm_unreachable("illegal opcode!");
18767     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18768     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18769     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18770     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18771     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18772     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18773     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18774     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18775     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18776     }
18777
18778     X86AddressMode AM;
18779     MachineOperand &Op = MI->getOperand(0);
18780     if (Op.isReg()) {
18781       AM.BaseType = X86AddressMode::RegBase;
18782       AM.Base.Reg = Op.getReg();
18783     } else {
18784       AM.BaseType = X86AddressMode::FrameIndexBase;
18785       AM.Base.FrameIndex = Op.getIndex();
18786     }
18787     Op = MI->getOperand(1);
18788     if (Op.isImm())
18789       AM.Scale = Op.getImm();
18790     Op = MI->getOperand(2);
18791     if (Op.isImm())
18792       AM.IndexReg = Op.getImm();
18793     Op = MI->getOperand(3);
18794     if (Op.isGlobal()) {
18795       AM.GV = Op.getGlobal();
18796     } else {
18797       AM.Disp = Op.getImm();
18798     }
18799     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18800                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18801
18802     // Reload the original control word now.
18803     addFrameReference(BuildMI(*BB, MI, DL,
18804                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18805
18806     MI->eraseFromParent();   // The pseudo instruction is gone now.
18807     return BB;
18808   }
18809     // String/text processing lowering.
18810   case X86::PCMPISTRM128REG:
18811   case X86::VPCMPISTRM128REG:
18812   case X86::PCMPISTRM128MEM:
18813   case X86::VPCMPISTRM128MEM:
18814   case X86::PCMPESTRM128REG:
18815   case X86::VPCMPESTRM128REG:
18816   case X86::PCMPESTRM128MEM:
18817   case X86::VPCMPESTRM128MEM:
18818     assert(Subtarget->hasSSE42() &&
18819            "Target must have SSE4.2 or AVX features enabled");
18820     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18821
18822   // String/text processing lowering.
18823   case X86::PCMPISTRIREG:
18824   case X86::VPCMPISTRIREG:
18825   case X86::PCMPISTRIMEM:
18826   case X86::VPCMPISTRIMEM:
18827   case X86::PCMPESTRIREG:
18828   case X86::VPCMPESTRIREG:
18829   case X86::PCMPESTRIMEM:
18830   case X86::VPCMPESTRIMEM:
18831     assert(Subtarget->hasSSE42() &&
18832            "Target must have SSE4.2 or AVX features enabled");
18833     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18834
18835   // Thread synchronization.
18836   case X86::MONITOR:
18837     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18838
18839   // xbegin
18840   case X86::XBEGIN:
18841     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18842
18843   // Atomic Lowering.
18844   case X86::ATOMAND8:
18845   case X86::ATOMAND16:
18846   case X86::ATOMAND32:
18847   case X86::ATOMAND64:
18848     // Fall through
18849   case X86::ATOMOR8:
18850   case X86::ATOMOR16:
18851   case X86::ATOMOR32:
18852   case X86::ATOMOR64:
18853     // Fall through
18854   case X86::ATOMXOR16:
18855   case X86::ATOMXOR8:
18856   case X86::ATOMXOR32:
18857   case X86::ATOMXOR64:
18858     // Fall through
18859   case X86::ATOMNAND8:
18860   case X86::ATOMNAND16:
18861   case X86::ATOMNAND32:
18862   case X86::ATOMNAND64:
18863     // Fall through
18864   case X86::ATOMMAX8:
18865   case X86::ATOMMAX16:
18866   case X86::ATOMMAX32:
18867   case X86::ATOMMAX64:
18868     // Fall through
18869   case X86::ATOMMIN8:
18870   case X86::ATOMMIN16:
18871   case X86::ATOMMIN32:
18872   case X86::ATOMMIN64:
18873     // Fall through
18874   case X86::ATOMUMAX8:
18875   case X86::ATOMUMAX16:
18876   case X86::ATOMUMAX32:
18877   case X86::ATOMUMAX64:
18878     // Fall through
18879   case X86::ATOMUMIN8:
18880   case X86::ATOMUMIN16:
18881   case X86::ATOMUMIN32:
18882   case X86::ATOMUMIN64:
18883     return EmitAtomicLoadArith(MI, BB);
18884
18885   // This group does 64-bit operations on a 32-bit host.
18886   case X86::ATOMAND6432:
18887   case X86::ATOMOR6432:
18888   case X86::ATOMXOR6432:
18889   case X86::ATOMNAND6432:
18890   case X86::ATOMADD6432:
18891   case X86::ATOMSUB6432:
18892   case X86::ATOMMAX6432:
18893   case X86::ATOMMIN6432:
18894   case X86::ATOMUMAX6432:
18895   case X86::ATOMUMIN6432:
18896   case X86::ATOMSWAP6432:
18897     return EmitAtomicLoadArith6432(MI, BB);
18898
18899   case X86::VASTART_SAVE_XMM_REGS:
18900     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18901
18902   case X86::VAARG_64:
18903     return EmitVAARG64WithCustomInserter(MI, BB);
18904
18905   case X86::EH_SjLj_SetJmp32:
18906   case X86::EH_SjLj_SetJmp64:
18907     return emitEHSjLjSetJmp(MI, BB);
18908
18909   case X86::EH_SjLj_LongJmp32:
18910   case X86::EH_SjLj_LongJmp64:
18911     return emitEHSjLjLongJmp(MI, BB);
18912
18913   case TargetOpcode::STACKMAP:
18914   case TargetOpcode::PATCHPOINT:
18915     return emitPatchPoint(MI, BB);
18916
18917   case X86::VFMADDPDr213r:
18918   case X86::VFMADDPSr213r:
18919   case X86::VFMADDSDr213r:
18920   case X86::VFMADDSSr213r:
18921   case X86::VFMSUBPDr213r:
18922   case X86::VFMSUBPSr213r:
18923   case X86::VFMSUBSDr213r:
18924   case X86::VFMSUBSSr213r:
18925   case X86::VFNMADDPDr213r:
18926   case X86::VFNMADDPSr213r:
18927   case X86::VFNMADDSDr213r:
18928   case X86::VFNMADDSSr213r:
18929   case X86::VFNMSUBPDr213r:
18930   case X86::VFNMSUBPSr213r:
18931   case X86::VFNMSUBSDr213r:
18932   case X86::VFNMSUBSSr213r:
18933   case X86::VFMADDPDr213rY:
18934   case X86::VFMADDPSr213rY:
18935   case X86::VFMSUBPDr213rY:
18936   case X86::VFMSUBPSr213rY:
18937   case X86::VFNMADDPDr213rY:
18938   case X86::VFNMADDPSr213rY:
18939   case X86::VFNMSUBPDr213rY:
18940   case X86::VFNMSUBPSr213rY:
18941     return emitFMA3Instr(MI, BB);
18942   }
18943 }
18944
18945 //===----------------------------------------------------------------------===//
18946 //                           X86 Optimization Hooks
18947 //===----------------------------------------------------------------------===//
18948
18949 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18950                                                       APInt &KnownZero,
18951                                                       APInt &KnownOne,
18952                                                       const SelectionDAG &DAG,
18953                                                       unsigned Depth) const {
18954   unsigned BitWidth = KnownZero.getBitWidth();
18955   unsigned Opc = Op.getOpcode();
18956   assert((Opc >= ISD::BUILTIN_OP_END ||
18957           Opc == ISD::INTRINSIC_WO_CHAIN ||
18958           Opc == ISD::INTRINSIC_W_CHAIN ||
18959           Opc == ISD::INTRINSIC_VOID) &&
18960          "Should use MaskedValueIsZero if you don't know whether Op"
18961          " is a target node!");
18962
18963   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18964   switch (Opc) {
18965   default: break;
18966   case X86ISD::ADD:
18967   case X86ISD::SUB:
18968   case X86ISD::ADC:
18969   case X86ISD::SBB:
18970   case X86ISD::SMUL:
18971   case X86ISD::UMUL:
18972   case X86ISD::INC:
18973   case X86ISD::DEC:
18974   case X86ISD::OR:
18975   case X86ISD::XOR:
18976   case X86ISD::AND:
18977     // These nodes' second result is a boolean.
18978     if (Op.getResNo() == 0)
18979       break;
18980     // Fallthrough
18981   case X86ISD::SETCC:
18982     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18983     break;
18984   case ISD::INTRINSIC_WO_CHAIN: {
18985     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18986     unsigned NumLoBits = 0;
18987     switch (IntId) {
18988     default: break;
18989     case Intrinsic::x86_sse_movmsk_ps:
18990     case Intrinsic::x86_avx_movmsk_ps_256:
18991     case Intrinsic::x86_sse2_movmsk_pd:
18992     case Intrinsic::x86_avx_movmsk_pd_256:
18993     case Intrinsic::x86_mmx_pmovmskb:
18994     case Intrinsic::x86_sse2_pmovmskb_128:
18995     case Intrinsic::x86_avx2_pmovmskb: {
18996       // High bits of movmskp{s|d}, pmovmskb are known zero.
18997       switch (IntId) {
18998         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18999         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19000         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19001         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19002         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19003         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19004         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19005         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19006       }
19007       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19008       break;
19009     }
19010     }
19011     break;
19012   }
19013   }
19014 }
19015
19016 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19017   SDValue Op,
19018   const SelectionDAG &,
19019   unsigned Depth) const {
19020   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19021   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19022     return Op.getValueType().getScalarType().getSizeInBits();
19023
19024   // Fallback case.
19025   return 1;
19026 }
19027
19028 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19029 /// node is a GlobalAddress + offset.
19030 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19031                                        const GlobalValue* &GA,
19032                                        int64_t &Offset) const {
19033   if (N->getOpcode() == X86ISD::Wrapper) {
19034     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19035       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19036       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19037       return true;
19038     }
19039   }
19040   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19041 }
19042
19043 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19044 /// same as extracting the high 128-bit part of 256-bit vector and then
19045 /// inserting the result into the low part of a new 256-bit vector
19046 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19047   EVT VT = SVOp->getValueType(0);
19048   unsigned NumElems = VT.getVectorNumElements();
19049
19050   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19051   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19052     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19053         SVOp->getMaskElt(j) >= 0)
19054       return false;
19055
19056   return true;
19057 }
19058
19059 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19060 /// same as extracting the low 128-bit part of 256-bit vector and then
19061 /// inserting the result into the high part of a new 256-bit vector
19062 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19063   EVT VT = SVOp->getValueType(0);
19064   unsigned NumElems = VT.getVectorNumElements();
19065
19066   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19067   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19068     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19069         SVOp->getMaskElt(j) >= 0)
19070       return false;
19071
19072   return true;
19073 }
19074
19075 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19076 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19077                                         TargetLowering::DAGCombinerInfo &DCI,
19078                                         const X86Subtarget* Subtarget) {
19079   SDLoc dl(N);
19080   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19081   SDValue V1 = SVOp->getOperand(0);
19082   SDValue V2 = SVOp->getOperand(1);
19083   EVT VT = SVOp->getValueType(0);
19084   unsigned NumElems = VT.getVectorNumElements();
19085
19086   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19087       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19088     //
19089     //                   0,0,0,...
19090     //                      |
19091     //    V      UNDEF    BUILD_VECTOR    UNDEF
19092     //     \      /           \           /
19093     //  CONCAT_VECTOR         CONCAT_VECTOR
19094     //         \                  /
19095     //          \                /
19096     //          RESULT: V + zero extended
19097     //
19098     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19099         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19100         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19101       return SDValue();
19102
19103     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19104       return SDValue();
19105
19106     // To match the shuffle mask, the first half of the mask should
19107     // be exactly the first vector, and all the rest a splat with the
19108     // first element of the second one.
19109     for (unsigned i = 0; i != NumElems/2; ++i)
19110       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19111           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19112         return SDValue();
19113
19114     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19115     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19116       if (Ld->hasNUsesOfValue(1, 0)) {
19117         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19118         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19119         SDValue ResNode =
19120           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19121                                   Ld->getMemoryVT(),
19122                                   Ld->getPointerInfo(),
19123                                   Ld->getAlignment(),
19124                                   false/*isVolatile*/, true/*ReadMem*/,
19125                                   false/*WriteMem*/);
19126
19127         // Make sure the newly-created LOAD is in the same position as Ld in
19128         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19129         // and update uses of Ld's output chain to use the TokenFactor.
19130         if (Ld->hasAnyUseOfValue(1)) {
19131           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19132                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19133           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19134           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19135                                  SDValue(ResNode.getNode(), 1));
19136         }
19137
19138         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19139       }
19140     }
19141
19142     // Emit a zeroed vector and insert the desired subvector on its
19143     // first half.
19144     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19145     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19146     return DCI.CombineTo(N, InsV);
19147   }
19148
19149   //===--------------------------------------------------------------------===//
19150   // Combine some shuffles into subvector extracts and inserts:
19151   //
19152
19153   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19154   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19155     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19156     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19157     return DCI.CombineTo(N, InsV);
19158   }
19159
19160   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19161   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19162     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19163     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19164     return DCI.CombineTo(N, InsV);
19165   }
19166
19167   return SDValue();
19168 }
19169
19170 /// \brief Get the PSHUF-style mask from PSHUF node.
19171 ///
19172 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19173 /// PSHUF-style masks that can be reused with such instructions.
19174 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19175   SmallVector<int, 4> Mask;
19176   bool IsUnary;
19177   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19178   (void)HaveMask;
19179   assert(HaveMask);
19180
19181   switch (N.getOpcode()) {
19182   case X86ISD::PSHUFD:
19183     return Mask;
19184   case X86ISD::PSHUFLW:
19185     Mask.resize(4);
19186     return Mask;
19187   case X86ISD::PSHUFHW:
19188     Mask.erase(Mask.begin(), Mask.begin() + 4);
19189     for (int &M : Mask)
19190       M -= 4;
19191     return Mask;
19192   default:
19193     llvm_unreachable("No valid shuffle instruction found!");
19194   }
19195 }
19196
19197 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19198 ///
19199 /// We walk up the chain and look for a combinable shuffle, skipping over
19200 /// shuffles that we could hoist this shuffle's transformation past without
19201 /// altering anything.
19202 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19203                                          SelectionDAG &DAG,
19204                                          TargetLowering::DAGCombinerInfo &DCI) {
19205   assert(N.getOpcode() == X86ISD::PSHUFD &&
19206          "Called with something other than an x86 128-bit half shuffle!");
19207   SDLoc DL(N);
19208
19209   // Walk up a single-use chain looking for a combinable shuffle.
19210   SDValue V = N.getOperand(0);
19211   for (; V.hasOneUse(); V = V.getOperand(0)) {
19212     switch (V.getOpcode()) {
19213     default:
19214       return false; // Nothing combined!
19215
19216     case ISD::BITCAST:
19217       // Skip bitcasts as we always know the type for the target specific
19218       // instructions.
19219       continue;
19220
19221     case X86ISD::PSHUFD:
19222       // Found another dword shuffle.
19223       break;
19224
19225     case X86ISD::PSHUFLW:
19226       // Check that the low words (being shuffled) are the identity in the
19227       // dword shuffle, and the high words are self-contained.
19228       if (Mask[0] != 0 || Mask[1] != 1 ||
19229           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19230         return false;
19231
19232       continue;
19233
19234     case X86ISD::PSHUFHW:
19235       // Check that the high words (being shuffled) are the identity in the
19236       // dword shuffle, and the low words are self-contained.
19237       if (Mask[2] != 2 || Mask[3] != 3 ||
19238           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19239         return false;
19240
19241       continue;
19242     }
19243     // Break out of the loop if we break out of the switch.
19244     break;
19245   }
19246
19247   if (!V.hasOneUse())
19248     // We fell out of the loop without finding a viable combining instruction.
19249     return false;
19250
19251   // Record the old value to use in RAUW-ing.
19252   SDValue Old = V;
19253
19254   // Merge this node's mask and our incoming mask.
19255   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19256   for (int &M : Mask)
19257     M = VMask[M];
19258   V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
19259                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19260
19261   // Replace N with its operand as we're going to combine that shuffle away.
19262   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19263
19264   // Replace the combinable shuffle with the combined one, updating all users
19265   // so that we re-evaluate the chain here.
19266   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19267   return true;
19268 }
19269
19270 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19271 ///
19272 /// We walk up the chain, skipping shuffles of the other half and looking
19273 /// through shuffles which switch halves trying to find a shuffle of the same
19274 /// pair of dwords.
19275 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19276                                         SelectionDAG &DAG,
19277                                         TargetLowering::DAGCombinerInfo &DCI) {
19278   assert(
19279       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19280       "Called with something other than an x86 128-bit half shuffle!");
19281   SDLoc DL(N);
19282   unsigned CombineOpcode = N.getOpcode();
19283
19284   // Walk up a single-use chain looking for a combinable shuffle.
19285   SDValue V = N.getOperand(0);
19286   for (; V.hasOneUse(); V = V.getOperand(0)) {
19287     switch (V.getOpcode()) {
19288     default:
19289       return false; // Nothing combined!
19290
19291     case ISD::BITCAST:
19292       // Skip bitcasts as we always know the type for the target specific
19293       // instructions.
19294       continue;
19295
19296     case X86ISD::PSHUFLW:
19297     case X86ISD::PSHUFHW:
19298       if (V.getOpcode() == CombineOpcode)
19299         break;
19300
19301       // Other-half shuffles are no-ops.
19302       continue;
19303
19304     case X86ISD::PSHUFD: {
19305       // We can only handle pshufd if the half we are combining either stays in
19306       // its half, or switches to the other half. Bail if one of these isn't
19307       // true.
19308       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19309       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19310       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19311             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19312         return false;
19313
19314       // Map the mask through the pshufd and keep walking up the chain.
19315       for (int i = 0; i < 4; ++i)
19316         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19317
19318       // Switch halves if the pshufd does.
19319       CombineOpcode =
19320           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19321       continue;
19322     }
19323     }
19324     // Break out of the loop if we break out of the switch.
19325     break;
19326   }
19327
19328   if (!V.hasOneUse())
19329     // We fell out of the loop without finding a viable combining instruction.
19330     return false;
19331
19332   // Record the old value to use in RAUW-ing.
19333   SDValue Old = V;
19334
19335   // Merge this node's mask and our incoming mask (adjusted to account for all
19336   // the pshufd instructions encountered).
19337   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19338   for (int &M : Mask)
19339     M = VMask[M];
19340   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19341                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19342
19343   // Replace N with its operand as we're going to combine that shuffle away.
19344   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19345
19346   // Replace the combinable shuffle with the combined one, updating all users
19347   // so that we re-evaluate the chain here.
19348   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19349   return true;
19350 }
19351
19352 /// \brief Try to combine x86 target specific shuffles.
19353 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19354                                            TargetLowering::DAGCombinerInfo &DCI,
19355                                            const X86Subtarget *Subtarget) {
19356   SDLoc DL(N);
19357   MVT VT = N.getSimpleValueType();
19358   SmallVector<int, 4> Mask;
19359
19360   switch (N.getOpcode()) {
19361   case X86ISD::PSHUFD:
19362   case X86ISD::PSHUFLW:
19363   case X86ISD::PSHUFHW:
19364     Mask = getPSHUFShuffleMask(N);
19365     assert(Mask.size() == 4);
19366     break;
19367   default:
19368     return SDValue();
19369   }
19370
19371   // Nuke no-op shuffles that show up after combining.
19372   if (isNoopShuffleMask(Mask))
19373     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19374
19375   // Look for simplifications involving one or two shuffle instructions.
19376   SDValue V = N.getOperand(0);
19377   switch (N.getOpcode()) {
19378   default:
19379     break;
19380   case X86ISD::PSHUFLW:
19381   case X86ISD::PSHUFHW:
19382     assert(VT == MVT::v8i16);
19383     (void)VT;
19384
19385     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19386       return SDValue(); // We combined away this shuffle, so we're done.
19387
19388     // See if this reduces to a PSHUFD which is no more expensive and can
19389     // combine with more operations.
19390     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19391         areAdjacentMasksSequential(Mask)) {
19392       int DMask[] = {-1, -1, -1, -1};
19393       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19394       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19395       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19396       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19397       DCI.AddToWorklist(V.getNode());
19398       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19399                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19400       DCI.AddToWorklist(V.getNode());
19401       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19402     }
19403
19404     break;
19405
19406   case X86ISD::PSHUFD:
19407     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19408       return SDValue(); // We combined away this shuffle.
19409
19410     break;
19411   }
19412
19413   return SDValue();
19414 }
19415
19416 /// PerformShuffleCombine - Performs several different shuffle combines.
19417 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19418                                      TargetLowering::DAGCombinerInfo &DCI,
19419                                      const X86Subtarget *Subtarget) {
19420   SDLoc dl(N);
19421   SDValue N0 = N->getOperand(0);
19422   SDValue N1 = N->getOperand(1);
19423   EVT VT = N->getValueType(0);
19424
19425   // Canonicalize shuffles that perform 'addsub' on packed float vectors
19426   // according to the rule:
19427   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
19428   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
19429   //
19430   // Where 'Mask' is:
19431   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
19432   //  <0,3>                 -- for v2f64 shuffles;
19433   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
19434   //
19435   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
19436   // during ISel stage.
19437   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
19438       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19439        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19440       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
19441       // Operands to the FADD and FSUB must be the same.
19442       ((N0->getOperand(0) == N1->getOperand(0) &&
19443         N0->getOperand(1) == N1->getOperand(1)) ||
19444        // FADD is commutable. See if by commuting the operands of the FADD
19445        // we would still be able to match the operands of the FSUB dag node.
19446        (N0->getOperand(1) == N1->getOperand(0) &&
19447         N0->getOperand(0) == N1->getOperand(1))) &&
19448       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
19449       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
19450     
19451     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
19452     unsigned NumElts = VT.getVectorNumElements();
19453     ArrayRef<int> Mask = SV->getMask();
19454     bool CanFold = true;
19455
19456     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
19457       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
19458
19459     if (CanFold) {
19460       SDValue Op0 = N1->getOperand(0);
19461       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
19462       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
19463       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
19464       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
19465     }
19466   }
19467
19468   // Don't create instructions with illegal types after legalize types has run.
19469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19470   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19471     return SDValue();
19472
19473   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19474   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19475       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19476     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19477
19478   // During Type Legalization, when promoting illegal vector types,
19479   // the backend might introduce new shuffle dag nodes and bitcasts.
19480   //
19481   // This code performs the following transformation:
19482   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19483   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19484   //
19485   // We do this only if both the bitcast and the BINOP dag nodes have
19486   // one use. Also, perform this transformation only if the new binary
19487   // operation is legal. This is to avoid introducing dag nodes that
19488   // potentially need to be further expanded (or custom lowered) into a
19489   // less optimal sequence of dag nodes.
19490   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19491       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19492       N0.getOpcode() == ISD::BITCAST) {
19493     SDValue BC0 = N0.getOperand(0);
19494     EVT SVT = BC0.getValueType();
19495     unsigned Opcode = BC0.getOpcode();
19496     unsigned NumElts = VT.getVectorNumElements();
19497     
19498     if (BC0.hasOneUse() && SVT.isVector() &&
19499         SVT.getVectorNumElements() * 2 == NumElts &&
19500         TLI.isOperationLegal(Opcode, VT)) {
19501       bool CanFold = false;
19502       switch (Opcode) {
19503       default : break;
19504       case ISD::ADD :
19505       case ISD::FADD :
19506       case ISD::SUB :
19507       case ISD::FSUB :
19508       case ISD::MUL :
19509       case ISD::FMUL :
19510         CanFold = true;
19511       }
19512
19513       unsigned SVTNumElts = SVT.getVectorNumElements();
19514       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19515       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19516         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19517       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19518         CanFold = SVOp->getMaskElt(i) < 0;
19519
19520       if (CanFold) {
19521         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19522         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19523         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19524         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19525       }
19526     }
19527   }
19528
19529   // Only handle 128 wide vector from here on.
19530   if (!VT.is128BitVector())
19531     return SDValue();
19532
19533   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19534   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19535   // consecutive, non-overlapping, and in the right order.
19536   SmallVector<SDValue, 16> Elts;
19537   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19538     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19539
19540   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19541   if (LD.getNode())
19542     return LD;
19543
19544   if (isTargetShuffle(N->getOpcode())) {
19545     SDValue Shuffle =
19546         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19547     if (Shuffle.getNode())
19548       return Shuffle;
19549   }
19550
19551   return SDValue();
19552 }
19553
19554 /// PerformTruncateCombine - Converts truncate operation to
19555 /// a sequence of vector shuffle operations.
19556 /// It is possible when we truncate 256-bit vector to 128-bit vector
19557 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19558                                       TargetLowering::DAGCombinerInfo &DCI,
19559                                       const X86Subtarget *Subtarget)  {
19560   return SDValue();
19561 }
19562
19563 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19564 /// specific shuffle of a load can be folded into a single element load.
19565 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19566 /// shuffles have been customed lowered so we need to handle those here.
19567 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19568                                          TargetLowering::DAGCombinerInfo &DCI) {
19569   if (DCI.isBeforeLegalizeOps())
19570     return SDValue();
19571
19572   SDValue InVec = N->getOperand(0);
19573   SDValue EltNo = N->getOperand(1);
19574
19575   if (!isa<ConstantSDNode>(EltNo))
19576     return SDValue();
19577
19578   EVT VT = InVec.getValueType();
19579
19580   bool HasShuffleIntoBitcast = false;
19581   if (InVec.getOpcode() == ISD::BITCAST) {
19582     // Don't duplicate a load with other uses.
19583     if (!InVec.hasOneUse())
19584       return SDValue();
19585     EVT BCVT = InVec.getOperand(0).getValueType();
19586     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19587       return SDValue();
19588     InVec = InVec.getOperand(0);
19589     HasShuffleIntoBitcast = true;
19590   }
19591
19592   if (!isTargetShuffle(InVec.getOpcode()))
19593     return SDValue();
19594
19595   // Don't duplicate a load with other uses.
19596   if (!InVec.hasOneUse())
19597     return SDValue();
19598
19599   SmallVector<int, 16> ShuffleMask;
19600   bool UnaryShuffle;
19601   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19602                             UnaryShuffle))
19603     return SDValue();
19604
19605   // Select the input vector, guarding against out of range extract vector.
19606   unsigned NumElems = VT.getVectorNumElements();
19607   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19608   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19609   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19610                                          : InVec.getOperand(1);
19611
19612   // If inputs to shuffle are the same for both ops, then allow 2 uses
19613   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19614
19615   if (LdNode.getOpcode() == ISD::BITCAST) {
19616     // Don't duplicate a load with other uses.
19617     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19618       return SDValue();
19619
19620     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19621     LdNode = LdNode.getOperand(0);
19622   }
19623
19624   if (!ISD::isNormalLoad(LdNode.getNode()))
19625     return SDValue();
19626
19627   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19628
19629   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19630     return SDValue();
19631
19632   if (HasShuffleIntoBitcast) {
19633     // If there's a bitcast before the shuffle, check if the load type and
19634     // alignment is valid.
19635     unsigned Align = LN0->getAlignment();
19636     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19637     unsigned NewAlign = TLI.getDataLayout()->
19638       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19639
19640     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19641       return SDValue();
19642   }
19643
19644   // All checks match so transform back to vector_shuffle so that DAG combiner
19645   // can finish the job
19646   SDLoc dl(N);
19647
19648   // Create shuffle node taking into account the case that its a unary shuffle
19649   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19650   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19651                                  InVec.getOperand(0), Shuffle,
19652                                  &ShuffleMask[0]);
19653   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19654   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19655                      EltNo);
19656 }
19657
19658 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19659 /// generation and convert it from being a bunch of shuffles and extracts
19660 /// to a simple store and scalar loads to extract the elements.
19661 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19662                                          TargetLowering::DAGCombinerInfo &DCI) {
19663   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19664   if (NewOp.getNode())
19665     return NewOp;
19666
19667   SDValue InputVector = N->getOperand(0);
19668
19669   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19670   // from mmx to v2i32 has a single usage.
19671   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19672       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19673       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19674     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19675                        N->getValueType(0),
19676                        InputVector.getNode()->getOperand(0));
19677
19678   // Only operate on vectors of 4 elements, where the alternative shuffling
19679   // gets to be more expensive.
19680   if (InputVector.getValueType() != MVT::v4i32)
19681     return SDValue();
19682
19683   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19684   // single use which is a sign-extend or zero-extend, and all elements are
19685   // used.
19686   SmallVector<SDNode *, 4> Uses;
19687   unsigned ExtractedElements = 0;
19688   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19689        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19690     if (UI.getUse().getResNo() != InputVector.getResNo())
19691       return SDValue();
19692
19693     SDNode *Extract = *UI;
19694     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19695       return SDValue();
19696
19697     if (Extract->getValueType(0) != MVT::i32)
19698       return SDValue();
19699     if (!Extract->hasOneUse())
19700       return SDValue();
19701     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19702         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19703       return SDValue();
19704     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19705       return SDValue();
19706
19707     // Record which element was extracted.
19708     ExtractedElements |=
19709       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19710
19711     Uses.push_back(Extract);
19712   }
19713
19714   // If not all the elements were used, this may not be worthwhile.
19715   if (ExtractedElements != 15)
19716     return SDValue();
19717
19718   // Ok, we've now decided to do the transformation.
19719   SDLoc dl(InputVector);
19720
19721   // Store the value to a temporary stack slot.
19722   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19723   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19724                             MachinePointerInfo(), false, false, 0);
19725
19726   // Replace each use (extract) with a load of the appropriate element.
19727   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19728        UE = Uses.end(); UI != UE; ++UI) {
19729     SDNode *Extract = *UI;
19730
19731     // cOMpute the element's address.
19732     SDValue Idx = Extract->getOperand(1);
19733     unsigned EltSize =
19734         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19735     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19736     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19737     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19738
19739     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19740                                      StackPtr, OffsetVal);
19741
19742     // Load the scalar.
19743     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19744                                      ScalarAddr, MachinePointerInfo(),
19745                                      false, false, false, 0);
19746
19747     // Replace the exact with the load.
19748     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19749   }
19750
19751   // The replacement was made in place; don't return anything.
19752   return SDValue();
19753 }
19754
19755 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19756 static std::pair<unsigned, bool>
19757 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19758                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19759   if (!VT.isVector())
19760     return std::make_pair(0, false);
19761
19762   bool NeedSplit = false;
19763   switch (VT.getSimpleVT().SimpleTy) {
19764   default: return std::make_pair(0, false);
19765   case MVT::v32i8:
19766   case MVT::v16i16:
19767   case MVT::v8i32:
19768     if (!Subtarget->hasAVX2())
19769       NeedSplit = true;
19770     if (!Subtarget->hasAVX())
19771       return std::make_pair(0, false);
19772     break;
19773   case MVT::v16i8:
19774   case MVT::v8i16:
19775   case MVT::v4i32:
19776     if (!Subtarget->hasSSE2())
19777       return std::make_pair(0, false);
19778   }
19779
19780   // SSE2 has only a small subset of the operations.
19781   bool hasUnsigned = Subtarget->hasSSE41() ||
19782                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19783   bool hasSigned = Subtarget->hasSSE41() ||
19784                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19785
19786   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19787
19788   unsigned Opc = 0;
19789   // Check for x CC y ? x : y.
19790   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19791       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19792     switch (CC) {
19793     default: break;
19794     case ISD::SETULT:
19795     case ISD::SETULE:
19796       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19797     case ISD::SETUGT:
19798     case ISD::SETUGE:
19799       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19800     case ISD::SETLT:
19801     case ISD::SETLE:
19802       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19803     case ISD::SETGT:
19804     case ISD::SETGE:
19805       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19806     }
19807   // Check for x CC y ? y : x -- a min/max with reversed arms.
19808   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19809              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19810     switch (CC) {
19811     default: break;
19812     case ISD::SETULT:
19813     case ISD::SETULE:
19814       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19815     case ISD::SETUGT:
19816     case ISD::SETUGE:
19817       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19818     case ISD::SETLT:
19819     case ISD::SETLE:
19820       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19821     case ISD::SETGT:
19822     case ISD::SETGE:
19823       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19824     }
19825   }
19826
19827   return std::make_pair(Opc, NeedSplit);
19828 }
19829
19830 static SDValue
19831 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19832                                       const X86Subtarget *Subtarget) {
19833   SDLoc dl(N);
19834   SDValue Cond = N->getOperand(0);
19835   SDValue LHS = N->getOperand(1);
19836   SDValue RHS = N->getOperand(2);
19837
19838   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19839     SDValue CondSrc = Cond->getOperand(0);
19840     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19841       Cond = CondSrc->getOperand(0);
19842   }
19843
19844   MVT VT = N->getSimpleValueType(0);
19845   MVT EltVT = VT.getVectorElementType();
19846   unsigned NumElems = VT.getVectorNumElements();
19847   // There is no blend with immediate in AVX-512.
19848   if (VT.is512BitVector())
19849     return SDValue();
19850
19851   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19852     return SDValue();
19853   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19854     return SDValue();
19855
19856   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19857     return SDValue();
19858
19859   unsigned MaskValue = 0;
19860   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19861     return SDValue();
19862
19863   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19864   for (unsigned i = 0; i < NumElems; ++i) {
19865     // Be sure we emit undef where we can.
19866     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19867       ShuffleMask[i] = -1;
19868     else
19869       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19870   }
19871
19872   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19873 }
19874
19875 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19876 /// nodes.
19877 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19878                                     TargetLowering::DAGCombinerInfo &DCI,
19879                                     const X86Subtarget *Subtarget) {
19880   SDLoc DL(N);
19881   SDValue Cond = N->getOperand(0);
19882   // Get the LHS/RHS of the select.
19883   SDValue LHS = N->getOperand(1);
19884   SDValue RHS = N->getOperand(2);
19885   EVT VT = LHS.getValueType();
19886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19887
19888   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19889   // instructions match the semantics of the common C idiom x<y?x:y but not
19890   // x<=y?x:y, because of how they handle negative zero (which can be
19891   // ignored in unsafe-math mode).
19892   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19893       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19894       (Subtarget->hasSSE2() ||
19895        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19896     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19897
19898     unsigned Opcode = 0;
19899     // Check for x CC y ? x : y.
19900     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19901         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19902       switch (CC) {
19903       default: break;
19904       case ISD::SETULT:
19905         // Converting this to a min would handle NaNs incorrectly, and swapping
19906         // the operands would cause it to handle comparisons between positive
19907         // and negative zero incorrectly.
19908         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19909           if (!DAG.getTarget().Options.UnsafeFPMath &&
19910               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19911             break;
19912           std::swap(LHS, RHS);
19913         }
19914         Opcode = X86ISD::FMIN;
19915         break;
19916       case ISD::SETOLE:
19917         // Converting this to a min would handle comparisons between positive
19918         // and negative zero incorrectly.
19919         if (!DAG.getTarget().Options.UnsafeFPMath &&
19920             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19921           break;
19922         Opcode = X86ISD::FMIN;
19923         break;
19924       case ISD::SETULE:
19925         // Converting this to a min would handle both negative zeros and NaNs
19926         // incorrectly, but we can swap the operands to fix both.
19927         std::swap(LHS, RHS);
19928       case ISD::SETOLT:
19929       case ISD::SETLT:
19930       case ISD::SETLE:
19931         Opcode = X86ISD::FMIN;
19932         break;
19933
19934       case ISD::SETOGE:
19935         // Converting this to a max would handle comparisons between positive
19936         // and negative zero incorrectly.
19937         if (!DAG.getTarget().Options.UnsafeFPMath &&
19938             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19939           break;
19940         Opcode = X86ISD::FMAX;
19941         break;
19942       case ISD::SETUGT:
19943         // Converting this to a max would handle NaNs incorrectly, and swapping
19944         // the operands would cause it to handle comparisons between positive
19945         // and negative zero incorrectly.
19946         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19947           if (!DAG.getTarget().Options.UnsafeFPMath &&
19948               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19949             break;
19950           std::swap(LHS, RHS);
19951         }
19952         Opcode = X86ISD::FMAX;
19953         break;
19954       case ISD::SETUGE:
19955         // Converting this to a max would handle both negative zeros and NaNs
19956         // incorrectly, but we can swap the operands to fix both.
19957         std::swap(LHS, RHS);
19958       case ISD::SETOGT:
19959       case ISD::SETGT:
19960       case ISD::SETGE:
19961         Opcode = X86ISD::FMAX;
19962         break;
19963       }
19964     // Check for x CC y ? y : x -- a min/max with reversed arms.
19965     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19966                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19967       switch (CC) {
19968       default: break;
19969       case ISD::SETOGE:
19970         // Converting this to a min would handle comparisons between positive
19971         // and negative zero incorrectly, and swapping the operands would
19972         // cause it to handle NaNs incorrectly.
19973         if (!DAG.getTarget().Options.UnsafeFPMath &&
19974             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19975           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19976             break;
19977           std::swap(LHS, RHS);
19978         }
19979         Opcode = X86ISD::FMIN;
19980         break;
19981       case ISD::SETUGT:
19982         // Converting this to a min would handle NaNs incorrectly.
19983         if (!DAG.getTarget().Options.UnsafeFPMath &&
19984             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19985           break;
19986         Opcode = X86ISD::FMIN;
19987         break;
19988       case ISD::SETUGE:
19989         // Converting this to a min would handle both negative zeros and NaNs
19990         // incorrectly, but we can swap the operands to fix both.
19991         std::swap(LHS, RHS);
19992       case ISD::SETOGT:
19993       case ISD::SETGT:
19994       case ISD::SETGE:
19995         Opcode = X86ISD::FMIN;
19996         break;
19997
19998       case ISD::SETULT:
19999         // Converting this to a max would handle NaNs incorrectly.
20000         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20001           break;
20002         Opcode = X86ISD::FMAX;
20003         break;
20004       case ISD::SETOLE:
20005         // Converting this to a max would handle comparisons between positive
20006         // and negative zero incorrectly, and swapping the operands would
20007         // cause it to handle NaNs incorrectly.
20008         if (!DAG.getTarget().Options.UnsafeFPMath &&
20009             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20010           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20011             break;
20012           std::swap(LHS, RHS);
20013         }
20014         Opcode = X86ISD::FMAX;
20015         break;
20016       case ISD::SETULE:
20017         // Converting this to a max would handle both negative zeros and NaNs
20018         // incorrectly, but we can swap the operands to fix both.
20019         std::swap(LHS, RHS);
20020       case ISD::SETOLT:
20021       case ISD::SETLT:
20022       case ISD::SETLE:
20023         Opcode = X86ISD::FMAX;
20024         break;
20025       }
20026     }
20027
20028     if (Opcode)
20029       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20030   }
20031
20032   EVT CondVT = Cond.getValueType();
20033   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20034       CondVT.getVectorElementType() == MVT::i1) {
20035     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20036     // lowering on AVX-512. In this case we convert it to
20037     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20038     // The same situation for all 128 and 256-bit vectors of i8 and i16
20039     EVT OpVT = LHS.getValueType();
20040     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20041         (OpVT.getVectorElementType() == MVT::i8 ||
20042          OpVT.getVectorElementType() == MVT::i16)) {
20043       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20044       DCI.AddToWorklist(Cond.getNode());
20045       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20046     }
20047   }
20048   // If this is a select between two integer constants, try to do some
20049   // optimizations.
20050   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20051     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20052       // Don't do this for crazy integer types.
20053       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20054         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20055         // so that TrueC (the true value) is larger than FalseC.
20056         bool NeedsCondInvert = false;
20057
20058         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20059             // Efficiently invertible.
20060             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20061              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20062               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20063           NeedsCondInvert = true;
20064           std::swap(TrueC, FalseC);
20065         }
20066
20067         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20068         if (FalseC->getAPIntValue() == 0 &&
20069             TrueC->getAPIntValue().isPowerOf2()) {
20070           if (NeedsCondInvert) // Invert the condition if needed.
20071             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20072                                DAG.getConstant(1, Cond.getValueType()));
20073
20074           // Zero extend the condition if needed.
20075           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20076
20077           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20078           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20079                              DAG.getConstant(ShAmt, MVT::i8));
20080         }
20081
20082         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20083         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20084           if (NeedsCondInvert) // Invert the condition if needed.
20085             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20086                                DAG.getConstant(1, Cond.getValueType()));
20087
20088           // Zero extend the condition if needed.
20089           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20090                              FalseC->getValueType(0), Cond);
20091           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20092                              SDValue(FalseC, 0));
20093         }
20094
20095         // Optimize cases that will turn into an LEA instruction.  This requires
20096         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20097         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20098           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20099           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20100
20101           bool isFastMultiplier = false;
20102           if (Diff < 10) {
20103             switch ((unsigned char)Diff) {
20104               default: break;
20105               case 1:  // result = add base, cond
20106               case 2:  // result = lea base(    , cond*2)
20107               case 3:  // result = lea base(cond, cond*2)
20108               case 4:  // result = lea base(    , cond*4)
20109               case 5:  // result = lea base(cond, cond*4)
20110               case 8:  // result = lea base(    , cond*8)
20111               case 9:  // result = lea base(cond, cond*8)
20112                 isFastMultiplier = true;
20113                 break;
20114             }
20115           }
20116
20117           if (isFastMultiplier) {
20118             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20119             if (NeedsCondInvert) // Invert the condition if needed.
20120               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20121                                  DAG.getConstant(1, Cond.getValueType()));
20122
20123             // Zero extend the condition if needed.
20124             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20125                                Cond);
20126             // Scale the condition by the difference.
20127             if (Diff != 1)
20128               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20129                                  DAG.getConstant(Diff, Cond.getValueType()));
20130
20131             // Add the base if non-zero.
20132             if (FalseC->getAPIntValue() != 0)
20133               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20134                                  SDValue(FalseC, 0));
20135             return Cond;
20136           }
20137         }
20138       }
20139   }
20140
20141   // Canonicalize max and min:
20142   // (x > y) ? x : y -> (x >= y) ? x : y
20143   // (x < y) ? x : y -> (x <= y) ? x : y
20144   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20145   // the need for an extra compare
20146   // against zero. e.g.
20147   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20148   // subl   %esi, %edi
20149   // testl  %edi, %edi
20150   // movl   $0, %eax
20151   // cmovgl %edi, %eax
20152   // =>
20153   // xorl   %eax, %eax
20154   // subl   %esi, $edi
20155   // cmovsl %eax, %edi
20156   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20157       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20158       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20159     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20160     switch (CC) {
20161     default: break;
20162     case ISD::SETLT:
20163     case ISD::SETGT: {
20164       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20165       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20166                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20167       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20168     }
20169     }
20170   }
20171
20172   // Early exit check
20173   if (!TLI.isTypeLegal(VT))
20174     return SDValue();
20175
20176   // Match VSELECTs into subs with unsigned saturation.
20177   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20178       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20179       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20180        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20181     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20182
20183     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20184     // left side invert the predicate to simplify logic below.
20185     SDValue Other;
20186     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20187       Other = RHS;
20188       CC = ISD::getSetCCInverse(CC, true);
20189     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20190       Other = LHS;
20191     }
20192
20193     if (Other.getNode() && Other->getNumOperands() == 2 &&
20194         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20195       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20196       SDValue CondRHS = Cond->getOperand(1);
20197
20198       // Look for a general sub with unsigned saturation first.
20199       // x >= y ? x-y : 0 --> subus x, y
20200       // x >  y ? x-y : 0 --> subus x, y
20201       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20202           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20203         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20204
20205       // If the RHS is a constant we have to reverse the const canonicalization.
20206       // x > C-1 ? x+-C : 0 --> subus x, C
20207       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20208           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
20209         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20210         if (CondRHS.getConstantOperandVal(0) == -A-1)
20211           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
20212                              DAG.getConstant(-A, VT));
20213       }
20214
20215       // Another special case: If C was a sign bit, the sub has been
20216       // canonicalized into a xor.
20217       // FIXME: Would it be better to use computeKnownBits to determine whether
20218       //        it's safe to decanonicalize the xor?
20219       // x s< 0 ? x^C : 0 --> subus x, C
20220       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20221           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20222           isSplatVector(OpRHS.getNode())) {
20223         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20224         if (A.isSignBit())
20225           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20226       }
20227     }
20228   }
20229
20230   // Try to match a min/max vector operation.
20231   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20232     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20233     unsigned Opc = ret.first;
20234     bool NeedSplit = ret.second;
20235
20236     if (Opc && NeedSplit) {
20237       unsigned NumElems = VT.getVectorNumElements();
20238       // Extract the LHS vectors
20239       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20240       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20241
20242       // Extract the RHS vectors
20243       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20244       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20245
20246       // Create min/max for each subvector
20247       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20248       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20249
20250       // Merge the result
20251       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20252     } else if (Opc)
20253       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20254   }
20255
20256   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20257   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20258       // Check if SETCC has already been promoted
20259       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20260       // Check that condition value type matches vselect operand type
20261       CondVT == VT) { 
20262
20263     assert(Cond.getValueType().isVector() &&
20264            "vector select expects a vector selector!");
20265
20266     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20267     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20268
20269     if (!TValIsAllOnes && !FValIsAllZeros) {
20270       // Try invert the condition if true value is not all 1s and false value
20271       // is not all 0s.
20272       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20273       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20274
20275       if (TValIsAllZeros || FValIsAllOnes) {
20276         SDValue CC = Cond.getOperand(2);
20277         ISD::CondCode NewCC =
20278           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20279                                Cond.getOperand(0).getValueType().isInteger());
20280         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20281         std::swap(LHS, RHS);
20282         TValIsAllOnes = FValIsAllOnes;
20283         FValIsAllZeros = TValIsAllZeros;
20284       }
20285     }
20286
20287     if (TValIsAllOnes || FValIsAllZeros) {
20288       SDValue Ret;
20289
20290       if (TValIsAllOnes && FValIsAllZeros)
20291         Ret = Cond;
20292       else if (TValIsAllOnes)
20293         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20294                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20295       else if (FValIsAllZeros)
20296         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20297                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20298
20299       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20300     }
20301   }
20302
20303   // Try to fold this VSELECT into a MOVSS/MOVSD
20304   if (N->getOpcode() == ISD::VSELECT &&
20305       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20306     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20307         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20308       bool CanFold = false;
20309       unsigned NumElems = Cond.getNumOperands();
20310       SDValue A = LHS;
20311       SDValue B = RHS;
20312       
20313       if (isZero(Cond.getOperand(0))) {
20314         CanFold = true;
20315
20316         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20317         // fold (vselect <0,-1> -> (movsd A, B)
20318         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20319           CanFold = isAllOnes(Cond.getOperand(i));
20320       } else if (isAllOnes(Cond.getOperand(0))) {
20321         CanFold = true;
20322         std::swap(A, B);
20323
20324         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20325         // fold (vselect <-1,0> -> (movsd B, A)
20326         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20327           CanFold = isZero(Cond.getOperand(i));
20328       }
20329
20330       if (CanFold) {
20331         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20332           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20333         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20334       }
20335
20336       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20337         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20338         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20339         //                             (v2i64 (bitcast B)))))
20340         //
20341         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20342         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20343         //                             (v2f64 (bitcast B)))))
20344         //
20345         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20346         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20347         //                             (v2i64 (bitcast A)))))
20348         //
20349         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20350         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20351         //                             (v2f64 (bitcast A)))))
20352
20353         CanFold = (isZero(Cond.getOperand(0)) &&
20354                    isZero(Cond.getOperand(1)) &&
20355                    isAllOnes(Cond.getOperand(2)) &&
20356                    isAllOnes(Cond.getOperand(3)));
20357
20358         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20359             isAllOnes(Cond.getOperand(1)) &&
20360             isZero(Cond.getOperand(2)) &&
20361             isZero(Cond.getOperand(3))) {
20362           CanFold = true;
20363           std::swap(LHS, RHS);
20364         }
20365
20366         if (CanFold) {
20367           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20368           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20369           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20370           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20371                                                 NewB, DAG);
20372           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20373         }
20374       }
20375     }
20376   }
20377
20378   // If we know that this node is legal then we know that it is going to be
20379   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20380   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20381   // to simplify previous instructions.
20382   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20383       !DCI.isBeforeLegalize() &&
20384       // We explicitly check against v8i16 and v16i16 because, although
20385       // they're marked as Custom, they might only be legal when Cond is a
20386       // build_vector of constants. This will be taken care in a later
20387       // condition.
20388       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20389        VT != MVT::v8i16)) {
20390     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20391
20392     // Don't optimize vector selects that map to mask-registers.
20393     if (BitWidth == 1)
20394       return SDValue();
20395
20396     // Check all uses of that condition operand to check whether it will be
20397     // consumed by non-BLEND instructions, which may depend on all bits are set
20398     // properly.
20399     for (SDNode::use_iterator I = Cond->use_begin(),
20400                               E = Cond->use_end(); I != E; ++I)
20401       if (I->getOpcode() != ISD::VSELECT)
20402         // TODO: Add other opcodes eventually lowered into BLEND.
20403         return SDValue();
20404
20405     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20406     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20407
20408     APInt KnownZero, KnownOne;
20409     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20410                                           DCI.isBeforeLegalizeOps());
20411     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20412         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20413       DCI.CommitTargetLoweringOpt(TLO);
20414   }
20415
20416   // We should generate an X86ISD::BLENDI from a vselect if its argument
20417   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20418   // constants. This specific pattern gets generated when we split a
20419   // selector for a 512 bit vector in a machine without AVX512 (but with
20420   // 256-bit vectors), during legalization:
20421   //
20422   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20423   //
20424   // Iff we find this pattern and the build_vectors are built from
20425   // constants, we translate the vselect into a shuffle_vector that we
20426   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20427   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20428     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20429     if (Shuffle.getNode())
20430       return Shuffle;
20431   }
20432
20433   return SDValue();
20434 }
20435
20436 // Check whether a boolean test is testing a boolean value generated by
20437 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20438 // code.
20439 //
20440 // Simplify the following patterns:
20441 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20442 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20443 // to (Op EFLAGS Cond)
20444 //
20445 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20446 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20447 // to (Op EFLAGS !Cond)
20448 //
20449 // where Op could be BRCOND or CMOV.
20450 //
20451 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20452   // Quit if not CMP and SUB with its value result used.
20453   if (Cmp.getOpcode() != X86ISD::CMP &&
20454       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20455       return SDValue();
20456
20457   // Quit if not used as a boolean value.
20458   if (CC != X86::COND_E && CC != X86::COND_NE)
20459     return SDValue();
20460
20461   // Check CMP operands. One of them should be 0 or 1 and the other should be
20462   // an SetCC or extended from it.
20463   SDValue Op1 = Cmp.getOperand(0);
20464   SDValue Op2 = Cmp.getOperand(1);
20465
20466   SDValue SetCC;
20467   const ConstantSDNode* C = nullptr;
20468   bool needOppositeCond = (CC == X86::COND_E);
20469   bool checkAgainstTrue = false; // Is it a comparison against 1?
20470
20471   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20472     SetCC = Op2;
20473   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20474     SetCC = Op1;
20475   else // Quit if all operands are not constants.
20476     return SDValue();
20477
20478   if (C->getZExtValue() == 1) {
20479     needOppositeCond = !needOppositeCond;
20480     checkAgainstTrue = true;
20481   } else if (C->getZExtValue() != 0)
20482     // Quit if the constant is neither 0 or 1.
20483     return SDValue();
20484
20485   bool truncatedToBoolWithAnd = false;
20486   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20487   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20488          SetCC.getOpcode() == ISD::TRUNCATE ||
20489          SetCC.getOpcode() == ISD::AND) {
20490     if (SetCC.getOpcode() == ISD::AND) {
20491       int OpIdx = -1;
20492       ConstantSDNode *CS;
20493       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20494           CS->getZExtValue() == 1)
20495         OpIdx = 1;
20496       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20497           CS->getZExtValue() == 1)
20498         OpIdx = 0;
20499       if (OpIdx == -1)
20500         break;
20501       SetCC = SetCC.getOperand(OpIdx);
20502       truncatedToBoolWithAnd = true;
20503     } else
20504       SetCC = SetCC.getOperand(0);
20505   }
20506
20507   switch (SetCC.getOpcode()) {
20508   case X86ISD::SETCC_CARRY:
20509     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20510     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20511     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20512     // truncated to i1 using 'and'.
20513     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20514       break;
20515     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20516            "Invalid use of SETCC_CARRY!");
20517     // FALL THROUGH
20518   case X86ISD::SETCC:
20519     // Set the condition code or opposite one if necessary.
20520     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20521     if (needOppositeCond)
20522       CC = X86::GetOppositeBranchCondition(CC);
20523     return SetCC.getOperand(1);
20524   case X86ISD::CMOV: {
20525     // Check whether false/true value has canonical one, i.e. 0 or 1.
20526     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20527     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20528     // Quit if true value is not a constant.
20529     if (!TVal)
20530       return SDValue();
20531     // Quit if false value is not a constant.
20532     if (!FVal) {
20533       SDValue Op = SetCC.getOperand(0);
20534       // Skip 'zext' or 'trunc' node.
20535       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20536           Op.getOpcode() == ISD::TRUNCATE)
20537         Op = Op.getOperand(0);
20538       // A special case for rdrand/rdseed, where 0 is set if false cond is
20539       // found.
20540       if ((Op.getOpcode() != X86ISD::RDRAND &&
20541            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20542         return SDValue();
20543     }
20544     // Quit if false value is not the constant 0 or 1.
20545     bool FValIsFalse = true;
20546     if (FVal && FVal->getZExtValue() != 0) {
20547       if (FVal->getZExtValue() != 1)
20548         return SDValue();
20549       // If FVal is 1, opposite cond is needed.
20550       needOppositeCond = !needOppositeCond;
20551       FValIsFalse = false;
20552     }
20553     // Quit if TVal is not the constant opposite of FVal.
20554     if (FValIsFalse && TVal->getZExtValue() != 1)
20555       return SDValue();
20556     if (!FValIsFalse && TVal->getZExtValue() != 0)
20557       return SDValue();
20558     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20559     if (needOppositeCond)
20560       CC = X86::GetOppositeBranchCondition(CC);
20561     return SetCC.getOperand(3);
20562   }
20563   }
20564
20565   return SDValue();
20566 }
20567
20568 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20569 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20570                                   TargetLowering::DAGCombinerInfo &DCI,
20571                                   const X86Subtarget *Subtarget) {
20572   SDLoc DL(N);
20573
20574   // If the flag operand isn't dead, don't touch this CMOV.
20575   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20576     return SDValue();
20577
20578   SDValue FalseOp = N->getOperand(0);
20579   SDValue TrueOp = N->getOperand(1);
20580   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20581   SDValue Cond = N->getOperand(3);
20582
20583   if (CC == X86::COND_E || CC == X86::COND_NE) {
20584     switch (Cond.getOpcode()) {
20585     default: break;
20586     case X86ISD::BSR:
20587     case X86ISD::BSF:
20588       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20589       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20590         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20591     }
20592   }
20593
20594   SDValue Flags;
20595
20596   Flags = checkBoolTestSetCCCombine(Cond, CC);
20597   if (Flags.getNode() &&
20598       // Extra check as FCMOV only supports a subset of X86 cond.
20599       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20600     SDValue Ops[] = { FalseOp, TrueOp,
20601                       DAG.getConstant(CC, MVT::i8), Flags };
20602     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20603   }
20604
20605   // If this is a select between two integer constants, try to do some
20606   // optimizations.  Note that the operands are ordered the opposite of SELECT
20607   // operands.
20608   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20609     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20610       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20611       // larger than FalseC (the false value).
20612       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20613         CC = X86::GetOppositeBranchCondition(CC);
20614         std::swap(TrueC, FalseC);
20615         std::swap(TrueOp, FalseOp);
20616       }
20617
20618       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20619       // This is efficient for any integer data type (including i8/i16) and
20620       // shift amount.
20621       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20622         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20623                            DAG.getConstant(CC, MVT::i8), Cond);
20624
20625         // Zero extend the condition if needed.
20626         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20627
20628         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20629         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20630                            DAG.getConstant(ShAmt, MVT::i8));
20631         if (N->getNumValues() == 2)  // Dead flag value?
20632           return DCI.CombineTo(N, Cond, SDValue());
20633         return Cond;
20634       }
20635
20636       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20637       // for any integer data type, including i8/i16.
20638       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20639         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20640                            DAG.getConstant(CC, MVT::i8), Cond);
20641
20642         // Zero extend the condition if needed.
20643         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20644                            FalseC->getValueType(0), Cond);
20645         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20646                            SDValue(FalseC, 0));
20647
20648         if (N->getNumValues() == 2)  // Dead flag value?
20649           return DCI.CombineTo(N, Cond, SDValue());
20650         return Cond;
20651       }
20652
20653       // Optimize cases that will turn into an LEA instruction.  This requires
20654       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20655       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20656         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20657         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20658
20659         bool isFastMultiplier = false;
20660         if (Diff < 10) {
20661           switch ((unsigned char)Diff) {
20662           default: break;
20663           case 1:  // result = add base, cond
20664           case 2:  // result = lea base(    , cond*2)
20665           case 3:  // result = lea base(cond, cond*2)
20666           case 4:  // result = lea base(    , cond*4)
20667           case 5:  // result = lea base(cond, cond*4)
20668           case 8:  // result = lea base(    , cond*8)
20669           case 9:  // result = lea base(cond, cond*8)
20670             isFastMultiplier = true;
20671             break;
20672           }
20673         }
20674
20675         if (isFastMultiplier) {
20676           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20677           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20678                              DAG.getConstant(CC, MVT::i8), Cond);
20679           // Zero extend the condition if needed.
20680           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20681                              Cond);
20682           // Scale the condition by the difference.
20683           if (Diff != 1)
20684             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20685                                DAG.getConstant(Diff, Cond.getValueType()));
20686
20687           // Add the base if non-zero.
20688           if (FalseC->getAPIntValue() != 0)
20689             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20690                                SDValue(FalseC, 0));
20691           if (N->getNumValues() == 2)  // Dead flag value?
20692             return DCI.CombineTo(N, Cond, SDValue());
20693           return Cond;
20694         }
20695       }
20696     }
20697   }
20698
20699   // Handle these cases:
20700   //   (select (x != c), e, c) -> select (x != c), e, x),
20701   //   (select (x == c), c, e) -> select (x == c), x, e)
20702   // where the c is an integer constant, and the "select" is the combination
20703   // of CMOV and CMP.
20704   //
20705   // The rationale for this change is that the conditional-move from a constant
20706   // needs two instructions, however, conditional-move from a register needs
20707   // only one instruction.
20708   //
20709   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20710   //  some instruction-combining opportunities. This opt needs to be
20711   //  postponed as late as possible.
20712   //
20713   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20714     // the DCI.xxxx conditions are provided to postpone the optimization as
20715     // late as possible.
20716
20717     ConstantSDNode *CmpAgainst = nullptr;
20718     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20719         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20720         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20721
20722       if (CC == X86::COND_NE &&
20723           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20724         CC = X86::GetOppositeBranchCondition(CC);
20725         std::swap(TrueOp, FalseOp);
20726       }
20727
20728       if (CC == X86::COND_E &&
20729           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20730         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20731                           DAG.getConstant(CC, MVT::i8), Cond };
20732         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20733       }
20734     }
20735   }
20736
20737   return SDValue();
20738 }
20739
20740 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20741                                                 const X86Subtarget *Subtarget) {
20742   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20743   switch (IntNo) {
20744   default: return SDValue();
20745   // SSE/AVX/AVX2 blend intrinsics.
20746   case Intrinsic::x86_avx2_pblendvb:
20747   case Intrinsic::x86_avx2_pblendw:
20748   case Intrinsic::x86_avx2_pblendd_128:
20749   case Intrinsic::x86_avx2_pblendd_256:
20750     // Don't try to simplify this intrinsic if we don't have AVX2.
20751     if (!Subtarget->hasAVX2())
20752       return SDValue();
20753     // FALL-THROUGH
20754   case Intrinsic::x86_avx_blend_pd_256:
20755   case Intrinsic::x86_avx_blend_ps_256:
20756   case Intrinsic::x86_avx_blendv_pd_256:
20757   case Intrinsic::x86_avx_blendv_ps_256:
20758     // Don't try to simplify this intrinsic if we don't have AVX.
20759     if (!Subtarget->hasAVX())
20760       return SDValue();
20761     // FALL-THROUGH
20762   case Intrinsic::x86_sse41_pblendw:
20763   case Intrinsic::x86_sse41_blendpd:
20764   case Intrinsic::x86_sse41_blendps:
20765   case Intrinsic::x86_sse41_blendvps:
20766   case Intrinsic::x86_sse41_blendvpd:
20767   case Intrinsic::x86_sse41_pblendvb: {
20768     SDValue Op0 = N->getOperand(1);
20769     SDValue Op1 = N->getOperand(2);
20770     SDValue Mask = N->getOperand(3);
20771
20772     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20773     if (!Subtarget->hasSSE41())
20774       return SDValue();
20775
20776     // fold (blend A, A, Mask) -> A
20777     if (Op0 == Op1)
20778       return Op0;
20779     // fold (blend A, B, allZeros) -> A
20780     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20781       return Op0;
20782     // fold (blend A, B, allOnes) -> B
20783     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20784       return Op1;
20785     
20786     // Simplify the case where the mask is a constant i32 value.
20787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20788       if (C->isNullValue())
20789         return Op0;
20790       if (C->isAllOnesValue())
20791         return Op1;
20792     }
20793
20794     return SDValue();
20795   }
20796
20797   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20798   case Intrinsic::x86_sse2_psrai_w:
20799   case Intrinsic::x86_sse2_psrai_d:
20800   case Intrinsic::x86_avx2_psrai_w:
20801   case Intrinsic::x86_avx2_psrai_d:
20802   case Intrinsic::x86_sse2_psra_w:
20803   case Intrinsic::x86_sse2_psra_d:
20804   case Intrinsic::x86_avx2_psra_w:
20805   case Intrinsic::x86_avx2_psra_d: {
20806     SDValue Op0 = N->getOperand(1);
20807     SDValue Op1 = N->getOperand(2);
20808     EVT VT = Op0.getValueType();
20809     assert(VT.isVector() && "Expected a vector type!");
20810
20811     if (isa<BuildVectorSDNode>(Op1))
20812       Op1 = Op1.getOperand(0);
20813
20814     if (!isa<ConstantSDNode>(Op1))
20815       return SDValue();
20816
20817     EVT SVT = VT.getVectorElementType();
20818     unsigned SVTBits = SVT.getSizeInBits();
20819
20820     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20821     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20822     uint64_t ShAmt = C.getZExtValue();
20823
20824     // Don't try to convert this shift into a ISD::SRA if the shift
20825     // count is bigger than or equal to the element size.
20826     if (ShAmt >= SVTBits)
20827       return SDValue();
20828
20829     // Trivial case: if the shift count is zero, then fold this
20830     // into the first operand.
20831     if (ShAmt == 0)
20832       return Op0;
20833
20834     // Replace this packed shift intrinsic with a target independent
20835     // shift dag node.
20836     SDValue Splat = DAG.getConstant(C, VT);
20837     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20838   }
20839   }
20840 }
20841
20842 /// PerformMulCombine - Optimize a single multiply with constant into two
20843 /// in order to implement it with two cheaper instructions, e.g.
20844 /// LEA + SHL, LEA + LEA.
20845 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20846                                  TargetLowering::DAGCombinerInfo &DCI) {
20847   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20848     return SDValue();
20849
20850   EVT VT = N->getValueType(0);
20851   if (VT != MVT::i64)
20852     return SDValue();
20853
20854   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20855   if (!C)
20856     return SDValue();
20857   uint64_t MulAmt = C->getZExtValue();
20858   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20859     return SDValue();
20860
20861   uint64_t MulAmt1 = 0;
20862   uint64_t MulAmt2 = 0;
20863   if ((MulAmt % 9) == 0) {
20864     MulAmt1 = 9;
20865     MulAmt2 = MulAmt / 9;
20866   } else if ((MulAmt % 5) == 0) {
20867     MulAmt1 = 5;
20868     MulAmt2 = MulAmt / 5;
20869   } else if ((MulAmt % 3) == 0) {
20870     MulAmt1 = 3;
20871     MulAmt2 = MulAmt / 3;
20872   }
20873   if (MulAmt2 &&
20874       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20875     SDLoc DL(N);
20876
20877     if (isPowerOf2_64(MulAmt2) &&
20878         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20879       // If second multiplifer is pow2, issue it first. We want the multiply by
20880       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20881       // is an add.
20882       std::swap(MulAmt1, MulAmt2);
20883
20884     SDValue NewMul;
20885     if (isPowerOf2_64(MulAmt1))
20886       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20887                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20888     else
20889       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20890                            DAG.getConstant(MulAmt1, VT));
20891
20892     if (isPowerOf2_64(MulAmt2))
20893       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20894                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20895     else
20896       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20897                            DAG.getConstant(MulAmt2, VT));
20898
20899     // Do not add new nodes to DAG combiner worklist.
20900     DCI.CombineTo(N, NewMul, false);
20901   }
20902   return SDValue();
20903 }
20904
20905 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20906   SDValue N0 = N->getOperand(0);
20907   SDValue N1 = N->getOperand(1);
20908   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20909   EVT VT = N0.getValueType();
20910
20911   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20912   // since the result of setcc_c is all zero's or all ones.
20913   if (VT.isInteger() && !VT.isVector() &&
20914       N1C && N0.getOpcode() == ISD::AND &&
20915       N0.getOperand(1).getOpcode() == ISD::Constant) {
20916     SDValue N00 = N0.getOperand(0);
20917     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20918         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20919           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20920          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20921       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20922       APInt ShAmt = N1C->getAPIntValue();
20923       Mask = Mask.shl(ShAmt);
20924       if (Mask != 0)
20925         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20926                            N00, DAG.getConstant(Mask, VT));
20927     }
20928   }
20929
20930   // Hardware support for vector shifts is sparse which makes us scalarize the
20931   // vector operations in many cases. Also, on sandybridge ADD is faster than
20932   // shl.
20933   // (shl V, 1) -> add V,V
20934   if (isSplatVector(N1.getNode())) {
20935     assert(N0.getValueType().isVector() && "Invalid vector shift type");
20936     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20937     // We shift all of the values by one. In many cases we do not have
20938     // hardware support for this operation. This is better expressed as an ADD
20939     // of two values.
20940     if (N1C && (1 == N1C->getZExtValue())) {
20941       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20942     }
20943   }
20944
20945   return SDValue();
20946 }
20947
20948 /// \brief Returns a vector of 0s if the node in input is a vector logical
20949 /// shift by a constant amount which is known to be bigger than or equal
20950 /// to the vector element size in bits.
20951 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20952                                       const X86Subtarget *Subtarget) {
20953   EVT VT = N->getValueType(0);
20954
20955   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20956       (!Subtarget->hasInt256() ||
20957        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20958     return SDValue();
20959
20960   SDValue Amt = N->getOperand(1);
20961   SDLoc DL(N);
20962   if (isSplatVector(Amt.getNode())) {
20963     SDValue SclrAmt = Amt->getOperand(0);
20964     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20965       APInt ShiftAmt = C->getAPIntValue();
20966       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20967
20968       // SSE2/AVX2 logical shifts always return a vector of 0s
20969       // if the shift amount is bigger than or equal to
20970       // the element size. The constant shift amount will be
20971       // encoded as a 8-bit immediate.
20972       if (ShiftAmt.trunc(8).uge(MaxAmount))
20973         return getZeroVector(VT, Subtarget, DAG, DL);
20974     }
20975   }
20976
20977   return SDValue();
20978 }
20979
20980 /// PerformShiftCombine - Combine shifts.
20981 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20982                                    TargetLowering::DAGCombinerInfo &DCI,
20983                                    const X86Subtarget *Subtarget) {
20984   if (N->getOpcode() == ISD::SHL) {
20985     SDValue V = PerformSHLCombine(N, DAG);
20986     if (V.getNode()) return V;
20987   }
20988
20989   if (N->getOpcode() != ISD::SRA) {
20990     // Try to fold this logical shift into a zero vector.
20991     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20992     if (V.getNode()) return V;
20993   }
20994
20995   return SDValue();
20996 }
20997
20998 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20999 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21000 // and friends.  Likewise for OR -> CMPNEQSS.
21001 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21002                             TargetLowering::DAGCombinerInfo &DCI,
21003                             const X86Subtarget *Subtarget) {
21004   unsigned opcode;
21005
21006   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21007   // we're requiring SSE2 for both.
21008   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21009     SDValue N0 = N->getOperand(0);
21010     SDValue N1 = N->getOperand(1);
21011     SDValue CMP0 = N0->getOperand(1);
21012     SDValue CMP1 = N1->getOperand(1);
21013     SDLoc DL(N);
21014
21015     // The SETCCs should both refer to the same CMP.
21016     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21017       return SDValue();
21018
21019     SDValue CMP00 = CMP0->getOperand(0);
21020     SDValue CMP01 = CMP0->getOperand(1);
21021     EVT     VT    = CMP00.getValueType();
21022
21023     if (VT == MVT::f32 || VT == MVT::f64) {
21024       bool ExpectingFlags = false;
21025       // Check for any users that want flags:
21026       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21027            !ExpectingFlags && UI != UE; ++UI)
21028         switch (UI->getOpcode()) {
21029         default:
21030         case ISD::BR_CC:
21031         case ISD::BRCOND:
21032         case ISD::SELECT:
21033           ExpectingFlags = true;
21034           break;
21035         case ISD::CopyToReg:
21036         case ISD::SIGN_EXTEND:
21037         case ISD::ZERO_EXTEND:
21038         case ISD::ANY_EXTEND:
21039           break;
21040         }
21041
21042       if (!ExpectingFlags) {
21043         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21044         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21045
21046         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21047           X86::CondCode tmp = cc0;
21048           cc0 = cc1;
21049           cc1 = tmp;
21050         }
21051
21052         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21053             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21054           // FIXME: need symbolic constants for these magic numbers.
21055           // See X86ATTInstPrinter.cpp:printSSECC().
21056           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21057           if (Subtarget->hasAVX512()) {
21058             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21059                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21060             if (N->getValueType(0) != MVT::i1)
21061               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21062                                  FSetCC);
21063             return FSetCC;
21064           }
21065           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21066                                               CMP00.getValueType(), CMP00, CMP01,
21067                                               DAG.getConstant(x86cc, MVT::i8));
21068
21069           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21070           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21071
21072           if (is64BitFP && !Subtarget->is64Bit()) {
21073             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21074             // 64-bit integer, since that's not a legal type. Since
21075             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21076             // bits, but can do this little dance to extract the lowest 32 bits
21077             // and work with those going forward.
21078             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21079                                            OnesOrZeroesF);
21080             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21081                                            Vector64);
21082             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21083                                         Vector32, DAG.getIntPtrConstant(0));
21084             IntVT = MVT::i32;
21085           }
21086
21087           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21088           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21089                                       DAG.getConstant(1, IntVT));
21090           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21091           return OneBitOfTruth;
21092         }
21093       }
21094     }
21095   }
21096   return SDValue();
21097 }
21098
21099 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21100 /// so it can be folded inside ANDNP.
21101 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21102   EVT VT = N->getValueType(0);
21103
21104   // Match direct AllOnes for 128 and 256-bit vectors
21105   if (ISD::isBuildVectorAllOnes(N))
21106     return true;
21107
21108   // Look through a bit convert.
21109   if (N->getOpcode() == ISD::BITCAST)
21110     N = N->getOperand(0).getNode();
21111
21112   // Sometimes the operand may come from a insert_subvector building a 256-bit
21113   // allones vector
21114   if (VT.is256BitVector() &&
21115       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21116     SDValue V1 = N->getOperand(0);
21117     SDValue V2 = N->getOperand(1);
21118
21119     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21120         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21121         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21122         ISD::isBuildVectorAllOnes(V2.getNode()))
21123       return true;
21124   }
21125
21126   return false;
21127 }
21128
21129 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21130 // register. In most cases we actually compare or select YMM-sized registers
21131 // and mixing the two types creates horrible code. This method optimizes
21132 // some of the transition sequences.
21133 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21134                                  TargetLowering::DAGCombinerInfo &DCI,
21135                                  const X86Subtarget *Subtarget) {
21136   EVT VT = N->getValueType(0);
21137   if (!VT.is256BitVector())
21138     return SDValue();
21139
21140   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21141           N->getOpcode() == ISD::ZERO_EXTEND ||
21142           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21143
21144   SDValue Narrow = N->getOperand(0);
21145   EVT NarrowVT = Narrow->getValueType(0);
21146   if (!NarrowVT.is128BitVector())
21147     return SDValue();
21148
21149   if (Narrow->getOpcode() != ISD::XOR &&
21150       Narrow->getOpcode() != ISD::AND &&
21151       Narrow->getOpcode() != ISD::OR)
21152     return SDValue();
21153
21154   SDValue N0  = Narrow->getOperand(0);
21155   SDValue N1  = Narrow->getOperand(1);
21156   SDLoc DL(Narrow);
21157
21158   // The Left side has to be a trunc.
21159   if (N0.getOpcode() != ISD::TRUNCATE)
21160     return SDValue();
21161
21162   // The type of the truncated inputs.
21163   EVT WideVT = N0->getOperand(0)->getValueType(0);
21164   if (WideVT != VT)
21165     return SDValue();
21166
21167   // The right side has to be a 'trunc' or a constant vector.
21168   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21169   bool RHSConst = (isSplatVector(N1.getNode()) &&
21170                    isa<ConstantSDNode>(N1->getOperand(0)));
21171   if (!RHSTrunc && !RHSConst)
21172     return SDValue();
21173
21174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21175
21176   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21177     return SDValue();
21178
21179   // Set N0 and N1 to hold the inputs to the new wide operation.
21180   N0 = N0->getOperand(0);
21181   if (RHSConst) {
21182     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21183                      N1->getOperand(0));
21184     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21185     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21186   } else if (RHSTrunc) {
21187     N1 = N1->getOperand(0);
21188   }
21189
21190   // Generate the wide operation.
21191   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21192   unsigned Opcode = N->getOpcode();
21193   switch (Opcode) {
21194   case ISD::ANY_EXTEND:
21195     return Op;
21196   case ISD::ZERO_EXTEND: {
21197     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21198     APInt Mask = APInt::getAllOnesValue(InBits);
21199     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21200     return DAG.getNode(ISD::AND, DL, VT,
21201                        Op, DAG.getConstant(Mask, VT));
21202   }
21203   case ISD::SIGN_EXTEND:
21204     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21205                        Op, DAG.getValueType(NarrowVT));
21206   default:
21207     llvm_unreachable("Unexpected opcode");
21208   }
21209 }
21210
21211 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21212                                  TargetLowering::DAGCombinerInfo &DCI,
21213                                  const X86Subtarget *Subtarget) {
21214   EVT VT = N->getValueType(0);
21215   if (DCI.isBeforeLegalizeOps())
21216     return SDValue();
21217
21218   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21219   if (R.getNode())
21220     return R;
21221
21222   // Create BEXTR instructions
21223   // BEXTR is ((X >> imm) & (2**size-1))
21224   if (VT == MVT::i32 || VT == MVT::i64) {
21225     SDValue N0 = N->getOperand(0);
21226     SDValue N1 = N->getOperand(1);
21227     SDLoc DL(N);
21228
21229     // Check for BEXTR.
21230     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21231         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21232       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21233       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21234       if (MaskNode && ShiftNode) {
21235         uint64_t Mask = MaskNode->getZExtValue();
21236         uint64_t Shift = ShiftNode->getZExtValue();
21237         if (isMask_64(Mask)) {
21238           uint64_t MaskSize = CountPopulation_64(Mask);
21239           if (Shift + MaskSize <= VT.getSizeInBits())
21240             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21241                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21242         }
21243       }
21244     } // BEXTR
21245
21246     return SDValue();
21247   }
21248
21249   // Want to form ANDNP nodes:
21250   // 1) In the hopes of then easily combining them with OR and AND nodes
21251   //    to form PBLEND/PSIGN.
21252   // 2) To match ANDN packed intrinsics
21253   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21254     return SDValue();
21255
21256   SDValue N0 = N->getOperand(0);
21257   SDValue N1 = N->getOperand(1);
21258   SDLoc DL(N);
21259
21260   // Check LHS for vnot
21261   if (N0.getOpcode() == ISD::XOR &&
21262       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21263       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21264     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21265
21266   // Check RHS for vnot
21267   if (N1.getOpcode() == ISD::XOR &&
21268       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21269       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21270     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21271
21272   return SDValue();
21273 }
21274
21275 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21276                                 TargetLowering::DAGCombinerInfo &DCI,
21277                                 const X86Subtarget *Subtarget) {
21278   if (DCI.isBeforeLegalizeOps())
21279     return SDValue();
21280
21281   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21282   if (R.getNode())
21283     return R;
21284
21285   SDValue N0 = N->getOperand(0);
21286   SDValue N1 = N->getOperand(1);
21287   EVT VT = N->getValueType(0);
21288
21289   // look for psign/blend
21290   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21291     if (!Subtarget->hasSSSE3() ||
21292         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21293       return SDValue();
21294
21295     // Canonicalize pandn to RHS
21296     if (N0.getOpcode() == X86ISD::ANDNP)
21297       std::swap(N0, N1);
21298     // or (and (m, y), (pandn m, x))
21299     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21300       SDValue Mask = N1.getOperand(0);
21301       SDValue X    = N1.getOperand(1);
21302       SDValue Y;
21303       if (N0.getOperand(0) == Mask)
21304         Y = N0.getOperand(1);
21305       if (N0.getOperand(1) == Mask)
21306         Y = N0.getOperand(0);
21307
21308       // Check to see if the mask appeared in both the AND and ANDNP and
21309       if (!Y.getNode())
21310         return SDValue();
21311
21312       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21313       // Look through mask bitcast.
21314       if (Mask.getOpcode() == ISD::BITCAST)
21315         Mask = Mask.getOperand(0);
21316       if (X.getOpcode() == ISD::BITCAST)
21317         X = X.getOperand(0);
21318       if (Y.getOpcode() == ISD::BITCAST)
21319         Y = Y.getOperand(0);
21320
21321       EVT MaskVT = Mask.getValueType();
21322
21323       // Validate that the Mask operand is a vector sra node.
21324       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21325       // there is no psrai.b
21326       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21327       unsigned SraAmt = ~0;
21328       if (Mask.getOpcode() == ISD::SRA) {
21329         SDValue Amt = Mask.getOperand(1);
21330         if (isSplatVector(Amt.getNode())) {
21331           SDValue SclrAmt = Amt->getOperand(0);
21332           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
21333             SraAmt = C->getZExtValue();
21334         }
21335       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21336         SDValue SraC = Mask.getOperand(1);
21337         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21338       }
21339       if ((SraAmt + 1) != EltBits)
21340         return SDValue();
21341
21342       SDLoc DL(N);
21343
21344       // Now we know we at least have a plendvb with the mask val.  See if
21345       // we can form a psignb/w/d.
21346       // psign = x.type == y.type == mask.type && y = sub(0, x);
21347       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21348           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21349           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21350         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21351                "Unsupported VT for PSIGN");
21352         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21353         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21354       }
21355       // PBLENDVB only available on SSE 4.1
21356       if (!Subtarget->hasSSE41())
21357         return SDValue();
21358
21359       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21360
21361       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21362       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21363       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21364       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21365       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21366     }
21367   }
21368
21369   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21370     return SDValue();
21371
21372   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21373   MachineFunction &MF = DAG.getMachineFunction();
21374   bool OptForSize = MF.getFunction()->getAttributes().
21375     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21376
21377   // SHLD/SHRD instructions have lower register pressure, but on some
21378   // platforms they have higher latency than the equivalent
21379   // series of shifts/or that would otherwise be generated.
21380   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21381   // have higher latencies and we are not optimizing for size.
21382   if (!OptForSize && Subtarget->isSHLDSlow())
21383     return SDValue();
21384
21385   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21386     std::swap(N0, N1);
21387   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21388     return SDValue();
21389   if (!N0.hasOneUse() || !N1.hasOneUse())
21390     return SDValue();
21391
21392   SDValue ShAmt0 = N0.getOperand(1);
21393   if (ShAmt0.getValueType() != MVT::i8)
21394     return SDValue();
21395   SDValue ShAmt1 = N1.getOperand(1);
21396   if (ShAmt1.getValueType() != MVT::i8)
21397     return SDValue();
21398   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21399     ShAmt0 = ShAmt0.getOperand(0);
21400   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21401     ShAmt1 = ShAmt1.getOperand(0);
21402
21403   SDLoc DL(N);
21404   unsigned Opc = X86ISD::SHLD;
21405   SDValue Op0 = N0.getOperand(0);
21406   SDValue Op1 = N1.getOperand(0);
21407   if (ShAmt0.getOpcode() == ISD::SUB) {
21408     Opc = X86ISD::SHRD;
21409     std::swap(Op0, Op1);
21410     std::swap(ShAmt0, ShAmt1);
21411   }
21412
21413   unsigned Bits = VT.getSizeInBits();
21414   if (ShAmt1.getOpcode() == ISD::SUB) {
21415     SDValue Sum = ShAmt1.getOperand(0);
21416     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21417       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21418       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21419         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21420       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21421         return DAG.getNode(Opc, DL, VT,
21422                            Op0, Op1,
21423                            DAG.getNode(ISD::TRUNCATE, DL,
21424                                        MVT::i8, ShAmt0));
21425     }
21426   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21427     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21428     if (ShAmt0C &&
21429         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21430       return DAG.getNode(Opc, DL, VT,
21431                          N0.getOperand(0), N1.getOperand(0),
21432                          DAG.getNode(ISD::TRUNCATE, DL,
21433                                        MVT::i8, ShAmt0));
21434   }
21435
21436   return SDValue();
21437 }
21438
21439 // Generate NEG and CMOV for integer abs.
21440 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21441   EVT VT = N->getValueType(0);
21442
21443   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21444   // 8-bit integer abs to NEG and CMOV.
21445   if (VT.isInteger() && VT.getSizeInBits() == 8)
21446     return SDValue();
21447
21448   SDValue N0 = N->getOperand(0);
21449   SDValue N1 = N->getOperand(1);
21450   SDLoc DL(N);
21451
21452   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21453   // and change it to SUB and CMOV.
21454   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21455       N0.getOpcode() == ISD::ADD &&
21456       N0.getOperand(1) == N1 &&
21457       N1.getOpcode() == ISD::SRA &&
21458       N1.getOperand(0) == N0.getOperand(0))
21459     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21460       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21461         // Generate SUB & CMOV.
21462         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21463                                   DAG.getConstant(0, VT), N0.getOperand(0));
21464
21465         SDValue Ops[] = { N0.getOperand(0), Neg,
21466                           DAG.getConstant(X86::COND_GE, MVT::i8),
21467                           SDValue(Neg.getNode(), 1) };
21468         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21469       }
21470   return SDValue();
21471 }
21472
21473 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21474 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21475                                  TargetLowering::DAGCombinerInfo &DCI,
21476                                  const X86Subtarget *Subtarget) {
21477   if (DCI.isBeforeLegalizeOps())
21478     return SDValue();
21479
21480   if (Subtarget->hasCMov()) {
21481     SDValue RV = performIntegerAbsCombine(N, DAG);
21482     if (RV.getNode())
21483       return RV;
21484   }
21485
21486   return SDValue();
21487 }
21488
21489 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21490 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21491                                   TargetLowering::DAGCombinerInfo &DCI,
21492                                   const X86Subtarget *Subtarget) {
21493   LoadSDNode *Ld = cast<LoadSDNode>(N);
21494   EVT RegVT = Ld->getValueType(0);
21495   EVT MemVT = Ld->getMemoryVT();
21496   SDLoc dl(Ld);
21497   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21498   unsigned RegSz = RegVT.getSizeInBits();
21499
21500   // On Sandybridge unaligned 256bit loads are inefficient.
21501   ISD::LoadExtType Ext = Ld->getExtensionType();
21502   unsigned Alignment = Ld->getAlignment();
21503   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21504   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21505       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21506     unsigned NumElems = RegVT.getVectorNumElements();
21507     if (NumElems < 2)
21508       return SDValue();
21509
21510     SDValue Ptr = Ld->getBasePtr();
21511     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21512
21513     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21514                                   NumElems/2);
21515     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21516                                 Ld->getPointerInfo(), Ld->isVolatile(),
21517                                 Ld->isNonTemporal(), Ld->isInvariant(),
21518                                 Alignment);
21519     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21520     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21521                                 Ld->getPointerInfo(), Ld->isVolatile(),
21522                                 Ld->isNonTemporal(), Ld->isInvariant(),
21523                                 std::min(16U, Alignment));
21524     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21525                              Load1.getValue(1),
21526                              Load2.getValue(1));
21527
21528     SDValue NewVec = DAG.getUNDEF(RegVT);
21529     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21530     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21531     return DCI.CombineTo(N, NewVec, TF, true);
21532   }
21533
21534   // If this is a vector EXT Load then attempt to optimize it using a
21535   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
21536   // expansion is still better than scalar code.
21537   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
21538   // emit a shuffle and a arithmetic shift.
21539   // TODO: It is possible to support ZExt by zeroing the undef values
21540   // during the shuffle phase or after the shuffle.
21541   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
21542       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
21543     assert(MemVT != RegVT && "Cannot extend to the same type");
21544     assert(MemVT.isVector() && "Must load a vector from memory");
21545
21546     unsigned NumElems = RegVT.getVectorNumElements();
21547     unsigned MemSz = MemVT.getSizeInBits();
21548     assert(RegSz > MemSz && "Register size must be greater than the mem size");
21549
21550     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
21551       return SDValue();
21552
21553     // All sizes must be a power of two.
21554     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
21555       return SDValue();
21556
21557     // Attempt to load the original value using scalar loads.
21558     // Find the largest scalar type that divides the total loaded size.
21559     MVT SclrLoadTy = MVT::i8;
21560     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21561          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21562       MVT Tp = (MVT::SimpleValueType)tp;
21563       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
21564         SclrLoadTy = Tp;
21565       }
21566     }
21567
21568     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21569     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
21570         (64 <= MemSz))
21571       SclrLoadTy = MVT::f64;
21572
21573     // Calculate the number of scalar loads that we need to perform
21574     // in order to load our vector from memory.
21575     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
21576     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
21577       return SDValue();
21578
21579     unsigned loadRegZize = RegSz;
21580     if (Ext == ISD::SEXTLOAD && RegSz == 256)
21581       loadRegZize /= 2;
21582
21583     // Represent our vector as a sequence of elements which are the
21584     // largest scalar that we can load.
21585     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
21586       loadRegZize/SclrLoadTy.getSizeInBits());
21587
21588     // Represent the data using the same element type that is stored in
21589     // memory. In practice, we ''widen'' MemVT.
21590     EVT WideVecVT =
21591           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21592                        loadRegZize/MemVT.getScalarType().getSizeInBits());
21593
21594     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
21595       "Invalid vector type");
21596
21597     // We can't shuffle using an illegal type.
21598     if (!TLI.isTypeLegal(WideVecVT))
21599       return SDValue();
21600
21601     SmallVector<SDValue, 8> Chains;
21602     SDValue Ptr = Ld->getBasePtr();
21603     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
21604                                         TLI.getPointerTy());
21605     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
21606
21607     for (unsigned i = 0; i < NumLoads; ++i) {
21608       // Perform a single load.
21609       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
21610                                        Ptr, Ld->getPointerInfo(),
21611                                        Ld->isVolatile(), Ld->isNonTemporal(),
21612                                        Ld->isInvariant(), Ld->getAlignment());
21613       Chains.push_back(ScalarLoad.getValue(1));
21614       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
21615       // another round of DAGCombining.
21616       if (i == 0)
21617         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
21618       else
21619         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
21620                           ScalarLoad, DAG.getIntPtrConstant(i));
21621
21622       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21623     }
21624
21625     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21626
21627     // Bitcast the loaded value to a vector of the original element type, in
21628     // the size of the target vector type.
21629     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21630     unsigned SizeRatio = RegSz/MemSz;
21631
21632     if (Ext == ISD::SEXTLOAD) {
21633       // If we have SSE4.1 we can directly emit a VSEXT node.
21634       if (Subtarget->hasSSE41()) {
21635         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21636         return DCI.CombineTo(N, Sext, TF, true);
21637       }
21638
21639       // Otherwise we'll shuffle the small elements in the high bits of the
21640       // larger type and perform an arithmetic shift. If the shift is not legal
21641       // it's better to scalarize.
21642       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21643         return SDValue();
21644
21645       // Redistribute the loaded elements into the different locations.
21646       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21647       for (unsigned i = 0; i != NumElems; ++i)
21648         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21649
21650       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21651                                            DAG.getUNDEF(WideVecVT),
21652                                            &ShuffleVec[0]);
21653
21654       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21655
21656       // Build the arithmetic shift.
21657       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21658                      MemVT.getVectorElementType().getSizeInBits();
21659       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21660                           DAG.getConstant(Amt, RegVT));
21661
21662       return DCI.CombineTo(N, Shuff, TF, true);
21663     }
21664
21665     // Redistribute the loaded elements into the different locations.
21666     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21667     for (unsigned i = 0; i != NumElems; ++i)
21668       ShuffleVec[i*SizeRatio] = i;
21669
21670     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21671                                          DAG.getUNDEF(WideVecVT),
21672                                          &ShuffleVec[0]);
21673
21674     // Bitcast to the requested type.
21675     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21676     // Replace the original load with the new sequence
21677     // and return the new chain.
21678     return DCI.CombineTo(N, Shuff, TF, true);
21679   }
21680
21681   return SDValue();
21682 }
21683
21684 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21685 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21686                                    const X86Subtarget *Subtarget) {
21687   StoreSDNode *St = cast<StoreSDNode>(N);
21688   EVT VT = St->getValue().getValueType();
21689   EVT StVT = St->getMemoryVT();
21690   SDLoc dl(St);
21691   SDValue StoredVal = St->getOperand(1);
21692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21693
21694   // If we are saving a concatenation of two XMM registers, perform two stores.
21695   // On Sandy Bridge, 256-bit memory operations are executed by two
21696   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21697   // memory  operation.
21698   unsigned Alignment = St->getAlignment();
21699   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21700   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21701       StVT == VT && !IsAligned) {
21702     unsigned NumElems = VT.getVectorNumElements();
21703     if (NumElems < 2)
21704       return SDValue();
21705
21706     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21707     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21708
21709     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21710     SDValue Ptr0 = St->getBasePtr();
21711     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21712
21713     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21714                                 St->getPointerInfo(), St->isVolatile(),
21715                                 St->isNonTemporal(), Alignment);
21716     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21717                                 St->getPointerInfo(), St->isVolatile(),
21718                                 St->isNonTemporal(),
21719                                 std::min(16U, Alignment));
21720     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21721   }
21722
21723   // Optimize trunc store (of multiple scalars) to shuffle and store.
21724   // First, pack all of the elements in one place. Next, store to memory
21725   // in fewer chunks.
21726   if (St->isTruncatingStore() && VT.isVector()) {
21727     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21728     unsigned NumElems = VT.getVectorNumElements();
21729     assert(StVT != VT && "Cannot truncate to the same type");
21730     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21731     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21732
21733     // From, To sizes and ElemCount must be pow of two
21734     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21735     // We are going to use the original vector elt for storing.
21736     // Accumulated smaller vector elements must be a multiple of the store size.
21737     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21738
21739     unsigned SizeRatio  = FromSz / ToSz;
21740
21741     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21742
21743     // Create a type on which we perform the shuffle
21744     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21745             StVT.getScalarType(), NumElems*SizeRatio);
21746
21747     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21748
21749     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21750     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21751     for (unsigned i = 0; i != NumElems; ++i)
21752       ShuffleVec[i] = i * SizeRatio;
21753
21754     // Can't shuffle using an illegal type.
21755     if (!TLI.isTypeLegal(WideVecVT))
21756       return SDValue();
21757
21758     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21759                                          DAG.getUNDEF(WideVecVT),
21760                                          &ShuffleVec[0]);
21761     // At this point all of the data is stored at the bottom of the
21762     // register. We now need to save it to mem.
21763
21764     // Find the largest store unit
21765     MVT StoreType = MVT::i8;
21766     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21767          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21768       MVT Tp = (MVT::SimpleValueType)tp;
21769       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21770         StoreType = Tp;
21771     }
21772
21773     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21774     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21775         (64 <= NumElems * ToSz))
21776       StoreType = MVT::f64;
21777
21778     // Bitcast the original vector into a vector of store-size units
21779     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21780             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21781     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21782     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21783     SmallVector<SDValue, 8> Chains;
21784     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21785                                         TLI.getPointerTy());
21786     SDValue Ptr = St->getBasePtr();
21787
21788     // Perform one or more big stores into memory.
21789     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21790       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21791                                    StoreType, ShuffWide,
21792                                    DAG.getIntPtrConstant(i));
21793       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21794                                 St->getPointerInfo(), St->isVolatile(),
21795                                 St->isNonTemporal(), St->getAlignment());
21796       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21797       Chains.push_back(Ch);
21798     }
21799
21800     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21801   }
21802
21803   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21804   // the FP state in cases where an emms may be missing.
21805   // A preferable solution to the general problem is to figure out the right
21806   // places to insert EMMS.  This qualifies as a quick hack.
21807
21808   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21809   if (VT.getSizeInBits() != 64)
21810     return SDValue();
21811
21812   const Function *F = DAG.getMachineFunction().getFunction();
21813   bool NoImplicitFloatOps = F->getAttributes().
21814     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21815   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21816                      && Subtarget->hasSSE2();
21817   if ((VT.isVector() ||
21818        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21819       isa<LoadSDNode>(St->getValue()) &&
21820       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21821       St->getChain().hasOneUse() && !St->isVolatile()) {
21822     SDNode* LdVal = St->getValue().getNode();
21823     LoadSDNode *Ld = nullptr;
21824     int TokenFactorIndex = -1;
21825     SmallVector<SDValue, 8> Ops;
21826     SDNode* ChainVal = St->getChain().getNode();
21827     // Must be a store of a load.  We currently handle two cases:  the load
21828     // is a direct child, and it's under an intervening TokenFactor.  It is
21829     // possible to dig deeper under nested TokenFactors.
21830     if (ChainVal == LdVal)
21831       Ld = cast<LoadSDNode>(St->getChain());
21832     else if (St->getValue().hasOneUse() &&
21833              ChainVal->getOpcode() == ISD::TokenFactor) {
21834       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21835         if (ChainVal->getOperand(i).getNode() == LdVal) {
21836           TokenFactorIndex = i;
21837           Ld = cast<LoadSDNode>(St->getValue());
21838         } else
21839           Ops.push_back(ChainVal->getOperand(i));
21840       }
21841     }
21842
21843     if (!Ld || !ISD::isNormalLoad(Ld))
21844       return SDValue();
21845
21846     // If this is not the MMX case, i.e. we are just turning i64 load/store
21847     // into f64 load/store, avoid the transformation if there are multiple
21848     // uses of the loaded value.
21849     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21850       return SDValue();
21851
21852     SDLoc LdDL(Ld);
21853     SDLoc StDL(N);
21854     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21855     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21856     // pair instead.
21857     if (Subtarget->is64Bit() || F64IsLegal) {
21858       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21859       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21860                                   Ld->getPointerInfo(), Ld->isVolatile(),
21861                                   Ld->isNonTemporal(), Ld->isInvariant(),
21862                                   Ld->getAlignment());
21863       SDValue NewChain = NewLd.getValue(1);
21864       if (TokenFactorIndex != -1) {
21865         Ops.push_back(NewChain);
21866         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21867       }
21868       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21869                           St->getPointerInfo(),
21870                           St->isVolatile(), St->isNonTemporal(),
21871                           St->getAlignment());
21872     }
21873
21874     // Otherwise, lower to two pairs of 32-bit loads / stores.
21875     SDValue LoAddr = Ld->getBasePtr();
21876     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21877                                  DAG.getConstant(4, MVT::i32));
21878
21879     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21880                                Ld->getPointerInfo(),
21881                                Ld->isVolatile(), Ld->isNonTemporal(),
21882                                Ld->isInvariant(), Ld->getAlignment());
21883     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21884                                Ld->getPointerInfo().getWithOffset(4),
21885                                Ld->isVolatile(), Ld->isNonTemporal(),
21886                                Ld->isInvariant(),
21887                                MinAlign(Ld->getAlignment(), 4));
21888
21889     SDValue NewChain = LoLd.getValue(1);
21890     if (TokenFactorIndex != -1) {
21891       Ops.push_back(LoLd);
21892       Ops.push_back(HiLd);
21893       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21894     }
21895
21896     LoAddr = St->getBasePtr();
21897     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21898                          DAG.getConstant(4, MVT::i32));
21899
21900     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21901                                 St->getPointerInfo(),
21902                                 St->isVolatile(), St->isNonTemporal(),
21903                                 St->getAlignment());
21904     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21905                                 St->getPointerInfo().getWithOffset(4),
21906                                 St->isVolatile(),
21907                                 St->isNonTemporal(),
21908                                 MinAlign(St->getAlignment(), 4));
21909     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21910   }
21911   return SDValue();
21912 }
21913
21914 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21915 /// and return the operands for the horizontal operation in LHS and RHS.  A
21916 /// horizontal operation performs the binary operation on successive elements
21917 /// of its first operand, then on successive elements of its second operand,
21918 /// returning the resulting values in a vector.  For example, if
21919 ///   A = < float a0, float a1, float a2, float a3 >
21920 /// and
21921 ///   B = < float b0, float b1, float b2, float b3 >
21922 /// then the result of doing a horizontal operation on A and B is
21923 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21924 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21925 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21926 /// set to A, RHS to B, and the routine returns 'true'.
21927 /// Note that the binary operation should have the property that if one of the
21928 /// operands is UNDEF then the result is UNDEF.
21929 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21930   // Look for the following pattern: if
21931   //   A = < float a0, float a1, float a2, float a3 >
21932   //   B = < float b0, float b1, float b2, float b3 >
21933   // and
21934   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21935   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21936   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21937   // which is A horizontal-op B.
21938
21939   // At least one of the operands should be a vector shuffle.
21940   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21941       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21942     return false;
21943
21944   MVT VT = LHS.getSimpleValueType();
21945
21946   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21947          "Unsupported vector type for horizontal add/sub");
21948
21949   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21950   // operate independently on 128-bit lanes.
21951   unsigned NumElts = VT.getVectorNumElements();
21952   unsigned NumLanes = VT.getSizeInBits()/128;
21953   unsigned NumLaneElts = NumElts / NumLanes;
21954   assert((NumLaneElts % 2 == 0) &&
21955          "Vector type should have an even number of elements in each lane");
21956   unsigned HalfLaneElts = NumLaneElts/2;
21957
21958   // View LHS in the form
21959   //   LHS = VECTOR_SHUFFLE A, B, LMask
21960   // If LHS is not a shuffle then pretend it is the shuffle
21961   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21962   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21963   // type VT.
21964   SDValue A, B;
21965   SmallVector<int, 16> LMask(NumElts);
21966   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21967     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21968       A = LHS.getOperand(0);
21969     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21970       B = LHS.getOperand(1);
21971     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21972     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21973   } else {
21974     if (LHS.getOpcode() != ISD::UNDEF)
21975       A = LHS;
21976     for (unsigned i = 0; i != NumElts; ++i)
21977       LMask[i] = i;
21978   }
21979
21980   // Likewise, view RHS in the form
21981   //   RHS = VECTOR_SHUFFLE C, D, RMask
21982   SDValue C, D;
21983   SmallVector<int, 16> RMask(NumElts);
21984   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21985     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21986       C = RHS.getOperand(0);
21987     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21988       D = RHS.getOperand(1);
21989     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21990     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21991   } else {
21992     if (RHS.getOpcode() != ISD::UNDEF)
21993       C = RHS;
21994     for (unsigned i = 0; i != NumElts; ++i)
21995       RMask[i] = i;
21996   }
21997
21998   // Check that the shuffles are both shuffling the same vectors.
21999   if (!(A == C && B == D) && !(A == D && B == C))
22000     return false;
22001
22002   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22003   if (!A.getNode() && !B.getNode())
22004     return false;
22005
22006   // If A and B occur in reverse order in RHS, then "swap" them (which means
22007   // rewriting the mask).
22008   if (A != C)
22009     CommuteVectorShuffleMask(RMask, NumElts);
22010
22011   // At this point LHS and RHS are equivalent to
22012   //   LHS = VECTOR_SHUFFLE A, B, LMask
22013   //   RHS = VECTOR_SHUFFLE A, B, RMask
22014   // Check that the masks correspond to performing a horizontal operation.
22015   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22016     for (unsigned i = 0; i != NumLaneElts; ++i) {
22017       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22018
22019       // Ignore any UNDEF components.
22020       if (LIdx < 0 || RIdx < 0 ||
22021           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22022           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22023         continue;
22024
22025       // Check that successive elements are being operated on.  If not, this is
22026       // not a horizontal operation.
22027       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22028       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22029       if (!(LIdx == Index && RIdx == Index + 1) &&
22030           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22031         return false;
22032     }
22033   }
22034
22035   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22036   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22037   return true;
22038 }
22039
22040 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22041 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22042                                   const X86Subtarget *Subtarget) {
22043   EVT VT = N->getValueType(0);
22044   SDValue LHS = N->getOperand(0);
22045   SDValue RHS = N->getOperand(1);
22046
22047   // Try to synthesize horizontal adds from adds of shuffles.
22048   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22049        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22050       isHorizontalBinOp(LHS, RHS, true))
22051     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22052   return SDValue();
22053 }
22054
22055 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22056 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22057                                   const X86Subtarget *Subtarget) {
22058   EVT VT = N->getValueType(0);
22059   SDValue LHS = N->getOperand(0);
22060   SDValue RHS = N->getOperand(1);
22061
22062   // Try to synthesize horizontal subs from subs of shuffles.
22063   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22064        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22065       isHorizontalBinOp(LHS, RHS, false))
22066     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22067   return SDValue();
22068 }
22069
22070 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22071 /// X86ISD::FXOR nodes.
22072 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22073   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22074   // F[X]OR(0.0, x) -> x
22075   // F[X]OR(x, 0.0) -> x
22076   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22077     if (C->getValueAPF().isPosZero())
22078       return N->getOperand(1);
22079   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22080     if (C->getValueAPF().isPosZero())
22081       return N->getOperand(0);
22082   return SDValue();
22083 }
22084
22085 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22086 /// X86ISD::FMAX nodes.
22087 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22088   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22089
22090   // Only perform optimizations if UnsafeMath is used.
22091   if (!DAG.getTarget().Options.UnsafeFPMath)
22092     return SDValue();
22093
22094   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22095   // into FMINC and FMAXC, which are Commutative operations.
22096   unsigned NewOp = 0;
22097   switch (N->getOpcode()) {
22098     default: llvm_unreachable("unknown opcode");
22099     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22100     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22101   }
22102
22103   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22104                      N->getOperand(0), N->getOperand(1));
22105 }
22106
22107 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22108 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22109   // FAND(0.0, x) -> 0.0
22110   // FAND(x, 0.0) -> 0.0
22111   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22112     if (C->getValueAPF().isPosZero())
22113       return N->getOperand(0);
22114   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22115     if (C->getValueAPF().isPosZero())
22116       return N->getOperand(1);
22117   return SDValue();
22118 }
22119
22120 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22121 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22122   // FANDN(x, 0.0) -> 0.0
22123   // FANDN(0.0, x) -> x
22124   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22125     if (C->getValueAPF().isPosZero())
22126       return N->getOperand(1);
22127   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22128     if (C->getValueAPF().isPosZero())
22129       return N->getOperand(1);
22130   return SDValue();
22131 }
22132
22133 static SDValue PerformBTCombine(SDNode *N,
22134                                 SelectionDAG &DAG,
22135                                 TargetLowering::DAGCombinerInfo &DCI) {
22136   // BT ignores high bits in the bit index operand.
22137   SDValue Op1 = N->getOperand(1);
22138   if (Op1.hasOneUse()) {
22139     unsigned BitWidth = Op1.getValueSizeInBits();
22140     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22141     APInt KnownZero, KnownOne;
22142     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22143                                           !DCI.isBeforeLegalizeOps());
22144     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22145     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22146         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22147       DCI.CommitTargetLoweringOpt(TLO);
22148   }
22149   return SDValue();
22150 }
22151
22152 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22153   SDValue Op = N->getOperand(0);
22154   if (Op.getOpcode() == ISD::BITCAST)
22155     Op = Op.getOperand(0);
22156   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22157   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22158       VT.getVectorElementType().getSizeInBits() ==
22159       OpVT.getVectorElementType().getSizeInBits()) {
22160     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22161   }
22162   return SDValue();
22163 }
22164
22165 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22166                                                const X86Subtarget *Subtarget) {
22167   EVT VT = N->getValueType(0);
22168   if (!VT.isVector())
22169     return SDValue();
22170
22171   SDValue N0 = N->getOperand(0);
22172   SDValue N1 = N->getOperand(1);
22173   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22174   SDLoc dl(N);
22175
22176   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22177   // both SSE and AVX2 since there is no sign-extended shift right
22178   // operation on a vector with 64-bit elements.
22179   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22180   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22181   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22182       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22183     SDValue N00 = N0.getOperand(0);
22184
22185     // EXTLOAD has a better solution on AVX2,
22186     // it may be replaced with X86ISD::VSEXT node.
22187     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22188       if (!ISD::isNormalLoad(N00.getNode()))
22189         return SDValue();
22190
22191     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22192         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22193                                   N00, N1);
22194       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22195     }
22196   }
22197   return SDValue();
22198 }
22199
22200 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22201                                   TargetLowering::DAGCombinerInfo &DCI,
22202                                   const X86Subtarget *Subtarget) {
22203   if (!DCI.isBeforeLegalizeOps())
22204     return SDValue();
22205
22206   if (!Subtarget->hasFp256())
22207     return SDValue();
22208
22209   EVT VT = N->getValueType(0);
22210   if (VT.isVector() && VT.getSizeInBits() == 256) {
22211     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22212     if (R.getNode())
22213       return R;
22214   }
22215
22216   return SDValue();
22217 }
22218
22219 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22220                                  const X86Subtarget* Subtarget) {
22221   SDLoc dl(N);
22222   EVT VT = N->getValueType(0);
22223
22224   // Let legalize expand this if it isn't a legal type yet.
22225   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22226     return SDValue();
22227
22228   EVT ScalarVT = VT.getScalarType();
22229   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22230       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22231     return SDValue();
22232
22233   SDValue A = N->getOperand(0);
22234   SDValue B = N->getOperand(1);
22235   SDValue C = N->getOperand(2);
22236
22237   bool NegA = (A.getOpcode() == ISD::FNEG);
22238   bool NegB = (B.getOpcode() == ISD::FNEG);
22239   bool NegC = (C.getOpcode() == ISD::FNEG);
22240
22241   // Negative multiplication when NegA xor NegB
22242   bool NegMul = (NegA != NegB);
22243   if (NegA)
22244     A = A.getOperand(0);
22245   if (NegB)
22246     B = B.getOperand(0);
22247   if (NegC)
22248     C = C.getOperand(0);
22249
22250   unsigned Opcode;
22251   if (!NegMul)
22252     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22253   else
22254     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22255
22256   return DAG.getNode(Opcode, dl, VT, A, B, C);
22257 }
22258
22259 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22260                                   TargetLowering::DAGCombinerInfo &DCI,
22261                                   const X86Subtarget *Subtarget) {
22262   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22263   //           (and (i32 x86isd::setcc_carry), 1)
22264   // This eliminates the zext. This transformation is necessary because
22265   // ISD::SETCC is always legalized to i8.
22266   SDLoc dl(N);
22267   SDValue N0 = N->getOperand(0);
22268   EVT VT = N->getValueType(0);
22269
22270   if (N0.getOpcode() == ISD::AND &&
22271       N0.hasOneUse() &&
22272       N0.getOperand(0).hasOneUse()) {
22273     SDValue N00 = N0.getOperand(0);
22274     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22275       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22276       if (!C || C->getZExtValue() != 1)
22277         return SDValue();
22278       return DAG.getNode(ISD::AND, dl, VT,
22279                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22280                                      N00.getOperand(0), N00.getOperand(1)),
22281                          DAG.getConstant(1, VT));
22282     }
22283   }
22284
22285   if (N0.getOpcode() == ISD::TRUNCATE &&
22286       N0.hasOneUse() &&
22287       N0.getOperand(0).hasOneUse()) {
22288     SDValue N00 = N0.getOperand(0);
22289     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22290       return DAG.getNode(ISD::AND, dl, VT,
22291                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22292                                      N00.getOperand(0), N00.getOperand(1)),
22293                          DAG.getConstant(1, VT));
22294     }
22295   }
22296   if (VT.is256BitVector()) {
22297     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22298     if (R.getNode())
22299       return R;
22300   }
22301
22302   return SDValue();
22303 }
22304
22305 // Optimize x == -y --> x+y == 0
22306 //          x != -y --> x+y != 0
22307 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22308                                       const X86Subtarget* Subtarget) {
22309   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22310   SDValue LHS = N->getOperand(0);
22311   SDValue RHS = N->getOperand(1);
22312   EVT VT = N->getValueType(0);
22313   SDLoc DL(N);
22314
22315   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22316     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22317       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22318         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22319                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22320         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22321                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22322       }
22323   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22325       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22326         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22327                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22328         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22329                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22330       }
22331
22332   if (VT.getScalarType() == MVT::i1) {
22333     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22334       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22335     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22336     if (!IsSEXT0 && !IsVZero0)
22337       return SDValue();
22338     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22339       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22340     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22341
22342     if (!IsSEXT1 && !IsVZero1)
22343       return SDValue();
22344
22345     if (IsSEXT0 && IsVZero1) {
22346       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22347       if (CC == ISD::SETEQ)
22348         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22349       return LHS.getOperand(0);
22350     }
22351     if (IsSEXT1 && IsVZero0) {
22352       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22353       if (CC == ISD::SETEQ)
22354         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22355       return RHS.getOperand(0);
22356     }
22357   }
22358
22359   return SDValue();
22360 }
22361
22362 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22363                                       const X86Subtarget *Subtarget) {
22364   SDLoc dl(N);
22365   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22366   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22367          "X86insertps is only defined for v4x32");
22368
22369   SDValue Ld = N->getOperand(1);
22370   if (MayFoldLoad(Ld)) {
22371     // Extract the countS bits from the immediate so we can get the proper
22372     // address when narrowing the vector load to a specific element.
22373     // When the second source op is a memory address, interps doesn't use
22374     // countS and just gets an f32 from that address.
22375     unsigned DestIndex =
22376         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22377     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22378   } else
22379     return SDValue();
22380
22381   // Create this as a scalar to vector to match the instruction pattern.
22382   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22383   // countS bits are ignored when loading from memory on insertps, which
22384   // means we don't need to explicitly set them to 0.
22385   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22386                      LoadScalarToVector, N->getOperand(2));
22387 }
22388
22389 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22390 // as "sbb reg,reg", since it can be extended without zext and produces
22391 // an all-ones bit which is more useful than 0/1 in some cases.
22392 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22393                                MVT VT) {
22394   if (VT == MVT::i8)
22395     return DAG.getNode(ISD::AND, DL, VT,
22396                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22397                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22398                        DAG.getConstant(1, VT));
22399   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22400   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22401                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22402                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22403 }
22404
22405 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22406 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22407                                    TargetLowering::DAGCombinerInfo &DCI,
22408                                    const X86Subtarget *Subtarget) {
22409   SDLoc DL(N);
22410   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22411   SDValue EFLAGS = N->getOperand(1);
22412
22413   if (CC == X86::COND_A) {
22414     // Try to convert COND_A into COND_B in an attempt to facilitate
22415     // materializing "setb reg".
22416     //
22417     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22418     // cannot take an immediate as its first operand.
22419     //
22420     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22421         EFLAGS.getValueType().isInteger() &&
22422         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22423       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22424                                    EFLAGS.getNode()->getVTList(),
22425                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22426       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22427       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22428     }
22429   }
22430
22431   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22432   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22433   // cases.
22434   if (CC == X86::COND_B)
22435     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22436
22437   SDValue Flags;
22438
22439   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22440   if (Flags.getNode()) {
22441     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22442     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22443   }
22444
22445   return SDValue();
22446 }
22447
22448 // Optimize branch condition evaluation.
22449 //
22450 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22451                                     TargetLowering::DAGCombinerInfo &DCI,
22452                                     const X86Subtarget *Subtarget) {
22453   SDLoc DL(N);
22454   SDValue Chain = N->getOperand(0);
22455   SDValue Dest = N->getOperand(1);
22456   SDValue EFLAGS = N->getOperand(3);
22457   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22458
22459   SDValue Flags;
22460
22461   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22462   if (Flags.getNode()) {
22463     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22464     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22465                        Flags);
22466   }
22467
22468   return SDValue();
22469 }
22470
22471 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22472                                         const X86TargetLowering *XTLI) {
22473   SDValue Op0 = N->getOperand(0);
22474   EVT InVT = Op0->getValueType(0);
22475
22476   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22477   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22478     SDLoc dl(N);
22479     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22480     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22481     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22482   }
22483
22484   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22485   // a 32-bit target where SSE doesn't support i64->FP operations.
22486   if (Op0.getOpcode() == ISD::LOAD) {
22487     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22488     EVT VT = Ld->getValueType(0);
22489     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22490         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22491         !XTLI->getSubtarget()->is64Bit() &&
22492         VT == MVT::i64) {
22493       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22494                                           Ld->getChain(), Op0, DAG);
22495       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22496       return FILDChain;
22497     }
22498   }
22499   return SDValue();
22500 }
22501
22502 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22503 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22504                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22505   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22506   // the result is either zero or one (depending on the input carry bit).
22507   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22508   if (X86::isZeroNode(N->getOperand(0)) &&
22509       X86::isZeroNode(N->getOperand(1)) &&
22510       // We don't have a good way to replace an EFLAGS use, so only do this when
22511       // dead right now.
22512       SDValue(N, 1).use_empty()) {
22513     SDLoc DL(N);
22514     EVT VT = N->getValueType(0);
22515     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22516     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22517                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22518                                            DAG.getConstant(X86::COND_B,MVT::i8),
22519                                            N->getOperand(2)),
22520                                DAG.getConstant(1, VT));
22521     return DCI.CombineTo(N, Res1, CarryOut);
22522   }
22523
22524   return SDValue();
22525 }
22526
22527 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22528 //      (add Y, (setne X, 0)) -> sbb -1, Y
22529 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22530 //      (sub (setne X, 0), Y) -> adc -1, Y
22531 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22532   SDLoc DL(N);
22533
22534   // Look through ZExts.
22535   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22536   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22537     return SDValue();
22538
22539   SDValue SetCC = Ext.getOperand(0);
22540   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22541     return SDValue();
22542
22543   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22544   if (CC != X86::COND_E && CC != X86::COND_NE)
22545     return SDValue();
22546
22547   SDValue Cmp = SetCC.getOperand(1);
22548   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22549       !X86::isZeroNode(Cmp.getOperand(1)) ||
22550       !Cmp.getOperand(0).getValueType().isInteger())
22551     return SDValue();
22552
22553   SDValue CmpOp0 = Cmp.getOperand(0);
22554   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22555                                DAG.getConstant(1, CmpOp0.getValueType()));
22556
22557   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22558   if (CC == X86::COND_NE)
22559     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22560                        DL, OtherVal.getValueType(), OtherVal,
22561                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22562   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22563                      DL, OtherVal.getValueType(), OtherVal,
22564                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22565 }
22566
22567 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22568 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22569                                  const X86Subtarget *Subtarget) {
22570   EVT VT = N->getValueType(0);
22571   SDValue Op0 = N->getOperand(0);
22572   SDValue Op1 = N->getOperand(1);
22573
22574   // Try to synthesize horizontal adds from adds of shuffles.
22575   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22576        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22577       isHorizontalBinOp(Op0, Op1, true))
22578     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22579
22580   return OptimizeConditionalInDecrement(N, DAG);
22581 }
22582
22583 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22584                                  const X86Subtarget *Subtarget) {
22585   SDValue Op0 = N->getOperand(0);
22586   SDValue Op1 = N->getOperand(1);
22587
22588   // X86 can't encode an immediate LHS of a sub. See if we can push the
22589   // negation into a preceding instruction.
22590   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22591     // If the RHS of the sub is a XOR with one use and a constant, invert the
22592     // immediate. Then add one to the LHS of the sub so we can turn
22593     // X-Y -> X+~Y+1, saving one register.
22594     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22595         isa<ConstantSDNode>(Op1.getOperand(1))) {
22596       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22597       EVT VT = Op0.getValueType();
22598       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22599                                    Op1.getOperand(0),
22600                                    DAG.getConstant(~XorC, VT));
22601       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22602                          DAG.getConstant(C->getAPIntValue()+1, VT));
22603     }
22604   }
22605
22606   // Try to synthesize horizontal adds from adds of shuffles.
22607   EVT VT = N->getValueType(0);
22608   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22609        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22610       isHorizontalBinOp(Op0, Op1, true))
22611     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22612
22613   return OptimizeConditionalInDecrement(N, DAG);
22614 }
22615
22616 /// performVZEXTCombine - Performs build vector combines
22617 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22618                                         TargetLowering::DAGCombinerInfo &DCI,
22619                                         const X86Subtarget *Subtarget) {
22620   // (vzext (bitcast (vzext (x)) -> (vzext x)
22621   SDValue In = N->getOperand(0);
22622   while (In.getOpcode() == ISD::BITCAST)
22623     In = In.getOperand(0);
22624
22625   if (In.getOpcode() != X86ISD::VZEXT)
22626     return SDValue();
22627
22628   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22629                      In.getOperand(0));
22630 }
22631
22632 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22633                                              DAGCombinerInfo &DCI) const {
22634   SelectionDAG &DAG = DCI.DAG;
22635   switch (N->getOpcode()) {
22636   default: break;
22637   case ISD::EXTRACT_VECTOR_ELT:
22638     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22639   case ISD::VSELECT:
22640   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22641   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22642   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22643   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22644   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22645   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22646   case ISD::SHL:
22647   case ISD::SRA:
22648   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22649   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22650   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22651   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22652   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22653   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22654   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22655   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22656   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22657   case X86ISD::FXOR:
22658   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22659   case X86ISD::FMIN:
22660   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22661   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22662   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22663   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22664   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22665   case ISD::ANY_EXTEND:
22666   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22667   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22668   case ISD::SIGN_EXTEND_INREG:
22669     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22670   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22671   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22672   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22673   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22674   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22675   case X86ISD::SHUFP:       // Handle all target specific shuffles
22676   case X86ISD::PALIGNR:
22677   case X86ISD::UNPCKH:
22678   case X86ISD::UNPCKL:
22679   case X86ISD::MOVHLPS:
22680   case X86ISD::MOVLHPS:
22681   case X86ISD::PSHUFD:
22682   case X86ISD::PSHUFHW:
22683   case X86ISD::PSHUFLW:
22684   case X86ISD::MOVSS:
22685   case X86ISD::MOVSD:
22686   case X86ISD::VPERMILP:
22687   case X86ISD::VPERM2X128:
22688   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22689   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22690   case ISD::INTRINSIC_WO_CHAIN:
22691     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22692   case X86ISD::INSERTPS:
22693     return PerformINSERTPSCombine(N, DAG, Subtarget);
22694   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22695   }
22696
22697   return SDValue();
22698 }
22699
22700 /// isTypeDesirableForOp - Return true if the target has native support for
22701 /// the specified value type and it is 'desirable' to use the type for the
22702 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22703 /// instruction encodings are longer and some i16 instructions are slow.
22704 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22705   if (!isTypeLegal(VT))
22706     return false;
22707   if (VT != MVT::i16)
22708     return true;
22709
22710   switch (Opc) {
22711   default:
22712     return true;
22713   case ISD::LOAD:
22714   case ISD::SIGN_EXTEND:
22715   case ISD::ZERO_EXTEND:
22716   case ISD::ANY_EXTEND:
22717   case ISD::SHL:
22718   case ISD::SRL:
22719   case ISD::SUB:
22720   case ISD::ADD:
22721   case ISD::MUL:
22722   case ISD::AND:
22723   case ISD::OR:
22724   case ISD::XOR:
22725     return false;
22726   }
22727 }
22728
22729 /// IsDesirableToPromoteOp - This method query the target whether it is
22730 /// beneficial for dag combiner to promote the specified node. If true, it
22731 /// should return the desired promotion type by reference.
22732 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22733   EVT VT = Op.getValueType();
22734   if (VT != MVT::i16)
22735     return false;
22736
22737   bool Promote = false;
22738   bool Commute = false;
22739   switch (Op.getOpcode()) {
22740   default: break;
22741   case ISD::LOAD: {
22742     LoadSDNode *LD = cast<LoadSDNode>(Op);
22743     // If the non-extending load has a single use and it's not live out, then it
22744     // might be folded.
22745     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22746                                                      Op.hasOneUse()*/) {
22747       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22748              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22749         // The only case where we'd want to promote LOAD (rather then it being
22750         // promoted as an operand is when it's only use is liveout.
22751         if (UI->getOpcode() != ISD::CopyToReg)
22752           return false;
22753       }
22754     }
22755     Promote = true;
22756     break;
22757   }
22758   case ISD::SIGN_EXTEND:
22759   case ISD::ZERO_EXTEND:
22760   case ISD::ANY_EXTEND:
22761     Promote = true;
22762     break;
22763   case ISD::SHL:
22764   case ISD::SRL: {
22765     SDValue N0 = Op.getOperand(0);
22766     // Look out for (store (shl (load), x)).
22767     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22768       return false;
22769     Promote = true;
22770     break;
22771   }
22772   case ISD::ADD:
22773   case ISD::MUL:
22774   case ISD::AND:
22775   case ISD::OR:
22776   case ISD::XOR:
22777     Commute = true;
22778     // fallthrough
22779   case ISD::SUB: {
22780     SDValue N0 = Op.getOperand(0);
22781     SDValue N1 = Op.getOperand(1);
22782     if (!Commute && MayFoldLoad(N1))
22783       return false;
22784     // Avoid disabling potential load folding opportunities.
22785     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22786       return false;
22787     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22788       return false;
22789     Promote = true;
22790   }
22791   }
22792
22793   PVT = MVT::i32;
22794   return Promote;
22795 }
22796
22797 //===----------------------------------------------------------------------===//
22798 //                           X86 Inline Assembly Support
22799 //===----------------------------------------------------------------------===//
22800
22801 namespace {
22802   // Helper to match a string separated by whitespace.
22803   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22804     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22805
22806     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22807       StringRef piece(*args[i]);
22808       if (!s.startswith(piece)) // Check if the piece matches.
22809         return false;
22810
22811       s = s.substr(piece.size());
22812       StringRef::size_type pos = s.find_first_not_of(" \t");
22813       if (pos == 0) // We matched a prefix.
22814         return false;
22815
22816       s = s.substr(pos);
22817     }
22818
22819     return s.empty();
22820   }
22821   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22822 }
22823
22824 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22825
22826   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22827     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22828         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22829         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22830
22831       if (AsmPieces.size() == 3)
22832         return true;
22833       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22834         return true;
22835     }
22836   }
22837   return false;
22838 }
22839
22840 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22841   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22842
22843   std::string AsmStr = IA->getAsmString();
22844
22845   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22846   if (!Ty || Ty->getBitWidth() % 16 != 0)
22847     return false;
22848
22849   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22850   SmallVector<StringRef, 4> AsmPieces;
22851   SplitString(AsmStr, AsmPieces, ";\n");
22852
22853   switch (AsmPieces.size()) {
22854   default: return false;
22855   case 1:
22856     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22857     // we will turn this bswap into something that will be lowered to logical
22858     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22859     // lower so don't worry about this.
22860     // bswap $0
22861     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22862         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22863         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22864         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22865         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22866         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22867       // No need to check constraints, nothing other than the equivalent of
22868       // "=r,0" would be valid here.
22869       return IntrinsicLowering::LowerToByteSwap(CI);
22870     }
22871
22872     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22873     if (CI->getType()->isIntegerTy(16) &&
22874         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22875         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22876          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22877       AsmPieces.clear();
22878       const std::string &ConstraintsStr = IA->getConstraintString();
22879       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22880       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22881       if (clobbersFlagRegisters(AsmPieces))
22882         return IntrinsicLowering::LowerToByteSwap(CI);
22883     }
22884     break;
22885   case 3:
22886     if (CI->getType()->isIntegerTy(32) &&
22887         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22888         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22889         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22890         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22891       AsmPieces.clear();
22892       const std::string &ConstraintsStr = IA->getConstraintString();
22893       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22894       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22895       if (clobbersFlagRegisters(AsmPieces))
22896         return IntrinsicLowering::LowerToByteSwap(CI);
22897     }
22898
22899     if (CI->getType()->isIntegerTy(64)) {
22900       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22901       if (Constraints.size() >= 2 &&
22902           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22903           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22904         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22905         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22906             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22907             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22908           return IntrinsicLowering::LowerToByteSwap(CI);
22909       }
22910     }
22911     break;
22912   }
22913   return false;
22914 }
22915
22916 /// getConstraintType - Given a constraint letter, return the type of
22917 /// constraint it is for this target.
22918 X86TargetLowering::ConstraintType
22919 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22920   if (Constraint.size() == 1) {
22921     switch (Constraint[0]) {
22922     case 'R':
22923     case 'q':
22924     case 'Q':
22925     case 'f':
22926     case 't':
22927     case 'u':
22928     case 'y':
22929     case 'x':
22930     case 'Y':
22931     case 'l':
22932       return C_RegisterClass;
22933     case 'a':
22934     case 'b':
22935     case 'c':
22936     case 'd':
22937     case 'S':
22938     case 'D':
22939     case 'A':
22940       return C_Register;
22941     case 'I':
22942     case 'J':
22943     case 'K':
22944     case 'L':
22945     case 'M':
22946     case 'N':
22947     case 'G':
22948     case 'C':
22949     case 'e':
22950     case 'Z':
22951       return C_Other;
22952     default:
22953       break;
22954     }
22955   }
22956   return TargetLowering::getConstraintType(Constraint);
22957 }
22958
22959 /// Examine constraint type and operand type and determine a weight value.
22960 /// This object must already have been set up with the operand type
22961 /// and the current alternative constraint selected.
22962 TargetLowering::ConstraintWeight
22963   X86TargetLowering::getSingleConstraintMatchWeight(
22964     AsmOperandInfo &info, const char *constraint) const {
22965   ConstraintWeight weight = CW_Invalid;
22966   Value *CallOperandVal = info.CallOperandVal;
22967     // If we don't have a value, we can't do a match,
22968     // but allow it at the lowest weight.
22969   if (!CallOperandVal)
22970     return CW_Default;
22971   Type *type = CallOperandVal->getType();
22972   // Look at the constraint type.
22973   switch (*constraint) {
22974   default:
22975     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22976   case 'R':
22977   case 'q':
22978   case 'Q':
22979   case 'a':
22980   case 'b':
22981   case 'c':
22982   case 'd':
22983   case 'S':
22984   case 'D':
22985   case 'A':
22986     if (CallOperandVal->getType()->isIntegerTy())
22987       weight = CW_SpecificReg;
22988     break;
22989   case 'f':
22990   case 't':
22991   case 'u':
22992     if (type->isFloatingPointTy())
22993       weight = CW_SpecificReg;
22994     break;
22995   case 'y':
22996     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22997       weight = CW_SpecificReg;
22998     break;
22999   case 'x':
23000   case 'Y':
23001     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23002         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23003       weight = CW_Register;
23004     break;
23005   case 'I':
23006     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23007       if (C->getZExtValue() <= 31)
23008         weight = CW_Constant;
23009     }
23010     break;
23011   case 'J':
23012     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23013       if (C->getZExtValue() <= 63)
23014         weight = CW_Constant;
23015     }
23016     break;
23017   case 'K':
23018     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23019       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23020         weight = CW_Constant;
23021     }
23022     break;
23023   case 'L':
23024     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23025       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23026         weight = CW_Constant;
23027     }
23028     break;
23029   case 'M':
23030     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23031       if (C->getZExtValue() <= 3)
23032         weight = CW_Constant;
23033     }
23034     break;
23035   case 'N':
23036     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23037       if (C->getZExtValue() <= 0xff)
23038         weight = CW_Constant;
23039     }
23040     break;
23041   case 'G':
23042   case 'C':
23043     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23044       weight = CW_Constant;
23045     }
23046     break;
23047   case 'e':
23048     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23049       if ((C->getSExtValue() >= -0x80000000LL) &&
23050           (C->getSExtValue() <= 0x7fffffffLL))
23051         weight = CW_Constant;
23052     }
23053     break;
23054   case 'Z':
23055     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23056       if (C->getZExtValue() <= 0xffffffff)
23057         weight = CW_Constant;
23058     }
23059     break;
23060   }
23061   return weight;
23062 }
23063
23064 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23065 /// with another that has more specific requirements based on the type of the
23066 /// corresponding operand.
23067 const char *X86TargetLowering::
23068 LowerXConstraint(EVT ConstraintVT) const {
23069   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23070   // 'f' like normal targets.
23071   if (ConstraintVT.isFloatingPoint()) {
23072     if (Subtarget->hasSSE2())
23073       return "Y";
23074     if (Subtarget->hasSSE1())
23075       return "x";
23076   }
23077
23078   return TargetLowering::LowerXConstraint(ConstraintVT);
23079 }
23080
23081 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23082 /// vector.  If it is invalid, don't add anything to Ops.
23083 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23084                                                      std::string &Constraint,
23085                                                      std::vector<SDValue>&Ops,
23086                                                      SelectionDAG &DAG) const {
23087   SDValue Result;
23088
23089   // Only support length 1 constraints for now.
23090   if (Constraint.length() > 1) return;
23091
23092   char ConstraintLetter = Constraint[0];
23093   switch (ConstraintLetter) {
23094   default: break;
23095   case 'I':
23096     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23097       if (C->getZExtValue() <= 31) {
23098         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23099         break;
23100       }
23101     }
23102     return;
23103   case 'J':
23104     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23105       if (C->getZExtValue() <= 63) {
23106         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23107         break;
23108       }
23109     }
23110     return;
23111   case 'K':
23112     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23113       if (isInt<8>(C->getSExtValue())) {
23114         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23115         break;
23116       }
23117     }
23118     return;
23119   case 'N':
23120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23121       if (C->getZExtValue() <= 255) {
23122         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23123         break;
23124       }
23125     }
23126     return;
23127   case 'e': {
23128     // 32-bit signed value
23129     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23130       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23131                                            C->getSExtValue())) {
23132         // Widen to 64 bits here to get it sign extended.
23133         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23134         break;
23135       }
23136     // FIXME gcc accepts some relocatable values here too, but only in certain
23137     // memory models; it's complicated.
23138     }
23139     return;
23140   }
23141   case 'Z': {
23142     // 32-bit unsigned value
23143     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23144       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23145                                            C->getZExtValue())) {
23146         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23147         break;
23148       }
23149     }
23150     // FIXME gcc accepts some relocatable values here too, but only in certain
23151     // memory models; it's complicated.
23152     return;
23153   }
23154   case 'i': {
23155     // Literal immediates are always ok.
23156     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23157       // Widen to 64 bits here to get it sign extended.
23158       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23159       break;
23160     }
23161
23162     // In any sort of PIC mode addresses need to be computed at runtime by
23163     // adding in a register or some sort of table lookup.  These can't
23164     // be used as immediates.
23165     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23166       return;
23167
23168     // If we are in non-pic codegen mode, we allow the address of a global (with
23169     // an optional displacement) to be used with 'i'.
23170     GlobalAddressSDNode *GA = nullptr;
23171     int64_t Offset = 0;
23172
23173     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23174     while (1) {
23175       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23176         Offset += GA->getOffset();
23177         break;
23178       } else if (Op.getOpcode() == ISD::ADD) {
23179         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23180           Offset += C->getZExtValue();
23181           Op = Op.getOperand(0);
23182           continue;
23183         }
23184       } else if (Op.getOpcode() == ISD::SUB) {
23185         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23186           Offset += -C->getZExtValue();
23187           Op = Op.getOperand(0);
23188           continue;
23189         }
23190       }
23191
23192       // Otherwise, this isn't something we can handle, reject it.
23193       return;
23194     }
23195
23196     const GlobalValue *GV = GA->getGlobal();
23197     // If we require an extra load to get this address, as in PIC mode, we
23198     // can't accept it.
23199     if (isGlobalStubReference(
23200             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23201       return;
23202
23203     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23204                                         GA->getValueType(0), Offset);
23205     break;
23206   }
23207   }
23208
23209   if (Result.getNode()) {
23210     Ops.push_back(Result);
23211     return;
23212   }
23213   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23214 }
23215
23216 std::pair<unsigned, const TargetRegisterClass*>
23217 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23218                                                 MVT VT) const {
23219   // First, see if this is a constraint that directly corresponds to an LLVM
23220   // register class.
23221   if (Constraint.size() == 1) {
23222     // GCC Constraint Letters
23223     switch (Constraint[0]) {
23224     default: break;
23225       // TODO: Slight differences here in allocation order and leaving
23226       // RIP in the class. Do they matter any more here than they do
23227       // in the normal allocation?
23228     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23229       if (Subtarget->is64Bit()) {
23230         if (VT == MVT::i32 || VT == MVT::f32)
23231           return std::make_pair(0U, &X86::GR32RegClass);
23232         if (VT == MVT::i16)
23233           return std::make_pair(0U, &X86::GR16RegClass);
23234         if (VT == MVT::i8 || VT == MVT::i1)
23235           return std::make_pair(0U, &X86::GR8RegClass);
23236         if (VT == MVT::i64 || VT == MVT::f64)
23237           return std::make_pair(0U, &X86::GR64RegClass);
23238         break;
23239       }
23240       // 32-bit fallthrough
23241     case 'Q':   // Q_REGS
23242       if (VT == MVT::i32 || VT == MVT::f32)
23243         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23244       if (VT == MVT::i16)
23245         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23246       if (VT == MVT::i8 || VT == MVT::i1)
23247         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23248       if (VT == MVT::i64)
23249         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23250       break;
23251     case 'r':   // GENERAL_REGS
23252     case 'l':   // INDEX_REGS
23253       if (VT == MVT::i8 || VT == MVT::i1)
23254         return std::make_pair(0U, &X86::GR8RegClass);
23255       if (VT == MVT::i16)
23256         return std::make_pair(0U, &X86::GR16RegClass);
23257       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23258         return std::make_pair(0U, &X86::GR32RegClass);
23259       return std::make_pair(0U, &X86::GR64RegClass);
23260     case 'R':   // LEGACY_REGS
23261       if (VT == MVT::i8 || VT == MVT::i1)
23262         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23263       if (VT == MVT::i16)
23264         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23265       if (VT == MVT::i32 || !Subtarget->is64Bit())
23266         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23267       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23268     case 'f':  // FP Stack registers.
23269       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23270       // value to the correct fpstack register class.
23271       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23272         return std::make_pair(0U, &X86::RFP32RegClass);
23273       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23274         return std::make_pair(0U, &X86::RFP64RegClass);
23275       return std::make_pair(0U, &X86::RFP80RegClass);
23276     case 'y':   // MMX_REGS if MMX allowed.
23277       if (!Subtarget->hasMMX()) break;
23278       return std::make_pair(0U, &X86::VR64RegClass);
23279     case 'Y':   // SSE_REGS if SSE2 allowed
23280       if (!Subtarget->hasSSE2()) break;
23281       // FALL THROUGH.
23282     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23283       if (!Subtarget->hasSSE1()) break;
23284
23285       switch (VT.SimpleTy) {
23286       default: break;
23287       // Scalar SSE types.
23288       case MVT::f32:
23289       case MVT::i32:
23290         return std::make_pair(0U, &X86::FR32RegClass);
23291       case MVT::f64:
23292       case MVT::i64:
23293         return std::make_pair(0U, &X86::FR64RegClass);
23294       // Vector types.
23295       case MVT::v16i8:
23296       case MVT::v8i16:
23297       case MVT::v4i32:
23298       case MVT::v2i64:
23299       case MVT::v4f32:
23300       case MVT::v2f64:
23301         return std::make_pair(0U, &X86::VR128RegClass);
23302       // AVX types.
23303       case MVT::v32i8:
23304       case MVT::v16i16:
23305       case MVT::v8i32:
23306       case MVT::v4i64:
23307       case MVT::v8f32:
23308       case MVT::v4f64:
23309         return std::make_pair(0U, &X86::VR256RegClass);
23310       case MVT::v8f64:
23311       case MVT::v16f32:
23312       case MVT::v16i32:
23313       case MVT::v8i64:
23314         return std::make_pair(0U, &X86::VR512RegClass);
23315       }
23316       break;
23317     }
23318   }
23319
23320   // Use the default implementation in TargetLowering to convert the register
23321   // constraint into a member of a register class.
23322   std::pair<unsigned, const TargetRegisterClass*> Res;
23323   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23324
23325   // Not found as a standard register?
23326   if (!Res.second) {
23327     // Map st(0) -> st(7) -> ST0
23328     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23329         tolower(Constraint[1]) == 's' &&
23330         tolower(Constraint[2]) == 't' &&
23331         Constraint[3] == '(' &&
23332         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23333         Constraint[5] == ')' &&
23334         Constraint[6] == '}') {
23335
23336       Res.first = X86::ST0+Constraint[4]-'0';
23337       Res.second = &X86::RFP80RegClass;
23338       return Res;
23339     }
23340
23341     // GCC allows "st(0)" to be called just plain "st".
23342     if (StringRef("{st}").equals_lower(Constraint)) {
23343       Res.first = X86::ST0;
23344       Res.second = &X86::RFP80RegClass;
23345       return Res;
23346     }
23347
23348     // flags -> EFLAGS
23349     if (StringRef("{flags}").equals_lower(Constraint)) {
23350       Res.first = X86::EFLAGS;
23351       Res.second = &X86::CCRRegClass;
23352       return Res;
23353     }
23354
23355     // 'A' means EAX + EDX.
23356     if (Constraint == "A") {
23357       Res.first = X86::EAX;
23358       Res.second = &X86::GR32_ADRegClass;
23359       return Res;
23360     }
23361     return Res;
23362   }
23363
23364   // Otherwise, check to see if this is a register class of the wrong value
23365   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23366   // turn into {ax},{dx}.
23367   if (Res.second->hasType(VT))
23368     return Res;   // Correct type already, nothing to do.
23369
23370   // All of the single-register GCC register classes map their values onto
23371   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23372   // really want an 8-bit or 32-bit register, map to the appropriate register
23373   // class and return the appropriate register.
23374   if (Res.second == &X86::GR16RegClass) {
23375     if (VT == MVT::i8 || VT == MVT::i1) {
23376       unsigned DestReg = 0;
23377       switch (Res.first) {
23378       default: break;
23379       case X86::AX: DestReg = X86::AL; break;
23380       case X86::DX: DestReg = X86::DL; break;
23381       case X86::CX: DestReg = X86::CL; break;
23382       case X86::BX: DestReg = X86::BL; break;
23383       }
23384       if (DestReg) {
23385         Res.first = DestReg;
23386         Res.second = &X86::GR8RegClass;
23387       }
23388     } else if (VT == MVT::i32 || VT == MVT::f32) {
23389       unsigned DestReg = 0;
23390       switch (Res.first) {
23391       default: break;
23392       case X86::AX: DestReg = X86::EAX; break;
23393       case X86::DX: DestReg = X86::EDX; break;
23394       case X86::CX: DestReg = X86::ECX; break;
23395       case X86::BX: DestReg = X86::EBX; break;
23396       case X86::SI: DestReg = X86::ESI; break;
23397       case X86::DI: DestReg = X86::EDI; break;
23398       case X86::BP: DestReg = X86::EBP; break;
23399       case X86::SP: DestReg = X86::ESP; break;
23400       }
23401       if (DestReg) {
23402         Res.first = DestReg;
23403         Res.second = &X86::GR32RegClass;
23404       }
23405     } else if (VT == MVT::i64 || VT == MVT::f64) {
23406       unsigned DestReg = 0;
23407       switch (Res.first) {
23408       default: break;
23409       case X86::AX: DestReg = X86::RAX; break;
23410       case X86::DX: DestReg = X86::RDX; break;
23411       case X86::CX: DestReg = X86::RCX; break;
23412       case X86::BX: DestReg = X86::RBX; break;
23413       case X86::SI: DestReg = X86::RSI; break;
23414       case X86::DI: DestReg = X86::RDI; break;
23415       case X86::BP: DestReg = X86::RBP; break;
23416       case X86::SP: DestReg = X86::RSP; break;
23417       }
23418       if (DestReg) {
23419         Res.first = DestReg;
23420         Res.second = &X86::GR64RegClass;
23421       }
23422     }
23423   } else if (Res.second == &X86::FR32RegClass ||
23424              Res.second == &X86::FR64RegClass ||
23425              Res.second == &X86::VR128RegClass ||
23426              Res.second == &X86::VR256RegClass ||
23427              Res.second == &X86::FR32XRegClass ||
23428              Res.second == &X86::FR64XRegClass ||
23429              Res.second == &X86::VR128XRegClass ||
23430              Res.second == &X86::VR256XRegClass ||
23431              Res.second == &X86::VR512RegClass) {
23432     // Handle references to XMM physical registers that got mapped into the
23433     // wrong class.  This can happen with constraints like {xmm0} where the
23434     // target independent register mapper will just pick the first match it can
23435     // find, ignoring the required type.
23436
23437     if (VT == MVT::f32 || VT == MVT::i32)
23438       Res.second = &X86::FR32RegClass;
23439     else if (VT == MVT::f64 || VT == MVT::i64)
23440       Res.second = &X86::FR64RegClass;
23441     else if (X86::VR128RegClass.hasType(VT))
23442       Res.second = &X86::VR128RegClass;
23443     else if (X86::VR256RegClass.hasType(VT))
23444       Res.second = &X86::VR256RegClass;
23445     else if (X86::VR512RegClass.hasType(VT))
23446       Res.second = &X86::VR512RegClass;
23447   }
23448
23449   return Res;
23450 }
23451
23452 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23453                                             Type *Ty) const {
23454   // Scaling factors are not free at all.
23455   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23456   // will take 2 allocations in the out of order engine instead of 1
23457   // for plain addressing mode, i.e. inst (reg1).
23458   // E.g.,
23459   // vaddps (%rsi,%drx), %ymm0, %ymm1
23460   // Requires two allocations (one for the load, one for the computation)
23461   // whereas:
23462   // vaddps (%rsi), %ymm0, %ymm1
23463   // Requires just 1 allocation, i.e., freeing allocations for other operations
23464   // and having less micro operations to execute.
23465   //
23466   // For some X86 architectures, this is even worse because for instance for
23467   // stores, the complex addressing mode forces the instruction to use the
23468   // "load" ports instead of the dedicated "store" port.
23469   // E.g., on Haswell:
23470   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23471   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23472   if (isLegalAddressingMode(AM, Ty))
23473     // Scale represents reg2 * scale, thus account for 1
23474     // as soon as we use a second register.
23475     return AM.Scale != 0;
23476   return -1;
23477 }
23478
23479 bool X86TargetLowering::isTargetFTOL() const {
23480   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23481 }