Delete getAliasedGlobal.
[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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
182   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183   bool is64Bit = Subtarget->is64Bit();
184
185   if (Subtarget->isTargetMacho()) {
186     if (is64Bit)
187       return new X86_64MachoTargetObjectFile();
188     return new TargetLoweringObjectFileMachO();
189   }
190
191   if (Subtarget->isTargetLinux())
192     return new X86LinuxTargetObjectFile();
193   if (Subtarget->isTargetELF())
194     return new TargetLoweringObjectFileELF();
195   if (Subtarget->isTargetKnownWindowsMSVC())
196     return new X86WindowsTargetObjectFile();
197   if (Subtarget->isTargetCOFF())
198     return new TargetLoweringObjectFileCOFF();
199   llvm_unreachable("unknown subtarget type");
200 }
201
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203   : TargetLowering(TM, createTLOF(TM)) {
204   Subtarget = &TM.getSubtarget<X86Subtarget>();
205   X86ScalarSSEf64 = Subtarget->hasSSE2();
206   X86ScalarSSEf32 = Subtarget->hasSSE1();
207   TD = getDataLayout();
208
209   resetOperationActions();
210 }
211
212 void X86TargetLowering::resetOperationActions() {
213   const TargetMachine &TM = getTargetMachine();
214   static bool FirstTimeThrough = true;
215
216   // If none of the target options have changed, then we don't need to reset the
217   // operation actions.
218   if (!FirstTimeThrough && TO == TM.Options) return;
219
220   if (!FirstTimeThrough) {
221     // Reinitialize the actions.
222     initActions();
223     FirstTimeThrough = false;
224   }
225
226   TO = TM.Options;
227
228   // Set up the TargetLowering object.
229   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230
231   // X86 is weird, it always uses i8 for shift amounts and setcc results.
232   setBooleanContents(ZeroOrOneBooleanContent);
233   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235
236   // For 64-bit since we have so many registers use the ILP scheduler, for
237   // 32-bit code use the register pressure specific scheduling.
238   // For Atom, always use ILP scheduling.
239   if (Subtarget->isAtom())
240     setSchedulingPreference(Sched::ILP);
241   else if (Subtarget->is64Bit())
242     setSchedulingPreference(Sched::ILP);
243   else
244     setSchedulingPreference(Sched::RegPressure);
245   const X86RegisterInfo *RegInfo =
246     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248
249   // Bypass expensive divides on Atom when compiling with O2
250   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251     addBypassSlowDiv(32, 8);
252     if (Subtarget->is64Bit())
253       addBypassSlowDiv(64, 16);
254   }
255
256   if (Subtarget->isTargetKnownWindowsMSVC()) {
257     // Setup Windows compiler runtime calls.
258     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260     setLibcallName(RTLIB::SREM_I64, "_allrem");
261     setLibcallName(RTLIB::UREM_I64, "_aullrem");
262     setLibcallName(RTLIB::MUL_I64, "_allmul");
263     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268
269     // The _ftol2 runtime function has an unusual calling conv, which
270     // is modeled by a special pseudo-instruction.
271     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275   }
276
277   if (Subtarget->isTargetDarwin()) {
278     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279     setUseUnderscoreSetJmp(false);
280     setUseUnderscoreLongJmp(false);
281   } else if (Subtarget->isTargetWindowsGNU()) {
282     // MS runtime is weird: it exports _setjmp, but longjmp!
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(false);
285   } else {
286     setUseUnderscoreSetJmp(true);
287     setUseUnderscoreLongJmp(true);
288   }
289
290   // Set up the register classes.
291   addRegisterClass(MVT::i8, &X86::GR8RegClass);
292   addRegisterClass(MVT::i16, &X86::GR16RegClass);
293   addRegisterClass(MVT::i32, &X86::GR32RegClass);
294   if (Subtarget->is64Bit())
295     addRegisterClass(MVT::i64, &X86::GR64RegClass);
296
297   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298
299   // We don't accept any truncstore of integer registers.
300   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
447   if (Subtarget->is64Bit())
448     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
450   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
451   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
452   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
454   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
455   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
456   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
457
458   // Promote the i8 variants and force them on up to i32 which has a shorter
459   // encoding.
460   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
462   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
463   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
464   if (Subtarget->hasBMI()) {
465     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
466     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
469   } else {
470     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
471     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
472     if (Subtarget->is64Bit())
473       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
474   }
475
476   if (Subtarget->hasLZCNT()) {
477     // When promoting the i8 variants, force them to i32 for a shorter
478     // encoding.
479     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
482     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
483     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
492     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
494     if (Subtarget->is64Bit()) {
495       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
496       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497     }
498   }
499
500   if (Subtarget->hasPOPCNT()) {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
502   } else {
503     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
504     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
505     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
506     if (Subtarget->is64Bit())
507       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
508   }
509
510   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
511
512   if (!Subtarget->hasMOVBE())
513     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
514
515   // These should be promoted to a larger select which is supported.
516   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
517   // X86 wants to expand cmov itself.
518   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
519   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
530   if (Subtarget->is64Bit()) {
531     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
532     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
533   }
534   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
535   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537   // support continuation, user-level threading, and etc.. As a result, no
538   // other SjLj exception interfaces are implemented and please don't build
539   // your own exception handling based on them.
540   // LLVM/Clang supports zero-cost DWARF exception handling.
541   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543
544   // Darwin ABI issue.
545   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
546   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
547   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
548   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
549   if (Subtarget->is64Bit())
550     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
552   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
553   if (Subtarget->is64Bit()) {
554     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
555     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
556     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
557     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
558     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
559   }
560   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
562   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
563   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
566     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
567     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
568   }
569
570   if (Subtarget->hasSSE1())
571     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
572
573   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
574
575   // Expand certain atomics
576   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
577     MVT VT = IntVTs[i];
578     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581   }
582
583   if (!Subtarget->is64Bit()) {
584     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596   }
597
598   if (Subtarget->hasCmpxchg16b()) {
599     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600   }
601
602   // FIXME - use subtarget debug flags
603   if (!Subtarget->isTargetDarwin() &&
604       !Subtarget->isTargetELF() &&
605       !Subtarget->isTargetCygMing()) {
606     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607   }
608
609   if (Subtarget->is64Bit()) {
610     setExceptionPointerRegister(X86::RAX);
611     setExceptionSelectorRegister(X86::RDX);
612   } else {
613     setExceptionPointerRegister(X86::EAX);
614     setExceptionSelectorRegister(X86::EDX);
615   }
616   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
618
619   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
621
622   setOperationAction(ISD::TRAP, MVT::Other, Legal);
623   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
624
625   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
627   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
628   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629     // TargetInfo::X86_64ABIBuiltinVaList
630     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
631     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
632   } else {
633     // TargetInfo::CharPtrBuiltinVaList
634     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
635     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
636   }
637
638   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
639   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
640
641   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                      MVT::i64 : MVT::i32, Custom);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::MULHS, VT, Expand);
832     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::MULHU, VT, Expand);
834     setOperationAction(ISD::SDIVREM, VT, Expand);
835     setOperationAction(ISD::UDIVREM, VT, Expand);
836     setOperationAction(ISD::FPOW, VT, Expand);
837     setOperationAction(ISD::CTPOP, VT, Expand);
838     setOperationAction(ISD::CTTZ, VT, Expand);
839     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::CTLZ, VT, Expand);
841     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::SHL, VT, Expand);
843     setOperationAction(ISD::SRA, VT, Expand);
844     setOperationAction(ISD::SRL, VT, Expand);
845     setOperationAction(ISD::ROTL, VT, Expand);
846     setOperationAction(ISD::ROTR, VT, Expand);
847     setOperationAction(ISD::BSWAP, VT, Expand);
848     setOperationAction(ISD::SETCC, VT, Expand);
849     setOperationAction(ISD::FLOG, VT, Expand);
850     setOperationAction(ISD::FLOG2, VT, Expand);
851     setOperationAction(ISD::FLOG10, VT, Expand);
852     setOperationAction(ISD::FEXP, VT, Expand);
853     setOperationAction(ISD::FEXP2, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::VSELECT, VT, Expand);
864     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866       setTruncStoreAction(VT,
867                           (MVT::SimpleValueType)InnerVT, Expand);
868     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871   }
872
873   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874   // with -msoft-float, disable use of MMX as well.
875   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877     // No operations on x86mmx supported, everything uses intrinsics.
878   }
879
880   // MMX-sized vectors (other than x86mmx) are expected to be expanded
881   // into smaller operations.
882   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
883   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
885   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
886   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
888   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
889   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
890   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
891   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
892   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
893   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
894   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
895   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
896   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
897   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
902   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
904   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
906   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
911
912   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914
915     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
920     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
921     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
922     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
927   }
928
929   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931
932     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933     // registers cannot be used even for integer operations.
934     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938
939     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
940     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
941     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
942     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
943     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
944     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
945     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
946     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
947     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
948     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
950     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
951     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
952     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
953     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
954     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
957     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
958     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
959     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
960     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
961
962     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
964     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
965     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
966
967     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
968     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
971     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
972
973     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975       MVT VT = (MVT::SimpleValueType)i;
976       // Do not attempt to custom lower non-power-of-2 vectors
977       if (!isPowerOf2_32(VT.getVectorNumElements()))
978         continue;
979       // Do not attempt to custom lower non-128-bit vectors
980       if (!VT.is128BitVector())
981         continue;
982       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
984       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985     }
986
987     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
988     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
990     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
993
994     if (Subtarget->is64Bit()) {
995       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997     }
998
999     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002
1003       // Do not attempt to promote non-128-bit vectors
1004       if (!VT.is128BitVector())
1005         continue;
1006
1007       setOperationAction(ISD::AND,    VT, Promote);
1008       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1009       setOperationAction(ISD::OR,     VT, Promote);
1010       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1011       setOperationAction(ISD::XOR,    VT, Promote);
1012       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1013       setOperationAction(ISD::LOAD,   VT, Promote);
1014       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1015       setOperationAction(ISD::SELECT, VT, Promote);
1016       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017     }
1018
1019     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1020
1021     // Custom lower v2i64 and v2f64 selects.
1022     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1024     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1025     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1026
1027     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1028     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1029
1030     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1031     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1032     // As there is no 64-bit GPR available, we need build a special custom
1033     // sequence to convert from v2i32 to v2f32.
1034     if (!Subtarget->is64Bit())
1035       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1036
1037     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1038     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1039
1040     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1041
1042     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1043   }
1044
1045   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1046     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1049     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1051     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1052     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1053     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1054     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1055     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1056
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1062     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1063     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1064     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1065     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1066     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1067
1068     // FIXME: Do we need to handle scalar-to-vector here?
1069     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1072     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1073     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1074     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1075     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1076
1077     // i8 and i16 vectors are custom , because the source register and source
1078     // source memory operand types are not the same width.  f32 vectors are
1079     // custom since the immediate controlling the insert encodes additional
1080     // information.
1081     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1082     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1083     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1085
1086     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1087     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1088     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1089     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1090
1091     // FIXME: these should be Legal but thats only for the case where
1092     // the index is constant.  For now custom expand to deal with that.
1093     if (Subtarget->is64Bit()) {
1094       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1095       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1096     }
1097   }
1098
1099   if (Subtarget->hasSSE2()) {
1100     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1101     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1102
1103     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1104     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1105
1106     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1107     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1108
1109     // In the customized shift lowering, the legal cases in AVX2 will be
1110     // recognized.
1111     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1112     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1113
1114     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1115     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1116
1117     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1118   }
1119
1120   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1121     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1123     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1125     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1126     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1127
1128     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1130     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1131
1132     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1134     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1136     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1137     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1138     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1139     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1140     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1141     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1142     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1143     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1144
1145     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1149     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1150     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1151     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1152     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1153     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1154     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1155     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1156     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1157
1158     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1159     // even though v8i16 is a legal type.
1160     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1161     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1162     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1163
1164     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1165     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1166     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1167
1168     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1169     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1170
1171     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1172
1173     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1174     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1175
1176     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1177     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1178
1179     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1180     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1181
1182     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1184     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1185     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1186
1187     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1188     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1189     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1190
1191     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1193     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1194     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1195
1196     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1199     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1200     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1201     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1202     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1203     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1204     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1205     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1206     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1207     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1208
1209     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1210       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1212       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1214       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1215       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1216     }
1217
1218     if (Subtarget->hasInt256()) {
1219       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1225       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1227       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1228
1229       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1230       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1231       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1232       // Don't lower v32i8 because there is no 128-bit byte mul
1233
1234       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1235       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1236       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1237       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1238
1239       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1240     } else {
1241       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1242       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1243       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1244       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1245
1246       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1247       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1248       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1249       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1250
1251       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1252       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1253       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1254       // Don't lower v32i8 because there is no 128-bit byte mul
1255     }
1256
1257     // In the customized shift lowering, the legal cases in AVX2 will be
1258     // recognized.
1259     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1261
1262     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1264
1265     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1266
1267     // Custom lower several nodes for 256-bit types.
1268     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1269              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1270       MVT VT = (MVT::SimpleValueType)i;
1271
1272       // Extract subvector is special because the value type
1273       // (result) is 128-bit but the source is 256-bit wide.
1274       if (VT.is128BitVector())
1275         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276
1277       // Do not attempt to custom lower other non-256-bit vectors
1278       if (!VT.is256BitVector())
1279         continue;
1280
1281       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1282       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1283       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1284       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1286       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1287       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1288     }
1289
1290     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1291     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1292       MVT VT = (MVT::SimpleValueType)i;
1293
1294       // Do not attempt to promote non-256-bit vectors
1295       if (!VT.is256BitVector())
1296         continue;
1297
1298       setOperationAction(ISD::AND,    VT, Promote);
1299       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1300       setOperationAction(ISD::OR,     VT, Promote);
1301       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1302       setOperationAction(ISD::XOR,    VT, Promote);
1303       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1304       setOperationAction(ISD::LOAD,   VT, Promote);
1305       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1306       setOperationAction(ISD::SELECT, VT, Promote);
1307       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308     }
1309   }
1310
1311   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1312     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1315     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1316
1317     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1318     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1319     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1320
1321     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1322     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1323     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1324     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1325     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1326     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1329     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1332
1333     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1339
1340     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1342     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1343     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1346     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1347     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1348
1349     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1352     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1353     if (Subtarget->is64Bit()) {
1354       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1355       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1356       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1357       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1358     }
1359     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1365     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1366     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1367     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1368     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1369
1370     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1373     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1374     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1375     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1376     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1377     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1379     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1380     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1381     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1382     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1383
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405
1406     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1407     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1408
1409     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1410     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1411
1412     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1413
1414     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1415     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1416
1417     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1418     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1419
1420     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1421     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1422
1423     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1424     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1425     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1426     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1427     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1428     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1429
1430     // Custom lower several nodes.
1431     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1432              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1433       MVT VT = (MVT::SimpleValueType)i;
1434
1435       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1436       // Extract subvector is special because the value type
1437       // (result) is 256/128-bit but the source is 512-bit wide.
1438       if (VT.is128BitVector() || VT.is256BitVector())
1439         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1440
1441       if (VT.getVectorElementType() == MVT::i1)
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1443
1444       // Do not attempt to custom lower other non-512-bit vectors
1445       if (!VT.is512BitVector())
1446         continue;
1447
1448       if ( EltSize >= 32) {
1449         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1450         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1451         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1452         setOperationAction(ISD::VSELECT,             VT, Legal);
1453         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1454         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1455         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1456       }
1457     }
1458     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1459       MVT VT = (MVT::SimpleValueType)i;
1460
1461       // Do not attempt to promote non-256-bit vectors
1462       if (!VT.is512BitVector())
1463         continue;
1464
1465       setOperationAction(ISD::SELECT, VT, Promote);
1466       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1467     }
1468   }// has  AVX-512
1469
1470   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1471   // of this type with custom code.
1472   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1473            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1474     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1475                        Custom);
1476   }
1477
1478   // We want to custom lower some of our intrinsics.
1479   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1480   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1481   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1482   if (!Subtarget->is64Bit())
1483     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1484
1485   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1486   // handle type legalization for these operations here.
1487   //
1488   // FIXME: We really should do custom legalization for addition and
1489   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1490   // than generic legalization for 64-bit multiplication-with-overflow, though.
1491   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1492     // Add/Sub/Mul with overflow operations are custom lowered.
1493     MVT VT = IntVTs[i];
1494     setOperationAction(ISD::SADDO, VT, Custom);
1495     setOperationAction(ISD::UADDO, VT, Custom);
1496     setOperationAction(ISD::SSUBO, VT, Custom);
1497     setOperationAction(ISD::USUBO, VT, Custom);
1498     setOperationAction(ISD::SMULO, VT, Custom);
1499     setOperationAction(ISD::UMULO, VT, Custom);
1500   }
1501
1502   // There are no 8-bit 3-address imul/mul instructions
1503   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1504   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1505
1506   if (!Subtarget->is64Bit()) {
1507     // These libcalls are not available in 32-bit.
1508     setLibcallName(RTLIB::SHL_I128, nullptr);
1509     setLibcallName(RTLIB::SRL_I128, nullptr);
1510     setLibcallName(RTLIB::SRA_I128, nullptr);
1511   }
1512
1513   // Combine sin / cos into one node or libcall if possible.
1514   if (Subtarget->hasSinCos()) {
1515     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1516     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1517     if (Subtarget->isTargetDarwin()) {
1518       // For MacOSX, we don't want to the normal expansion of a libcall to
1519       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1520       // traffic.
1521       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1522       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1523     }
1524   }
1525
1526   if (Subtarget->isTargetWin64()) {
1527     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1528     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1529     setOperationAction(ISD::SREM, MVT::i128, Custom);
1530     setOperationAction(ISD::UREM, MVT::i128, Custom);
1531     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1532     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1533   }
1534
1535   // We have target-specific dag combine patterns for the following nodes:
1536   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1537   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1538   setTargetDAGCombine(ISD::VSELECT);
1539   setTargetDAGCombine(ISD::SELECT);
1540   setTargetDAGCombine(ISD::SHL);
1541   setTargetDAGCombine(ISD::SRA);
1542   setTargetDAGCombine(ISD::SRL);
1543   setTargetDAGCombine(ISD::OR);
1544   setTargetDAGCombine(ISD::AND);
1545   setTargetDAGCombine(ISD::ADD);
1546   setTargetDAGCombine(ISD::FADD);
1547   setTargetDAGCombine(ISD::FSUB);
1548   setTargetDAGCombine(ISD::FMA);
1549   setTargetDAGCombine(ISD::SUB);
1550   setTargetDAGCombine(ISD::LOAD);
1551   setTargetDAGCombine(ISD::STORE);
1552   setTargetDAGCombine(ISD::ZERO_EXTEND);
1553   setTargetDAGCombine(ISD::ANY_EXTEND);
1554   setTargetDAGCombine(ISD::SIGN_EXTEND);
1555   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1556   setTargetDAGCombine(ISD::TRUNCATE);
1557   setTargetDAGCombine(ISD::SINT_TO_FP);
1558   setTargetDAGCombine(ISD::SETCC);
1559   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1560   if (Subtarget->is64Bit())
1561     setTargetDAGCombine(ISD::MUL);
1562   setTargetDAGCombine(ISD::XOR);
1563
1564   computeRegisterProperties();
1565
1566   // On Darwin, -Os means optimize for size without hurting performance,
1567   // do not reduce the limit.
1568   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1569   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1570   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1571   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1572   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1573   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1574   setPrefLoopAlignment(4); // 2^4 bytes.
1575
1576   // Predictable cmov don't hurt on atom because it's in-order.
1577   PredictableSelectIsExpensive = !Subtarget->isAtom();
1578
1579   setPrefFunctionAlignment(4); // 2^4 bytes.
1580 }
1581
1582 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1583   if (!VT.isVector())
1584     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1585
1586   if (Subtarget->hasAVX512())
1587     switch(VT.getVectorNumElements()) {
1588     case  8: return MVT::v8i1;
1589     case 16: return MVT::v16i1;
1590   }
1591
1592   return VT.changeVectorElementTypeToInteger();
1593 }
1594
1595 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1596 /// the desired ByVal argument alignment.
1597 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1598   if (MaxAlign == 16)
1599     return;
1600   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1601     if (VTy->getBitWidth() == 128)
1602       MaxAlign = 16;
1603   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1604     unsigned EltAlign = 0;
1605     getMaxByValAlign(ATy->getElementType(), EltAlign);
1606     if (EltAlign > MaxAlign)
1607       MaxAlign = EltAlign;
1608   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1609     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1610       unsigned EltAlign = 0;
1611       getMaxByValAlign(STy->getElementType(i), EltAlign);
1612       if (EltAlign > MaxAlign)
1613         MaxAlign = EltAlign;
1614       if (MaxAlign == 16)
1615         break;
1616     }
1617   }
1618 }
1619
1620 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1621 /// function arguments in the caller parameter area. For X86, aggregates
1622 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1623 /// are at 4-byte boundaries.
1624 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1625   if (Subtarget->is64Bit()) {
1626     // Max of 8 and alignment of type.
1627     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1628     if (TyAlign > 8)
1629       return TyAlign;
1630     return 8;
1631   }
1632
1633   unsigned Align = 4;
1634   if (Subtarget->hasSSE1())
1635     getMaxByValAlign(Ty, Align);
1636   return Align;
1637 }
1638
1639 /// getOptimalMemOpType - Returns the target specific optimal type for load
1640 /// and store operations as a result of memset, memcpy, and memmove
1641 /// lowering. If DstAlign is zero that means it's safe to destination
1642 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1643 /// means there isn't a need to check it against alignment requirement,
1644 /// probably because the source does not need to be loaded. If 'IsMemset' is
1645 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1646 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1647 /// source is constant so it does not need to be loaded.
1648 /// It returns EVT::Other if the type should be determined using generic
1649 /// target-independent logic.
1650 EVT
1651 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1652                                        unsigned DstAlign, unsigned SrcAlign,
1653                                        bool IsMemset, bool ZeroMemset,
1654                                        bool MemcpyStrSrc,
1655                                        MachineFunction &MF) const {
1656   const Function *F = MF.getFunction();
1657   if ((!IsMemset || ZeroMemset) &&
1658       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1659                                        Attribute::NoImplicitFloat)) {
1660     if (Size >= 16 &&
1661         (Subtarget->isUnalignedMemAccessFast() ||
1662          ((DstAlign == 0 || DstAlign >= 16) &&
1663           (SrcAlign == 0 || SrcAlign >= 16)))) {
1664       if (Size >= 32) {
1665         if (Subtarget->hasInt256())
1666           return MVT::v8i32;
1667         if (Subtarget->hasFp256())
1668           return MVT::v8f32;
1669       }
1670       if (Subtarget->hasSSE2())
1671         return MVT::v4i32;
1672       if (Subtarget->hasSSE1())
1673         return MVT::v4f32;
1674     } else if (!MemcpyStrSrc && Size >= 8 &&
1675                !Subtarget->is64Bit() &&
1676                Subtarget->hasSSE2()) {
1677       // Do not use f64 to lower memcpy if source is string constant. It's
1678       // better to use i32 to avoid the loads.
1679       return MVT::f64;
1680     }
1681   }
1682   if (Subtarget->is64Bit() && Size >= 8)
1683     return MVT::i64;
1684   return MVT::i32;
1685 }
1686
1687 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1688   if (VT == MVT::f32)
1689     return X86ScalarSSEf32;
1690   else if (VT == MVT::f64)
1691     return X86ScalarSSEf64;
1692   return true;
1693 }
1694
1695 bool
1696 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1697                                                  unsigned,
1698                                                  bool *Fast) const {
1699   if (Fast)
1700     *Fast = Subtarget->isUnalignedMemAccessFast();
1701   return true;
1702 }
1703
1704 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1705 /// current function.  The returned value is a member of the
1706 /// MachineJumpTableInfo::JTEntryKind enum.
1707 unsigned X86TargetLowering::getJumpTableEncoding() const {
1708   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1709   // symbol.
1710   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1711       Subtarget->isPICStyleGOT())
1712     return MachineJumpTableInfo::EK_Custom32;
1713
1714   // Otherwise, use the normal jump table encoding heuristics.
1715   return TargetLowering::getJumpTableEncoding();
1716 }
1717
1718 const MCExpr *
1719 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1720                                              const MachineBasicBlock *MBB,
1721                                              unsigned uid,MCContext &Ctx) const{
1722   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1723          Subtarget->isPICStyleGOT());
1724   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1725   // entries.
1726   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1727                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1728 }
1729
1730 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1731 /// jumptable.
1732 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1733                                                     SelectionDAG &DAG) const {
1734   if (!Subtarget->is64Bit())
1735     // This doesn't have SDLoc associated with it, but is not really the
1736     // same as a Register.
1737     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1738   return Table;
1739 }
1740
1741 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1742 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1743 /// MCExpr.
1744 const MCExpr *X86TargetLowering::
1745 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1746                              MCContext &Ctx) const {
1747   // X86-64 uses RIP relative addressing based on the jump table label.
1748   if (Subtarget->isPICStyleRIPRel())
1749     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1750
1751   // Otherwise, the reference is relative to the PIC base.
1752   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1753 }
1754
1755 // FIXME: Why this routine is here? Move to RegInfo!
1756 std::pair<const TargetRegisterClass*, uint8_t>
1757 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1758   const TargetRegisterClass *RRC = nullptr;
1759   uint8_t Cost = 1;
1760   switch (VT.SimpleTy) {
1761   default:
1762     return TargetLowering::findRepresentativeClass(VT);
1763   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1764     RRC = Subtarget->is64Bit() ?
1765       (const TargetRegisterClass*)&X86::GR64RegClass :
1766       (const TargetRegisterClass*)&X86::GR32RegClass;
1767     break;
1768   case MVT::x86mmx:
1769     RRC = &X86::VR64RegClass;
1770     break;
1771   case MVT::f32: case MVT::f64:
1772   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1773   case MVT::v4f32: case MVT::v2f64:
1774   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1775   case MVT::v4f64:
1776     RRC = &X86::VR128RegClass;
1777     break;
1778   }
1779   return std::make_pair(RRC, Cost);
1780 }
1781
1782 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1783                                                unsigned &Offset) const {
1784   if (!Subtarget->isTargetLinux())
1785     return false;
1786
1787   if (Subtarget->is64Bit()) {
1788     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1789     Offset = 0x28;
1790     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1791       AddressSpace = 256;
1792     else
1793       AddressSpace = 257;
1794   } else {
1795     // %gs:0x14 on i386
1796     Offset = 0x14;
1797     AddressSpace = 256;
1798   }
1799   return true;
1800 }
1801
1802 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1803                                             unsigned DestAS) const {
1804   assert(SrcAS != DestAS && "Expected different address spaces!");
1805
1806   return SrcAS < 256 && DestAS < 256;
1807 }
1808
1809 //===----------------------------------------------------------------------===//
1810 //               Return Value Calling Convention Implementation
1811 //===----------------------------------------------------------------------===//
1812
1813 #include "X86GenCallingConv.inc"
1814
1815 bool
1816 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1817                                   MachineFunction &MF, bool isVarArg,
1818                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1819                         LLVMContext &Context) const {
1820   SmallVector<CCValAssign, 16> RVLocs;
1821   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822                  RVLocs, Context);
1823   return CCInfo.CheckReturn(Outs, RetCC_X86);
1824 }
1825
1826 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1827   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1828   return ScratchRegs;
1829 }
1830
1831 SDValue
1832 X86TargetLowering::LowerReturn(SDValue Chain,
1833                                CallingConv::ID CallConv, bool isVarArg,
1834                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1835                                const SmallVectorImpl<SDValue> &OutVals,
1836                                SDLoc dl, SelectionDAG &DAG) const {
1837   MachineFunction &MF = DAG.getMachineFunction();
1838   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1839
1840   SmallVector<CCValAssign, 16> RVLocs;
1841   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1842                  RVLocs, *DAG.getContext());
1843   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1844
1845   SDValue Flag;
1846   SmallVector<SDValue, 6> RetOps;
1847   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1848   // Operand #1 = Bytes To Pop
1849   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1850                    MVT::i16));
1851
1852   // Copy the result values into the output registers.
1853   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1854     CCValAssign &VA = RVLocs[i];
1855     assert(VA.isRegLoc() && "Can only return in registers!");
1856     SDValue ValToCopy = OutVals[i];
1857     EVT ValVT = ValToCopy.getValueType();
1858
1859     // Promote values to the appropriate types
1860     if (VA.getLocInfo() == CCValAssign::SExt)
1861       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1862     else if (VA.getLocInfo() == CCValAssign::ZExt)
1863       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1864     else if (VA.getLocInfo() == CCValAssign::AExt)
1865       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866     else if (VA.getLocInfo() == CCValAssign::BCvt)
1867       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1868
1869     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1870            "Unexpected FP-extend for return value.");  
1871
1872     // If this is x86-64, and we disabled SSE, we can't return FP values,
1873     // or SSE or MMX vectors.
1874     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1875          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1876           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1877       report_fatal_error("SSE register return with SSE disabled");
1878     }
1879     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1880     // llvm-gcc has never done it right and no one has noticed, so this
1881     // should be OK for now.
1882     if (ValVT == MVT::f64 &&
1883         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1884       report_fatal_error("SSE2 register return with SSE2 disabled");
1885
1886     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1887     // the RET instruction and handled by the FP Stackifier.
1888     if (VA.getLocReg() == X86::ST0 ||
1889         VA.getLocReg() == X86::ST1) {
1890       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1891       // change the value to the FP stack register class.
1892       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1893         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1894       RetOps.push_back(ValToCopy);
1895       // Don't emit a copytoreg.
1896       continue;
1897     }
1898
1899     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1900     // which is returned in RAX / RDX.
1901     if (Subtarget->is64Bit()) {
1902       if (ValVT == MVT::x86mmx) {
1903         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1904           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1905           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1906                                   ValToCopy);
1907           // If we don't have SSE2 available, convert to v4f32 so the generated
1908           // register is legal.
1909           if (!Subtarget->hasSSE2())
1910             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1911         }
1912       }
1913     }
1914
1915     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1916     Flag = Chain.getValue(1);
1917     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1918   }
1919
1920   // The x86-64 ABIs require that for returning structs by value we copy
1921   // the sret argument into %rax/%eax (depending on ABI) for the return.
1922   // Win32 requires us to put the sret argument to %eax as well.
1923   // We saved the argument into a virtual register in the entry block,
1924   // so now we copy the value out and into %rax/%eax.
1925   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1926       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1927     MachineFunction &MF = DAG.getMachineFunction();
1928     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1929     unsigned Reg = FuncInfo->getSRetReturnReg();
1930     assert(Reg &&
1931            "SRetReturnReg should have been set in LowerFormalArguments().");
1932     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1933
1934     unsigned RetValReg
1935         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1936           X86::RAX : X86::EAX;
1937     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1938     Flag = Chain.getValue(1);
1939
1940     // RAX/EAX now acts like a return value.
1941     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1942   }
1943
1944   RetOps[0] = Chain;  // Update chain.
1945
1946   // Add the flag if we have it.
1947   if (Flag.getNode())
1948     RetOps.push_back(Flag);
1949
1950   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1951 }
1952
1953 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1954   if (N->getNumValues() != 1)
1955     return false;
1956   if (!N->hasNUsesOfValue(1, 0))
1957     return false;
1958
1959   SDValue TCChain = Chain;
1960   SDNode *Copy = *N->use_begin();
1961   if (Copy->getOpcode() == ISD::CopyToReg) {
1962     // If the copy has a glue operand, we conservatively assume it isn't safe to
1963     // perform a tail call.
1964     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1965       return false;
1966     TCChain = Copy->getOperand(0);
1967   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1968     return false;
1969
1970   bool HasRet = false;
1971   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1972        UI != UE; ++UI) {
1973     if (UI->getOpcode() != X86ISD::RET_FLAG)
1974       return false;
1975     HasRet = true;
1976   }
1977
1978   if (!HasRet)
1979     return false;
1980
1981   Chain = TCChain;
1982   return true;
1983 }
1984
1985 MVT
1986 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1987                                             ISD::NodeType ExtendKind) const {
1988   MVT ReturnMVT;
1989   // TODO: Is this also valid on 32-bit?
1990   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1991     ReturnMVT = MVT::i8;
1992   else
1993     ReturnMVT = MVT::i32;
1994
1995   MVT MinVT = getRegisterType(ReturnMVT);
1996   return VT.bitsLT(MinVT) ? MinVT : VT;
1997 }
1998
1999 /// LowerCallResult - Lower the result values of a call into the
2000 /// appropriate copies out of appropriate physical registers.
2001 ///
2002 SDValue
2003 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2004                                    CallingConv::ID CallConv, bool isVarArg,
2005                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2006                                    SDLoc dl, SelectionDAG &DAG,
2007                                    SmallVectorImpl<SDValue> &InVals) const {
2008
2009   // Assign locations to each value returned by this call.
2010   SmallVector<CCValAssign, 16> RVLocs;
2011   bool Is64Bit = Subtarget->is64Bit();
2012   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2013                  getTargetMachine(), RVLocs, *DAG.getContext());
2014   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2015
2016   // Copy all of the result registers out of their specified physreg.
2017   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2018     CCValAssign &VA = RVLocs[i];
2019     EVT CopyVT = VA.getValVT();
2020
2021     // If this is x86-64, and we disabled SSE, we can't return FP values
2022     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2023         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2024       report_fatal_error("SSE register return with SSE disabled");
2025     }
2026
2027     SDValue Val;
2028
2029     // If this is a call to a function that returns an fp value on the floating
2030     // point stack, we must guarantee the value is popped from the stack, so
2031     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2032     // if the return value is not used. We use the FpPOP_RETVAL instruction
2033     // instead.
2034     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2035       // If we prefer to use the value in xmm registers, copy it out as f80 and
2036       // use a truncate to move it from fp stack reg to xmm reg.
2037       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2038       SDValue Ops[] = { Chain, InFlag };
2039       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2040                                          MVT::Other, MVT::Glue, Ops), 1);
2041       Val = Chain.getValue(0);
2042
2043       // Round the f80 to the right size, which also moves it to the appropriate
2044       // xmm register.
2045       if (CopyVT != VA.getValVT())
2046         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2047                           // This truncation won't change the value.
2048                           DAG.getIntPtrConstant(1));
2049     } else {
2050       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2051                                  CopyVT, InFlag).getValue(1);
2052       Val = Chain.getValue(0);
2053     }
2054     InFlag = Chain.getValue(2);
2055     InVals.push_back(Val);
2056   }
2057
2058   return Chain;
2059 }
2060
2061 //===----------------------------------------------------------------------===//
2062 //                C & StdCall & Fast Calling Convention implementation
2063 //===----------------------------------------------------------------------===//
2064 //  StdCall calling convention seems to be standard for many Windows' API
2065 //  routines and around. It differs from C calling convention just a little:
2066 //  callee should clean up the stack, not caller. Symbols should be also
2067 //  decorated in some fancy way :) It doesn't support any vector arguments.
2068 //  For info on fast calling convention see Fast Calling Convention (tail call)
2069 //  implementation LowerX86_32FastCCCallTo.
2070
2071 /// CallIsStructReturn - Determines whether a call uses struct return
2072 /// semantics.
2073 enum StructReturnType {
2074   NotStructReturn,
2075   RegStructReturn,
2076   StackStructReturn
2077 };
2078 static StructReturnType
2079 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2080   if (Outs.empty())
2081     return NotStructReturn;
2082
2083   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2084   if (!Flags.isSRet())
2085     return NotStructReturn;
2086   if (Flags.isInReg())
2087     return RegStructReturn;
2088   return StackStructReturn;
2089 }
2090
2091 /// ArgsAreStructReturn - Determines whether a function uses struct
2092 /// return semantics.
2093 static StructReturnType
2094 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2095   if (Ins.empty())
2096     return NotStructReturn;
2097
2098   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2099   if (!Flags.isSRet())
2100     return NotStructReturn;
2101   if (Flags.isInReg())
2102     return RegStructReturn;
2103   return StackStructReturn;
2104 }
2105
2106 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2107 /// by "Src" to address "Dst" with size and alignment information specified by
2108 /// the specific parameter attribute. The copy will be passed as a byval
2109 /// function parameter.
2110 static SDValue
2111 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2112                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2113                           SDLoc dl) {
2114   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2115
2116   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2117                        /*isVolatile*/false, /*AlwaysInline=*/true,
2118                        MachinePointerInfo(), MachinePointerInfo());
2119 }
2120
2121 /// IsTailCallConvention - Return true if the calling convention is one that
2122 /// supports tail call optimization.
2123 static bool IsTailCallConvention(CallingConv::ID CC) {
2124   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2125           CC == CallingConv::HiPE);
2126 }
2127
2128 /// \brief Return true if the calling convention is a C calling convention.
2129 static bool IsCCallConvention(CallingConv::ID CC) {
2130   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2131           CC == CallingConv::X86_64_SysV);
2132 }
2133
2134 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2135   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2136     return false;
2137
2138   CallSite CS(CI);
2139   CallingConv::ID CalleeCC = CS.getCallingConv();
2140   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2141     return false;
2142
2143   return true;
2144 }
2145
2146 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2147 /// a tailcall target by changing its ABI.
2148 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2149                                    bool GuaranteedTailCallOpt) {
2150   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2151 }
2152
2153 SDValue
2154 X86TargetLowering::LowerMemArgument(SDValue Chain,
2155                                     CallingConv::ID CallConv,
2156                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2157                                     SDLoc dl, SelectionDAG &DAG,
2158                                     const CCValAssign &VA,
2159                                     MachineFrameInfo *MFI,
2160                                     unsigned i) const {
2161   // Create the nodes corresponding to a load from this parameter slot.
2162   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2163   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2164                               getTargetMachine().Options.GuaranteedTailCallOpt);
2165   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2166   EVT ValVT;
2167
2168   // If value is passed by pointer we have address passed instead of the value
2169   // itself.
2170   if (VA.getLocInfo() == CCValAssign::Indirect)
2171     ValVT = VA.getLocVT();
2172   else
2173     ValVT = VA.getValVT();
2174
2175   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2176   // changed with more analysis.
2177   // In case of tail call optimization mark all arguments mutable. Since they
2178   // could be overwritten by lowering of arguments in case of a tail call.
2179   if (Flags.isByVal()) {
2180     unsigned Bytes = Flags.getByValSize();
2181     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2182     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2183     return DAG.getFrameIndex(FI, getPointerTy());
2184   } else {
2185     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2186                                     VA.getLocMemOffset(), isImmutable);
2187     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2188     return DAG.getLoad(ValVT, dl, Chain, FIN,
2189                        MachinePointerInfo::getFixedStack(FI),
2190                        false, false, false, 0);
2191   }
2192 }
2193
2194 SDValue
2195 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2196                                         CallingConv::ID CallConv,
2197                                         bool isVarArg,
2198                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2199                                         SDLoc dl,
2200                                         SelectionDAG &DAG,
2201                                         SmallVectorImpl<SDValue> &InVals)
2202                                           const {
2203   MachineFunction &MF = DAG.getMachineFunction();
2204   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2205
2206   const Function* Fn = MF.getFunction();
2207   if (Fn->hasExternalLinkage() &&
2208       Subtarget->isTargetCygMing() &&
2209       Fn->getName() == "main")
2210     FuncInfo->setForceFramePointer(true);
2211
2212   MachineFrameInfo *MFI = MF.getFrameInfo();
2213   bool Is64Bit = Subtarget->is64Bit();
2214   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2215
2216   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2217          "Var args not supported with calling convention fastcc, ghc or hipe");
2218
2219   // Assign locations to all of the incoming arguments.
2220   SmallVector<CCValAssign, 16> ArgLocs;
2221   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2222                  ArgLocs, *DAG.getContext());
2223
2224   // Allocate shadow area for Win64
2225   if (IsWin64)
2226     CCInfo.AllocateStack(32, 8);
2227
2228   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2229
2230   unsigned LastVal = ~0U;
2231   SDValue ArgValue;
2232   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2233     CCValAssign &VA = ArgLocs[i];
2234     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2235     // places.
2236     assert(VA.getValNo() != LastVal &&
2237            "Don't support value assigned to multiple locs yet");
2238     (void)LastVal;
2239     LastVal = VA.getValNo();
2240
2241     if (VA.isRegLoc()) {
2242       EVT RegVT = VA.getLocVT();
2243       const TargetRegisterClass *RC;
2244       if (RegVT == MVT::i32)
2245         RC = &X86::GR32RegClass;
2246       else if (Is64Bit && RegVT == MVT::i64)
2247         RC = &X86::GR64RegClass;
2248       else if (RegVT == MVT::f32)
2249         RC = &X86::FR32RegClass;
2250       else if (RegVT == MVT::f64)
2251         RC = &X86::FR64RegClass;
2252       else if (RegVT.is512BitVector())
2253         RC = &X86::VR512RegClass;
2254       else if (RegVT.is256BitVector())
2255         RC = &X86::VR256RegClass;
2256       else if (RegVT.is128BitVector())
2257         RC = &X86::VR128RegClass;
2258       else if (RegVT == MVT::x86mmx)
2259         RC = &X86::VR64RegClass;
2260       else if (RegVT == MVT::i1)
2261         RC = &X86::VK1RegClass;
2262       else if (RegVT == MVT::v8i1)
2263         RC = &X86::VK8RegClass;
2264       else if (RegVT == MVT::v16i1)
2265         RC = &X86::VK16RegClass;
2266       else
2267         llvm_unreachable("Unknown argument type!");
2268
2269       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2270       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2271
2272       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2273       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2274       // right size.
2275       if (VA.getLocInfo() == CCValAssign::SExt)
2276         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2277                                DAG.getValueType(VA.getValVT()));
2278       else if (VA.getLocInfo() == CCValAssign::ZExt)
2279         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2280                                DAG.getValueType(VA.getValVT()));
2281       else if (VA.getLocInfo() == CCValAssign::BCvt)
2282         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2283
2284       if (VA.isExtInLoc()) {
2285         // Handle MMX values passed in XMM regs.
2286         if (RegVT.isVector())
2287           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2288         else
2289           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2290       }
2291     } else {
2292       assert(VA.isMemLoc());
2293       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2294     }
2295
2296     // If value is passed via pointer - do a load.
2297     if (VA.getLocInfo() == CCValAssign::Indirect)
2298       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2299                              MachinePointerInfo(), false, false, false, 0);
2300
2301     InVals.push_back(ArgValue);
2302   }
2303
2304   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2305     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2306       // The x86-64 ABIs require that for returning structs by value we copy
2307       // the sret argument into %rax/%eax (depending on ABI) for the return.
2308       // Win32 requires us to put the sret argument to %eax as well.
2309       // Save the argument into a virtual register so that we can access it
2310       // from the return points.
2311       if (Ins[i].Flags.isSRet()) {
2312         unsigned Reg = FuncInfo->getSRetReturnReg();
2313         if (!Reg) {
2314           MVT PtrTy = getPointerTy();
2315           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2316           FuncInfo->setSRetReturnReg(Reg);
2317         }
2318         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2319         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2320         break;
2321       }
2322     }
2323   }
2324
2325   unsigned StackSize = CCInfo.getNextStackOffset();
2326   // Align stack specially for tail calls.
2327   if (FuncIsMadeTailCallSafe(CallConv,
2328                              MF.getTarget().Options.GuaranteedTailCallOpt))
2329     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2330
2331   // If the function takes variable number of arguments, make a frame index for
2332   // the start of the first vararg value... for expansion of llvm.va_start.
2333   if (isVarArg) {
2334     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2335                     CallConv != CallingConv::X86_ThisCall)) {
2336       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2337     }
2338     if (Is64Bit) {
2339       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2340
2341       // FIXME: We should really autogenerate these arrays
2342       static const MCPhysReg GPR64ArgRegsWin64[] = {
2343         X86::RCX, X86::RDX, X86::R8,  X86::R9
2344       };
2345       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2346         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2347       };
2348       static const MCPhysReg XMMArgRegs64Bit[] = {
2349         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2350         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2351       };
2352       const MCPhysReg *GPR64ArgRegs;
2353       unsigned NumXMMRegs = 0;
2354
2355       if (IsWin64) {
2356         // The XMM registers which might contain var arg parameters are shadowed
2357         // in their paired GPR.  So we only need to save the GPR to their home
2358         // slots.
2359         TotalNumIntRegs = 4;
2360         GPR64ArgRegs = GPR64ArgRegsWin64;
2361       } else {
2362         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2363         GPR64ArgRegs = GPR64ArgRegs64Bit;
2364
2365         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2366                                                 TotalNumXMMRegs);
2367       }
2368       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2369                                                        TotalNumIntRegs);
2370
2371       bool NoImplicitFloatOps = Fn->getAttributes().
2372         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2373       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2374              "SSE register cannot be used when SSE is disabled!");
2375       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2376                NoImplicitFloatOps) &&
2377              "SSE register cannot be used when SSE is disabled!");
2378       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2379           !Subtarget->hasSSE1())
2380         // Kernel mode asks for SSE to be disabled, so don't push them
2381         // on the stack.
2382         TotalNumXMMRegs = 0;
2383
2384       if (IsWin64) {
2385         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2386         // Get to the caller-allocated home save location.  Add 8 to account
2387         // for the return address.
2388         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2389         FuncInfo->setRegSaveFrameIndex(
2390           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2391         // Fixup to set vararg frame on shadow area (4 x i64).
2392         if (NumIntRegs < 4)
2393           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2394       } else {
2395         // For X86-64, if there are vararg parameters that are passed via
2396         // registers, then we must store them to their spots on the stack so
2397         // they may be loaded by deferencing the result of va_next.
2398         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2399         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2400         FuncInfo->setRegSaveFrameIndex(
2401           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2402                                false));
2403       }
2404
2405       // Store the integer parameter registers.
2406       SmallVector<SDValue, 8> MemOps;
2407       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2408                                         getPointerTy());
2409       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2410       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2411         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2412                                   DAG.getIntPtrConstant(Offset));
2413         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2414                                      &X86::GR64RegClass);
2415         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2416         SDValue Store =
2417           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2418                        MachinePointerInfo::getFixedStack(
2419                          FuncInfo->getRegSaveFrameIndex(), Offset),
2420                        false, false, 0);
2421         MemOps.push_back(Store);
2422         Offset += 8;
2423       }
2424
2425       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2426         // Now store the XMM (fp + vector) parameter registers.
2427         SmallVector<SDValue, 11> SaveXMMOps;
2428         SaveXMMOps.push_back(Chain);
2429
2430         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2431         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2432         SaveXMMOps.push_back(ALVal);
2433
2434         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2435                                FuncInfo->getRegSaveFrameIndex()));
2436         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2437                                FuncInfo->getVarArgsFPOffset()));
2438
2439         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2440           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2441                                        &X86::VR128RegClass);
2442           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2443           SaveXMMOps.push_back(Val);
2444         }
2445         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2446                                      MVT::Other, SaveXMMOps));
2447       }
2448
2449       if (!MemOps.empty())
2450         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2451     }
2452   }
2453
2454   // Some CCs need callee pop.
2455   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2456                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2457     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2458   } else {
2459     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2460     // If this is an sret function, the return should pop the hidden pointer.
2461     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2462         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2463         argsAreStructReturn(Ins) == StackStructReturn)
2464       FuncInfo->setBytesToPopOnReturn(4);
2465   }
2466
2467   if (!Is64Bit) {
2468     // RegSaveFrameIndex is X86-64 only.
2469     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2470     if (CallConv == CallingConv::X86_FastCall ||
2471         CallConv == CallingConv::X86_ThisCall)
2472       // fastcc functions can't have varargs.
2473       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2474   }
2475
2476   FuncInfo->setArgumentStackSize(StackSize);
2477
2478   return Chain;
2479 }
2480
2481 SDValue
2482 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2483                                     SDValue StackPtr, SDValue Arg,
2484                                     SDLoc dl, SelectionDAG &DAG,
2485                                     const CCValAssign &VA,
2486                                     ISD::ArgFlagsTy Flags) const {
2487   unsigned LocMemOffset = VA.getLocMemOffset();
2488   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2489   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2490   if (Flags.isByVal())
2491     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2492
2493   return DAG.getStore(Chain, dl, Arg, PtrOff,
2494                       MachinePointerInfo::getStack(LocMemOffset),
2495                       false, false, 0);
2496 }
2497
2498 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2499 /// optimization is performed and it is required.
2500 SDValue
2501 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2502                                            SDValue &OutRetAddr, SDValue Chain,
2503                                            bool IsTailCall, bool Is64Bit,
2504                                            int FPDiff, SDLoc dl) const {
2505   // Adjust the Return address stack slot.
2506   EVT VT = getPointerTy();
2507   OutRetAddr = getReturnAddressFrameIndex(DAG);
2508
2509   // Load the "old" Return address.
2510   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2511                            false, false, false, 0);
2512   return SDValue(OutRetAddr.getNode(), 1);
2513 }
2514
2515 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2516 /// optimization is performed and it is required (FPDiff!=0).
2517 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2518                                         SDValue Chain, SDValue RetAddrFrIdx,
2519                                         EVT PtrVT, unsigned SlotSize,
2520                                         int FPDiff, SDLoc dl) {
2521   // Store the return address to the appropriate stack slot.
2522   if (!FPDiff) return Chain;
2523   // Calculate the new stack slot for the return address.
2524   int NewReturnAddrFI =
2525     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2526                                          false);
2527   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2528   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2529                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2530                        false, false, 0);
2531   return Chain;
2532 }
2533
2534 SDValue
2535 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2536                              SmallVectorImpl<SDValue> &InVals) const {
2537   SelectionDAG &DAG                     = CLI.DAG;
2538   SDLoc &dl                             = CLI.DL;
2539   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2540   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2541   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2542   SDValue Chain                         = CLI.Chain;
2543   SDValue Callee                        = CLI.Callee;
2544   CallingConv::ID CallConv              = CLI.CallConv;
2545   bool &isTailCall                      = CLI.IsTailCall;
2546   bool isVarArg                         = CLI.IsVarArg;
2547
2548   MachineFunction &MF = DAG.getMachineFunction();
2549   bool Is64Bit        = Subtarget->is64Bit();
2550   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2551   StructReturnType SR = callIsStructReturn(Outs);
2552   bool IsSibcall      = false;
2553
2554   if (MF.getTarget().Options.DisableTailCalls)
2555     isTailCall = false;
2556
2557   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2558   if (IsMustTail) {
2559     // Force this to be a tail call.  The verifier rules are enough to ensure
2560     // that we can lower this successfully without moving the return address
2561     // around.
2562     isTailCall = true;
2563   } else if (isTailCall) {
2564     // Check if it's really possible to do a tail call.
2565     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2566                     isVarArg, SR != NotStructReturn,
2567                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2568                     Outs, OutVals, Ins, DAG);
2569
2570     // Sibcalls are automatically detected tailcalls which do not require
2571     // ABI changes.
2572     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2573       IsSibcall = true;
2574
2575     if (isTailCall)
2576       ++NumTailCalls;
2577   }
2578
2579   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2580          "Var args not supported with calling convention fastcc, ghc or hipe");
2581
2582   // Analyze operands of the call, assigning locations to each operand.
2583   SmallVector<CCValAssign, 16> ArgLocs;
2584   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2585                  ArgLocs, *DAG.getContext());
2586
2587   // Allocate shadow area for Win64
2588   if (IsWin64)
2589     CCInfo.AllocateStack(32, 8);
2590
2591   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2592
2593   // Get a count of how many bytes are to be pushed on the stack.
2594   unsigned NumBytes = CCInfo.getNextStackOffset();
2595   if (IsSibcall)
2596     // This is a sibcall. The memory operands are available in caller's
2597     // own caller's stack.
2598     NumBytes = 0;
2599   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2600            IsTailCallConvention(CallConv))
2601     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2602
2603   int FPDiff = 0;
2604   if (isTailCall && !IsSibcall && !IsMustTail) {
2605     // Lower arguments at fp - stackoffset + fpdiff.
2606     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2607     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2608
2609     FPDiff = NumBytesCallerPushed - NumBytes;
2610
2611     // Set the delta of movement of the returnaddr stackslot.
2612     // But only set if delta is greater than previous delta.
2613     if (FPDiff < X86Info->getTCReturnAddrDelta())
2614       X86Info->setTCReturnAddrDelta(FPDiff);
2615   }
2616
2617   unsigned NumBytesToPush = NumBytes;
2618   unsigned NumBytesToPop = NumBytes;
2619
2620   // If we have an inalloca argument, all stack space has already been allocated
2621   // for us and be right at the top of the stack.  We don't support multiple
2622   // arguments passed in memory when using inalloca.
2623   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2624     NumBytesToPush = 0;
2625     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2626            "an inalloca argument must be the only memory argument");
2627   }
2628
2629   if (!IsSibcall)
2630     Chain = DAG.getCALLSEQ_START(
2631         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2632
2633   SDValue RetAddrFrIdx;
2634   // Load return address for tail calls.
2635   if (isTailCall && FPDiff)
2636     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2637                                     Is64Bit, FPDiff, dl);
2638
2639   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2640   SmallVector<SDValue, 8> MemOpChains;
2641   SDValue StackPtr;
2642
2643   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2644   // of tail call optimization arguments are handle later.
2645   const X86RegisterInfo *RegInfo =
2646     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2647   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2648     // Skip inalloca arguments, they have already been written.
2649     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2650     if (Flags.isInAlloca())
2651       continue;
2652
2653     CCValAssign &VA = ArgLocs[i];
2654     EVT RegVT = VA.getLocVT();
2655     SDValue Arg = OutVals[i];
2656     bool isByVal = Flags.isByVal();
2657
2658     // Promote the value if needed.
2659     switch (VA.getLocInfo()) {
2660     default: llvm_unreachable("Unknown loc info!");
2661     case CCValAssign::Full: break;
2662     case CCValAssign::SExt:
2663       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2664       break;
2665     case CCValAssign::ZExt:
2666       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2667       break;
2668     case CCValAssign::AExt:
2669       if (RegVT.is128BitVector()) {
2670         // Special case: passing MMX values in XMM registers.
2671         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2672         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2673         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2674       } else
2675         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2676       break;
2677     case CCValAssign::BCvt:
2678       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2679       break;
2680     case CCValAssign::Indirect: {
2681       // Store the argument.
2682       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2683       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2684       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2685                            MachinePointerInfo::getFixedStack(FI),
2686                            false, false, 0);
2687       Arg = SpillSlot;
2688       break;
2689     }
2690     }
2691
2692     if (VA.isRegLoc()) {
2693       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2694       if (isVarArg && IsWin64) {
2695         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2696         // shadow reg if callee is a varargs function.
2697         unsigned ShadowReg = 0;
2698         switch (VA.getLocReg()) {
2699         case X86::XMM0: ShadowReg = X86::RCX; break;
2700         case X86::XMM1: ShadowReg = X86::RDX; break;
2701         case X86::XMM2: ShadowReg = X86::R8; break;
2702         case X86::XMM3: ShadowReg = X86::R9; break;
2703         }
2704         if (ShadowReg)
2705           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2706       }
2707     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2708       assert(VA.isMemLoc());
2709       if (!StackPtr.getNode())
2710         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2711                                       getPointerTy());
2712       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2713                                              dl, DAG, VA, Flags));
2714     }
2715   }
2716
2717   if (!MemOpChains.empty())
2718     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2719
2720   if (Subtarget->isPICStyleGOT()) {
2721     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2722     // GOT pointer.
2723     if (!isTailCall) {
2724       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2725                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2726     } else {
2727       // If we are tail calling and generating PIC/GOT style code load the
2728       // address of the callee into ECX. The value in ecx is used as target of
2729       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2730       // for tail calls on PIC/GOT architectures. Normally we would just put the
2731       // address of GOT into ebx and then call target@PLT. But for tail calls
2732       // ebx would be restored (since ebx is callee saved) before jumping to the
2733       // target@PLT.
2734
2735       // Note: The actual moving to ECX is done further down.
2736       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2737       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2738           !G->getGlobal()->hasProtectedVisibility())
2739         Callee = LowerGlobalAddress(Callee, DAG);
2740       else if (isa<ExternalSymbolSDNode>(Callee))
2741         Callee = LowerExternalSymbol(Callee, DAG);
2742     }
2743   }
2744
2745   if (Is64Bit && isVarArg && !IsWin64) {
2746     // From AMD64 ABI document:
2747     // For calls that may call functions that use varargs or stdargs
2748     // (prototype-less calls or calls to functions containing ellipsis (...) in
2749     // the declaration) %al is used as hidden argument to specify the number
2750     // of SSE registers used. The contents of %al do not need to match exactly
2751     // the number of registers, but must be an ubound on the number of SSE
2752     // registers used and is in the range 0 - 8 inclusive.
2753
2754     // Count the number of XMM registers allocated.
2755     static const MCPhysReg XMMArgRegs[] = {
2756       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2757       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2758     };
2759     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2760     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2761            && "SSE registers cannot be used when SSE is disabled");
2762
2763     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2764                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2765   }
2766
2767   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2768   // don't need this because the eligibility check rejects calls that require
2769   // shuffling arguments passed in memory.
2770   if (!IsSibcall && isTailCall) {
2771     // Force all the incoming stack arguments to be loaded from the stack
2772     // before any new outgoing arguments are stored to the stack, because the
2773     // outgoing stack slots may alias the incoming argument stack slots, and
2774     // the alias isn't otherwise explicit. This is slightly more conservative
2775     // than necessary, because it means that each store effectively depends
2776     // on every argument instead of just those arguments it would clobber.
2777     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2778
2779     SmallVector<SDValue, 8> MemOpChains2;
2780     SDValue FIN;
2781     int FI = 0;
2782     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2783       CCValAssign &VA = ArgLocs[i];
2784       if (VA.isRegLoc())
2785         continue;
2786       assert(VA.isMemLoc());
2787       SDValue Arg = OutVals[i];
2788       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2789       // Skip inalloca arguments.  They don't require any work.
2790       if (Flags.isInAlloca())
2791         continue;
2792       // Create frame index.
2793       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2794       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2795       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2796       FIN = DAG.getFrameIndex(FI, getPointerTy());
2797
2798       if (Flags.isByVal()) {
2799         // Copy relative to framepointer.
2800         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2801         if (!StackPtr.getNode())
2802           StackPtr = DAG.getCopyFromReg(Chain, dl,
2803                                         RegInfo->getStackRegister(),
2804                                         getPointerTy());
2805         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2806
2807         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2808                                                          ArgChain,
2809                                                          Flags, DAG, dl));
2810       } else {
2811         // Store relative to framepointer.
2812         MemOpChains2.push_back(
2813           DAG.getStore(ArgChain, dl, Arg, FIN,
2814                        MachinePointerInfo::getFixedStack(FI),
2815                        false, false, 0));
2816       }
2817     }
2818
2819     if (!MemOpChains2.empty())
2820       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2821
2822     // Store the return address to the appropriate stack slot.
2823     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2824                                      getPointerTy(), RegInfo->getSlotSize(),
2825                                      FPDiff, dl);
2826   }
2827
2828   // Build a sequence of copy-to-reg nodes chained together with token chain
2829   // and flag operands which copy the outgoing args into registers.
2830   SDValue InFlag;
2831   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2832     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2833                              RegsToPass[i].second, InFlag);
2834     InFlag = Chain.getValue(1);
2835   }
2836
2837   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2838     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2839     // In the 64-bit large code model, we have to make all calls
2840     // through a register, since the call instruction's 32-bit
2841     // pc-relative offset may not be large enough to hold the whole
2842     // address.
2843   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2844     // If the callee is a GlobalAddress node (quite common, every direct call
2845     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2846     // it.
2847
2848     // We should use extra load for direct calls to dllimported functions in
2849     // non-JIT mode.
2850     const GlobalValue *GV = G->getGlobal();
2851     if (!GV->hasDLLImportStorageClass()) {
2852       unsigned char OpFlags = 0;
2853       bool ExtraLoad = false;
2854       unsigned WrapperKind = ISD::DELETED_NODE;
2855
2856       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2857       // external symbols most go through the PLT in PIC mode.  If the symbol
2858       // has hidden or protected visibility, or if it is static or local, then
2859       // we don't need to use the PLT - we can directly call it.
2860       if (Subtarget->isTargetELF() &&
2861           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2862           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2863         OpFlags = X86II::MO_PLT;
2864       } else if (Subtarget->isPICStyleStubAny() &&
2865                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2866                  (!Subtarget->getTargetTriple().isMacOSX() ||
2867                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2868         // PC-relative references to external symbols should go through $stub,
2869         // unless we're building with the leopard linker or later, which
2870         // automatically synthesizes these stubs.
2871         OpFlags = X86II::MO_DARWIN_STUB;
2872       } else if (Subtarget->isPICStyleRIPRel() &&
2873                  isa<Function>(GV) &&
2874                  cast<Function>(GV)->getAttributes().
2875                    hasAttribute(AttributeSet::FunctionIndex,
2876                                 Attribute::NonLazyBind)) {
2877         // If the function is marked as non-lazy, generate an indirect call
2878         // which loads from the GOT directly. This avoids runtime overhead
2879         // at the cost of eager binding (and one extra byte of encoding).
2880         OpFlags = X86II::MO_GOTPCREL;
2881         WrapperKind = X86ISD::WrapperRIP;
2882         ExtraLoad = true;
2883       }
2884
2885       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2886                                           G->getOffset(), OpFlags);
2887
2888       // Add a wrapper if needed.
2889       if (WrapperKind != ISD::DELETED_NODE)
2890         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2891       // Add extra indirection if needed.
2892       if (ExtraLoad)
2893         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2894                              MachinePointerInfo::getGOT(),
2895                              false, false, false, 0);
2896     }
2897   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2898     unsigned char OpFlags = 0;
2899
2900     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2901     // external symbols should go through the PLT.
2902     if (Subtarget->isTargetELF() &&
2903         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2904       OpFlags = X86II::MO_PLT;
2905     } else if (Subtarget->isPICStyleStubAny() &&
2906                (!Subtarget->getTargetTriple().isMacOSX() ||
2907                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2908       // PC-relative references to external symbols should go through $stub,
2909       // unless we're building with the leopard linker or later, which
2910       // automatically synthesizes these stubs.
2911       OpFlags = X86II::MO_DARWIN_STUB;
2912     }
2913
2914     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2915                                          OpFlags);
2916   }
2917
2918   // Returns a chain & a flag for retval copy to use.
2919   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2920   SmallVector<SDValue, 8> Ops;
2921
2922   if (!IsSibcall && isTailCall) {
2923     Chain = DAG.getCALLSEQ_END(Chain,
2924                                DAG.getIntPtrConstant(NumBytesToPop, true),
2925                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2926     InFlag = Chain.getValue(1);
2927   }
2928
2929   Ops.push_back(Chain);
2930   Ops.push_back(Callee);
2931
2932   if (isTailCall)
2933     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2934
2935   // Add argument registers to the end of the list so that they are known live
2936   // into the call.
2937   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2938     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2939                                   RegsToPass[i].second.getValueType()));
2940
2941   // Add a register mask operand representing the call-preserved registers.
2942   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2943   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2944   assert(Mask && "Missing call preserved mask for calling convention");
2945   Ops.push_back(DAG.getRegisterMask(Mask));
2946
2947   if (InFlag.getNode())
2948     Ops.push_back(InFlag);
2949
2950   if (isTailCall) {
2951     // We used to do:
2952     //// If this is the first return lowered for this function, add the regs
2953     //// to the liveout set for the function.
2954     // This isn't right, although it's probably harmless on x86; liveouts
2955     // should be computed from returns not tail calls.  Consider a void
2956     // function making a tail call to a function returning int.
2957     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2958   }
2959
2960   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2961   InFlag = Chain.getValue(1);
2962
2963   // Create the CALLSEQ_END node.
2964   unsigned NumBytesForCalleeToPop;
2965   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2966                        getTargetMachine().Options.GuaranteedTailCallOpt))
2967     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2968   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2969            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2970            SR == StackStructReturn)
2971     // If this is a call to a struct-return function, the callee
2972     // pops the hidden struct pointer, so we have to push it back.
2973     // This is common for Darwin/X86, Linux & Mingw32 targets.
2974     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2975     NumBytesForCalleeToPop = 4;
2976   else
2977     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2978
2979   // Returns a flag for retval copy to use.
2980   if (!IsSibcall) {
2981     Chain = DAG.getCALLSEQ_END(Chain,
2982                                DAG.getIntPtrConstant(NumBytesToPop, true),
2983                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2984                                                      true),
2985                                InFlag, dl);
2986     InFlag = Chain.getValue(1);
2987   }
2988
2989   // Handle result values, copying them out of physregs into vregs that we
2990   // return.
2991   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2992                          Ins, dl, DAG, InVals);
2993 }
2994
2995 //===----------------------------------------------------------------------===//
2996 //                Fast Calling Convention (tail call) implementation
2997 //===----------------------------------------------------------------------===//
2998
2999 //  Like std call, callee cleans arguments, convention except that ECX is
3000 //  reserved for storing the tail called function address. Only 2 registers are
3001 //  free for argument passing (inreg). Tail call optimization is performed
3002 //  provided:
3003 //                * tailcallopt is enabled
3004 //                * caller/callee are fastcc
3005 //  On X86_64 architecture with GOT-style position independent code only local
3006 //  (within module) calls are supported at the moment.
3007 //  To keep the stack aligned according to platform abi the function
3008 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3009 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3010 //  If a tail called function callee has more arguments than the caller the
3011 //  caller needs to make sure that there is room to move the RETADDR to. This is
3012 //  achieved by reserving an area the size of the argument delta right after the
3013 //  original REtADDR, but before the saved framepointer or the spilled registers
3014 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3015 //  stack layout:
3016 //    arg1
3017 //    arg2
3018 //    RETADDR
3019 //    [ new RETADDR
3020 //      move area ]
3021 //    (possible EBP)
3022 //    ESI
3023 //    EDI
3024 //    local1 ..
3025
3026 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3027 /// for a 16 byte align requirement.
3028 unsigned
3029 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3030                                                SelectionDAG& DAG) const {
3031   MachineFunction &MF = DAG.getMachineFunction();
3032   const TargetMachine &TM = MF.getTarget();
3033   const X86RegisterInfo *RegInfo =
3034     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3035   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3036   unsigned StackAlignment = TFI.getStackAlignment();
3037   uint64_t AlignMask = StackAlignment - 1;
3038   int64_t Offset = StackSize;
3039   unsigned SlotSize = RegInfo->getSlotSize();
3040   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3041     // Number smaller than 12 so just add the difference.
3042     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3043   } else {
3044     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3045     Offset = ((~AlignMask) & Offset) + StackAlignment +
3046       (StackAlignment-SlotSize);
3047   }
3048   return Offset;
3049 }
3050
3051 /// MatchingStackOffset - Return true if the given stack call argument is
3052 /// already available in the same position (relatively) of the caller's
3053 /// incoming argument stack.
3054 static
3055 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3056                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3057                          const X86InstrInfo *TII) {
3058   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3059   int FI = INT_MAX;
3060   if (Arg.getOpcode() == ISD::CopyFromReg) {
3061     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3062     if (!TargetRegisterInfo::isVirtualRegister(VR))
3063       return false;
3064     MachineInstr *Def = MRI->getVRegDef(VR);
3065     if (!Def)
3066       return false;
3067     if (!Flags.isByVal()) {
3068       if (!TII->isLoadFromStackSlot(Def, FI))
3069         return false;
3070     } else {
3071       unsigned Opcode = Def->getOpcode();
3072       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3073           Def->getOperand(1).isFI()) {
3074         FI = Def->getOperand(1).getIndex();
3075         Bytes = Flags.getByValSize();
3076       } else
3077         return false;
3078     }
3079   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3080     if (Flags.isByVal())
3081       // ByVal argument is passed in as a pointer but it's now being
3082       // dereferenced. e.g.
3083       // define @foo(%struct.X* %A) {
3084       //   tail call @bar(%struct.X* byval %A)
3085       // }
3086       return false;
3087     SDValue Ptr = Ld->getBasePtr();
3088     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3089     if (!FINode)
3090       return false;
3091     FI = FINode->getIndex();
3092   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3093     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3094     FI = FINode->getIndex();
3095     Bytes = Flags.getByValSize();
3096   } else
3097     return false;
3098
3099   assert(FI != INT_MAX);
3100   if (!MFI->isFixedObjectIndex(FI))
3101     return false;
3102   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3103 }
3104
3105 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3106 /// for tail call optimization. Targets which want to do tail call
3107 /// optimization should implement this function.
3108 bool
3109 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3110                                                      CallingConv::ID CalleeCC,
3111                                                      bool isVarArg,
3112                                                      bool isCalleeStructRet,
3113                                                      bool isCallerStructRet,
3114                                                      Type *RetTy,
3115                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3116                                     const SmallVectorImpl<SDValue> &OutVals,
3117                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3118                                                      SelectionDAG &DAG) const {
3119   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3120     return false;
3121
3122   // If -tailcallopt is specified, make fastcc functions tail-callable.
3123   const MachineFunction &MF = DAG.getMachineFunction();
3124   const Function *CallerF = MF.getFunction();
3125
3126   // If the function return type is x86_fp80 and the callee return type is not,
3127   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3128   // perform a tailcall optimization here.
3129   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3130     return false;
3131
3132   CallingConv::ID CallerCC = CallerF->getCallingConv();
3133   bool CCMatch = CallerCC == CalleeCC;
3134   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3135   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3136
3137   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3138     if (IsTailCallConvention(CalleeCC) && CCMatch)
3139       return true;
3140     return false;
3141   }
3142
3143   // Look for obvious safe cases to perform tail call optimization that do not
3144   // require ABI changes. This is what gcc calls sibcall.
3145
3146   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3147   // emit a special epilogue.
3148   const X86RegisterInfo *RegInfo =
3149     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3150   if (RegInfo->needsStackRealignment(MF))
3151     return false;
3152
3153   // Also avoid sibcall optimization if either caller or callee uses struct
3154   // return semantics.
3155   if (isCalleeStructRet || isCallerStructRet)
3156     return false;
3157
3158   // An stdcall/thiscall caller is expected to clean up its arguments; the
3159   // callee isn't going to do that.
3160   // FIXME: this is more restrictive than needed. We could produce a tailcall
3161   // when the stack adjustment matches. For example, with a thiscall that takes
3162   // only one argument.
3163   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3164                    CallerCC == CallingConv::X86_ThisCall))
3165     return false;
3166
3167   // Do not sibcall optimize vararg calls unless all arguments are passed via
3168   // registers.
3169   if (isVarArg && !Outs.empty()) {
3170
3171     // Optimizing for varargs on Win64 is unlikely to be safe without
3172     // additional testing.
3173     if (IsCalleeWin64 || IsCallerWin64)
3174       return false;
3175
3176     SmallVector<CCValAssign, 16> ArgLocs;
3177     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3178                    getTargetMachine(), ArgLocs, *DAG.getContext());
3179
3180     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3181     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3182       if (!ArgLocs[i].isRegLoc())
3183         return false;
3184   }
3185
3186   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3187   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3188   // this into a sibcall.
3189   bool Unused = false;
3190   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3191     if (!Ins[i].Used) {
3192       Unused = true;
3193       break;
3194     }
3195   }
3196   if (Unused) {
3197     SmallVector<CCValAssign, 16> RVLocs;
3198     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3199                    getTargetMachine(), RVLocs, *DAG.getContext());
3200     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3201     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3202       CCValAssign &VA = RVLocs[i];
3203       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3204         return false;
3205     }
3206   }
3207
3208   // If the calling conventions do not match, then we'd better make sure the
3209   // results are returned in the same way as what the caller expects.
3210   if (!CCMatch) {
3211     SmallVector<CCValAssign, 16> RVLocs1;
3212     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3213                     getTargetMachine(), RVLocs1, *DAG.getContext());
3214     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3215
3216     SmallVector<CCValAssign, 16> RVLocs2;
3217     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3218                     getTargetMachine(), RVLocs2, *DAG.getContext());
3219     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3220
3221     if (RVLocs1.size() != RVLocs2.size())
3222       return false;
3223     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3224       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3225         return false;
3226       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3227         return false;
3228       if (RVLocs1[i].isRegLoc()) {
3229         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3230           return false;
3231       } else {
3232         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3233           return false;
3234       }
3235     }
3236   }
3237
3238   // If the callee takes no arguments then go on to check the results of the
3239   // call.
3240   if (!Outs.empty()) {
3241     // Check if stack adjustment is needed. For now, do not do this if any
3242     // argument is passed on the stack.
3243     SmallVector<CCValAssign, 16> ArgLocs;
3244     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3245                    getTargetMachine(), ArgLocs, *DAG.getContext());
3246
3247     // Allocate shadow area for Win64
3248     if (IsCalleeWin64)
3249       CCInfo.AllocateStack(32, 8);
3250
3251     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3252     if (CCInfo.getNextStackOffset()) {
3253       MachineFunction &MF = DAG.getMachineFunction();
3254       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3255         return false;
3256
3257       // Check if the arguments are already laid out in the right way as
3258       // the caller's fixed stack objects.
3259       MachineFrameInfo *MFI = MF.getFrameInfo();
3260       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3261       const X86InstrInfo *TII =
3262         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3263       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3264         CCValAssign &VA = ArgLocs[i];
3265         SDValue Arg = OutVals[i];
3266         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3267         if (VA.getLocInfo() == CCValAssign::Indirect)
3268           return false;
3269         if (!VA.isRegLoc()) {
3270           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3271                                    MFI, MRI, TII))
3272             return false;
3273         }
3274       }
3275     }
3276
3277     // If the tailcall address may be in a register, then make sure it's
3278     // possible to register allocate for it. In 32-bit, the call address can
3279     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3280     // callee-saved registers are restored. These happen to be the same
3281     // registers used to pass 'inreg' arguments so watch out for those.
3282     if (!Subtarget->is64Bit() &&
3283         ((!isa<GlobalAddressSDNode>(Callee) &&
3284           !isa<ExternalSymbolSDNode>(Callee)) ||
3285          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3286       unsigned NumInRegs = 0;
3287       // In PIC we need an extra register to formulate the address computation
3288       // for the callee.
3289       unsigned MaxInRegs =
3290           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3291
3292       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3293         CCValAssign &VA = ArgLocs[i];
3294         if (!VA.isRegLoc())
3295           continue;
3296         unsigned Reg = VA.getLocReg();
3297         switch (Reg) {
3298         default: break;
3299         case X86::EAX: case X86::EDX: case X86::ECX:
3300           if (++NumInRegs == MaxInRegs)
3301             return false;
3302           break;
3303         }
3304       }
3305     }
3306   }
3307
3308   return true;
3309 }
3310
3311 FastISel *
3312 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3313                                   const TargetLibraryInfo *libInfo) const {
3314   return X86::createFastISel(funcInfo, libInfo);
3315 }
3316
3317 //===----------------------------------------------------------------------===//
3318 //                           Other Lowering Hooks
3319 //===----------------------------------------------------------------------===//
3320
3321 static bool MayFoldLoad(SDValue Op) {
3322   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3323 }
3324
3325 static bool MayFoldIntoStore(SDValue Op) {
3326   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3327 }
3328
3329 static bool isTargetShuffle(unsigned Opcode) {
3330   switch(Opcode) {
3331   default: return false;
3332   case X86ISD::PSHUFD:
3333   case X86ISD::PSHUFHW:
3334   case X86ISD::PSHUFLW:
3335   case X86ISD::SHUFP:
3336   case X86ISD::PALIGNR:
3337   case X86ISD::MOVLHPS:
3338   case X86ISD::MOVLHPD:
3339   case X86ISD::MOVHLPS:
3340   case X86ISD::MOVLPS:
3341   case X86ISD::MOVLPD:
3342   case X86ISD::MOVSHDUP:
3343   case X86ISD::MOVSLDUP:
3344   case X86ISD::MOVDDUP:
3345   case X86ISD::MOVSS:
3346   case X86ISD::MOVSD:
3347   case X86ISD::UNPCKL:
3348   case X86ISD::UNPCKH:
3349   case X86ISD::VPERMILP:
3350   case X86ISD::VPERM2X128:
3351   case X86ISD::VPERMI:
3352     return true;
3353   }
3354 }
3355
3356 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3357                                     SDValue V1, SelectionDAG &DAG) {
3358   switch(Opc) {
3359   default: llvm_unreachable("Unknown x86 shuffle node");
3360   case X86ISD::MOVSHDUP:
3361   case X86ISD::MOVSLDUP:
3362   case X86ISD::MOVDDUP:
3363     return DAG.getNode(Opc, dl, VT, V1);
3364   }
3365 }
3366
3367 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3368                                     SDValue V1, unsigned TargetMask,
3369                                     SelectionDAG &DAG) {
3370   switch(Opc) {
3371   default: llvm_unreachable("Unknown x86 shuffle node");
3372   case X86ISD::PSHUFD:
3373   case X86ISD::PSHUFHW:
3374   case X86ISD::PSHUFLW:
3375   case X86ISD::VPERMILP:
3376   case X86ISD::VPERMI:
3377     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3378   }
3379 }
3380
3381 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3382                                     SDValue V1, SDValue V2, unsigned TargetMask,
3383                                     SelectionDAG &DAG) {
3384   switch(Opc) {
3385   default: llvm_unreachable("Unknown x86 shuffle node");
3386   case X86ISD::PALIGNR:
3387   case X86ISD::SHUFP:
3388   case X86ISD::VPERM2X128:
3389     return DAG.getNode(Opc, dl, VT, V1, V2,
3390                        DAG.getConstant(TargetMask, MVT::i8));
3391   }
3392 }
3393
3394 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3395                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3396   switch(Opc) {
3397   default: llvm_unreachable("Unknown x86 shuffle node");
3398   case X86ISD::MOVLHPS:
3399   case X86ISD::MOVLHPD:
3400   case X86ISD::MOVHLPS:
3401   case X86ISD::MOVLPS:
3402   case X86ISD::MOVLPD:
3403   case X86ISD::MOVSS:
3404   case X86ISD::MOVSD:
3405   case X86ISD::UNPCKL:
3406   case X86ISD::UNPCKH:
3407     return DAG.getNode(Opc, dl, VT, V1, V2);
3408   }
3409 }
3410
3411 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3412   MachineFunction &MF = DAG.getMachineFunction();
3413   const X86RegisterInfo *RegInfo =
3414     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3415   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3416   int ReturnAddrIndex = FuncInfo->getRAIndex();
3417
3418   if (ReturnAddrIndex == 0) {
3419     // Set up a frame object for the return address.
3420     unsigned SlotSize = RegInfo->getSlotSize();
3421     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3422                                                            -(int64_t)SlotSize,
3423                                                            false);
3424     FuncInfo->setRAIndex(ReturnAddrIndex);
3425   }
3426
3427   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3428 }
3429
3430 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3431                                        bool hasSymbolicDisplacement) {
3432   // Offset should fit into 32 bit immediate field.
3433   if (!isInt<32>(Offset))
3434     return false;
3435
3436   // If we don't have a symbolic displacement - we don't have any extra
3437   // restrictions.
3438   if (!hasSymbolicDisplacement)
3439     return true;
3440
3441   // FIXME: Some tweaks might be needed for medium code model.
3442   if (M != CodeModel::Small && M != CodeModel::Kernel)
3443     return false;
3444
3445   // For small code model we assume that latest object is 16MB before end of 31
3446   // bits boundary. We may also accept pretty large negative constants knowing
3447   // that all objects are in the positive half of address space.
3448   if (M == CodeModel::Small && Offset < 16*1024*1024)
3449     return true;
3450
3451   // For kernel code model we know that all object resist in the negative half
3452   // of 32bits address space. We may not accept negative offsets, since they may
3453   // be just off and we may accept pretty large positive ones.
3454   if (M == CodeModel::Kernel && Offset > 0)
3455     return true;
3456
3457   return false;
3458 }
3459
3460 /// isCalleePop - Determines whether the callee is required to pop its
3461 /// own arguments. Callee pop is necessary to support tail calls.
3462 bool X86::isCalleePop(CallingConv::ID CallingConv,
3463                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3464   if (IsVarArg)
3465     return false;
3466
3467   switch (CallingConv) {
3468   default:
3469     return false;
3470   case CallingConv::X86_StdCall:
3471     return !is64Bit;
3472   case CallingConv::X86_FastCall:
3473     return !is64Bit;
3474   case CallingConv::X86_ThisCall:
3475     return !is64Bit;
3476   case CallingConv::Fast:
3477     return TailCallOpt;
3478   case CallingConv::GHC:
3479     return TailCallOpt;
3480   case CallingConv::HiPE:
3481     return TailCallOpt;
3482   }
3483 }
3484
3485 /// \brief Return true if the condition is an unsigned comparison operation.
3486 static bool isX86CCUnsigned(unsigned X86CC) {
3487   switch (X86CC) {
3488   default: llvm_unreachable("Invalid integer condition!");
3489   case X86::COND_E:     return true;
3490   case X86::COND_G:     return false;
3491   case X86::COND_GE:    return false;
3492   case X86::COND_L:     return false;
3493   case X86::COND_LE:    return false;
3494   case X86::COND_NE:    return true;
3495   case X86::COND_B:     return true;
3496   case X86::COND_A:     return true;
3497   case X86::COND_BE:    return true;
3498   case X86::COND_AE:    return true;
3499   }
3500   llvm_unreachable("covered switch fell through?!");
3501 }
3502
3503 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3504 /// specific condition code, returning the condition code and the LHS/RHS of the
3505 /// comparison to make.
3506 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3507                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3508   if (!isFP) {
3509     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3510       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3511         // X > -1   -> X == 0, jump !sign.
3512         RHS = DAG.getConstant(0, RHS.getValueType());
3513         return X86::COND_NS;
3514       }
3515       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3516         // X < 0   -> X == 0, jump on sign.
3517         return X86::COND_S;
3518       }
3519       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3520         // X < 1   -> X <= 0
3521         RHS = DAG.getConstant(0, RHS.getValueType());
3522         return X86::COND_LE;
3523       }
3524     }
3525
3526     switch (SetCCOpcode) {
3527     default: llvm_unreachable("Invalid integer condition!");
3528     case ISD::SETEQ:  return X86::COND_E;
3529     case ISD::SETGT:  return X86::COND_G;
3530     case ISD::SETGE:  return X86::COND_GE;
3531     case ISD::SETLT:  return X86::COND_L;
3532     case ISD::SETLE:  return X86::COND_LE;
3533     case ISD::SETNE:  return X86::COND_NE;
3534     case ISD::SETULT: return X86::COND_B;
3535     case ISD::SETUGT: return X86::COND_A;
3536     case ISD::SETULE: return X86::COND_BE;
3537     case ISD::SETUGE: return X86::COND_AE;
3538     }
3539   }
3540
3541   // First determine if it is required or is profitable to flip the operands.
3542
3543   // If LHS is a foldable load, but RHS is not, flip the condition.
3544   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3545       !ISD::isNON_EXTLoad(RHS.getNode())) {
3546     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3547     std::swap(LHS, RHS);
3548   }
3549
3550   switch (SetCCOpcode) {
3551   default: break;
3552   case ISD::SETOLT:
3553   case ISD::SETOLE:
3554   case ISD::SETUGT:
3555   case ISD::SETUGE:
3556     std::swap(LHS, RHS);
3557     break;
3558   }
3559
3560   // On a floating point condition, the flags are set as follows:
3561   // ZF  PF  CF   op
3562   //  0 | 0 | 0 | X > Y
3563   //  0 | 0 | 1 | X < Y
3564   //  1 | 0 | 0 | X == Y
3565   //  1 | 1 | 1 | unordered
3566   switch (SetCCOpcode) {
3567   default: llvm_unreachable("Condcode should be pre-legalized away");
3568   case ISD::SETUEQ:
3569   case ISD::SETEQ:   return X86::COND_E;
3570   case ISD::SETOLT:              // flipped
3571   case ISD::SETOGT:
3572   case ISD::SETGT:   return X86::COND_A;
3573   case ISD::SETOLE:              // flipped
3574   case ISD::SETOGE:
3575   case ISD::SETGE:   return X86::COND_AE;
3576   case ISD::SETUGT:              // flipped
3577   case ISD::SETULT:
3578   case ISD::SETLT:   return X86::COND_B;
3579   case ISD::SETUGE:              // flipped
3580   case ISD::SETULE:
3581   case ISD::SETLE:   return X86::COND_BE;
3582   case ISD::SETONE:
3583   case ISD::SETNE:   return X86::COND_NE;
3584   case ISD::SETUO:   return X86::COND_P;
3585   case ISD::SETO:    return X86::COND_NP;
3586   case ISD::SETOEQ:
3587   case ISD::SETUNE:  return X86::COND_INVALID;
3588   }
3589 }
3590
3591 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3592 /// code. Current x86 isa includes the following FP cmov instructions:
3593 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3594 static bool hasFPCMov(unsigned X86CC) {
3595   switch (X86CC) {
3596   default:
3597     return false;
3598   case X86::COND_B:
3599   case X86::COND_BE:
3600   case X86::COND_E:
3601   case X86::COND_P:
3602   case X86::COND_A:
3603   case X86::COND_AE:
3604   case X86::COND_NE:
3605   case X86::COND_NP:
3606     return true;
3607   }
3608 }
3609
3610 /// isFPImmLegal - Returns true if the target can instruction select the
3611 /// specified FP immediate natively. If false, the legalizer will
3612 /// materialize the FP immediate as a load from a constant pool.
3613 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3614   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3615     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3616       return true;
3617   }
3618   return false;
3619 }
3620
3621 /// \brief Returns true if it is beneficial to convert a load of a constant
3622 /// to just the constant itself.
3623 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3624                                                           Type *Ty) const {
3625   assert(Ty->isIntegerTy());
3626
3627   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3628   if (BitSize == 0 || BitSize > 64)
3629     return false;
3630   return true;
3631 }
3632
3633 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3634 /// the specified range (L, H].
3635 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3636   return (Val < 0) || (Val >= Low && Val < Hi);
3637 }
3638
3639 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3640 /// specified value.
3641 static bool isUndefOrEqual(int Val, int CmpVal) {
3642   return (Val < 0 || Val == CmpVal);
3643 }
3644
3645 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3646 /// from position Pos and ending in Pos+Size, falls within the specified
3647 /// sequential range (L, L+Pos]. or is undef.
3648 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3649                                        unsigned Pos, unsigned Size, int Low) {
3650   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3651     if (!isUndefOrEqual(Mask[i], Low))
3652       return false;
3653   return true;
3654 }
3655
3656 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3657 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3658 /// the second operand.
3659 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3660   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3661     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3662   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3663     return (Mask[0] < 2 && Mask[1] < 2);
3664   return false;
3665 }
3666
3667 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3668 /// is suitable for input to PSHUFHW.
3669 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3670   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3671     return false;
3672
3673   // Lower quadword copied in order or undef.
3674   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3675     return false;
3676
3677   // Upper quadword shuffled.
3678   for (unsigned i = 4; i != 8; ++i)
3679     if (!isUndefOrInRange(Mask[i], 4, 8))
3680       return false;
3681
3682   if (VT == MVT::v16i16) {
3683     // Lower quadword copied in order or undef.
3684     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3685       return false;
3686
3687     // Upper quadword shuffled.
3688     for (unsigned i = 12; i != 16; ++i)
3689       if (!isUndefOrInRange(Mask[i], 12, 16))
3690         return false;
3691   }
3692
3693   return true;
3694 }
3695
3696 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3697 /// is suitable for input to PSHUFLW.
3698 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3699   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3700     return false;
3701
3702   // Upper quadword copied in order.
3703   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3704     return false;
3705
3706   // Lower quadword shuffled.
3707   for (unsigned i = 0; i != 4; ++i)
3708     if (!isUndefOrInRange(Mask[i], 0, 4))
3709       return false;
3710
3711   if (VT == MVT::v16i16) {
3712     // Upper quadword copied in order.
3713     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3714       return false;
3715
3716     // Lower quadword shuffled.
3717     for (unsigned i = 8; i != 12; ++i)
3718       if (!isUndefOrInRange(Mask[i], 8, 12))
3719         return false;
3720   }
3721
3722   return true;
3723 }
3724
3725 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3726 /// is suitable for input to PALIGNR.
3727 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3728                           const X86Subtarget *Subtarget) {
3729   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3730       (VT.is256BitVector() && !Subtarget->hasInt256()))
3731     return false;
3732
3733   unsigned NumElts = VT.getVectorNumElements();
3734   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3735   unsigned NumLaneElts = NumElts/NumLanes;
3736
3737   // Do not handle 64-bit element shuffles with palignr.
3738   if (NumLaneElts == 2)
3739     return false;
3740
3741   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3742     unsigned i;
3743     for (i = 0; i != NumLaneElts; ++i) {
3744       if (Mask[i+l] >= 0)
3745         break;
3746     }
3747
3748     // Lane is all undef, go to next lane
3749     if (i == NumLaneElts)
3750       continue;
3751
3752     int Start = Mask[i+l];
3753
3754     // Make sure its in this lane in one of the sources
3755     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3756         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3757       return false;
3758
3759     // If not lane 0, then we must match lane 0
3760     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3761       return false;
3762
3763     // Correct second source to be contiguous with first source
3764     if (Start >= (int)NumElts)
3765       Start -= NumElts - NumLaneElts;
3766
3767     // Make sure we're shifting in the right direction.
3768     if (Start <= (int)(i+l))
3769       return false;
3770
3771     Start -= i;
3772
3773     // Check the rest of the elements to see if they are consecutive.
3774     for (++i; i != NumLaneElts; ++i) {
3775       int Idx = Mask[i+l];
3776
3777       // Make sure its in this lane
3778       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3779           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3780         return false;
3781
3782       // If not lane 0, then we must match lane 0
3783       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3784         return false;
3785
3786       if (Idx >= (int)NumElts)
3787         Idx -= NumElts - NumLaneElts;
3788
3789       if (!isUndefOrEqual(Idx, Start+i))
3790         return false;
3791
3792     }
3793   }
3794
3795   return true;
3796 }
3797
3798 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3799 /// the two vector operands have swapped position.
3800 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3801                                      unsigned NumElems) {
3802   for (unsigned i = 0; i != NumElems; ++i) {
3803     int idx = Mask[i];
3804     if (idx < 0)
3805       continue;
3806     else if (idx < (int)NumElems)
3807       Mask[i] = idx + NumElems;
3808     else
3809       Mask[i] = idx - NumElems;
3810   }
3811 }
3812
3813 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3814 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3815 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3816 /// reverse of what x86 shuffles want.
3817 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3818
3819   unsigned NumElems = VT.getVectorNumElements();
3820   unsigned NumLanes = VT.getSizeInBits()/128;
3821   unsigned NumLaneElems = NumElems/NumLanes;
3822
3823   if (NumLaneElems != 2 && NumLaneElems != 4)
3824     return false;
3825
3826   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3827   bool symetricMaskRequired =
3828     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3829
3830   // VSHUFPSY divides the resulting vector into 4 chunks.
3831   // The sources are also splitted into 4 chunks, and each destination
3832   // chunk must come from a different source chunk.
3833   //
3834   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3835   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3836   //
3837   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3838   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3839   //
3840   // VSHUFPDY divides the resulting vector into 4 chunks.
3841   // The sources are also splitted into 4 chunks, and each destination
3842   // chunk must come from a different source chunk.
3843   //
3844   //  SRC1 =>      X3       X2       X1       X0
3845   //  SRC2 =>      Y3       Y2       Y1       Y0
3846   //
3847   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3848   //
3849   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3850   unsigned HalfLaneElems = NumLaneElems/2;
3851   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3852     for (unsigned i = 0; i != NumLaneElems; ++i) {
3853       int Idx = Mask[i+l];
3854       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3855       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3856         return false;
3857       // For VSHUFPSY, the mask of the second half must be the same as the
3858       // first but with the appropriate offsets. This works in the same way as
3859       // VPERMILPS works with masks.
3860       if (!symetricMaskRequired || Idx < 0)
3861         continue;
3862       if (MaskVal[i] < 0) {
3863         MaskVal[i] = Idx - l;
3864         continue;
3865       }
3866       if ((signed)(Idx - l) != MaskVal[i])
3867         return false;
3868     }
3869   }
3870
3871   return true;
3872 }
3873
3874 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3875 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3876 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3877   if (!VT.is128BitVector())
3878     return false;
3879
3880   unsigned NumElems = VT.getVectorNumElements();
3881
3882   if (NumElems != 4)
3883     return false;
3884
3885   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3886   return isUndefOrEqual(Mask[0], 6) &&
3887          isUndefOrEqual(Mask[1], 7) &&
3888          isUndefOrEqual(Mask[2], 2) &&
3889          isUndefOrEqual(Mask[3], 3);
3890 }
3891
3892 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3893 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3894 /// <2, 3, 2, 3>
3895 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3896   if (!VT.is128BitVector())
3897     return false;
3898
3899   unsigned NumElems = VT.getVectorNumElements();
3900
3901   if (NumElems != 4)
3902     return false;
3903
3904   return isUndefOrEqual(Mask[0], 2) &&
3905          isUndefOrEqual(Mask[1], 3) &&
3906          isUndefOrEqual(Mask[2], 2) &&
3907          isUndefOrEqual(Mask[3], 3);
3908 }
3909
3910 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3912 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3913   if (!VT.is128BitVector())
3914     return false;
3915
3916   unsigned NumElems = VT.getVectorNumElements();
3917
3918   if (NumElems != 2 && NumElems != 4)
3919     return false;
3920
3921   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922     if (!isUndefOrEqual(Mask[i], i + NumElems))
3923       return false;
3924
3925   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3926     if (!isUndefOrEqual(Mask[i], i))
3927       return false;
3928
3929   return true;
3930 }
3931
3932 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3934 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3935   if (!VT.is128BitVector())
3936     return false;
3937
3938   unsigned NumElems = VT.getVectorNumElements();
3939
3940   if (NumElems != 2 && NumElems != 4)
3941     return false;
3942
3943   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3944     if (!isUndefOrEqual(Mask[i], i))
3945       return false;
3946
3947   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3948     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3949       return false;
3950
3951   return true;
3952 }
3953
3954 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3955 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3956 /// i. e: If all but one element come from the same vector.
3957 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3958   // TODO: Deal with AVX's VINSERTPS
3959   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3960     return false;
3961
3962   unsigned CorrectPosV1 = 0;
3963   unsigned CorrectPosV2 = 0;
3964   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3965     if (Mask[i] == i)
3966       ++CorrectPosV1;
3967     else if (Mask[i] == i + 4)
3968       ++CorrectPosV2;
3969
3970   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3971     // We have 3 elements from one vector, and one from another.
3972     return true;
3973
3974   return false;
3975 }
3976
3977 //
3978 // Some special combinations that can be optimized.
3979 //
3980 static
3981 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3982                                SelectionDAG &DAG) {
3983   MVT VT = SVOp->getSimpleValueType(0);
3984   SDLoc dl(SVOp);
3985
3986   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3987     return SDValue();
3988
3989   ArrayRef<int> Mask = SVOp->getMask();
3990
3991   // These are the special masks that may be optimized.
3992   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3993   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3994   bool MatchEvenMask = true;
3995   bool MatchOddMask  = true;
3996   for (int i=0; i<8; ++i) {
3997     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3998       MatchEvenMask = false;
3999     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4000       MatchOddMask = false;
4001   }
4002
4003   if (!MatchEvenMask && !MatchOddMask)
4004     return SDValue();
4005
4006   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4007
4008   SDValue Op0 = SVOp->getOperand(0);
4009   SDValue Op1 = SVOp->getOperand(1);
4010
4011   if (MatchEvenMask) {
4012     // Shift the second operand right to 32 bits.
4013     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4014     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4015   } else {
4016     // Shift the first operand left to 32 bits.
4017     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4018     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4019   }
4020   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4021   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4022 }
4023
4024 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4025 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4026 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4027                          bool HasInt256, bool V2IsSplat = false) {
4028
4029   assert(VT.getSizeInBits() >= 128 &&
4030          "Unsupported vector type for unpckl");
4031
4032   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4033   unsigned NumLanes;
4034   unsigned NumOf256BitLanes;
4035   unsigned NumElts = VT.getVectorNumElements();
4036   if (VT.is256BitVector()) {
4037     if (NumElts != 4 && NumElts != 8 &&
4038         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4039     return false;
4040     NumLanes = 2;
4041     NumOf256BitLanes = 1;
4042   } else if (VT.is512BitVector()) {
4043     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4044            "Unsupported vector type for unpckh");
4045     NumLanes = 2;
4046     NumOf256BitLanes = 2;
4047   } else {
4048     NumLanes = 1;
4049     NumOf256BitLanes = 1;
4050   }
4051
4052   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4053   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4054
4055   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4056     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4057       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4058         int BitI  = Mask[l256*NumEltsInStride+l+i];
4059         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4060         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4061           return false;
4062         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4063           return false;
4064         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4065           return false;
4066       }
4067     }
4068   }
4069   return true;
4070 }
4071
4072 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4073 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4074 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4075                          bool HasInt256, bool V2IsSplat = false) {
4076   assert(VT.getSizeInBits() >= 128 &&
4077          "Unsupported vector type for unpckh");
4078
4079   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4080   unsigned NumLanes;
4081   unsigned NumOf256BitLanes;
4082   unsigned NumElts = VT.getVectorNumElements();
4083   if (VT.is256BitVector()) {
4084     if (NumElts != 4 && NumElts != 8 &&
4085         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4086     return false;
4087     NumLanes = 2;
4088     NumOf256BitLanes = 1;
4089   } else if (VT.is512BitVector()) {
4090     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4091            "Unsupported vector type for unpckh");
4092     NumLanes = 2;
4093     NumOf256BitLanes = 2;
4094   } else {
4095     NumLanes = 1;
4096     NumOf256BitLanes = 1;
4097   }
4098
4099   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4100   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4101
4102   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4103     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4104       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4105         int BitI  = Mask[l256*NumEltsInStride+l+i];
4106         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4107         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4108           return false;
4109         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4110           return false;
4111         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4112           return false;
4113       }
4114     }
4115   }
4116   return true;
4117 }
4118
4119 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4120 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4121 /// <0, 0, 1, 1>
4122 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4123   unsigned NumElts = VT.getVectorNumElements();
4124   bool Is256BitVec = VT.is256BitVector();
4125
4126   if (VT.is512BitVector())
4127     return false;
4128   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4129          "Unsupported vector type for unpckh");
4130
4131   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4132       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4133     return false;
4134
4135   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4136   // FIXME: Need a better way to get rid of this, there's no latency difference
4137   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4138   // the former later. We should also remove the "_undef" special mask.
4139   if (NumElts == 4 && Is256BitVec)
4140     return false;
4141
4142   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4143   // independently on 128-bit lanes.
4144   unsigned NumLanes = VT.getSizeInBits()/128;
4145   unsigned NumLaneElts = NumElts/NumLanes;
4146
4147   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4148     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4149       int BitI  = Mask[l+i];
4150       int BitI1 = Mask[l+i+1];
4151
4152       if (!isUndefOrEqual(BitI, j))
4153         return false;
4154       if (!isUndefOrEqual(BitI1, j))
4155         return false;
4156     }
4157   }
4158
4159   return true;
4160 }
4161
4162 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4163 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4164 /// <2, 2, 3, 3>
4165 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4166   unsigned NumElts = VT.getVectorNumElements();
4167
4168   if (VT.is512BitVector())
4169     return false;
4170
4171   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4172          "Unsupported vector type for unpckh");
4173
4174   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4175       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4176     return false;
4177
4178   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4179   // independently on 128-bit lanes.
4180   unsigned NumLanes = VT.getSizeInBits()/128;
4181   unsigned NumLaneElts = NumElts/NumLanes;
4182
4183   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4184     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4185       int BitI  = Mask[l+i];
4186       int BitI1 = Mask[l+i+1];
4187       if (!isUndefOrEqual(BitI, j))
4188         return false;
4189       if (!isUndefOrEqual(BitI1, j))
4190         return false;
4191     }
4192   }
4193   return true;
4194 }
4195
4196 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4197 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4198 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4199   if (!VT.is512BitVector())
4200     return false;
4201
4202   unsigned NumElts = VT.getVectorNumElements();
4203   unsigned HalfSize = NumElts/2;
4204   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4205     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4206       *Imm = 1;
4207       return true;
4208     }
4209   }
4210   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4211     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4212       *Imm = 0;
4213       return true;
4214     }
4215   }
4216   return false;
4217 }
4218
4219 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4220 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4221 /// MOVSD, and MOVD, i.e. setting the lowest element.
4222 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4223   if (VT.getVectorElementType().getSizeInBits() < 32)
4224     return false;
4225   if (!VT.is128BitVector())
4226     return false;
4227
4228   unsigned NumElts = VT.getVectorNumElements();
4229
4230   if (!isUndefOrEqual(Mask[0], NumElts))
4231     return false;
4232
4233   for (unsigned i = 1; i != NumElts; ++i)
4234     if (!isUndefOrEqual(Mask[i], i))
4235       return false;
4236
4237   return true;
4238 }
4239
4240 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4241 /// as permutations between 128-bit chunks or halves. As an example: this
4242 /// shuffle bellow:
4243 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4244 /// The first half comes from the second half of V1 and the second half from the
4245 /// the second half of V2.
4246 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4247   if (!HasFp256 || !VT.is256BitVector())
4248     return false;
4249
4250   // The shuffle result is divided into half A and half B. In total the two
4251   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4252   // B must come from C, D, E or F.
4253   unsigned HalfSize = VT.getVectorNumElements()/2;
4254   bool MatchA = false, MatchB = false;
4255
4256   // Check if A comes from one of C, D, E, F.
4257   for (unsigned Half = 0; Half != 4; ++Half) {
4258     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4259       MatchA = true;
4260       break;
4261     }
4262   }
4263
4264   // Check if B comes from one of C, D, E, F.
4265   for (unsigned Half = 0; Half != 4; ++Half) {
4266     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4267       MatchB = true;
4268       break;
4269     }
4270   }
4271
4272   return MatchA && MatchB;
4273 }
4274
4275 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4276 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4277 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4278   MVT VT = SVOp->getSimpleValueType(0);
4279
4280   unsigned HalfSize = VT.getVectorNumElements()/2;
4281
4282   unsigned FstHalf = 0, SndHalf = 0;
4283   for (unsigned i = 0; i < HalfSize; ++i) {
4284     if (SVOp->getMaskElt(i) > 0) {
4285       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4286       break;
4287     }
4288   }
4289   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4290     if (SVOp->getMaskElt(i) > 0) {
4291       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4292       break;
4293     }
4294   }
4295
4296   return (FstHalf | (SndHalf << 4));
4297 }
4298
4299 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4300 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4301   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4302   if (EltSize < 32)
4303     return false;
4304
4305   unsigned NumElts = VT.getVectorNumElements();
4306   Imm8 = 0;
4307   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4308     for (unsigned i = 0; i != NumElts; ++i) {
4309       if (Mask[i] < 0)
4310         continue;
4311       Imm8 |= Mask[i] << (i*2);
4312     }
4313     return true;
4314   }
4315
4316   unsigned LaneSize = 4;
4317   SmallVector<int, 4> MaskVal(LaneSize, -1);
4318
4319   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4320     for (unsigned i = 0; i != LaneSize; ++i) {
4321       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4322         return false;
4323       if (Mask[i+l] < 0)
4324         continue;
4325       if (MaskVal[i] < 0) {
4326         MaskVal[i] = Mask[i+l] - l;
4327         Imm8 |= MaskVal[i] << (i*2);
4328         continue;
4329       }
4330       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4331         return false;
4332     }
4333   }
4334   return true;
4335 }
4336
4337 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4338 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4339 /// Note that VPERMIL mask matching is different depending whether theunderlying
4340 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4341 /// to the same elements of the low, but to the higher half of the source.
4342 /// In VPERMILPD the two lanes could be shuffled independently of each other
4343 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4344 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4345   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4346   if (VT.getSizeInBits() < 256 || EltSize < 32)
4347     return false;
4348   bool symetricMaskRequired = (EltSize == 32);
4349   unsigned NumElts = VT.getVectorNumElements();
4350
4351   unsigned NumLanes = VT.getSizeInBits()/128;
4352   unsigned LaneSize = NumElts/NumLanes;
4353   // 2 or 4 elements in one lane
4354
4355   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4356   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4357     for (unsigned i = 0; i != LaneSize; ++i) {
4358       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4359         return false;
4360       if (symetricMaskRequired) {
4361         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4362           ExpectedMaskVal[i] = Mask[i+l] - l;
4363           continue;
4364         }
4365         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4366           return false;
4367       }
4368     }
4369   }
4370   return true;
4371 }
4372
4373 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4374 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4375 /// element of vector 2 and the other elements to come from vector 1 in order.
4376 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4377                                bool V2IsSplat = false, bool V2IsUndef = false) {
4378   if (!VT.is128BitVector())
4379     return false;
4380
4381   unsigned NumOps = VT.getVectorNumElements();
4382   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4383     return false;
4384
4385   if (!isUndefOrEqual(Mask[0], 0))
4386     return false;
4387
4388   for (unsigned i = 1; i != NumOps; ++i)
4389     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4390           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4391           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4392       return false;
4393
4394   return true;
4395 }
4396
4397 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4398 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4399 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4400 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4401                            const X86Subtarget *Subtarget) {
4402   if (!Subtarget->hasSSE3())
4403     return false;
4404
4405   unsigned NumElems = VT.getVectorNumElements();
4406
4407   if ((VT.is128BitVector() && NumElems != 4) ||
4408       (VT.is256BitVector() && NumElems != 8) ||
4409       (VT.is512BitVector() && NumElems != 16))
4410     return false;
4411
4412   // "i+1" is the value the indexed mask element must have
4413   for (unsigned i = 0; i != NumElems; i += 2)
4414     if (!isUndefOrEqual(Mask[i], i+1) ||
4415         !isUndefOrEqual(Mask[i+1], i+1))
4416       return false;
4417
4418   return true;
4419 }
4420
4421 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4422 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4423 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4424 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4425                            const X86Subtarget *Subtarget) {
4426   if (!Subtarget->hasSSE3())
4427     return false;
4428
4429   unsigned NumElems = VT.getVectorNumElements();
4430
4431   if ((VT.is128BitVector() && NumElems != 4) ||
4432       (VT.is256BitVector() && NumElems != 8) ||
4433       (VT.is512BitVector() && NumElems != 16))
4434     return false;
4435
4436   // "i" is the value the indexed mask element must have
4437   for (unsigned i = 0; i != NumElems; i += 2)
4438     if (!isUndefOrEqual(Mask[i], i) ||
4439         !isUndefOrEqual(Mask[i+1], i))
4440       return false;
4441
4442   return true;
4443 }
4444
4445 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4446 /// specifies a shuffle of elements that is suitable for input to 256-bit
4447 /// version of MOVDDUP.
4448 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4449   if (!HasFp256 || !VT.is256BitVector())
4450     return false;
4451
4452   unsigned NumElts = VT.getVectorNumElements();
4453   if (NumElts != 4)
4454     return false;
4455
4456   for (unsigned i = 0; i != NumElts/2; ++i)
4457     if (!isUndefOrEqual(Mask[i], 0))
4458       return false;
4459   for (unsigned i = NumElts/2; i != NumElts; ++i)
4460     if (!isUndefOrEqual(Mask[i], NumElts/2))
4461       return false;
4462   return true;
4463 }
4464
4465 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4466 /// specifies a shuffle of elements that is suitable for input to 128-bit
4467 /// version of MOVDDUP.
4468 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4469   if (!VT.is128BitVector())
4470     return false;
4471
4472   unsigned e = VT.getVectorNumElements() / 2;
4473   for (unsigned i = 0; i != e; ++i)
4474     if (!isUndefOrEqual(Mask[i], i))
4475       return false;
4476   for (unsigned i = 0; i != e; ++i)
4477     if (!isUndefOrEqual(Mask[e+i], i))
4478       return false;
4479   return true;
4480 }
4481
4482 /// isVEXTRACTIndex - Return true if the specified
4483 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4484 /// suitable for instruction that extract 128 or 256 bit vectors
4485 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4486   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4487   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4488     return false;
4489
4490   // The index should be aligned on a vecWidth-bit boundary.
4491   uint64_t Index =
4492     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4493
4494   MVT VT = N->getSimpleValueType(0);
4495   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4496   bool Result = (Index * ElSize) % vecWidth == 0;
4497
4498   return Result;
4499 }
4500
4501 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4502 /// operand specifies a subvector insert that is suitable for input to
4503 /// insertion of 128 or 256-bit subvectors
4504 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4505   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4506   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4507     return false;
4508   // The index should be aligned on a vecWidth-bit boundary.
4509   uint64_t Index =
4510     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4511
4512   MVT VT = N->getSimpleValueType(0);
4513   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4514   bool Result = (Index * ElSize) % vecWidth == 0;
4515
4516   return Result;
4517 }
4518
4519 bool X86::isVINSERT128Index(SDNode *N) {
4520   return isVINSERTIndex(N, 128);
4521 }
4522
4523 bool X86::isVINSERT256Index(SDNode *N) {
4524   return isVINSERTIndex(N, 256);
4525 }
4526
4527 bool X86::isVEXTRACT128Index(SDNode *N) {
4528   return isVEXTRACTIndex(N, 128);
4529 }
4530
4531 bool X86::isVEXTRACT256Index(SDNode *N) {
4532   return isVEXTRACTIndex(N, 256);
4533 }
4534
4535 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4536 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4537 /// Handles 128-bit and 256-bit.
4538 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4539   MVT VT = N->getSimpleValueType(0);
4540
4541   assert((VT.getSizeInBits() >= 128) &&
4542          "Unsupported vector type for PSHUF/SHUFP");
4543
4544   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4545   // independently on 128-bit lanes.
4546   unsigned NumElts = VT.getVectorNumElements();
4547   unsigned NumLanes = VT.getSizeInBits()/128;
4548   unsigned NumLaneElts = NumElts/NumLanes;
4549
4550   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4551          "Only supports 2, 4 or 8 elements per lane");
4552
4553   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4554   unsigned Mask = 0;
4555   for (unsigned i = 0; i != NumElts; ++i) {
4556     int Elt = N->getMaskElt(i);
4557     if (Elt < 0) continue;
4558     Elt &= NumLaneElts - 1;
4559     unsigned ShAmt = (i << Shift) % 8;
4560     Mask |= Elt << ShAmt;
4561   }
4562
4563   return Mask;
4564 }
4565
4566 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4567 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4568 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4569   MVT VT = N->getSimpleValueType(0);
4570
4571   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4572          "Unsupported vector type for PSHUFHW");
4573
4574   unsigned NumElts = VT.getVectorNumElements();
4575
4576   unsigned Mask = 0;
4577   for (unsigned l = 0; l != NumElts; l += 8) {
4578     // 8 nodes per lane, but we only care about the last 4.
4579     for (unsigned i = 0; i < 4; ++i) {
4580       int Elt = N->getMaskElt(l+i+4);
4581       if (Elt < 0) continue;
4582       Elt &= 0x3; // only 2-bits.
4583       Mask |= Elt << (i * 2);
4584     }
4585   }
4586
4587   return Mask;
4588 }
4589
4590 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4591 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4592 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4593   MVT VT = N->getSimpleValueType(0);
4594
4595   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4596          "Unsupported vector type for PSHUFHW");
4597
4598   unsigned NumElts = VT.getVectorNumElements();
4599
4600   unsigned Mask = 0;
4601   for (unsigned l = 0; l != NumElts; l += 8) {
4602     // 8 nodes per lane, but we only care about the first 4.
4603     for (unsigned i = 0; i < 4; ++i) {
4604       int Elt = N->getMaskElt(l+i);
4605       if (Elt < 0) continue;
4606       Elt &= 0x3; // only 2-bits
4607       Mask |= Elt << (i * 2);
4608     }
4609   }
4610
4611   return Mask;
4612 }
4613
4614 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4615 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4616 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4617   MVT VT = SVOp->getSimpleValueType(0);
4618   unsigned EltSize = VT.is512BitVector() ? 1 :
4619     VT.getVectorElementType().getSizeInBits() >> 3;
4620
4621   unsigned NumElts = VT.getVectorNumElements();
4622   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4623   unsigned NumLaneElts = NumElts/NumLanes;
4624
4625   int Val = 0;
4626   unsigned i;
4627   for (i = 0; i != NumElts; ++i) {
4628     Val = SVOp->getMaskElt(i);
4629     if (Val >= 0)
4630       break;
4631   }
4632   if (Val >= (int)NumElts)
4633     Val -= NumElts - NumLaneElts;
4634
4635   assert(Val - i > 0 && "PALIGNR imm should be positive");
4636   return (Val - i) * EltSize;
4637 }
4638
4639 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4640   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4641   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4642     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4643
4644   uint64_t Index =
4645     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4646
4647   MVT VecVT = N->getOperand(0).getSimpleValueType();
4648   MVT ElVT = VecVT.getVectorElementType();
4649
4650   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4651   return Index / NumElemsPerChunk;
4652 }
4653
4654 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4655   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4656   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4657     llvm_unreachable("Illegal insert subvector for VINSERT");
4658
4659   uint64_t Index =
4660     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4661
4662   MVT VecVT = N->getSimpleValueType(0);
4663   MVT ElVT = VecVT.getVectorElementType();
4664
4665   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4666   return Index / NumElemsPerChunk;
4667 }
4668
4669 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4670 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4671 /// and VINSERTI128 instructions.
4672 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4673   return getExtractVEXTRACTImmediate(N, 128);
4674 }
4675
4676 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4677 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4678 /// and VINSERTI64x4 instructions.
4679 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4680   return getExtractVEXTRACTImmediate(N, 256);
4681 }
4682
4683 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4684 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4685 /// and VINSERTI128 instructions.
4686 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4687   return getInsertVINSERTImmediate(N, 128);
4688 }
4689
4690 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4691 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4692 /// and VINSERTI64x4 instructions.
4693 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4694   return getInsertVINSERTImmediate(N, 256);
4695 }
4696
4697 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4698 /// constant +0.0.
4699 bool X86::isZeroNode(SDValue Elt) {
4700   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4701     return CN->isNullValue();
4702   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4703     return CFP->getValueAPF().isPosZero();
4704   return false;
4705 }
4706
4707 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4708 /// their permute mask.
4709 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4710                                     SelectionDAG &DAG) {
4711   MVT VT = SVOp->getSimpleValueType(0);
4712   unsigned NumElems = VT.getVectorNumElements();
4713   SmallVector<int, 8> MaskVec;
4714
4715   for (unsigned i = 0; i != NumElems; ++i) {
4716     int Idx = SVOp->getMaskElt(i);
4717     if (Idx >= 0) {
4718       if (Idx < (int)NumElems)
4719         Idx += NumElems;
4720       else
4721         Idx -= NumElems;
4722     }
4723     MaskVec.push_back(Idx);
4724   }
4725   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4726                               SVOp->getOperand(0), &MaskVec[0]);
4727 }
4728
4729 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4730 /// match movhlps. The lower half elements should come from upper half of
4731 /// V1 (and in order), and the upper half elements should come from the upper
4732 /// half of V2 (and in order).
4733 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4734   if (!VT.is128BitVector())
4735     return false;
4736   if (VT.getVectorNumElements() != 4)
4737     return false;
4738   for (unsigned i = 0, e = 2; i != e; ++i)
4739     if (!isUndefOrEqual(Mask[i], i+2))
4740       return false;
4741   for (unsigned i = 2; i != 4; ++i)
4742     if (!isUndefOrEqual(Mask[i], i+4))
4743       return false;
4744   return true;
4745 }
4746
4747 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4748 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4749 /// required.
4750 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4751   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4752     return false;
4753   N = N->getOperand(0).getNode();
4754   if (!ISD::isNON_EXTLoad(N))
4755     return false;
4756   if (LD)
4757     *LD = cast<LoadSDNode>(N);
4758   return true;
4759 }
4760
4761 // Test whether the given value is a vector value which will be legalized
4762 // into a load.
4763 static bool WillBeConstantPoolLoad(SDNode *N) {
4764   if (N->getOpcode() != ISD::BUILD_VECTOR)
4765     return false;
4766
4767   // Check for any non-constant elements.
4768   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4769     switch (N->getOperand(i).getNode()->getOpcode()) {
4770     case ISD::UNDEF:
4771     case ISD::ConstantFP:
4772     case ISD::Constant:
4773       break;
4774     default:
4775       return false;
4776     }
4777
4778   // Vectors of all-zeros and all-ones are materialized with special
4779   // instructions rather than being loaded.
4780   return !ISD::isBuildVectorAllZeros(N) &&
4781          !ISD::isBuildVectorAllOnes(N);
4782 }
4783
4784 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4785 /// match movlp{s|d}. The lower half elements should come from lower half of
4786 /// V1 (and in order), and the upper half elements should come from the upper
4787 /// half of V2 (and in order). And since V1 will become the source of the
4788 /// MOVLP, it must be either a vector load or a scalar load to vector.
4789 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4790                                ArrayRef<int> Mask, MVT VT) {
4791   if (!VT.is128BitVector())
4792     return false;
4793
4794   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4795     return false;
4796   // Is V2 is a vector load, don't do this transformation. We will try to use
4797   // load folding shufps op.
4798   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4799     return false;
4800
4801   unsigned NumElems = VT.getVectorNumElements();
4802
4803   if (NumElems != 2 && NumElems != 4)
4804     return false;
4805   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4806     if (!isUndefOrEqual(Mask[i], i))
4807       return false;
4808   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4809     if (!isUndefOrEqual(Mask[i], i+NumElems))
4810       return false;
4811   return true;
4812 }
4813
4814 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4815 /// all the same.
4816 static bool isSplatVector(SDNode *N) {
4817   if (N->getOpcode() != ISD::BUILD_VECTOR)
4818     return false;
4819
4820   SDValue SplatValue = N->getOperand(0);
4821   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4822     if (N->getOperand(i) != SplatValue)
4823       return false;
4824   return true;
4825 }
4826
4827 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4828 /// to an zero vector.
4829 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4830 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4831   SDValue V1 = N->getOperand(0);
4832   SDValue V2 = N->getOperand(1);
4833   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4834   for (unsigned i = 0; i != NumElems; ++i) {
4835     int Idx = N->getMaskElt(i);
4836     if (Idx >= (int)NumElems) {
4837       unsigned Opc = V2.getOpcode();
4838       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4839         continue;
4840       if (Opc != ISD::BUILD_VECTOR ||
4841           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4842         return false;
4843     } else if (Idx >= 0) {
4844       unsigned Opc = V1.getOpcode();
4845       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4846         continue;
4847       if (Opc != ISD::BUILD_VECTOR ||
4848           !X86::isZeroNode(V1.getOperand(Idx)))
4849         return false;
4850     }
4851   }
4852   return true;
4853 }
4854
4855 /// getZeroVector - Returns a vector of specified type with all zero elements.
4856 ///
4857 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4858                              SelectionDAG &DAG, SDLoc dl) {
4859   assert(VT.isVector() && "Expected a vector type");
4860
4861   // Always build SSE zero vectors as <4 x i32> bitcasted
4862   // to their dest type. This ensures they get CSE'd.
4863   SDValue Vec;
4864   if (VT.is128BitVector()) {  // SSE
4865     if (Subtarget->hasSSE2()) {  // SSE2
4866       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4867       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4868     } else { // SSE1
4869       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4870       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4871     }
4872   } else if (VT.is256BitVector()) { // AVX
4873     if (Subtarget->hasInt256()) { // AVX2
4874       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4875       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4876       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4877     } else {
4878       // 256-bit logic and arithmetic instructions in AVX are all
4879       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4880       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4881       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4882       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4883     }
4884   } else if (VT.is512BitVector()) { // AVX-512
4885       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4886       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4887                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4888       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4889   } else if (VT.getScalarType() == MVT::i1) {
4890     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4891     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4892     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4893     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4894   } else
4895     llvm_unreachable("Unexpected vector type");
4896
4897   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4898 }
4899
4900 /// getOnesVector - Returns a vector of specified type with all bits set.
4901 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4902 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4903 /// Then bitcast to their original type, ensuring they get CSE'd.
4904 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4905                              SDLoc dl) {
4906   assert(VT.isVector() && "Expected a vector type");
4907
4908   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4909   SDValue Vec;
4910   if (VT.is256BitVector()) {
4911     if (HasInt256) { // AVX2
4912       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4914     } else { // AVX
4915       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4916       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4917     }
4918   } else if (VT.is128BitVector()) {
4919     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4920   } else
4921     llvm_unreachable("Unexpected vector type");
4922
4923   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4924 }
4925
4926 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4927 /// that point to V2 points to its first element.
4928 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4929   for (unsigned i = 0; i != NumElems; ++i) {
4930     if (Mask[i] > (int)NumElems) {
4931       Mask[i] = NumElems;
4932     }
4933   }
4934 }
4935
4936 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4937 /// operation of specified width.
4938 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4939                        SDValue V2) {
4940   unsigned NumElems = VT.getVectorNumElements();
4941   SmallVector<int, 8> Mask;
4942   Mask.push_back(NumElems);
4943   for (unsigned i = 1; i != NumElems; ++i)
4944     Mask.push_back(i);
4945   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4946 }
4947
4948 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4949 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4950                           SDValue V2) {
4951   unsigned NumElems = VT.getVectorNumElements();
4952   SmallVector<int, 8> Mask;
4953   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4954     Mask.push_back(i);
4955     Mask.push_back(i + NumElems);
4956   }
4957   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4958 }
4959
4960 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4961 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4962                           SDValue V2) {
4963   unsigned NumElems = VT.getVectorNumElements();
4964   SmallVector<int, 8> Mask;
4965   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4966     Mask.push_back(i + Half);
4967     Mask.push_back(i + NumElems + Half);
4968   }
4969   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4970 }
4971
4972 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4973 // a generic shuffle instruction because the target has no such instructions.
4974 // Generate shuffles which repeat i16 and i8 several times until they can be
4975 // represented by v4f32 and then be manipulated by target suported shuffles.
4976 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4977   MVT VT = V.getSimpleValueType();
4978   int NumElems = VT.getVectorNumElements();
4979   SDLoc dl(V);
4980
4981   while (NumElems > 4) {
4982     if (EltNo < NumElems/2) {
4983       V = getUnpackl(DAG, dl, VT, V, V);
4984     } else {
4985       V = getUnpackh(DAG, dl, VT, V, V);
4986       EltNo -= NumElems/2;
4987     }
4988     NumElems >>= 1;
4989   }
4990   return V;
4991 }
4992
4993 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4994 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4995   MVT VT = V.getSimpleValueType();
4996   SDLoc dl(V);
4997
4998   if (VT.is128BitVector()) {
4999     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5000     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5001     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5002                              &SplatMask[0]);
5003   } else if (VT.is256BitVector()) {
5004     // To use VPERMILPS to splat scalars, the second half of indicies must
5005     // refer to the higher part, which is a duplication of the lower one,
5006     // because VPERMILPS can only handle in-lane permutations.
5007     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5008                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5009
5010     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5011     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5012                              &SplatMask[0]);
5013   } else
5014     llvm_unreachable("Vector size not supported");
5015
5016   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5017 }
5018
5019 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5020 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5021   MVT SrcVT = SV->getSimpleValueType(0);
5022   SDValue V1 = SV->getOperand(0);
5023   SDLoc dl(SV);
5024
5025   int EltNo = SV->getSplatIndex();
5026   int NumElems = SrcVT.getVectorNumElements();
5027   bool Is256BitVec = SrcVT.is256BitVector();
5028
5029   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5030          "Unknown how to promote splat for type");
5031
5032   // Extract the 128-bit part containing the splat element and update
5033   // the splat element index when it refers to the higher register.
5034   if (Is256BitVec) {
5035     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5036     if (EltNo >= NumElems/2)
5037       EltNo -= NumElems/2;
5038   }
5039
5040   // All i16 and i8 vector types can't be used directly by a generic shuffle
5041   // instruction because the target has no such instruction. Generate shuffles
5042   // which repeat i16 and i8 several times until they fit in i32, and then can
5043   // be manipulated by target suported shuffles.
5044   MVT EltVT = SrcVT.getVectorElementType();
5045   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5046     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5047
5048   // Recreate the 256-bit vector and place the same 128-bit vector
5049   // into the low and high part. This is necessary because we want
5050   // to use VPERM* to shuffle the vectors
5051   if (Is256BitVec) {
5052     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5053   }
5054
5055   return getLegalSplat(DAG, V1, EltNo);
5056 }
5057
5058 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5059 /// vector of zero or undef vector.  This produces a shuffle where the low
5060 /// element of V2 is swizzled into the zero/undef vector, landing at element
5061 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5062 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5063                                            bool IsZero,
5064                                            const X86Subtarget *Subtarget,
5065                                            SelectionDAG &DAG) {
5066   MVT VT = V2.getSimpleValueType();
5067   SDValue V1 = IsZero
5068     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5069   unsigned NumElems = VT.getVectorNumElements();
5070   SmallVector<int, 16> MaskVec;
5071   for (unsigned i = 0; i != NumElems; ++i)
5072     // If this is the insertion idx, put the low elt of V2 here.
5073     MaskVec.push_back(i == Idx ? NumElems : i);
5074   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5075 }
5076
5077 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5078 /// target specific opcode. Returns true if the Mask could be calculated.
5079 /// Sets IsUnary to true if only uses one source.
5080 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5081                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5082   unsigned NumElems = VT.getVectorNumElements();
5083   SDValue ImmN;
5084
5085   IsUnary = false;
5086   switch(N->getOpcode()) {
5087   case X86ISD::SHUFP:
5088     ImmN = N->getOperand(N->getNumOperands()-1);
5089     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5090     break;
5091   case X86ISD::UNPCKH:
5092     DecodeUNPCKHMask(VT, Mask);
5093     break;
5094   case X86ISD::UNPCKL:
5095     DecodeUNPCKLMask(VT, Mask);
5096     break;
5097   case X86ISD::MOVHLPS:
5098     DecodeMOVHLPSMask(NumElems, Mask);
5099     break;
5100   case X86ISD::MOVLHPS:
5101     DecodeMOVLHPSMask(NumElems, Mask);
5102     break;
5103   case X86ISD::PALIGNR:
5104     ImmN = N->getOperand(N->getNumOperands()-1);
5105     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5106     break;
5107   case X86ISD::PSHUFD:
5108   case X86ISD::VPERMILP:
5109     ImmN = N->getOperand(N->getNumOperands()-1);
5110     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5111     IsUnary = true;
5112     break;
5113   case X86ISD::PSHUFHW:
5114     ImmN = N->getOperand(N->getNumOperands()-1);
5115     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5116     IsUnary = true;
5117     break;
5118   case X86ISD::PSHUFLW:
5119     ImmN = N->getOperand(N->getNumOperands()-1);
5120     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5121     IsUnary = true;
5122     break;
5123   case X86ISD::VPERMI:
5124     ImmN = N->getOperand(N->getNumOperands()-1);
5125     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5126     IsUnary = true;
5127     break;
5128   case X86ISD::MOVSS:
5129   case X86ISD::MOVSD: {
5130     // The index 0 always comes from the first element of the second source,
5131     // this is why MOVSS and MOVSD are used in the first place. The other
5132     // elements come from the other positions of the first source vector
5133     Mask.push_back(NumElems);
5134     for (unsigned i = 1; i != NumElems; ++i) {
5135       Mask.push_back(i);
5136     }
5137     break;
5138   }
5139   case X86ISD::VPERM2X128:
5140     ImmN = N->getOperand(N->getNumOperands()-1);
5141     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5142     if (Mask.empty()) return false;
5143     break;
5144   case X86ISD::MOVDDUP:
5145   case X86ISD::MOVLHPD:
5146   case X86ISD::MOVLPD:
5147   case X86ISD::MOVLPS:
5148   case X86ISD::MOVSHDUP:
5149   case X86ISD::MOVSLDUP:
5150     // Not yet implemented
5151     return false;
5152   default: llvm_unreachable("unknown target shuffle node");
5153   }
5154
5155   return true;
5156 }
5157
5158 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5159 /// element of the result of the vector shuffle.
5160 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5161                                    unsigned Depth) {
5162   if (Depth == 6)
5163     return SDValue();  // Limit search depth.
5164
5165   SDValue V = SDValue(N, 0);
5166   EVT VT = V.getValueType();
5167   unsigned Opcode = V.getOpcode();
5168
5169   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5170   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5171     int Elt = SV->getMaskElt(Index);
5172
5173     if (Elt < 0)
5174       return DAG.getUNDEF(VT.getVectorElementType());
5175
5176     unsigned NumElems = VT.getVectorNumElements();
5177     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5178                                          : SV->getOperand(1);
5179     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5180   }
5181
5182   // Recurse into target specific vector shuffles to find scalars.
5183   if (isTargetShuffle(Opcode)) {
5184     MVT ShufVT = V.getSimpleValueType();
5185     unsigned NumElems = ShufVT.getVectorNumElements();
5186     SmallVector<int, 16> ShuffleMask;
5187     bool IsUnary;
5188
5189     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5190       return SDValue();
5191
5192     int Elt = ShuffleMask[Index];
5193     if (Elt < 0)
5194       return DAG.getUNDEF(ShufVT.getVectorElementType());
5195
5196     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5197                                          : N->getOperand(1);
5198     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5199                                Depth+1);
5200   }
5201
5202   // Actual nodes that may contain scalar elements
5203   if (Opcode == ISD::BITCAST) {
5204     V = V.getOperand(0);
5205     EVT SrcVT = V.getValueType();
5206     unsigned NumElems = VT.getVectorNumElements();
5207
5208     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5209       return SDValue();
5210   }
5211
5212   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5213     return (Index == 0) ? V.getOperand(0)
5214                         : DAG.getUNDEF(VT.getVectorElementType());
5215
5216   if (V.getOpcode() == ISD::BUILD_VECTOR)
5217     return V.getOperand(Index);
5218
5219   return SDValue();
5220 }
5221
5222 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5223 /// shuffle operation which come from a consecutively from a zero. The
5224 /// search can start in two different directions, from left or right.
5225 /// We count undefs as zeros until PreferredNum is reached.
5226 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5227                                          unsigned NumElems, bool ZerosFromLeft,
5228                                          SelectionDAG &DAG,
5229                                          unsigned PreferredNum = -1U) {
5230   unsigned NumZeros = 0;
5231   for (unsigned i = 0; i != NumElems; ++i) {
5232     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5233     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5234     if (!Elt.getNode())
5235       break;
5236
5237     if (X86::isZeroNode(Elt))
5238       ++NumZeros;
5239     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5240       NumZeros = std::min(NumZeros + 1, PreferredNum);
5241     else
5242       break;
5243   }
5244
5245   return NumZeros;
5246 }
5247
5248 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5249 /// correspond consecutively to elements from one of the vector operands,
5250 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5251 static
5252 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5253                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5254                               unsigned NumElems, unsigned &OpNum) {
5255   bool SeenV1 = false;
5256   bool SeenV2 = false;
5257
5258   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5259     int Idx = SVOp->getMaskElt(i);
5260     // Ignore undef indicies
5261     if (Idx < 0)
5262       continue;
5263
5264     if (Idx < (int)NumElems)
5265       SeenV1 = true;
5266     else
5267       SeenV2 = true;
5268
5269     // Only accept consecutive elements from the same vector
5270     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5271       return false;
5272   }
5273
5274   OpNum = SeenV1 ? 0 : 1;
5275   return true;
5276 }
5277
5278 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5279 /// logical left shift of a vector.
5280 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5281                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5282   unsigned NumElems =
5283     SVOp->getSimpleValueType(0).getVectorNumElements();
5284   unsigned NumZeros = getNumOfConsecutiveZeros(
5285       SVOp, NumElems, false /* check zeros from right */, DAG,
5286       SVOp->getMaskElt(0));
5287   unsigned OpSrc;
5288
5289   if (!NumZeros)
5290     return false;
5291
5292   // Considering the elements in the mask that are not consecutive zeros,
5293   // check if they consecutively come from only one of the source vectors.
5294   //
5295   //               V1 = {X, A, B, C}     0
5296   //                         \  \  \    /
5297   //   vector_shuffle V1, V2 <1, 2, 3, X>
5298   //
5299   if (!isShuffleMaskConsecutive(SVOp,
5300             0,                   // Mask Start Index
5301             NumElems-NumZeros,   // Mask End Index(exclusive)
5302             NumZeros,            // Where to start looking in the src vector
5303             NumElems,            // Number of elements in vector
5304             OpSrc))              // Which source operand ?
5305     return false;
5306
5307   isLeft = false;
5308   ShAmt = NumZeros;
5309   ShVal = SVOp->getOperand(OpSrc);
5310   return true;
5311 }
5312
5313 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5314 /// logical left shift of a vector.
5315 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5316                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5317   unsigned NumElems =
5318     SVOp->getSimpleValueType(0).getVectorNumElements();
5319   unsigned NumZeros = getNumOfConsecutiveZeros(
5320       SVOp, NumElems, true /* check zeros from left */, DAG,
5321       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5322   unsigned OpSrc;
5323
5324   if (!NumZeros)
5325     return false;
5326
5327   // Considering the elements in the mask that are not consecutive zeros,
5328   // check if they consecutively come from only one of the source vectors.
5329   //
5330   //                           0    { A, B, X, X } = V2
5331   //                          / \    /  /
5332   //   vector_shuffle V1, V2 <X, X, 4, 5>
5333   //
5334   if (!isShuffleMaskConsecutive(SVOp,
5335             NumZeros,     // Mask Start Index
5336             NumElems,     // Mask End Index(exclusive)
5337             0,            // Where to start looking in the src vector
5338             NumElems,     // Number of elements in vector
5339             OpSrc))       // Which source operand ?
5340     return false;
5341
5342   isLeft = true;
5343   ShAmt = NumZeros;
5344   ShVal = SVOp->getOperand(OpSrc);
5345   return true;
5346 }
5347
5348 /// isVectorShift - Returns true if the shuffle can be implemented as a
5349 /// logical left or right shift of a vector.
5350 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5351                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5352   // Although the logic below support any bitwidth size, there are no
5353   // shift instructions which handle more than 128-bit vectors.
5354   if (!SVOp->getSimpleValueType(0).is128BitVector())
5355     return false;
5356
5357   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5358       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5359     return true;
5360
5361   return false;
5362 }
5363
5364 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5365 ///
5366 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5367                                        unsigned NumNonZero, unsigned NumZero,
5368                                        SelectionDAG &DAG,
5369                                        const X86Subtarget* Subtarget,
5370                                        const TargetLowering &TLI) {
5371   if (NumNonZero > 8)
5372     return SDValue();
5373
5374   SDLoc dl(Op);
5375   SDValue V;
5376   bool First = true;
5377   for (unsigned i = 0; i < 16; ++i) {
5378     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5379     if (ThisIsNonZero && First) {
5380       if (NumZero)
5381         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5382       else
5383         V = DAG.getUNDEF(MVT::v8i16);
5384       First = false;
5385     }
5386
5387     if ((i & 1) != 0) {
5388       SDValue ThisElt, LastElt;
5389       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5390       if (LastIsNonZero) {
5391         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5392                               MVT::i16, Op.getOperand(i-1));
5393       }
5394       if (ThisIsNonZero) {
5395         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5396         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5397                               ThisElt, DAG.getConstant(8, MVT::i8));
5398         if (LastIsNonZero)
5399           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5400       } else
5401         ThisElt = LastElt;
5402
5403       if (ThisElt.getNode())
5404         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5405                         DAG.getIntPtrConstant(i/2));
5406     }
5407   }
5408
5409   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5410 }
5411
5412 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5413 ///
5414 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5415                                      unsigned NumNonZero, unsigned NumZero,
5416                                      SelectionDAG &DAG,
5417                                      const X86Subtarget* Subtarget,
5418                                      const TargetLowering &TLI) {
5419   if (NumNonZero > 4)
5420     return SDValue();
5421
5422   SDLoc dl(Op);
5423   SDValue V;
5424   bool First = true;
5425   for (unsigned i = 0; i < 8; ++i) {
5426     bool isNonZero = (NonZeros & (1 << i)) != 0;
5427     if (isNonZero) {
5428       if (First) {
5429         if (NumZero)
5430           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5431         else
5432           V = DAG.getUNDEF(MVT::v8i16);
5433         First = false;
5434       }
5435       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5436                       MVT::v8i16, V, Op.getOperand(i),
5437                       DAG.getIntPtrConstant(i));
5438     }
5439   }
5440
5441   return V;
5442 }
5443
5444 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5445 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5446                                      unsigned NonZeros, unsigned NumNonZero,
5447                                      unsigned NumZero, SelectionDAG &DAG,
5448                                      const X86Subtarget *Subtarget,
5449                                      const TargetLowering &TLI) {
5450   // We know there's at least one non-zero element
5451   unsigned FirstNonZeroIdx = 0;
5452   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5453   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5454          X86::isZeroNode(FirstNonZero)) {
5455     ++FirstNonZeroIdx;
5456     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5457   }
5458
5459   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5460       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5461     return SDValue();
5462
5463   SDValue V = FirstNonZero.getOperand(0);
5464   MVT VVT = V.getSimpleValueType();
5465   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5466     return SDValue();
5467
5468   unsigned FirstNonZeroDst =
5469       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5470   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5471   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5472   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5473
5474   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5475     SDValue Elem = Op.getOperand(Idx);
5476     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5477       continue;
5478
5479     // TODO: What else can be here? Deal with it.
5480     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5481       return SDValue();
5482
5483     // TODO: Some optimizations are still possible here
5484     // ex: Getting one element from a vector, and the rest from another.
5485     if (Elem.getOperand(0) != V)
5486       return SDValue();
5487
5488     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5489     if (Dst == Idx)
5490       ++CorrectIdx;
5491     else if (IncorrectIdx == -1U) {
5492       IncorrectIdx = Idx;
5493       IncorrectDst = Dst;
5494     } else
5495       // There was already one element with an incorrect index.
5496       // We can't optimize this case to an insertps.
5497       return SDValue();
5498   }
5499
5500   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5501     SDLoc dl(Op);
5502     EVT VT = Op.getSimpleValueType();
5503     unsigned ElementMoveMask = 0;
5504     if (IncorrectIdx == -1U)
5505       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5506     else
5507       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5508
5509     SDValue InsertpsMask =
5510         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5511     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5512   }
5513
5514   return SDValue();
5515 }
5516
5517 /// getVShift - Return a vector logical shift node.
5518 ///
5519 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5520                          unsigned NumBits, SelectionDAG &DAG,
5521                          const TargetLowering &TLI, SDLoc dl) {
5522   assert(VT.is128BitVector() && "Unknown type for VShift");
5523   EVT ShVT = MVT::v2i64;
5524   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5525   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5526   return DAG.getNode(ISD::BITCAST, dl, VT,
5527                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5528                              DAG.getConstant(NumBits,
5529                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5530 }
5531
5532 static SDValue
5533 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5534
5535   // Check if the scalar load can be widened into a vector load. And if
5536   // the address is "base + cst" see if the cst can be "absorbed" into
5537   // the shuffle mask.
5538   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5539     SDValue Ptr = LD->getBasePtr();
5540     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5541       return SDValue();
5542     EVT PVT = LD->getValueType(0);
5543     if (PVT != MVT::i32 && PVT != MVT::f32)
5544       return SDValue();
5545
5546     int FI = -1;
5547     int64_t Offset = 0;
5548     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5549       FI = FINode->getIndex();
5550       Offset = 0;
5551     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5552                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5553       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5554       Offset = Ptr.getConstantOperandVal(1);
5555       Ptr = Ptr.getOperand(0);
5556     } else {
5557       return SDValue();
5558     }
5559
5560     // FIXME: 256-bit vector instructions don't require a strict alignment,
5561     // improve this code to support it better.
5562     unsigned RequiredAlign = VT.getSizeInBits()/8;
5563     SDValue Chain = LD->getChain();
5564     // Make sure the stack object alignment is at least 16 or 32.
5565     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5566     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5567       if (MFI->isFixedObjectIndex(FI)) {
5568         // Can't change the alignment. FIXME: It's possible to compute
5569         // the exact stack offset and reference FI + adjust offset instead.
5570         // If someone *really* cares about this. That's the way to implement it.
5571         return SDValue();
5572       } else {
5573         MFI->setObjectAlignment(FI, RequiredAlign);
5574       }
5575     }
5576
5577     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5578     // Ptr + (Offset & ~15).
5579     if (Offset < 0)
5580       return SDValue();
5581     if ((Offset % RequiredAlign) & 3)
5582       return SDValue();
5583     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5584     if (StartOffset)
5585       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5586                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5587
5588     int EltNo = (Offset - StartOffset) >> 2;
5589     unsigned NumElems = VT.getVectorNumElements();
5590
5591     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5592     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5593                              LD->getPointerInfo().getWithOffset(StartOffset),
5594                              false, false, false, 0);
5595
5596     SmallVector<int, 8> Mask;
5597     for (unsigned i = 0; i != NumElems; ++i)
5598       Mask.push_back(EltNo);
5599
5600     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5601   }
5602
5603   return SDValue();
5604 }
5605
5606 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5607 /// vector of type 'VT', see if the elements can be replaced by a single large
5608 /// load which has the same value as a build_vector whose operands are 'elts'.
5609 ///
5610 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5611 ///
5612 /// FIXME: we'd also like to handle the case where the last elements are zero
5613 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5614 /// There's even a handy isZeroNode for that purpose.
5615 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5616                                         SDLoc &DL, SelectionDAG &DAG,
5617                                         bool isAfterLegalize) {
5618   EVT EltVT = VT.getVectorElementType();
5619   unsigned NumElems = Elts.size();
5620
5621   LoadSDNode *LDBase = nullptr;
5622   unsigned LastLoadedElt = -1U;
5623
5624   // For each element in the initializer, see if we've found a load or an undef.
5625   // If we don't find an initial load element, or later load elements are
5626   // non-consecutive, bail out.
5627   for (unsigned i = 0; i < NumElems; ++i) {
5628     SDValue Elt = Elts[i];
5629
5630     if (!Elt.getNode() ||
5631         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5632       return SDValue();
5633     if (!LDBase) {
5634       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5635         return SDValue();
5636       LDBase = cast<LoadSDNode>(Elt.getNode());
5637       LastLoadedElt = i;
5638       continue;
5639     }
5640     if (Elt.getOpcode() == ISD::UNDEF)
5641       continue;
5642
5643     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5644     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5645       return SDValue();
5646     LastLoadedElt = i;
5647   }
5648
5649   // If we have found an entire vector of loads and undefs, then return a large
5650   // load of the entire vector width starting at the base pointer.  If we found
5651   // consecutive loads for the low half, generate a vzext_load node.
5652   if (LastLoadedElt == NumElems - 1) {
5653
5654     if (isAfterLegalize &&
5655         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5656       return SDValue();
5657
5658     SDValue NewLd = SDValue();
5659
5660     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5661       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5662                           LDBase->getPointerInfo(),
5663                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5664                           LDBase->isInvariant(), 0);
5665     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5666                         LDBase->getPointerInfo(),
5667                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5668                         LDBase->isInvariant(), LDBase->getAlignment());
5669
5670     if (LDBase->hasAnyUseOfValue(1)) {
5671       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5672                                      SDValue(LDBase, 1),
5673                                      SDValue(NewLd.getNode(), 1));
5674       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5675       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5676                              SDValue(NewLd.getNode(), 1));
5677     }
5678
5679     return NewLd;
5680   }
5681   if (NumElems == 4 && LastLoadedElt == 1 &&
5682       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5683     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5684     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5685     SDValue ResNode =
5686         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5687                                 LDBase->getPointerInfo(),
5688                                 LDBase->getAlignment(),
5689                                 false/*isVolatile*/, true/*ReadMem*/,
5690                                 false/*WriteMem*/);
5691
5692     // Make sure the newly-created LOAD is in the same position as LDBase in
5693     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5694     // update uses of LDBase's output chain to use the TokenFactor.
5695     if (LDBase->hasAnyUseOfValue(1)) {
5696       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5697                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5698       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5699       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5700                              SDValue(ResNode.getNode(), 1));
5701     }
5702
5703     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5704   }
5705   return SDValue();
5706 }
5707
5708 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5709 /// to generate a splat value for the following cases:
5710 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5711 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5712 /// a scalar load, or a constant.
5713 /// The VBROADCAST node is returned when a pattern is found,
5714 /// or SDValue() otherwise.
5715 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5716                                     SelectionDAG &DAG) {
5717   if (!Subtarget->hasFp256())
5718     return SDValue();
5719
5720   MVT VT = Op.getSimpleValueType();
5721   SDLoc dl(Op);
5722
5723   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5724          "Unsupported vector type for broadcast.");
5725
5726   SDValue Ld;
5727   bool ConstSplatVal;
5728
5729   switch (Op.getOpcode()) {
5730     default:
5731       // Unknown pattern found.
5732       return SDValue();
5733
5734     case ISD::BUILD_VECTOR: {
5735       // The BUILD_VECTOR node must be a splat.
5736       if (!isSplatVector(Op.getNode()))
5737         return SDValue();
5738
5739       Ld = Op.getOperand(0);
5740       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5741                      Ld.getOpcode() == ISD::ConstantFP);
5742
5743       // The suspected load node has several users. Make sure that all
5744       // of its users are from the BUILD_VECTOR node.
5745       // Constants may have multiple users.
5746       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5747         return SDValue();
5748       break;
5749     }
5750
5751     case ISD::VECTOR_SHUFFLE: {
5752       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5753
5754       // Shuffles must have a splat mask where the first element is
5755       // broadcasted.
5756       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5757         return SDValue();
5758
5759       SDValue Sc = Op.getOperand(0);
5760       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5761           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5762
5763         if (!Subtarget->hasInt256())
5764           return SDValue();
5765
5766         // Use the register form of the broadcast instruction available on AVX2.
5767         if (VT.getSizeInBits() >= 256)
5768           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5769         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5770       }
5771
5772       Ld = Sc.getOperand(0);
5773       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5774                        Ld.getOpcode() == ISD::ConstantFP);
5775
5776       // The scalar_to_vector node and the suspected
5777       // load node must have exactly one user.
5778       // Constants may have multiple users.
5779
5780       // AVX-512 has register version of the broadcast
5781       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5782         Ld.getValueType().getSizeInBits() >= 32;
5783       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5784           !hasRegVer))
5785         return SDValue();
5786       break;
5787     }
5788   }
5789
5790   bool IsGE256 = (VT.getSizeInBits() >= 256);
5791
5792   // Handle the broadcasting a single constant scalar from the constant pool
5793   // into a vector. On Sandybridge it is still better to load a constant vector
5794   // from the constant pool and not to broadcast it from a scalar.
5795   if (ConstSplatVal && Subtarget->hasInt256()) {
5796     EVT CVT = Ld.getValueType();
5797     assert(!CVT.isVector() && "Must not broadcast a vector type");
5798     unsigned ScalarSize = CVT.getSizeInBits();
5799
5800     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5801       const Constant *C = nullptr;
5802       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5803         C = CI->getConstantIntValue();
5804       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5805         C = CF->getConstantFPValue();
5806
5807       assert(C && "Invalid constant type");
5808
5809       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5810       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5811       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5812       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5813                        MachinePointerInfo::getConstantPool(),
5814                        false, false, false, Alignment);
5815
5816       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5817     }
5818   }
5819
5820   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5821   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5822
5823   // Handle AVX2 in-register broadcasts.
5824   if (!IsLoad && Subtarget->hasInt256() &&
5825       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5826     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5827
5828   // The scalar source must be a normal load.
5829   if (!IsLoad)
5830     return SDValue();
5831
5832   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5833     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5834
5835   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5836   // double since there is no vbroadcastsd xmm
5837   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5838     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5839       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5840   }
5841
5842   // Unsupported broadcast.
5843   return SDValue();
5844 }
5845
5846 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5847 /// underlying vector and index.
5848 ///
5849 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5850 /// index.
5851 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5852                                          SDValue ExtIdx) {
5853   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5854   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5855     return Idx;
5856
5857   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5858   // lowered this:
5859   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5860   // to:
5861   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5862   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5863   //                           undef)
5864   //                       Constant<0>)
5865   // In this case the vector is the extract_subvector expression and the index
5866   // is 2, as specified by the shuffle.
5867   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5868   SDValue ShuffleVec = SVOp->getOperand(0);
5869   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5870   assert(ShuffleVecVT.getVectorElementType() ==
5871          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5872
5873   int ShuffleIdx = SVOp->getMaskElt(Idx);
5874   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5875     ExtractedFromVec = ShuffleVec;
5876     return ShuffleIdx;
5877   }
5878   return Idx;
5879 }
5880
5881 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5882   MVT VT = Op.getSimpleValueType();
5883
5884   // Skip if insert_vec_elt is not supported.
5885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5886   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5887     return SDValue();
5888
5889   SDLoc DL(Op);
5890   unsigned NumElems = Op.getNumOperands();
5891
5892   SDValue VecIn1;
5893   SDValue VecIn2;
5894   SmallVector<unsigned, 4> InsertIndices;
5895   SmallVector<int, 8> Mask(NumElems, -1);
5896
5897   for (unsigned i = 0; i != NumElems; ++i) {
5898     unsigned Opc = Op.getOperand(i).getOpcode();
5899
5900     if (Opc == ISD::UNDEF)
5901       continue;
5902
5903     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5904       // Quit if more than 1 elements need inserting.
5905       if (InsertIndices.size() > 1)
5906         return SDValue();
5907
5908       InsertIndices.push_back(i);
5909       continue;
5910     }
5911
5912     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5913     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5914     // Quit if non-constant index.
5915     if (!isa<ConstantSDNode>(ExtIdx))
5916       return SDValue();
5917     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5918
5919     // Quit if extracted from vector of different type.
5920     if (ExtractedFromVec.getValueType() != VT)
5921       return SDValue();
5922
5923     if (!VecIn1.getNode())
5924       VecIn1 = ExtractedFromVec;
5925     else if (VecIn1 != ExtractedFromVec) {
5926       if (!VecIn2.getNode())
5927         VecIn2 = ExtractedFromVec;
5928       else if (VecIn2 != ExtractedFromVec)
5929         // Quit if more than 2 vectors to shuffle
5930         return SDValue();
5931     }
5932
5933     if (ExtractedFromVec == VecIn1)
5934       Mask[i] = Idx;
5935     else if (ExtractedFromVec == VecIn2)
5936       Mask[i] = Idx + NumElems;
5937   }
5938
5939   if (!VecIn1.getNode())
5940     return SDValue();
5941
5942   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5943   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5944   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5945     unsigned Idx = InsertIndices[i];
5946     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5947                      DAG.getIntPtrConstant(Idx));
5948   }
5949
5950   return NV;
5951 }
5952
5953 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5954 SDValue
5955 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5956
5957   MVT VT = Op.getSimpleValueType();
5958   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5959          "Unexpected type in LowerBUILD_VECTORvXi1!");
5960
5961   SDLoc dl(Op);
5962   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5963     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5964     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5965     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5966   }
5967
5968   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5969     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5970     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5971     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5972   }
5973
5974   bool AllContants = true;
5975   uint64_t Immediate = 0;
5976   int NonConstIdx = -1;
5977   bool IsSplat = true;
5978   unsigned NumNonConsts = 0;
5979   unsigned NumConsts = 0;
5980   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5981     SDValue In = Op.getOperand(idx);
5982     if (In.getOpcode() == ISD::UNDEF)
5983       continue;
5984     if (!isa<ConstantSDNode>(In)) {
5985       AllContants = false;
5986       NonConstIdx = idx;
5987       NumNonConsts++;
5988     }
5989     else {
5990       NumConsts++;
5991       if (cast<ConstantSDNode>(In)->getZExtValue())
5992       Immediate |= (1ULL << idx);
5993     }
5994     if (In != Op.getOperand(0))
5995       IsSplat = false;
5996   }
5997
5998   if (AllContants) {
5999     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6000       DAG.getConstant(Immediate, MVT::i16));
6001     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6002                        DAG.getIntPtrConstant(0));
6003   }
6004
6005   if (NumNonConsts == 1 && NonConstIdx != 0) {
6006     SDValue DstVec;
6007     if (NumConsts) {
6008       SDValue VecAsImm = DAG.getConstant(Immediate,
6009                                          MVT::getIntegerVT(VT.getSizeInBits()));
6010       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6011     }
6012     else 
6013       DstVec = DAG.getUNDEF(VT);
6014     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6015                        Op.getOperand(NonConstIdx),
6016                        DAG.getIntPtrConstant(NonConstIdx));
6017   }
6018   if (!IsSplat && (NonConstIdx != 0))
6019     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6020   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6021   SDValue Select;
6022   if (IsSplat)
6023     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6024                           DAG.getConstant(-1, SelectVT),
6025                           DAG.getConstant(0, SelectVT));
6026   else
6027     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6028                          DAG.getConstant((Immediate | 1), SelectVT),
6029                          DAG.getConstant(Immediate, SelectVT));
6030   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6031 }
6032
6033 SDValue
6034 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6035   SDLoc dl(Op);
6036
6037   MVT VT = Op.getSimpleValueType();
6038   MVT ExtVT = VT.getVectorElementType();
6039   unsigned NumElems = Op.getNumOperands();
6040
6041   // Generate vectors for predicate vectors.
6042   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6043     return LowerBUILD_VECTORvXi1(Op, DAG);
6044
6045   // Vectors containing all zeros can be matched by pxor and xorps later
6046   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6047     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6048     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6049     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6050       return Op;
6051
6052     return getZeroVector(VT, Subtarget, DAG, dl);
6053   }
6054
6055   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6056   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6057   // vpcmpeqd on 256-bit vectors.
6058   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6059     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6060       return Op;
6061
6062     if (!VT.is512BitVector())
6063       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6064   }
6065
6066   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6067   if (Broadcast.getNode())
6068     return Broadcast;
6069
6070   unsigned EVTBits = ExtVT.getSizeInBits();
6071
6072   unsigned NumZero  = 0;
6073   unsigned NumNonZero = 0;
6074   unsigned NonZeros = 0;
6075   bool IsAllConstants = true;
6076   SmallSet<SDValue, 8> Values;
6077   for (unsigned i = 0; i < NumElems; ++i) {
6078     SDValue Elt = Op.getOperand(i);
6079     if (Elt.getOpcode() == ISD::UNDEF)
6080       continue;
6081     Values.insert(Elt);
6082     if (Elt.getOpcode() != ISD::Constant &&
6083         Elt.getOpcode() != ISD::ConstantFP)
6084       IsAllConstants = false;
6085     if (X86::isZeroNode(Elt))
6086       NumZero++;
6087     else {
6088       NonZeros |= (1 << i);
6089       NumNonZero++;
6090     }
6091   }
6092
6093   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6094   if (NumNonZero == 0)
6095     return DAG.getUNDEF(VT);
6096
6097   // Special case for single non-zero, non-undef, element.
6098   if (NumNonZero == 1) {
6099     unsigned Idx = countTrailingZeros(NonZeros);
6100     SDValue Item = Op.getOperand(Idx);
6101
6102     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6103     // the value are obviously zero, truncate the value to i32 and do the
6104     // insertion that way.  Only do this if the value is non-constant or if the
6105     // value is a constant being inserted into element 0.  It is cheaper to do
6106     // a constant pool load than it is to do a movd + shuffle.
6107     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6108         (!IsAllConstants || Idx == 0)) {
6109       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6110         // Handle SSE only.
6111         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6112         EVT VecVT = MVT::v4i32;
6113         unsigned VecElts = 4;
6114
6115         // Truncate the value (which may itself be a constant) to i32, and
6116         // convert it to a vector with movd (S2V+shuffle to zero extend).
6117         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6118         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6119         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6120
6121         // Now we have our 32-bit value zero extended in the low element of
6122         // a vector.  If Idx != 0, swizzle it into place.
6123         if (Idx != 0) {
6124           SmallVector<int, 4> Mask;
6125           Mask.push_back(Idx);
6126           for (unsigned i = 1; i != VecElts; ++i)
6127             Mask.push_back(i);
6128           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6129                                       &Mask[0]);
6130         }
6131         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6132       }
6133     }
6134
6135     // If we have a constant or non-constant insertion into the low element of
6136     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6137     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6138     // depending on what the source datatype is.
6139     if (Idx == 0) {
6140       if (NumZero == 0)
6141         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6142
6143       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6144           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6145         if (VT.is256BitVector() || VT.is512BitVector()) {
6146           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6147           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6148                              Item, DAG.getIntPtrConstant(0));
6149         }
6150         assert(VT.is128BitVector() && "Expected an SSE value type!");
6151         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6152         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6153         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6154       }
6155
6156       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6157         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6158         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6159         if (VT.is256BitVector()) {
6160           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6161           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6162         } else {
6163           assert(VT.is128BitVector() && "Expected an SSE value type!");
6164           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6165         }
6166         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6167       }
6168     }
6169
6170     // Is it a vector logical left shift?
6171     if (NumElems == 2 && Idx == 1 &&
6172         X86::isZeroNode(Op.getOperand(0)) &&
6173         !X86::isZeroNode(Op.getOperand(1))) {
6174       unsigned NumBits = VT.getSizeInBits();
6175       return getVShift(true, VT,
6176                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6177                                    VT, Op.getOperand(1)),
6178                        NumBits/2, DAG, *this, dl);
6179     }
6180
6181     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6182       return SDValue();
6183
6184     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6185     // is a non-constant being inserted into an element other than the low one,
6186     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6187     // movd/movss) to move this into the low element, then shuffle it into
6188     // place.
6189     if (EVTBits == 32) {
6190       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6191
6192       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6193       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6194       SmallVector<int, 8> MaskVec;
6195       for (unsigned i = 0; i != NumElems; ++i)
6196         MaskVec.push_back(i == Idx ? 0 : 1);
6197       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6198     }
6199   }
6200
6201   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6202   if (Values.size() == 1) {
6203     if (EVTBits == 32) {
6204       // Instead of a shuffle like this:
6205       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6206       // Check if it's possible to issue this instead.
6207       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6208       unsigned Idx = countTrailingZeros(NonZeros);
6209       SDValue Item = Op.getOperand(Idx);
6210       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6211         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6212     }
6213     return SDValue();
6214   }
6215
6216   // A vector full of immediates; various special cases are already
6217   // handled, so this is best done with a single constant-pool load.
6218   if (IsAllConstants)
6219     return SDValue();
6220
6221   // For AVX-length vectors, build the individual 128-bit pieces and use
6222   // shuffles to put them in place.
6223   if (VT.is256BitVector() || VT.is512BitVector()) {
6224     SmallVector<SDValue, 64> V;
6225     for (unsigned i = 0; i != NumElems; ++i)
6226       V.push_back(Op.getOperand(i));
6227
6228     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6229
6230     // Build both the lower and upper subvector.
6231     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6232                                 makeArrayRef(&V[0], NumElems/2));
6233     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6234                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6235
6236     // Recreate the wider vector with the lower and upper part.
6237     if (VT.is256BitVector())
6238       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6239     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6240   }
6241
6242   // Let legalizer expand 2-wide build_vectors.
6243   if (EVTBits == 64) {
6244     if (NumNonZero == 1) {
6245       // One half is zero or undef.
6246       unsigned Idx = countTrailingZeros(NonZeros);
6247       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6248                                  Op.getOperand(Idx));
6249       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6250     }
6251     return SDValue();
6252   }
6253
6254   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6255   if (EVTBits == 8 && NumElems == 16) {
6256     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6257                                         Subtarget, *this);
6258     if (V.getNode()) return V;
6259   }
6260
6261   if (EVTBits == 16 && NumElems == 8) {
6262     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6263                                       Subtarget, *this);
6264     if (V.getNode()) return V;
6265   }
6266
6267   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6268   if (EVTBits == 32 && NumElems == 4) {
6269     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6270                                       NumZero, DAG, Subtarget, *this);
6271     if (V.getNode())
6272       return V;
6273   }
6274
6275   // If element VT is == 32 bits, turn it into a number of shuffles.
6276   SmallVector<SDValue, 8> V(NumElems);
6277   if (NumElems == 4 && NumZero > 0) {
6278     for (unsigned i = 0; i < 4; ++i) {
6279       bool isZero = !(NonZeros & (1 << i));
6280       if (isZero)
6281         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6282       else
6283         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6284     }
6285
6286     for (unsigned i = 0; i < 2; ++i) {
6287       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6288         default: break;
6289         case 0:
6290           V[i] = V[i*2];  // Must be a zero vector.
6291           break;
6292         case 1:
6293           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6294           break;
6295         case 2:
6296           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6297           break;
6298         case 3:
6299           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6300           break;
6301       }
6302     }
6303
6304     bool Reverse1 = (NonZeros & 0x3) == 2;
6305     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6306     int MaskVec[] = {
6307       Reverse1 ? 1 : 0,
6308       Reverse1 ? 0 : 1,
6309       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6310       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6311     };
6312     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6313   }
6314
6315   if (Values.size() > 1 && VT.is128BitVector()) {
6316     // Check for a build vector of consecutive loads.
6317     for (unsigned i = 0; i < NumElems; ++i)
6318       V[i] = Op.getOperand(i);
6319
6320     // Check for elements which are consecutive loads.
6321     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6322     if (LD.getNode())
6323       return LD;
6324
6325     // Check for a build vector from mostly shuffle plus few inserting.
6326     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6327     if (Sh.getNode())
6328       return Sh;
6329
6330     // For SSE 4.1, use insertps to put the high elements into the low element.
6331     if (getSubtarget()->hasSSE41()) {
6332       SDValue Result;
6333       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6334         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6335       else
6336         Result = DAG.getUNDEF(VT);
6337
6338       for (unsigned i = 1; i < NumElems; ++i) {
6339         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6340         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6341                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6342       }
6343       return Result;
6344     }
6345
6346     // Otherwise, expand into a number of unpckl*, start by extending each of
6347     // our (non-undef) elements to the full vector width with the element in the
6348     // bottom slot of the vector (which generates no code for SSE).
6349     for (unsigned i = 0; i < NumElems; ++i) {
6350       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6351         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6352       else
6353         V[i] = DAG.getUNDEF(VT);
6354     }
6355
6356     // Next, we iteratively mix elements, e.g. for v4f32:
6357     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6358     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6359     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6360     unsigned EltStride = NumElems >> 1;
6361     while (EltStride != 0) {
6362       for (unsigned i = 0; i < EltStride; ++i) {
6363         // If V[i+EltStride] is undef and this is the first round of mixing,
6364         // then it is safe to just drop this shuffle: V[i] is already in the
6365         // right place, the one element (since it's the first round) being
6366         // inserted as undef can be dropped.  This isn't safe for successive
6367         // rounds because they will permute elements within both vectors.
6368         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6369             EltStride == NumElems/2)
6370           continue;
6371
6372         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6373       }
6374       EltStride >>= 1;
6375     }
6376     return V[0];
6377   }
6378   return SDValue();
6379 }
6380
6381 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6382 // to create 256-bit vectors from two other 128-bit ones.
6383 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6384   SDLoc dl(Op);
6385   MVT ResVT = Op.getSimpleValueType();
6386
6387   assert((ResVT.is256BitVector() ||
6388           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6389
6390   SDValue V1 = Op.getOperand(0);
6391   SDValue V2 = Op.getOperand(1);
6392   unsigned NumElems = ResVT.getVectorNumElements();
6393   if(ResVT.is256BitVector())
6394     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6395
6396   if (Op.getNumOperands() == 4) {
6397     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6398                                 ResVT.getVectorNumElements()/2);
6399     SDValue V3 = Op.getOperand(2);
6400     SDValue V4 = Op.getOperand(3);
6401     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6402       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6403   }
6404   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6405 }
6406
6407 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6408   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6409   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6410          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6411           Op.getNumOperands() == 4)));
6412
6413   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6414   // from two other 128-bit ones.
6415
6416   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6417   return LowerAVXCONCAT_VECTORS(Op, DAG);
6418 }
6419
6420 // Try to lower a shuffle node into a simple blend instruction.
6421 static SDValue
6422 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6423                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6424   SDValue V1 = SVOp->getOperand(0);
6425   SDValue V2 = SVOp->getOperand(1);
6426   SDLoc dl(SVOp);
6427   MVT VT = SVOp->getSimpleValueType(0);
6428   MVT EltVT = VT.getVectorElementType();
6429   unsigned NumElems = VT.getVectorNumElements();
6430
6431   // There is no blend with immediate in AVX-512.
6432   if (VT.is512BitVector())
6433     return SDValue();
6434
6435   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6436     return SDValue();
6437   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6438     return SDValue();
6439
6440   // Check the mask for BLEND and build the value.
6441   unsigned MaskValue = 0;
6442   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6443   unsigned NumLanes = (NumElems-1)/8 + 1;
6444   unsigned NumElemsInLane = NumElems / NumLanes;
6445
6446   // Blend for v16i16 should be symetric for the both lanes.
6447   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6448
6449     int SndLaneEltIdx = (NumLanes == 2) ?
6450       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6451     int EltIdx = SVOp->getMaskElt(i);
6452
6453     if ((EltIdx < 0 || EltIdx == (int)i) &&
6454         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6455       continue;
6456
6457     if (((unsigned)EltIdx == (i + NumElems)) &&
6458         (SndLaneEltIdx < 0 ||
6459          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6460       MaskValue |= (1<<i);
6461     else
6462       return SDValue();
6463   }
6464
6465   // Convert i32 vectors to floating point if it is not AVX2.
6466   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6467   MVT BlendVT = VT;
6468   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6469     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6470                                NumElems);
6471     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6472     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6473   }
6474
6475   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6476                             DAG.getConstant(MaskValue, MVT::i32));
6477   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6478 }
6479
6480 /// In vector type \p VT, return true if the element at index \p InputIdx
6481 /// falls on a different 128-bit lane than \p OutputIdx.
6482 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6483                                      unsigned OutputIdx) {
6484   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6485   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6486 }
6487
6488 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6489 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6490 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6491 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6492 /// zero.
6493 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6494                          SelectionDAG &DAG) {
6495   MVT VT = V1.getSimpleValueType();
6496   assert(VT.is128BitVector() || VT.is256BitVector());
6497
6498   MVT EltVT = VT.getVectorElementType();
6499   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6500   unsigned NumElts = VT.getVectorNumElements();
6501
6502   SmallVector<SDValue, 32> PshufbMask;
6503   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6504     int InputIdx = MaskVals[OutputIdx];
6505     unsigned InputByteIdx;
6506
6507     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6508       InputByteIdx = 0x80;
6509     else {
6510       // Cross lane is not allowed.
6511       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6512         return SDValue();
6513       InputByteIdx = InputIdx * EltSizeInBytes;
6514       // Index is an byte offset within the 128-bit lane.
6515       InputByteIdx &= 0xf;
6516     }
6517
6518     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6519       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6520       if (InputByteIdx != 0x80)
6521         ++InputByteIdx;
6522     }
6523   }
6524
6525   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6526   if (ShufVT != VT)
6527     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6528   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6529                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6530 }
6531
6532 // v8i16 shuffles - Prefer shuffles in the following order:
6533 // 1. [all]   pshuflw, pshufhw, optional move
6534 // 2. [ssse3] 1 x pshufb
6535 // 3. [ssse3] 2 x pshufb + 1 x por
6536 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6537 static SDValue
6538 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6539                          SelectionDAG &DAG) {
6540   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6541   SDValue V1 = SVOp->getOperand(0);
6542   SDValue V2 = SVOp->getOperand(1);
6543   SDLoc dl(SVOp);
6544   SmallVector<int, 8> MaskVals;
6545
6546   // Determine if more than 1 of the words in each of the low and high quadwords
6547   // of the result come from the same quadword of one of the two inputs.  Undef
6548   // mask values count as coming from any quadword, for better codegen.
6549   //
6550   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6551   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6552   unsigned LoQuad[] = { 0, 0, 0, 0 };
6553   unsigned HiQuad[] = { 0, 0, 0, 0 };
6554   // Indices of quads used.
6555   std::bitset<4> InputQuads;
6556   for (unsigned i = 0; i < 8; ++i) {
6557     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6558     int EltIdx = SVOp->getMaskElt(i);
6559     MaskVals.push_back(EltIdx);
6560     if (EltIdx < 0) {
6561       ++Quad[0];
6562       ++Quad[1];
6563       ++Quad[2];
6564       ++Quad[3];
6565       continue;
6566     }
6567     ++Quad[EltIdx / 4];
6568     InputQuads.set(EltIdx / 4);
6569   }
6570
6571   int BestLoQuad = -1;
6572   unsigned MaxQuad = 1;
6573   for (unsigned i = 0; i < 4; ++i) {
6574     if (LoQuad[i] > MaxQuad) {
6575       BestLoQuad = i;
6576       MaxQuad = LoQuad[i];
6577     }
6578   }
6579
6580   int BestHiQuad = -1;
6581   MaxQuad = 1;
6582   for (unsigned i = 0; i < 4; ++i) {
6583     if (HiQuad[i] > MaxQuad) {
6584       BestHiQuad = i;
6585       MaxQuad = HiQuad[i];
6586     }
6587   }
6588
6589   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6590   // of the two input vectors, shuffle them into one input vector so only a
6591   // single pshufb instruction is necessary. If there are more than 2 input
6592   // quads, disable the next transformation since it does not help SSSE3.
6593   bool V1Used = InputQuads[0] || InputQuads[1];
6594   bool V2Used = InputQuads[2] || InputQuads[3];
6595   if (Subtarget->hasSSSE3()) {
6596     if (InputQuads.count() == 2 && V1Used && V2Used) {
6597       BestLoQuad = InputQuads[0] ? 0 : 1;
6598       BestHiQuad = InputQuads[2] ? 2 : 3;
6599     }
6600     if (InputQuads.count() > 2) {
6601       BestLoQuad = -1;
6602       BestHiQuad = -1;
6603     }
6604   }
6605
6606   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6607   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6608   // words from all 4 input quadwords.
6609   SDValue NewV;
6610   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6611     int MaskV[] = {
6612       BestLoQuad < 0 ? 0 : BestLoQuad,
6613       BestHiQuad < 0 ? 1 : BestHiQuad
6614     };
6615     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6616                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6617                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6618     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6619
6620     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6621     // source words for the shuffle, to aid later transformations.
6622     bool AllWordsInNewV = true;
6623     bool InOrder[2] = { true, true };
6624     for (unsigned i = 0; i != 8; ++i) {
6625       int idx = MaskVals[i];
6626       if (idx != (int)i)
6627         InOrder[i/4] = false;
6628       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6629         continue;
6630       AllWordsInNewV = false;
6631       break;
6632     }
6633
6634     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6635     if (AllWordsInNewV) {
6636       for (int i = 0; i != 8; ++i) {
6637         int idx = MaskVals[i];
6638         if (idx < 0)
6639           continue;
6640         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6641         if ((idx != i) && idx < 4)
6642           pshufhw = false;
6643         if ((idx != i) && idx > 3)
6644           pshuflw = false;
6645       }
6646       V1 = NewV;
6647       V2Used = false;
6648       BestLoQuad = 0;
6649       BestHiQuad = 1;
6650     }
6651
6652     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6653     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6654     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6655       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6656       unsigned TargetMask = 0;
6657       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6658                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6659       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6660       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6661                              getShufflePSHUFLWImmediate(SVOp);
6662       V1 = NewV.getOperand(0);
6663       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6664     }
6665   }
6666
6667   // Promote splats to a larger type which usually leads to more efficient code.
6668   // FIXME: Is this true if pshufb is available?
6669   if (SVOp->isSplat())
6670     return PromoteSplat(SVOp, DAG);
6671
6672   // If we have SSSE3, and all words of the result are from 1 input vector,
6673   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6674   // is present, fall back to case 4.
6675   if (Subtarget->hasSSSE3()) {
6676     SmallVector<SDValue,16> pshufbMask;
6677
6678     // If we have elements from both input vectors, set the high bit of the
6679     // shuffle mask element to zero out elements that come from V2 in the V1
6680     // mask, and elements that come from V1 in the V2 mask, so that the two
6681     // results can be OR'd together.
6682     bool TwoInputs = V1Used && V2Used;
6683     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6684     if (!TwoInputs)
6685       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6686
6687     // Calculate the shuffle mask for the second input, shuffle it, and
6688     // OR it with the first shuffled input.
6689     CommuteVectorShuffleMask(MaskVals, 8);
6690     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6691     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6692     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6693   }
6694
6695   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6696   // and update MaskVals with new element order.
6697   std::bitset<8> InOrder;
6698   if (BestLoQuad >= 0) {
6699     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6700     for (int i = 0; i != 4; ++i) {
6701       int idx = MaskVals[i];
6702       if (idx < 0) {
6703         InOrder.set(i);
6704       } else if ((idx / 4) == BestLoQuad) {
6705         MaskV[i] = idx & 3;
6706         InOrder.set(i);
6707       }
6708     }
6709     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6710                                 &MaskV[0]);
6711
6712     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6713       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6714       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6715                                   NewV.getOperand(0),
6716                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6717     }
6718   }
6719
6720   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6721   // and update MaskVals with the new element order.
6722   if (BestHiQuad >= 0) {
6723     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6724     for (unsigned i = 4; i != 8; ++i) {
6725       int idx = MaskVals[i];
6726       if (idx < 0) {
6727         InOrder.set(i);
6728       } else if ((idx / 4) == BestHiQuad) {
6729         MaskV[i] = (idx & 3) + 4;
6730         InOrder.set(i);
6731       }
6732     }
6733     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6734                                 &MaskV[0]);
6735
6736     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6737       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6738       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6739                                   NewV.getOperand(0),
6740                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6741     }
6742   }
6743
6744   // In case BestHi & BestLo were both -1, which means each quadword has a word
6745   // from each of the four input quadwords, calculate the InOrder bitvector now
6746   // before falling through to the insert/extract cleanup.
6747   if (BestLoQuad == -1 && BestHiQuad == -1) {
6748     NewV = V1;
6749     for (int i = 0; i != 8; ++i)
6750       if (MaskVals[i] < 0 || MaskVals[i] == i)
6751         InOrder.set(i);
6752   }
6753
6754   // The other elements are put in the right place using pextrw and pinsrw.
6755   for (unsigned i = 0; i != 8; ++i) {
6756     if (InOrder[i])
6757       continue;
6758     int EltIdx = MaskVals[i];
6759     if (EltIdx < 0)
6760       continue;
6761     SDValue ExtOp = (EltIdx < 8) ?
6762       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6763                   DAG.getIntPtrConstant(EltIdx)) :
6764       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6765                   DAG.getIntPtrConstant(EltIdx - 8));
6766     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6767                        DAG.getIntPtrConstant(i));
6768   }
6769   return NewV;
6770 }
6771
6772 /// \brief v16i16 shuffles
6773 ///
6774 /// FIXME: We only support generation of a single pshufb currently.  We can
6775 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6776 /// well (e.g 2 x pshufb + 1 x por).
6777 static SDValue
6778 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6779   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6780   SDValue V1 = SVOp->getOperand(0);
6781   SDValue V2 = SVOp->getOperand(1);
6782   SDLoc dl(SVOp);
6783
6784   if (V2.getOpcode() != ISD::UNDEF)
6785     return SDValue();
6786
6787   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6788   return getPSHUFB(MaskVals, V1, dl, DAG);
6789 }
6790
6791 // v16i8 shuffles - Prefer shuffles in the following order:
6792 // 1. [ssse3] 1 x pshufb
6793 // 2. [ssse3] 2 x pshufb + 1 x por
6794 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6795 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6796                                         const X86Subtarget* Subtarget,
6797                                         SelectionDAG &DAG) {
6798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6799   SDValue V1 = SVOp->getOperand(0);
6800   SDValue V2 = SVOp->getOperand(1);
6801   SDLoc dl(SVOp);
6802   ArrayRef<int> MaskVals = SVOp->getMask();
6803
6804   // Promote splats to a larger type which usually leads to more efficient code.
6805   // FIXME: Is this true if pshufb is available?
6806   if (SVOp->isSplat())
6807     return PromoteSplat(SVOp, DAG);
6808
6809   // If we have SSSE3, case 1 is generated when all result bytes come from
6810   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6811   // present, fall back to case 3.
6812
6813   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6814   if (Subtarget->hasSSSE3()) {
6815     SmallVector<SDValue,16> pshufbMask;
6816
6817     // If all result elements are from one input vector, then only translate
6818     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6819     //
6820     // Otherwise, we have elements from both input vectors, and must zero out
6821     // elements that come from V2 in the first mask, and V1 in the second mask
6822     // so that we can OR them together.
6823     for (unsigned i = 0; i != 16; ++i) {
6824       int EltIdx = MaskVals[i];
6825       if (EltIdx < 0 || EltIdx >= 16)
6826         EltIdx = 0x80;
6827       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6828     }
6829     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6830                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6831                                  MVT::v16i8, pshufbMask));
6832
6833     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6834     // the 2nd operand if it's undefined or zero.
6835     if (V2.getOpcode() == ISD::UNDEF ||
6836         ISD::isBuildVectorAllZeros(V2.getNode()))
6837       return V1;
6838
6839     // Calculate the shuffle mask for the second input, shuffle it, and
6840     // OR it with the first shuffled input.
6841     pshufbMask.clear();
6842     for (unsigned i = 0; i != 16; ++i) {
6843       int EltIdx = MaskVals[i];
6844       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6845       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6846     }
6847     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6848                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6849                                  MVT::v16i8, pshufbMask));
6850     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6851   }
6852
6853   // No SSSE3 - Calculate in place words and then fix all out of place words
6854   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6855   // the 16 different words that comprise the two doublequadword input vectors.
6856   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6857   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6858   SDValue NewV = V1;
6859   for (int i = 0; i != 8; ++i) {
6860     int Elt0 = MaskVals[i*2];
6861     int Elt1 = MaskVals[i*2+1];
6862
6863     // This word of the result is all undef, skip it.
6864     if (Elt0 < 0 && Elt1 < 0)
6865       continue;
6866
6867     // This word of the result is already in the correct place, skip it.
6868     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6869       continue;
6870
6871     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6872     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6873     SDValue InsElt;
6874
6875     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6876     // using a single extract together, load it and store it.
6877     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6878       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6879                            DAG.getIntPtrConstant(Elt1 / 2));
6880       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6881                         DAG.getIntPtrConstant(i));
6882       continue;
6883     }
6884
6885     // If Elt1 is defined, extract it from the appropriate source.  If the
6886     // source byte is not also odd, shift the extracted word left 8 bits
6887     // otherwise clear the bottom 8 bits if we need to do an or.
6888     if (Elt1 >= 0) {
6889       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6890                            DAG.getIntPtrConstant(Elt1 / 2));
6891       if ((Elt1 & 1) == 0)
6892         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6893                              DAG.getConstant(8,
6894                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6895       else if (Elt0 >= 0)
6896         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6897                              DAG.getConstant(0xFF00, MVT::i16));
6898     }
6899     // If Elt0 is defined, extract it from the appropriate source.  If the
6900     // source byte is not also even, shift the extracted word right 8 bits. If
6901     // Elt1 was also defined, OR the extracted values together before
6902     // inserting them in the result.
6903     if (Elt0 >= 0) {
6904       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6905                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6906       if ((Elt0 & 1) != 0)
6907         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6908                               DAG.getConstant(8,
6909                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6910       else if (Elt1 >= 0)
6911         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6912                              DAG.getConstant(0x00FF, MVT::i16));
6913       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6914                          : InsElt0;
6915     }
6916     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6917                        DAG.getIntPtrConstant(i));
6918   }
6919   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6920 }
6921
6922 // v32i8 shuffles - Translate to VPSHUFB if possible.
6923 static
6924 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6925                                  const X86Subtarget *Subtarget,
6926                                  SelectionDAG &DAG) {
6927   MVT VT = SVOp->getSimpleValueType(0);
6928   SDValue V1 = SVOp->getOperand(0);
6929   SDValue V2 = SVOp->getOperand(1);
6930   SDLoc dl(SVOp);
6931   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6932
6933   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6934   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6935   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6936
6937   // VPSHUFB may be generated if
6938   // (1) one of input vector is undefined or zeroinitializer.
6939   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6940   // And (2) the mask indexes don't cross the 128-bit lane.
6941   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6942       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6943     return SDValue();
6944
6945   if (V1IsAllZero && !V2IsAllZero) {
6946     CommuteVectorShuffleMask(MaskVals, 32);
6947     V1 = V2;
6948   }
6949   return getPSHUFB(MaskVals, V1, dl, DAG);
6950 }
6951
6952 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6953 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6954 /// done when every pair / quad of shuffle mask elements point to elements in
6955 /// the right sequence. e.g.
6956 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6957 static
6958 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6959                                  SelectionDAG &DAG) {
6960   MVT VT = SVOp->getSimpleValueType(0);
6961   SDLoc dl(SVOp);
6962   unsigned NumElems = VT.getVectorNumElements();
6963   MVT NewVT;
6964   unsigned Scale;
6965   switch (VT.SimpleTy) {
6966   default: llvm_unreachable("Unexpected!");
6967   case MVT::v2i64:
6968   case MVT::v2f64:
6969            return SDValue(SVOp, 0);
6970   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6971   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6972   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6973   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6974   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6975   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6976   }
6977
6978   SmallVector<int, 8> MaskVec;
6979   for (unsigned i = 0; i != NumElems; i += Scale) {
6980     int StartIdx = -1;
6981     for (unsigned j = 0; j != Scale; ++j) {
6982       int EltIdx = SVOp->getMaskElt(i+j);
6983       if (EltIdx < 0)
6984         continue;
6985       if (StartIdx < 0)
6986         StartIdx = (EltIdx / Scale);
6987       if (EltIdx != (int)(StartIdx*Scale + j))
6988         return SDValue();
6989     }
6990     MaskVec.push_back(StartIdx);
6991   }
6992
6993   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6994   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6995   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6996 }
6997
6998 /// getVZextMovL - Return a zero-extending vector move low node.
6999 ///
7000 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7001                             SDValue SrcOp, SelectionDAG &DAG,
7002                             const X86Subtarget *Subtarget, SDLoc dl) {
7003   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7004     LoadSDNode *LD = nullptr;
7005     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7006       LD = dyn_cast<LoadSDNode>(SrcOp);
7007     if (!LD) {
7008       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7009       // instead.
7010       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7011       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7012           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7013           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7014           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7015         // PR2108
7016         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7017         return DAG.getNode(ISD::BITCAST, dl, VT,
7018                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7019                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7020                                                    OpVT,
7021                                                    SrcOp.getOperand(0)
7022                                                           .getOperand(0))));
7023       }
7024     }
7025   }
7026
7027   return DAG.getNode(ISD::BITCAST, dl, VT,
7028                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7029                                  DAG.getNode(ISD::BITCAST, dl,
7030                                              OpVT, SrcOp)));
7031 }
7032
7033 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7034 /// which could not be matched by any known target speficic shuffle
7035 static SDValue
7036 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7037
7038   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7039   if (NewOp.getNode())
7040     return NewOp;
7041
7042   MVT VT = SVOp->getSimpleValueType(0);
7043
7044   unsigned NumElems = VT.getVectorNumElements();
7045   unsigned NumLaneElems = NumElems / 2;
7046
7047   SDLoc dl(SVOp);
7048   MVT EltVT = VT.getVectorElementType();
7049   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7050   SDValue Output[2];
7051
7052   SmallVector<int, 16> Mask;
7053   for (unsigned l = 0; l < 2; ++l) {
7054     // Build a shuffle mask for the output, discovering on the fly which
7055     // input vectors to use as shuffle operands (recorded in InputUsed).
7056     // If building a suitable shuffle vector proves too hard, then bail
7057     // out with UseBuildVector set.
7058     bool UseBuildVector = false;
7059     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7060     unsigned LaneStart = l * NumLaneElems;
7061     for (unsigned i = 0; i != NumLaneElems; ++i) {
7062       // The mask element.  This indexes into the input.
7063       int Idx = SVOp->getMaskElt(i+LaneStart);
7064       if (Idx < 0) {
7065         // the mask element does not index into any input vector.
7066         Mask.push_back(-1);
7067         continue;
7068       }
7069
7070       // The input vector this mask element indexes into.
7071       int Input = Idx / NumLaneElems;
7072
7073       // Turn the index into an offset from the start of the input vector.
7074       Idx -= Input * NumLaneElems;
7075
7076       // Find or create a shuffle vector operand to hold this input.
7077       unsigned OpNo;
7078       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7079         if (InputUsed[OpNo] == Input)
7080           // This input vector is already an operand.
7081           break;
7082         if (InputUsed[OpNo] < 0) {
7083           // Create a new operand for this input vector.
7084           InputUsed[OpNo] = Input;
7085           break;
7086         }
7087       }
7088
7089       if (OpNo >= array_lengthof(InputUsed)) {
7090         // More than two input vectors used!  Give up on trying to create a
7091         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7092         UseBuildVector = true;
7093         break;
7094       }
7095
7096       // Add the mask index for the new shuffle vector.
7097       Mask.push_back(Idx + OpNo * NumLaneElems);
7098     }
7099
7100     if (UseBuildVector) {
7101       SmallVector<SDValue, 16> SVOps;
7102       for (unsigned i = 0; i != NumLaneElems; ++i) {
7103         // The mask element.  This indexes into the input.
7104         int Idx = SVOp->getMaskElt(i+LaneStart);
7105         if (Idx < 0) {
7106           SVOps.push_back(DAG.getUNDEF(EltVT));
7107           continue;
7108         }
7109
7110         // The input vector this mask element indexes into.
7111         int Input = Idx / NumElems;
7112
7113         // Turn the index into an offset from the start of the input vector.
7114         Idx -= Input * NumElems;
7115
7116         // Extract the vector element by hand.
7117         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7118                                     SVOp->getOperand(Input),
7119                                     DAG.getIntPtrConstant(Idx)));
7120       }
7121
7122       // Construct the output using a BUILD_VECTOR.
7123       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7124     } else if (InputUsed[0] < 0) {
7125       // No input vectors were used! The result is undefined.
7126       Output[l] = DAG.getUNDEF(NVT);
7127     } else {
7128       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7129                                         (InputUsed[0] % 2) * NumLaneElems,
7130                                         DAG, dl);
7131       // If only one input was used, use an undefined vector for the other.
7132       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7133         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7134                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7135       // At least one input vector was used. Create a new shuffle vector.
7136       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7137     }
7138
7139     Mask.clear();
7140   }
7141
7142   // Concatenate the result back
7143   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7144 }
7145
7146 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7147 /// 4 elements, and match them with several different shuffle types.
7148 static SDValue
7149 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7150   SDValue V1 = SVOp->getOperand(0);
7151   SDValue V2 = SVOp->getOperand(1);
7152   SDLoc dl(SVOp);
7153   MVT VT = SVOp->getSimpleValueType(0);
7154
7155   assert(VT.is128BitVector() && "Unsupported vector size");
7156
7157   std::pair<int, int> Locs[4];
7158   int Mask1[] = { -1, -1, -1, -1 };
7159   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7160
7161   unsigned NumHi = 0;
7162   unsigned NumLo = 0;
7163   for (unsigned i = 0; i != 4; ++i) {
7164     int Idx = PermMask[i];
7165     if (Idx < 0) {
7166       Locs[i] = std::make_pair(-1, -1);
7167     } else {
7168       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7169       if (Idx < 4) {
7170         Locs[i] = std::make_pair(0, NumLo);
7171         Mask1[NumLo] = Idx;
7172         NumLo++;
7173       } else {
7174         Locs[i] = std::make_pair(1, NumHi);
7175         if (2+NumHi < 4)
7176           Mask1[2+NumHi] = Idx;
7177         NumHi++;
7178       }
7179     }
7180   }
7181
7182   if (NumLo <= 2 && NumHi <= 2) {
7183     // If no more than two elements come from either vector. This can be
7184     // implemented with two shuffles. First shuffle gather the elements.
7185     // The second shuffle, which takes the first shuffle as both of its
7186     // vector operands, put the elements into the right order.
7187     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7188
7189     int Mask2[] = { -1, -1, -1, -1 };
7190
7191     for (unsigned i = 0; i != 4; ++i)
7192       if (Locs[i].first != -1) {
7193         unsigned Idx = (i < 2) ? 0 : 4;
7194         Idx += Locs[i].first * 2 + Locs[i].second;
7195         Mask2[i] = Idx;
7196       }
7197
7198     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7199   }
7200
7201   if (NumLo == 3 || NumHi == 3) {
7202     // Otherwise, we must have three elements from one vector, call it X, and
7203     // one element from the other, call it Y.  First, use a shufps to build an
7204     // intermediate vector with the one element from Y and the element from X
7205     // that will be in the same half in the final destination (the indexes don't
7206     // matter). Then, use a shufps to build the final vector, taking the half
7207     // containing the element from Y from the intermediate, and the other half
7208     // from X.
7209     if (NumHi == 3) {
7210       // Normalize it so the 3 elements come from V1.
7211       CommuteVectorShuffleMask(PermMask, 4);
7212       std::swap(V1, V2);
7213     }
7214
7215     // Find the element from V2.
7216     unsigned HiIndex;
7217     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7218       int Val = PermMask[HiIndex];
7219       if (Val < 0)
7220         continue;
7221       if (Val >= 4)
7222         break;
7223     }
7224
7225     Mask1[0] = PermMask[HiIndex];
7226     Mask1[1] = -1;
7227     Mask1[2] = PermMask[HiIndex^1];
7228     Mask1[3] = -1;
7229     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7230
7231     if (HiIndex >= 2) {
7232       Mask1[0] = PermMask[0];
7233       Mask1[1] = PermMask[1];
7234       Mask1[2] = HiIndex & 1 ? 6 : 4;
7235       Mask1[3] = HiIndex & 1 ? 4 : 6;
7236       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7237     }
7238
7239     Mask1[0] = HiIndex & 1 ? 2 : 0;
7240     Mask1[1] = HiIndex & 1 ? 0 : 2;
7241     Mask1[2] = PermMask[2];
7242     Mask1[3] = PermMask[3];
7243     if (Mask1[2] >= 0)
7244       Mask1[2] += 4;
7245     if (Mask1[3] >= 0)
7246       Mask1[3] += 4;
7247     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7248   }
7249
7250   // Break it into (shuffle shuffle_hi, shuffle_lo).
7251   int LoMask[] = { -1, -1, -1, -1 };
7252   int HiMask[] = { -1, -1, -1, -1 };
7253
7254   int *MaskPtr = LoMask;
7255   unsigned MaskIdx = 0;
7256   unsigned LoIdx = 0;
7257   unsigned HiIdx = 2;
7258   for (unsigned i = 0; i != 4; ++i) {
7259     if (i == 2) {
7260       MaskPtr = HiMask;
7261       MaskIdx = 1;
7262       LoIdx = 0;
7263       HiIdx = 2;
7264     }
7265     int Idx = PermMask[i];
7266     if (Idx < 0) {
7267       Locs[i] = std::make_pair(-1, -1);
7268     } else if (Idx < 4) {
7269       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7270       MaskPtr[LoIdx] = Idx;
7271       LoIdx++;
7272     } else {
7273       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7274       MaskPtr[HiIdx] = Idx;
7275       HiIdx++;
7276     }
7277   }
7278
7279   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7280   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7281   int MaskOps[] = { -1, -1, -1, -1 };
7282   for (unsigned i = 0; i != 4; ++i)
7283     if (Locs[i].first != -1)
7284       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7285   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7286 }
7287
7288 static bool MayFoldVectorLoad(SDValue V) {
7289   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7290     V = V.getOperand(0);
7291
7292   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7293     V = V.getOperand(0);
7294   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7295       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7296     // BUILD_VECTOR (load), undef
7297     V = V.getOperand(0);
7298
7299   return MayFoldLoad(V);
7300 }
7301
7302 static
7303 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7304   MVT VT = Op.getSimpleValueType();
7305
7306   // Canonizalize to v2f64.
7307   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7308   return DAG.getNode(ISD::BITCAST, dl, VT,
7309                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7310                                           V1, DAG));
7311 }
7312
7313 static
7314 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7315                         bool HasSSE2) {
7316   SDValue V1 = Op.getOperand(0);
7317   SDValue V2 = Op.getOperand(1);
7318   MVT VT = Op.getSimpleValueType();
7319
7320   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7321
7322   if (HasSSE2 && VT == MVT::v2f64)
7323     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7324
7325   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7326   return DAG.getNode(ISD::BITCAST, dl, VT,
7327                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7328                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7329                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7330 }
7331
7332 static
7333 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7334   SDValue V1 = Op.getOperand(0);
7335   SDValue V2 = Op.getOperand(1);
7336   MVT VT = Op.getSimpleValueType();
7337
7338   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7339          "unsupported shuffle type");
7340
7341   if (V2.getOpcode() == ISD::UNDEF)
7342     V2 = V1;
7343
7344   // v4i32 or v4f32
7345   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7346 }
7347
7348 static
7349 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7350   SDValue V1 = Op.getOperand(0);
7351   SDValue V2 = Op.getOperand(1);
7352   MVT VT = Op.getSimpleValueType();
7353   unsigned NumElems = VT.getVectorNumElements();
7354
7355   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7356   // operand of these instructions is only memory, so check if there's a
7357   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7358   // same masks.
7359   bool CanFoldLoad = false;
7360
7361   // Trivial case, when V2 comes from a load.
7362   if (MayFoldVectorLoad(V2))
7363     CanFoldLoad = true;
7364
7365   // When V1 is a load, it can be folded later into a store in isel, example:
7366   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7367   //    turns into:
7368   //  (MOVLPSmr addr:$src1, VR128:$src2)
7369   // So, recognize this potential and also use MOVLPS or MOVLPD
7370   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7371     CanFoldLoad = true;
7372
7373   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7374   if (CanFoldLoad) {
7375     if (HasSSE2 && NumElems == 2)
7376       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7377
7378     if (NumElems == 4)
7379       // If we don't care about the second element, proceed to use movss.
7380       if (SVOp->getMaskElt(1) != -1)
7381         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7382   }
7383
7384   // movl and movlp will both match v2i64, but v2i64 is never matched by
7385   // movl earlier because we make it strict to avoid messing with the movlp load
7386   // folding logic (see the code above getMOVLP call). Match it here then,
7387   // this is horrible, but will stay like this until we move all shuffle
7388   // matching to x86 specific nodes. Note that for the 1st condition all
7389   // types are matched with movsd.
7390   if (HasSSE2) {
7391     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7392     // as to remove this logic from here, as much as possible
7393     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7394       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7395     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7396   }
7397
7398   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7399
7400   // Invert the operand order and use SHUFPS to match it.
7401   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7402                               getShuffleSHUFImmediate(SVOp), DAG);
7403 }
7404
7405 // It is only safe to call this function if isINSERTPSMask is true for
7406 // this shufflevector mask.
7407 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7408                            SelectionDAG &DAG) {
7409   // Generate an insertps instruction when inserting an f32 from memory onto a
7410   // v4f32 or when copying a member from one v4f32 to another.
7411   // We also use it for transferring i32 from one register to another,
7412   // since it simply copies the same bits.
7413   // If we're transferring an i32 from memory to a specific element in a
7414   // register, we output a generic DAG that will match the PINSRD
7415   // instruction.
7416   // TODO: Optimize for AVX cases too (VINSERTPS)
7417   MVT VT = SVOp->getSimpleValueType(0);
7418   MVT EVT = VT.getVectorElementType();
7419   SDValue V1 = SVOp->getOperand(0);
7420   SDValue V2 = SVOp->getOperand(1);
7421   auto Mask = SVOp->getMask();
7422   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7423          "unsupported vector type for insertps/pinsrd");
7424
7425   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7426                              [](const int &i) { return i < 4; });
7427
7428   SDValue From;
7429   SDValue To;
7430   unsigned DestIndex;
7431   if (FromV1 == 1) {
7432     From = V1;
7433     To = V2;
7434     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7435                              [](const int &i) { return i < 4; }) -
7436                 Mask.begin();
7437   } else {
7438     From = V2;
7439     To = V1;
7440     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7441                              [](const int &i) { return i >= 4; }) -
7442                 Mask.begin();
7443   }
7444
7445   if (MayFoldLoad(From)) {
7446     // Trivial case, when From comes from a load and is only used by the
7447     // shuffle. Make it use insertps from the vector that we need from that
7448     // load.
7449     SDValue Addr = From.getOperand(1);
7450     SDValue NewAddr =
7451         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7452                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7453                                     Addr.getSimpleValueType()));
7454
7455     LoadSDNode *Load = cast<LoadSDNode>(From);
7456     SDValue NewLoad =
7457         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7458                     DAG.getMachineFunction().getMachineMemOperand(
7459                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7460
7461     if (EVT == MVT::f32) {
7462       // Create this as a scalar to vector to match the instruction pattern.
7463       SDValue LoadScalarToVector =
7464           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7465       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7466       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7467                          InsertpsMask);
7468     } else { // EVT == MVT::i32
7469       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7470       // instruction, to match the PINSRD instruction, which loads an i32 to a
7471       // certain vector element.
7472       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7473                          DAG.getConstant(DestIndex, MVT::i32));
7474     }
7475   }
7476
7477   // Vector-element-to-vector
7478   unsigned SrcIndex = Mask[DestIndex] % 4;
7479   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7480   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7481 }
7482
7483 // Reduce a vector shuffle to zext.
7484 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7485                                     SelectionDAG &DAG) {
7486   // PMOVZX is only available from SSE41.
7487   if (!Subtarget->hasSSE41())
7488     return SDValue();
7489
7490   MVT VT = Op.getSimpleValueType();
7491
7492   // Only AVX2 support 256-bit vector integer extending.
7493   if (!Subtarget->hasInt256() && VT.is256BitVector())
7494     return SDValue();
7495
7496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7497   SDLoc DL(Op);
7498   SDValue V1 = Op.getOperand(0);
7499   SDValue V2 = Op.getOperand(1);
7500   unsigned NumElems = VT.getVectorNumElements();
7501
7502   // Extending is an unary operation and the element type of the source vector
7503   // won't be equal to or larger than i64.
7504   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7505       VT.getVectorElementType() == MVT::i64)
7506     return SDValue();
7507
7508   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7509   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7510   while ((1U << Shift) < NumElems) {
7511     if (SVOp->getMaskElt(1U << Shift) == 1)
7512       break;
7513     Shift += 1;
7514     // The maximal ratio is 8, i.e. from i8 to i64.
7515     if (Shift > 3)
7516       return SDValue();
7517   }
7518
7519   // Check the shuffle mask.
7520   unsigned Mask = (1U << Shift) - 1;
7521   for (unsigned i = 0; i != NumElems; ++i) {
7522     int EltIdx = SVOp->getMaskElt(i);
7523     if ((i & Mask) != 0 && EltIdx != -1)
7524       return SDValue();
7525     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7526       return SDValue();
7527   }
7528
7529   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7530   MVT NeVT = MVT::getIntegerVT(NBits);
7531   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7532
7533   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7534     return SDValue();
7535
7536   // Simplify the operand as it's prepared to be fed into shuffle.
7537   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7538   if (V1.getOpcode() == ISD::BITCAST &&
7539       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7540       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7541       V1.getOperand(0).getOperand(0)
7542         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7543     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7544     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7545     ConstantSDNode *CIdx =
7546       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7547     // If it's foldable, i.e. normal load with single use, we will let code
7548     // selection to fold it. Otherwise, we will short the conversion sequence.
7549     if (CIdx && CIdx->getZExtValue() == 0 &&
7550         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7551       MVT FullVT = V.getSimpleValueType();
7552       MVT V1VT = V1.getSimpleValueType();
7553       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7554         // The "ext_vec_elt" node is wider than the result node.
7555         // In this case we should extract subvector from V.
7556         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7557         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7558         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7559                                         FullVT.getVectorNumElements()/Ratio);
7560         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7561                         DAG.getIntPtrConstant(0));
7562       }
7563       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7564     }
7565   }
7566
7567   return DAG.getNode(ISD::BITCAST, DL, VT,
7568                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7569 }
7570
7571 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7572                                       SelectionDAG &DAG) {
7573   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7574   MVT VT = Op.getSimpleValueType();
7575   SDLoc dl(Op);
7576   SDValue V1 = Op.getOperand(0);
7577   SDValue V2 = Op.getOperand(1);
7578
7579   if (isZeroShuffle(SVOp))
7580     return getZeroVector(VT, Subtarget, DAG, dl);
7581
7582   // Handle splat operations
7583   if (SVOp->isSplat()) {
7584     // Use vbroadcast whenever the splat comes from a foldable load
7585     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7586     if (Broadcast.getNode())
7587       return Broadcast;
7588   }
7589
7590   // Check integer expanding shuffles.
7591   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7592   if (NewOp.getNode())
7593     return NewOp;
7594
7595   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7596   // do it!
7597   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7598       VT == MVT::v32i8) {
7599     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7600     if (NewOp.getNode())
7601       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7602   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7603     // FIXME: Figure out a cleaner way to do this.
7604     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7605       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7606       if (NewOp.getNode()) {
7607         MVT NewVT = NewOp.getSimpleValueType();
7608         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7609                                NewVT, true, false))
7610           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7611                               dl);
7612       }
7613     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7614       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7615       if (NewOp.getNode()) {
7616         MVT NewVT = NewOp.getSimpleValueType();
7617         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7618           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7619                               dl);
7620       }
7621     }
7622   }
7623   return SDValue();
7624 }
7625
7626 SDValue
7627 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7628   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7629   SDValue V1 = Op.getOperand(0);
7630   SDValue V2 = Op.getOperand(1);
7631   MVT VT = Op.getSimpleValueType();
7632   SDLoc dl(Op);
7633   unsigned NumElems = VT.getVectorNumElements();
7634   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7635   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7636   bool V1IsSplat = false;
7637   bool V2IsSplat = false;
7638   bool HasSSE2 = Subtarget->hasSSE2();
7639   bool HasFp256    = Subtarget->hasFp256();
7640   bool HasInt256   = Subtarget->hasInt256();
7641   MachineFunction &MF = DAG.getMachineFunction();
7642   bool OptForSize = MF.getFunction()->getAttributes().
7643     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7644
7645   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7646
7647   if (V1IsUndef && V2IsUndef)
7648     return DAG.getUNDEF(VT);
7649
7650   // When we create a shuffle node we put the UNDEF node to second operand,
7651   // but in some cases the first operand may be transformed to UNDEF.
7652   // In this case we should just commute the node.
7653   if (V1IsUndef)
7654     return CommuteVectorShuffle(SVOp, DAG);
7655
7656   // Vector shuffle lowering takes 3 steps:
7657   //
7658   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7659   //    narrowing and commutation of operands should be handled.
7660   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7661   //    shuffle nodes.
7662   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7663   //    so the shuffle can be broken into other shuffles and the legalizer can
7664   //    try the lowering again.
7665   //
7666   // The general idea is that no vector_shuffle operation should be left to
7667   // be matched during isel, all of them must be converted to a target specific
7668   // node here.
7669
7670   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7671   // narrowing and commutation of operands should be handled. The actual code
7672   // doesn't include all of those, work in progress...
7673   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7674   if (NewOp.getNode())
7675     return NewOp;
7676
7677   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7678
7679   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7680   // unpckh_undef). Only use pshufd if speed is more important than size.
7681   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7682     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7683   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7684     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7685
7686   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7687       V2IsUndef && MayFoldVectorLoad(V1))
7688     return getMOVDDup(Op, dl, V1, DAG);
7689
7690   if (isMOVHLPS_v_undef_Mask(M, VT))
7691     return getMOVHighToLow(Op, dl, DAG);
7692
7693   // Use to match splats
7694   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7695       (VT == MVT::v2f64 || VT == MVT::v2i64))
7696     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7697
7698   if (isPSHUFDMask(M, VT)) {
7699     // The actual implementation will match the mask in the if above and then
7700     // during isel it can match several different instructions, not only pshufd
7701     // as its name says, sad but true, emulate the behavior for now...
7702     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7703       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7704
7705     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7706
7707     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7708       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7709
7710     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7711       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7712                                   DAG);
7713
7714     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7715                                 TargetMask, DAG);
7716   }
7717
7718   if (isPALIGNRMask(M, VT, Subtarget))
7719     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7720                                 getShufflePALIGNRImmediate(SVOp),
7721                                 DAG);
7722
7723   // Check if this can be converted into a logical shift.
7724   bool isLeft = false;
7725   unsigned ShAmt = 0;
7726   SDValue ShVal;
7727   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7728   if (isShift && ShVal.hasOneUse()) {
7729     // If the shifted value has multiple uses, it may be cheaper to use
7730     // v_set0 + movlhps or movhlps, etc.
7731     MVT EltVT = VT.getVectorElementType();
7732     ShAmt *= EltVT.getSizeInBits();
7733     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7734   }
7735
7736   if (isMOVLMask(M, VT)) {
7737     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7738       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7739     if (!isMOVLPMask(M, VT)) {
7740       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7741         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7742
7743       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7744         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7745     }
7746   }
7747
7748   // FIXME: fold these into legal mask.
7749   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7750     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7751
7752   if (isMOVHLPSMask(M, VT))
7753     return getMOVHighToLow(Op, dl, DAG);
7754
7755   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7756     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7757
7758   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7759     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7760
7761   if (isMOVLPMask(M, VT))
7762     return getMOVLP(Op, dl, DAG, HasSSE2);
7763
7764   if (ShouldXformToMOVHLPS(M, VT) ||
7765       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7766     return CommuteVectorShuffle(SVOp, DAG);
7767
7768   if (isShift) {
7769     // No better options. Use a vshldq / vsrldq.
7770     MVT EltVT = VT.getVectorElementType();
7771     ShAmt *= EltVT.getSizeInBits();
7772     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7773   }
7774
7775   bool Commuted = false;
7776   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7777   // 1,1,1,1 -> v8i16 though.
7778   V1IsSplat = isSplatVector(V1.getNode());
7779   V2IsSplat = isSplatVector(V2.getNode());
7780
7781   // Canonicalize the splat or undef, if present, to be on the RHS.
7782   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7783     CommuteVectorShuffleMask(M, NumElems);
7784     std::swap(V1, V2);
7785     std::swap(V1IsSplat, V2IsSplat);
7786     Commuted = true;
7787   }
7788
7789   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7790     // Shuffling low element of v1 into undef, just return v1.
7791     if (V2IsUndef)
7792       return V1;
7793     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7794     // the instruction selector will not match, so get a canonical MOVL with
7795     // swapped operands to undo the commute.
7796     return getMOVL(DAG, dl, VT, V2, V1);
7797   }
7798
7799   if (isUNPCKLMask(M, VT, HasInt256))
7800     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7801
7802   if (isUNPCKHMask(M, VT, HasInt256))
7803     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7804
7805   if (V2IsSplat) {
7806     // Normalize mask so all entries that point to V2 points to its first
7807     // element then try to match unpck{h|l} again. If match, return a
7808     // new vector_shuffle with the corrected mask.p
7809     SmallVector<int, 8> NewMask(M.begin(), M.end());
7810     NormalizeMask(NewMask, NumElems);
7811     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7812       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7813     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7814       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7815   }
7816
7817   if (Commuted) {
7818     // Commute is back and try unpck* again.
7819     // FIXME: this seems wrong.
7820     CommuteVectorShuffleMask(M, NumElems);
7821     std::swap(V1, V2);
7822     std::swap(V1IsSplat, V2IsSplat);
7823
7824     if (isUNPCKLMask(M, VT, HasInt256))
7825       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7826
7827     if (isUNPCKHMask(M, VT, HasInt256))
7828       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7829   }
7830
7831   // Normalize the node to match x86 shuffle ops if needed
7832   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7833     return CommuteVectorShuffle(SVOp, DAG);
7834
7835   // The checks below are all present in isShuffleMaskLegal, but they are
7836   // inlined here right now to enable us to directly emit target specific
7837   // nodes, and remove one by one until they don't return Op anymore.
7838
7839   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7840       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7841     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7842       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7843   }
7844
7845   if (isPSHUFHWMask(M, VT, HasInt256))
7846     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7847                                 getShufflePSHUFHWImmediate(SVOp),
7848                                 DAG);
7849
7850   if (isPSHUFLWMask(M, VT, HasInt256))
7851     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7852                                 getShufflePSHUFLWImmediate(SVOp),
7853                                 DAG);
7854
7855   if (isSHUFPMask(M, VT))
7856     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7857                                 getShuffleSHUFImmediate(SVOp), DAG);
7858
7859   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7860     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7861   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7862     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7863
7864   //===--------------------------------------------------------------------===//
7865   // Generate target specific nodes for 128 or 256-bit shuffles only
7866   // supported in the AVX instruction set.
7867   //
7868
7869   // Handle VMOVDDUPY permutations
7870   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7871     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7872
7873   // Handle VPERMILPS/D* permutations
7874   if (isVPERMILPMask(M, VT)) {
7875     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7876       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7877                                   getShuffleSHUFImmediate(SVOp), DAG);
7878     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7879                                 getShuffleSHUFImmediate(SVOp), DAG);
7880   }
7881
7882   unsigned Idx;
7883   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7884     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7885                               Idx*(NumElems/2), DAG, dl);
7886
7887   // Handle VPERM2F128/VPERM2I128 permutations
7888   if (isVPERM2X128Mask(M, VT, HasFp256))
7889     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7890                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7891
7892   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7893   if (BlendOp.getNode())
7894     return BlendOp;
7895
7896   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7897     return getINSERTPS(SVOp, dl, DAG);
7898
7899   unsigned Imm8;
7900   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7901     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7902
7903   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7904       VT.is512BitVector()) {
7905     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7906     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7907     SmallVector<SDValue, 16> permclMask;
7908     for (unsigned i = 0; i != NumElems; ++i) {
7909       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7910     }
7911
7912     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7913     if (V2IsUndef)
7914       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7915       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7916                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7917     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7918                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7919   }
7920
7921   //===--------------------------------------------------------------------===//
7922   // Since no target specific shuffle was selected for this generic one,
7923   // lower it into other known shuffles. FIXME: this isn't true yet, but
7924   // this is the plan.
7925   //
7926
7927   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7928   if (VT == MVT::v8i16) {
7929     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7930     if (NewOp.getNode())
7931       return NewOp;
7932   }
7933
7934   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7935     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7936     if (NewOp.getNode())
7937       return NewOp;
7938   }
7939
7940   if (VT == MVT::v16i8) {
7941     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7942     if (NewOp.getNode())
7943       return NewOp;
7944   }
7945
7946   if (VT == MVT::v32i8) {
7947     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7948     if (NewOp.getNode())
7949       return NewOp;
7950   }
7951
7952   // Handle all 128-bit wide vectors with 4 elements, and match them with
7953   // several different shuffle types.
7954   if (NumElems == 4 && VT.is128BitVector())
7955     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7956
7957   // Handle general 256-bit shuffles
7958   if (VT.is256BitVector())
7959     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7960
7961   return SDValue();
7962 }
7963
7964 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7965   MVT VT = Op.getSimpleValueType();
7966   SDLoc dl(Op);
7967
7968   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7969     return SDValue();
7970
7971   if (VT.getSizeInBits() == 8) {
7972     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7973                                   Op.getOperand(0), Op.getOperand(1));
7974     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7975                                   DAG.getValueType(VT));
7976     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7977   }
7978
7979   if (VT.getSizeInBits() == 16) {
7980     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7981     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7982     if (Idx == 0)
7983       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7984                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7985                                      DAG.getNode(ISD::BITCAST, dl,
7986                                                  MVT::v4i32,
7987                                                  Op.getOperand(0)),
7988                                      Op.getOperand(1)));
7989     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7990                                   Op.getOperand(0), Op.getOperand(1));
7991     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7992                                   DAG.getValueType(VT));
7993     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7994   }
7995
7996   if (VT == MVT::f32) {
7997     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7998     // the result back to FR32 register. It's only worth matching if the
7999     // result has a single use which is a store or a bitcast to i32.  And in
8000     // the case of a store, it's not worth it if the index is a constant 0,
8001     // because a MOVSSmr can be used instead, which is smaller and faster.
8002     if (!Op.hasOneUse())
8003       return SDValue();
8004     SDNode *User = *Op.getNode()->use_begin();
8005     if ((User->getOpcode() != ISD::STORE ||
8006          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8007           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8008         (User->getOpcode() != ISD::BITCAST ||
8009          User->getValueType(0) != MVT::i32))
8010       return SDValue();
8011     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8012                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8013                                               Op.getOperand(0)),
8014                                               Op.getOperand(1));
8015     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8016   }
8017
8018   if (VT == MVT::i32 || VT == MVT::i64) {
8019     // ExtractPS/pextrq works with constant index.
8020     if (isa<ConstantSDNode>(Op.getOperand(1)))
8021       return Op;
8022   }
8023   return SDValue();
8024 }
8025
8026 /// Extract one bit from mask vector, like v16i1 or v8i1.
8027 /// AVX-512 feature.
8028 SDValue
8029 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8030   SDValue Vec = Op.getOperand(0);
8031   SDLoc dl(Vec);
8032   MVT VecVT = Vec.getSimpleValueType();
8033   SDValue Idx = Op.getOperand(1);
8034   MVT EltVT = Op.getSimpleValueType();
8035
8036   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8037
8038   // variable index can't be handled in mask registers,
8039   // extend vector to VR512
8040   if (!isa<ConstantSDNode>(Idx)) {
8041     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8042     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8043     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8044                               ExtVT.getVectorElementType(), Ext, Idx);
8045     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8046   }
8047
8048   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8049   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8050   unsigned MaxSift = rc->getSize()*8 - 1;
8051   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8052                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8053   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8054                     DAG.getConstant(MaxSift, MVT::i8));
8055   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8056                        DAG.getIntPtrConstant(0));
8057 }
8058
8059 SDValue
8060 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8061                                            SelectionDAG &DAG) const {
8062   SDLoc dl(Op);
8063   SDValue Vec = Op.getOperand(0);
8064   MVT VecVT = Vec.getSimpleValueType();
8065   SDValue Idx = Op.getOperand(1);
8066
8067   if (Op.getSimpleValueType() == MVT::i1)
8068     return ExtractBitFromMaskVector(Op, DAG);
8069
8070   if (!isa<ConstantSDNode>(Idx)) {
8071     if (VecVT.is512BitVector() ||
8072         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8073          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8074
8075       MVT MaskEltVT =
8076         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8077       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8078                                     MaskEltVT.getSizeInBits());
8079
8080       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8081       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8082                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8083                                 Idx, DAG.getConstant(0, getPointerTy()));
8084       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8085       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8086                         Perm, DAG.getConstant(0, getPointerTy()));
8087     }
8088     return SDValue();
8089   }
8090
8091   // If this is a 256-bit vector result, first extract the 128-bit vector and
8092   // then extract the element from the 128-bit vector.
8093   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8094
8095     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8096     // Get the 128-bit vector.
8097     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8098     MVT EltVT = VecVT.getVectorElementType();
8099
8100     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8101
8102     //if (IdxVal >= NumElems/2)
8103     //  IdxVal -= NumElems/2;
8104     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8105     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8106                        DAG.getConstant(IdxVal, MVT::i32));
8107   }
8108
8109   assert(VecVT.is128BitVector() && "Unexpected vector length");
8110
8111   if (Subtarget->hasSSE41()) {
8112     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8113     if (Res.getNode())
8114       return Res;
8115   }
8116
8117   MVT VT = Op.getSimpleValueType();
8118   // TODO: handle v16i8.
8119   if (VT.getSizeInBits() == 16) {
8120     SDValue Vec = Op.getOperand(0);
8121     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8122     if (Idx == 0)
8123       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8124                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8125                                      DAG.getNode(ISD::BITCAST, dl,
8126                                                  MVT::v4i32, Vec),
8127                                      Op.getOperand(1)));
8128     // Transform it so it match pextrw which produces a 32-bit result.
8129     MVT EltVT = MVT::i32;
8130     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8131                                   Op.getOperand(0), Op.getOperand(1));
8132     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8133                                   DAG.getValueType(VT));
8134     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8135   }
8136
8137   if (VT.getSizeInBits() == 32) {
8138     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8139     if (Idx == 0)
8140       return Op;
8141
8142     // SHUFPS the element to the lowest double word, then movss.
8143     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8144     MVT VVT = Op.getOperand(0).getSimpleValueType();
8145     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8146                                        DAG.getUNDEF(VVT), Mask);
8147     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8148                        DAG.getIntPtrConstant(0));
8149   }
8150
8151   if (VT.getSizeInBits() == 64) {
8152     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8153     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8154     //        to match extract_elt for f64.
8155     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8156     if (Idx == 0)
8157       return Op;
8158
8159     // UNPCKHPD the element to the lowest double word, then movsd.
8160     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8161     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8162     int Mask[2] = { 1, -1 };
8163     MVT VVT = Op.getOperand(0).getSimpleValueType();
8164     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8165                                        DAG.getUNDEF(VVT), Mask);
8166     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8167                        DAG.getIntPtrConstant(0));
8168   }
8169
8170   return SDValue();
8171 }
8172
8173 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8174   MVT VT = Op.getSimpleValueType();
8175   MVT EltVT = VT.getVectorElementType();
8176   SDLoc dl(Op);
8177
8178   SDValue N0 = Op.getOperand(0);
8179   SDValue N1 = Op.getOperand(1);
8180   SDValue N2 = Op.getOperand(2);
8181
8182   if (!VT.is128BitVector())
8183     return SDValue();
8184
8185   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8186       isa<ConstantSDNode>(N2)) {
8187     unsigned Opc;
8188     if (VT == MVT::v8i16)
8189       Opc = X86ISD::PINSRW;
8190     else if (VT == MVT::v16i8)
8191       Opc = X86ISD::PINSRB;
8192     else
8193       Opc = X86ISD::PINSRB;
8194
8195     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8196     // argument.
8197     if (N1.getValueType() != MVT::i32)
8198       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8199     if (N2.getValueType() != MVT::i32)
8200       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8201     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8202   }
8203
8204   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8205     // Bits [7:6] of the constant are the source select.  This will always be
8206     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8207     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8208     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8209     // Bits [5:4] of the constant are the destination select.  This is the
8210     //  value of the incoming immediate.
8211     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8212     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8213     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8214     // Create this as a scalar to vector..
8215     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8216     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8217   }
8218
8219   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8220     // PINSR* works with constant index.
8221     return Op;
8222   }
8223   return SDValue();
8224 }
8225
8226 /// Insert one bit to mask vector, like v16i1 or v8i1.
8227 /// AVX-512 feature.
8228 SDValue 
8229 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8230   SDLoc dl(Op);
8231   SDValue Vec = Op.getOperand(0);
8232   SDValue Elt = Op.getOperand(1);
8233   SDValue Idx = Op.getOperand(2);
8234   MVT VecVT = Vec.getSimpleValueType();
8235
8236   if (!isa<ConstantSDNode>(Idx)) {
8237     // Non constant index. Extend source and destination,
8238     // insert element and then truncate the result.
8239     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8240     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8241     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8242       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8243       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8244     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8245   }
8246
8247   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8248   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8249   if (Vec.getOpcode() == ISD::UNDEF)
8250     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8251                        DAG.getConstant(IdxVal, MVT::i8));
8252   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8253   unsigned MaxSift = rc->getSize()*8 - 1;
8254   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8255                     DAG.getConstant(MaxSift, MVT::i8));
8256   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8257                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8258   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8259 }
8260 SDValue
8261 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8262   MVT VT = Op.getSimpleValueType();
8263   MVT EltVT = VT.getVectorElementType();
8264   
8265   if (EltVT == MVT::i1)
8266     return InsertBitToMaskVector(Op, DAG);
8267
8268   SDLoc dl(Op);
8269   SDValue N0 = Op.getOperand(0);
8270   SDValue N1 = Op.getOperand(1);
8271   SDValue N2 = Op.getOperand(2);
8272
8273   // If this is a 256-bit vector result, first extract the 128-bit vector,
8274   // insert the element into the extracted half and then place it back.
8275   if (VT.is256BitVector() || VT.is512BitVector()) {
8276     if (!isa<ConstantSDNode>(N2))
8277       return SDValue();
8278
8279     // Get the desired 128-bit vector half.
8280     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8281     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8282
8283     // Insert the element into the desired half.
8284     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8285     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8286
8287     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8288                     DAG.getConstant(IdxIn128, MVT::i32));
8289
8290     // Insert the changed part back to the 256-bit vector
8291     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8292   }
8293
8294   if (Subtarget->hasSSE41())
8295     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8296
8297   if (EltVT == MVT::i8)
8298     return SDValue();
8299
8300   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8301     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8302     // as its second argument.
8303     if (N1.getValueType() != MVT::i32)
8304       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8305     if (N2.getValueType() != MVT::i32)
8306       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8307     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8308   }
8309   return SDValue();
8310 }
8311
8312 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8313   SDLoc dl(Op);
8314   MVT OpVT = Op.getSimpleValueType();
8315
8316   // If this is a 256-bit vector result, first insert into a 128-bit
8317   // vector and then insert into the 256-bit vector.
8318   if (!OpVT.is128BitVector()) {
8319     // Insert into a 128-bit vector.
8320     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8321     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8322                                  OpVT.getVectorNumElements() / SizeFactor);
8323
8324     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8325
8326     // Insert the 128-bit vector.
8327     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8328   }
8329
8330   if (OpVT == MVT::v1i64 &&
8331       Op.getOperand(0).getValueType() == MVT::i64)
8332     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8333
8334   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8335   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8336   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8337                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8338 }
8339
8340 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8341 // a simple subregister reference or explicit instructions to grab
8342 // upper bits of a vector.
8343 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8344                                       SelectionDAG &DAG) {
8345   SDLoc dl(Op);
8346   SDValue In =  Op.getOperand(0);
8347   SDValue Idx = Op.getOperand(1);
8348   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8349   MVT ResVT   = Op.getSimpleValueType();
8350   MVT InVT    = In.getSimpleValueType();
8351
8352   if (Subtarget->hasFp256()) {
8353     if (ResVT.is128BitVector() &&
8354         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8355         isa<ConstantSDNode>(Idx)) {
8356       return Extract128BitVector(In, IdxVal, DAG, dl);
8357     }
8358     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8359         isa<ConstantSDNode>(Idx)) {
8360       return Extract256BitVector(In, IdxVal, DAG, dl);
8361     }
8362   }
8363   return SDValue();
8364 }
8365
8366 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8367 // simple superregister reference or explicit instructions to insert
8368 // the upper bits of a vector.
8369 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8370                                      SelectionDAG &DAG) {
8371   if (Subtarget->hasFp256()) {
8372     SDLoc dl(Op.getNode());
8373     SDValue Vec = Op.getNode()->getOperand(0);
8374     SDValue SubVec = Op.getNode()->getOperand(1);
8375     SDValue Idx = Op.getNode()->getOperand(2);
8376
8377     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8378          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8379         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8380         isa<ConstantSDNode>(Idx)) {
8381       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8382       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8383     }
8384
8385     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8386         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8387         isa<ConstantSDNode>(Idx)) {
8388       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8389       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8390     }
8391   }
8392   return SDValue();
8393 }
8394
8395 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8396 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8397 // one of the above mentioned nodes. It has to be wrapped because otherwise
8398 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8399 // be used to form addressing mode. These wrapped nodes will be selected
8400 // into MOV32ri.
8401 SDValue
8402 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8403   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8404
8405   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8406   // global base reg.
8407   unsigned char OpFlag = 0;
8408   unsigned WrapperKind = X86ISD::Wrapper;
8409   CodeModel::Model M = getTargetMachine().getCodeModel();
8410
8411   if (Subtarget->isPICStyleRIPRel() &&
8412       (M == CodeModel::Small || M == CodeModel::Kernel))
8413     WrapperKind = X86ISD::WrapperRIP;
8414   else if (Subtarget->isPICStyleGOT())
8415     OpFlag = X86II::MO_GOTOFF;
8416   else if (Subtarget->isPICStyleStubPIC())
8417     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8418
8419   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8420                                              CP->getAlignment(),
8421                                              CP->getOffset(), OpFlag);
8422   SDLoc DL(CP);
8423   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8424   // With PIC, the address is actually $g + Offset.
8425   if (OpFlag) {
8426     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8427                          DAG.getNode(X86ISD::GlobalBaseReg,
8428                                      SDLoc(), getPointerTy()),
8429                          Result);
8430   }
8431
8432   return Result;
8433 }
8434
8435 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8436   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8437
8438   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8439   // global base reg.
8440   unsigned char OpFlag = 0;
8441   unsigned WrapperKind = X86ISD::Wrapper;
8442   CodeModel::Model M = getTargetMachine().getCodeModel();
8443
8444   if (Subtarget->isPICStyleRIPRel() &&
8445       (M == CodeModel::Small || M == CodeModel::Kernel))
8446     WrapperKind = X86ISD::WrapperRIP;
8447   else if (Subtarget->isPICStyleGOT())
8448     OpFlag = X86II::MO_GOTOFF;
8449   else if (Subtarget->isPICStyleStubPIC())
8450     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8451
8452   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8453                                           OpFlag);
8454   SDLoc DL(JT);
8455   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8456
8457   // With PIC, the address is actually $g + Offset.
8458   if (OpFlag)
8459     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8460                          DAG.getNode(X86ISD::GlobalBaseReg,
8461                                      SDLoc(), getPointerTy()),
8462                          Result);
8463
8464   return Result;
8465 }
8466
8467 SDValue
8468 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8469   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8470
8471   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8472   // global base reg.
8473   unsigned char OpFlag = 0;
8474   unsigned WrapperKind = X86ISD::Wrapper;
8475   CodeModel::Model M = getTargetMachine().getCodeModel();
8476
8477   if (Subtarget->isPICStyleRIPRel() &&
8478       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8479     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8480       OpFlag = X86II::MO_GOTPCREL;
8481     WrapperKind = X86ISD::WrapperRIP;
8482   } else if (Subtarget->isPICStyleGOT()) {
8483     OpFlag = X86II::MO_GOT;
8484   } else if (Subtarget->isPICStyleStubPIC()) {
8485     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8486   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8487     OpFlag = X86II::MO_DARWIN_NONLAZY;
8488   }
8489
8490   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8491
8492   SDLoc DL(Op);
8493   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8494
8495   // With PIC, the address is actually $g + Offset.
8496   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8497       !Subtarget->is64Bit()) {
8498     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8499                          DAG.getNode(X86ISD::GlobalBaseReg,
8500                                      SDLoc(), getPointerTy()),
8501                          Result);
8502   }
8503
8504   // For symbols that require a load from a stub to get the address, emit the
8505   // load.
8506   if (isGlobalStubReference(OpFlag))
8507     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8508                          MachinePointerInfo::getGOT(), false, false, false, 0);
8509
8510   return Result;
8511 }
8512
8513 SDValue
8514 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8515   // Create the TargetBlockAddressAddress node.
8516   unsigned char OpFlags =
8517     Subtarget->ClassifyBlockAddressReference();
8518   CodeModel::Model M = getTargetMachine().getCodeModel();
8519   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8520   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8521   SDLoc dl(Op);
8522   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8523                                              OpFlags);
8524
8525   if (Subtarget->isPICStyleRIPRel() &&
8526       (M == CodeModel::Small || M == CodeModel::Kernel))
8527     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8528   else
8529     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8530
8531   // With PIC, the address is actually $g + Offset.
8532   if (isGlobalRelativeToPICBase(OpFlags)) {
8533     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8534                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8535                          Result);
8536   }
8537
8538   return Result;
8539 }
8540
8541 SDValue
8542 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8543                                       int64_t Offset, SelectionDAG &DAG) const {
8544   // Create the TargetGlobalAddress node, folding in the constant
8545   // offset if it is legal.
8546   unsigned char OpFlags =
8547     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8548   CodeModel::Model M = getTargetMachine().getCodeModel();
8549   SDValue Result;
8550   if (OpFlags == X86II::MO_NO_FLAG &&
8551       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8552     // A direct static reference to a global.
8553     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8554     Offset = 0;
8555   } else {
8556     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8557   }
8558
8559   if (Subtarget->isPICStyleRIPRel() &&
8560       (M == CodeModel::Small || M == CodeModel::Kernel))
8561     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8562   else
8563     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8564
8565   // With PIC, the address is actually $g + Offset.
8566   if (isGlobalRelativeToPICBase(OpFlags)) {
8567     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8568                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8569                          Result);
8570   }
8571
8572   // For globals that require a load from a stub to get the address, emit the
8573   // load.
8574   if (isGlobalStubReference(OpFlags))
8575     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8576                          MachinePointerInfo::getGOT(), false, false, false, 0);
8577
8578   // If there was a non-zero offset that we didn't fold, create an explicit
8579   // addition for it.
8580   if (Offset != 0)
8581     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8582                          DAG.getConstant(Offset, getPointerTy()));
8583
8584   return Result;
8585 }
8586
8587 SDValue
8588 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8589   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8590   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8591   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8592 }
8593
8594 static SDValue
8595 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8596            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8597            unsigned char OperandFlags, bool LocalDynamic = false) {
8598   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8599   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8600   SDLoc dl(GA);
8601   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8602                                            GA->getValueType(0),
8603                                            GA->getOffset(),
8604                                            OperandFlags);
8605
8606   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8607                                            : X86ISD::TLSADDR;
8608
8609   if (InFlag) {
8610     SDValue Ops[] = { Chain,  TGA, *InFlag };
8611     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8612   } else {
8613     SDValue Ops[]  = { Chain, TGA };
8614     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8615   }
8616
8617   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8618   MFI->setAdjustsStack(true);
8619
8620   SDValue Flag = Chain.getValue(1);
8621   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8622 }
8623
8624 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8625 static SDValue
8626 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8627                                 const EVT PtrVT) {
8628   SDValue InFlag;
8629   SDLoc dl(GA);  // ? function entry point might be better
8630   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8631                                    DAG.getNode(X86ISD::GlobalBaseReg,
8632                                                SDLoc(), PtrVT), InFlag);
8633   InFlag = Chain.getValue(1);
8634
8635   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8636 }
8637
8638 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8639 static SDValue
8640 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8641                                 const EVT PtrVT) {
8642   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8643                     X86::RAX, X86II::MO_TLSGD);
8644 }
8645
8646 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8647                                            SelectionDAG &DAG,
8648                                            const EVT PtrVT,
8649                                            bool is64Bit) {
8650   SDLoc dl(GA);
8651
8652   // Get the start address of the TLS block for this module.
8653   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8654       .getInfo<X86MachineFunctionInfo>();
8655   MFI->incNumLocalDynamicTLSAccesses();
8656
8657   SDValue Base;
8658   if (is64Bit) {
8659     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8660                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8661   } else {
8662     SDValue InFlag;
8663     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8664         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8665     InFlag = Chain.getValue(1);
8666     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8667                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8668   }
8669
8670   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8671   // of Base.
8672
8673   // Build x@dtpoff.
8674   unsigned char OperandFlags = X86II::MO_DTPOFF;
8675   unsigned WrapperKind = X86ISD::Wrapper;
8676   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8677                                            GA->getValueType(0),
8678                                            GA->getOffset(), OperandFlags);
8679   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8680
8681   // Add x@dtpoff with the base.
8682   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8683 }
8684
8685 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8686 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8687                                    const EVT PtrVT, TLSModel::Model model,
8688                                    bool is64Bit, bool isPIC) {
8689   SDLoc dl(GA);
8690
8691   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8692   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8693                                                          is64Bit ? 257 : 256));
8694
8695   SDValue ThreadPointer =
8696       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8697                   MachinePointerInfo(Ptr), false, false, false, 0);
8698
8699   unsigned char OperandFlags = 0;
8700   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8701   // initialexec.
8702   unsigned WrapperKind = X86ISD::Wrapper;
8703   if (model == TLSModel::LocalExec) {
8704     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8705   } else if (model == TLSModel::InitialExec) {
8706     if (is64Bit) {
8707       OperandFlags = X86II::MO_GOTTPOFF;
8708       WrapperKind = X86ISD::WrapperRIP;
8709     } else {
8710       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8711     }
8712   } else {
8713     llvm_unreachable("Unexpected model");
8714   }
8715
8716   // emit "addl x@ntpoff,%eax" (local exec)
8717   // or "addl x@indntpoff,%eax" (initial exec)
8718   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8719   SDValue TGA =
8720       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8721                                  GA->getOffset(), OperandFlags);
8722   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8723
8724   if (model == TLSModel::InitialExec) {
8725     if (isPIC && !is64Bit) {
8726       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8727                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8728                            Offset);
8729     }
8730
8731     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8732                          MachinePointerInfo::getGOT(), false, false, false, 0);
8733   }
8734
8735   // The address of the thread local variable is the add of the thread
8736   // pointer with the offset of the variable.
8737   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8738 }
8739
8740 SDValue
8741 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8742
8743   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8744   const GlobalValue *GV = GA->getGlobal();
8745
8746   if (Subtarget->isTargetELF()) {
8747     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8748
8749     switch (model) {
8750       case TLSModel::GeneralDynamic:
8751         if (Subtarget->is64Bit())
8752           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8753         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8754       case TLSModel::LocalDynamic:
8755         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8756                                            Subtarget->is64Bit());
8757       case TLSModel::InitialExec:
8758       case TLSModel::LocalExec:
8759         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8760                                    Subtarget->is64Bit(),
8761                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8762     }
8763     llvm_unreachable("Unknown TLS model.");
8764   }
8765
8766   if (Subtarget->isTargetDarwin()) {
8767     // Darwin only has one model of TLS.  Lower to that.
8768     unsigned char OpFlag = 0;
8769     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8770                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8771
8772     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8773     // global base reg.
8774     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8775                   !Subtarget->is64Bit();
8776     if (PIC32)
8777       OpFlag = X86II::MO_TLVP_PIC_BASE;
8778     else
8779       OpFlag = X86II::MO_TLVP;
8780     SDLoc DL(Op);
8781     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8782                                                 GA->getValueType(0),
8783                                                 GA->getOffset(), OpFlag);
8784     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8785
8786     // With PIC32, the address is actually $g + Offset.
8787     if (PIC32)
8788       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8789                            DAG.getNode(X86ISD::GlobalBaseReg,
8790                                        SDLoc(), getPointerTy()),
8791                            Offset);
8792
8793     // Lowering the machine isd will make sure everything is in the right
8794     // location.
8795     SDValue Chain = DAG.getEntryNode();
8796     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8797     SDValue Args[] = { Chain, Offset };
8798     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8799
8800     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8801     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8802     MFI->setAdjustsStack(true);
8803
8804     // And our return value (tls address) is in the standard call return value
8805     // location.
8806     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8807     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8808                               Chain.getValue(1));
8809   }
8810
8811   if (Subtarget->isTargetKnownWindowsMSVC() ||
8812       Subtarget->isTargetWindowsGNU()) {
8813     // Just use the implicit TLS architecture
8814     // Need to generate someting similar to:
8815     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8816     //                                  ; from TEB
8817     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8818     //   mov     rcx, qword [rdx+rcx*8]
8819     //   mov     eax, .tls$:tlsvar
8820     //   [rax+rcx] contains the address
8821     // Windows 64bit: gs:0x58
8822     // Windows 32bit: fs:__tls_array
8823
8824     // If GV is an alias then use the aliasee for determining
8825     // thread-localness.
8826     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8827       GV = GA->getAliasee();
8828     SDLoc dl(GA);
8829     SDValue Chain = DAG.getEntryNode();
8830
8831     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8832     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8833     // use its literal value of 0x2C.
8834     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8835                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8836                                                              256)
8837                                         : Type::getInt32PtrTy(*DAG.getContext(),
8838                                                               257));
8839
8840     SDValue TlsArray =
8841         Subtarget->is64Bit()
8842             ? DAG.getIntPtrConstant(0x58)
8843             : (Subtarget->isTargetWindowsGNU()
8844                    ? DAG.getIntPtrConstant(0x2C)
8845                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8846
8847     SDValue ThreadPointer =
8848         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8849                     MachinePointerInfo(Ptr), false, false, false, 0);
8850
8851     // Load the _tls_index variable
8852     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8853     if (Subtarget->is64Bit())
8854       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8855                            IDX, MachinePointerInfo(), MVT::i32,
8856                            false, false, 0);
8857     else
8858       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8859                         false, false, false, 0);
8860
8861     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8862                                     getPointerTy());
8863     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8864
8865     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8866     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8867                       false, false, false, 0);
8868
8869     // Get the offset of start of .tls section
8870     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8871                                              GA->getValueType(0),
8872                                              GA->getOffset(), X86II::MO_SECREL);
8873     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8874
8875     // The address of the thread local variable is the add of the thread
8876     // pointer with the offset of the variable.
8877     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8878   }
8879
8880   llvm_unreachable("TLS not implemented for this target.");
8881 }
8882
8883 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8884 /// and take a 2 x i32 value to shift plus a shift amount.
8885 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8886   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8887   MVT VT = Op.getSimpleValueType();
8888   unsigned VTBits = VT.getSizeInBits();
8889   SDLoc dl(Op);
8890   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8891   SDValue ShOpLo = Op.getOperand(0);
8892   SDValue ShOpHi = Op.getOperand(1);
8893   SDValue ShAmt  = Op.getOperand(2);
8894   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8895   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8896   // during isel.
8897   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8898                                   DAG.getConstant(VTBits - 1, MVT::i8));
8899   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8900                                      DAG.getConstant(VTBits - 1, MVT::i8))
8901                        : DAG.getConstant(0, VT);
8902
8903   SDValue Tmp2, Tmp3;
8904   if (Op.getOpcode() == ISD::SHL_PARTS) {
8905     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8906     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8907   } else {
8908     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8909     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8910   }
8911
8912   // If the shift amount is larger or equal than the width of a part we can't
8913   // rely on the results of shld/shrd. Insert a test and select the appropriate
8914   // values for large shift amounts.
8915   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8916                                 DAG.getConstant(VTBits, MVT::i8));
8917   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8918                              AndNode, DAG.getConstant(0, MVT::i8));
8919
8920   SDValue Hi, Lo;
8921   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8922   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8923   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8924
8925   if (Op.getOpcode() == ISD::SHL_PARTS) {
8926     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8927     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8928   } else {
8929     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8930     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8931   }
8932
8933   SDValue Ops[2] = { Lo, Hi };
8934   return DAG.getMergeValues(Ops, dl);
8935 }
8936
8937 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8938                                            SelectionDAG &DAG) const {
8939   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8940
8941   if (SrcVT.isVector())
8942     return SDValue();
8943
8944   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8945          "Unknown SINT_TO_FP to lower!");
8946
8947   // These are really Legal; return the operand so the caller accepts it as
8948   // Legal.
8949   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8950     return Op;
8951   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8952       Subtarget->is64Bit()) {
8953     return Op;
8954   }
8955
8956   SDLoc dl(Op);
8957   unsigned Size = SrcVT.getSizeInBits()/8;
8958   MachineFunction &MF = DAG.getMachineFunction();
8959   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8960   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8961   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8962                                StackSlot,
8963                                MachinePointerInfo::getFixedStack(SSFI),
8964                                false, false, 0);
8965   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8966 }
8967
8968 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8969                                      SDValue StackSlot,
8970                                      SelectionDAG &DAG) const {
8971   // Build the FILD
8972   SDLoc DL(Op);
8973   SDVTList Tys;
8974   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8975   if (useSSE)
8976     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8977   else
8978     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8979
8980   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8981
8982   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8983   MachineMemOperand *MMO;
8984   if (FI) {
8985     int SSFI = FI->getIndex();
8986     MMO =
8987       DAG.getMachineFunction()
8988       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8989                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8990   } else {
8991     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8992     StackSlot = StackSlot.getOperand(1);
8993   }
8994   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8995   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8996                                            X86ISD::FILD, DL,
8997                                            Tys, Ops, SrcVT, MMO);
8998
8999   if (useSSE) {
9000     Chain = Result.getValue(1);
9001     SDValue InFlag = Result.getValue(2);
9002
9003     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9004     // shouldn't be necessary except that RFP cannot be live across
9005     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9006     MachineFunction &MF = DAG.getMachineFunction();
9007     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9008     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9009     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9010     Tys = DAG.getVTList(MVT::Other);
9011     SDValue Ops[] = {
9012       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9013     };
9014     MachineMemOperand *MMO =
9015       DAG.getMachineFunction()
9016       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9017                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9018
9019     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9020                                     Ops, Op.getValueType(), MMO);
9021     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9022                          MachinePointerInfo::getFixedStack(SSFI),
9023                          false, false, false, 0);
9024   }
9025
9026   return Result;
9027 }
9028
9029 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9030 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9031                                                SelectionDAG &DAG) const {
9032   // This algorithm is not obvious. Here it is what we're trying to output:
9033   /*
9034      movq       %rax,  %xmm0
9035      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9036      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9037      #ifdef __SSE3__
9038        haddpd   %xmm0, %xmm0
9039      #else
9040        pshufd   $0x4e, %xmm0, %xmm1
9041        addpd    %xmm1, %xmm0
9042      #endif
9043   */
9044
9045   SDLoc dl(Op);
9046   LLVMContext *Context = DAG.getContext();
9047
9048   // Build some magic constants.
9049   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9050   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9051   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9052
9053   SmallVector<Constant*,2> CV1;
9054   CV1.push_back(
9055     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9056                                       APInt(64, 0x4330000000000000ULL))));
9057   CV1.push_back(
9058     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9059                                       APInt(64, 0x4530000000000000ULL))));
9060   Constant *C1 = ConstantVector::get(CV1);
9061   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9062
9063   // Load the 64-bit value into an XMM register.
9064   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9065                             Op.getOperand(0));
9066   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9067                               MachinePointerInfo::getConstantPool(),
9068                               false, false, false, 16);
9069   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9070                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9071                               CLod0);
9072
9073   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9074                               MachinePointerInfo::getConstantPool(),
9075                               false, false, false, 16);
9076   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9077   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9078   SDValue Result;
9079
9080   if (Subtarget->hasSSE3()) {
9081     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9082     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9083   } else {
9084     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9085     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9086                                            S2F, 0x4E, DAG);
9087     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9088                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9089                          Sub);
9090   }
9091
9092   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9093                      DAG.getIntPtrConstant(0));
9094 }
9095
9096 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9097 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9098                                                SelectionDAG &DAG) const {
9099   SDLoc dl(Op);
9100   // FP constant to bias correct the final result.
9101   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9102                                    MVT::f64);
9103
9104   // Load the 32-bit value into an XMM register.
9105   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9106                              Op.getOperand(0));
9107
9108   // Zero out the upper parts of the register.
9109   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9110
9111   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9112                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9113                      DAG.getIntPtrConstant(0));
9114
9115   // Or the load with the bias.
9116   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9117                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9118                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9119                                                    MVT::v2f64, Load)),
9120                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9121                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9122                                                    MVT::v2f64, Bias)));
9123   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9124                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9125                    DAG.getIntPtrConstant(0));
9126
9127   // Subtract the bias.
9128   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9129
9130   // Handle final rounding.
9131   EVT DestVT = Op.getValueType();
9132
9133   if (DestVT.bitsLT(MVT::f64))
9134     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9135                        DAG.getIntPtrConstant(0));
9136   if (DestVT.bitsGT(MVT::f64))
9137     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9138
9139   // Handle final rounding.
9140   return Sub;
9141 }
9142
9143 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9144                                                SelectionDAG &DAG) const {
9145   SDValue N0 = Op.getOperand(0);
9146   MVT SVT = N0.getSimpleValueType();
9147   SDLoc dl(Op);
9148
9149   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9150           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9151          "Custom UINT_TO_FP is not supported!");
9152
9153   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9154   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9155                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9156 }
9157
9158 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9159                                            SelectionDAG &DAG) const {
9160   SDValue N0 = Op.getOperand(0);
9161   SDLoc dl(Op);
9162
9163   if (Op.getValueType().isVector())
9164     return lowerUINT_TO_FP_vec(Op, DAG);
9165
9166   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9167   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9168   // the optimization here.
9169   if (DAG.SignBitIsZero(N0))
9170     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9171
9172   MVT SrcVT = N0.getSimpleValueType();
9173   MVT DstVT = Op.getSimpleValueType();
9174   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9175     return LowerUINT_TO_FP_i64(Op, DAG);
9176   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9177     return LowerUINT_TO_FP_i32(Op, DAG);
9178   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9179     return SDValue();
9180
9181   // Make a 64-bit buffer, and use it to build an FILD.
9182   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9183   if (SrcVT == MVT::i32) {
9184     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9185     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9186                                      getPointerTy(), StackSlot, WordOff);
9187     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9188                                   StackSlot, MachinePointerInfo(),
9189                                   false, false, 0);
9190     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9191                                   OffsetSlot, MachinePointerInfo(),
9192                                   false, false, 0);
9193     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9194     return Fild;
9195   }
9196
9197   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9198   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9199                                StackSlot, MachinePointerInfo(),
9200                                false, false, 0);
9201   // For i64 source, we need to add the appropriate power of 2 if the input
9202   // was negative.  This is the same as the optimization in
9203   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9204   // we must be careful to do the computation in x87 extended precision, not
9205   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9206   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9207   MachineMemOperand *MMO =
9208     DAG.getMachineFunction()
9209     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9210                           MachineMemOperand::MOLoad, 8, 8);
9211
9212   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9213   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9214   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9215                                          MVT::i64, MMO);
9216
9217   APInt FF(32, 0x5F800000ULL);
9218
9219   // Check whether the sign bit is set.
9220   SDValue SignSet = DAG.getSetCC(dl,
9221                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9222                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9223                                  ISD::SETLT);
9224
9225   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9226   SDValue FudgePtr = DAG.getConstantPool(
9227                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9228                                          getPointerTy());
9229
9230   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9231   SDValue Zero = DAG.getIntPtrConstant(0);
9232   SDValue Four = DAG.getIntPtrConstant(4);
9233   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9234                                Zero, Four);
9235   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9236
9237   // Load the value out, extending it from f32 to f80.
9238   // FIXME: Avoid the extend by constructing the right constant pool?
9239   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9240                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9241                                  MVT::f32, false, false, 4);
9242   // Extend everything to 80 bits to force it to be done on x87.
9243   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9244   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9245 }
9246
9247 std::pair<SDValue,SDValue>
9248 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9249                                     bool IsSigned, bool IsReplace) const {
9250   SDLoc DL(Op);
9251
9252   EVT DstTy = Op.getValueType();
9253
9254   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9255     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9256     DstTy = MVT::i64;
9257   }
9258
9259   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9260          DstTy.getSimpleVT() >= MVT::i16 &&
9261          "Unknown FP_TO_INT to lower!");
9262
9263   // These are really Legal.
9264   if (DstTy == MVT::i32 &&
9265       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9266     return std::make_pair(SDValue(), SDValue());
9267   if (Subtarget->is64Bit() &&
9268       DstTy == MVT::i64 &&
9269       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9270     return std::make_pair(SDValue(), SDValue());
9271
9272   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9273   // stack slot, or into the FTOL runtime function.
9274   MachineFunction &MF = DAG.getMachineFunction();
9275   unsigned MemSize = DstTy.getSizeInBits()/8;
9276   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9277   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9278
9279   unsigned Opc;
9280   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9281     Opc = X86ISD::WIN_FTOL;
9282   else
9283     switch (DstTy.getSimpleVT().SimpleTy) {
9284     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9285     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9286     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9287     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9288     }
9289
9290   SDValue Chain = DAG.getEntryNode();
9291   SDValue Value = Op.getOperand(0);
9292   EVT TheVT = Op.getOperand(0).getValueType();
9293   // FIXME This causes a redundant load/store if the SSE-class value is already
9294   // in memory, such as if it is on the callstack.
9295   if (isScalarFPTypeInSSEReg(TheVT)) {
9296     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9297     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9298                          MachinePointerInfo::getFixedStack(SSFI),
9299                          false, false, 0);
9300     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9301     SDValue Ops[] = {
9302       Chain, StackSlot, DAG.getValueType(TheVT)
9303     };
9304
9305     MachineMemOperand *MMO =
9306       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9307                               MachineMemOperand::MOLoad, MemSize, MemSize);
9308     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9309     Chain = Value.getValue(1);
9310     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9311     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9312   }
9313
9314   MachineMemOperand *MMO =
9315     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9316                             MachineMemOperand::MOStore, MemSize, MemSize);
9317
9318   if (Opc != X86ISD::WIN_FTOL) {
9319     // Build the FP_TO_INT*_IN_MEM
9320     SDValue Ops[] = { Chain, Value, StackSlot };
9321     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9322                                            Ops, DstTy, MMO);
9323     return std::make_pair(FIST, StackSlot);
9324   } else {
9325     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9326       DAG.getVTList(MVT::Other, MVT::Glue),
9327       Chain, Value);
9328     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9329       MVT::i32, ftol.getValue(1));
9330     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9331       MVT::i32, eax.getValue(2));
9332     SDValue Ops[] = { eax, edx };
9333     SDValue pair = IsReplace
9334       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9335       : DAG.getMergeValues(Ops, DL);
9336     return std::make_pair(pair, SDValue());
9337   }
9338 }
9339
9340 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9341                               const X86Subtarget *Subtarget) {
9342   MVT VT = Op->getSimpleValueType(0);
9343   SDValue In = Op->getOperand(0);
9344   MVT InVT = In.getSimpleValueType();
9345   SDLoc dl(Op);
9346
9347   // Optimize vectors in AVX mode:
9348   //
9349   //   v8i16 -> v8i32
9350   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9351   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9352   //   Concat upper and lower parts.
9353   //
9354   //   v4i32 -> v4i64
9355   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9356   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9357   //   Concat upper and lower parts.
9358   //
9359
9360   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9361       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9362       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9363     return SDValue();
9364
9365   if (Subtarget->hasInt256())
9366     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9367
9368   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9369   SDValue Undef = DAG.getUNDEF(InVT);
9370   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9371   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9372   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9373
9374   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9375                              VT.getVectorNumElements()/2);
9376
9377   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9378   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9379
9380   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9381 }
9382
9383 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9384                                         SelectionDAG &DAG) {
9385   MVT VT = Op->getSimpleValueType(0);
9386   SDValue In = Op->getOperand(0);
9387   MVT InVT = In.getSimpleValueType();
9388   SDLoc DL(Op);
9389   unsigned int NumElts = VT.getVectorNumElements();
9390   if (NumElts != 8 && NumElts != 16)
9391     return SDValue();
9392
9393   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9394     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9395
9396   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398   // Now we have only mask extension
9399   assert(InVT.getVectorElementType() == MVT::i1);
9400   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9401   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9402   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9403   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9404   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9405                            MachinePointerInfo::getConstantPool(),
9406                            false, false, false, Alignment);
9407
9408   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9409   if (VT.is512BitVector())
9410     return Brcst;
9411   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9412 }
9413
9414 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9415                                SelectionDAG &DAG) {
9416   if (Subtarget->hasFp256()) {
9417     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9418     if (Res.getNode())
9419       return Res;
9420   }
9421
9422   return SDValue();
9423 }
9424
9425 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9426                                 SelectionDAG &DAG) {
9427   SDLoc DL(Op);
9428   MVT VT = Op.getSimpleValueType();
9429   SDValue In = Op.getOperand(0);
9430   MVT SVT = In.getSimpleValueType();
9431
9432   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9433     return LowerZERO_EXTEND_AVX512(Op, DAG);
9434
9435   if (Subtarget->hasFp256()) {
9436     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9437     if (Res.getNode())
9438       return Res;
9439   }
9440
9441   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9442          VT.getVectorNumElements() != SVT.getVectorNumElements());
9443   return SDValue();
9444 }
9445
9446 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9447   SDLoc DL(Op);
9448   MVT VT = Op.getSimpleValueType();
9449   SDValue In = Op.getOperand(0);
9450   MVT InVT = In.getSimpleValueType();
9451
9452   if (VT == MVT::i1) {
9453     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9454            "Invalid scalar TRUNCATE operation");
9455     if (InVT == MVT::i32)
9456       return SDValue();
9457     if (InVT.getSizeInBits() == 64)
9458       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9459     else if (InVT.getSizeInBits() < 32)
9460       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9461     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9462   }
9463   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9464          "Invalid TRUNCATE operation");
9465
9466   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9467     if (VT.getVectorElementType().getSizeInBits() >=8)
9468       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9469
9470     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9471     unsigned NumElts = InVT.getVectorNumElements();
9472     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9473     if (InVT.getSizeInBits() < 512) {
9474       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9475       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9476       InVT = ExtVT;
9477     }
9478     
9479     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9480     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9481     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9482     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9483     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9484                            MachinePointerInfo::getConstantPool(),
9485                            false, false, false, Alignment);
9486     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9487     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9488     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9489   }
9490
9491   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9492     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9493     if (Subtarget->hasInt256()) {
9494       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9495       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9496       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9497                                 ShufMask);
9498       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9499                          DAG.getIntPtrConstant(0));
9500     }
9501
9502     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9503                                DAG.getIntPtrConstant(0));
9504     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9505                                DAG.getIntPtrConstant(2));
9506     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9507     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9508     static const int ShufMask[] = {0, 2, 4, 6};
9509     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9510   }
9511
9512   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9513     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9514     if (Subtarget->hasInt256()) {
9515       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9516
9517       SmallVector<SDValue,32> pshufbMask;
9518       for (unsigned i = 0; i < 2; ++i) {
9519         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9520         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9521         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9522         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9523         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9524         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9525         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9526         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9527         for (unsigned j = 0; j < 8; ++j)
9528           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9529       }
9530       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9531       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9532       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9533
9534       static const int ShufMask[] = {0,  2,  -1,  -1};
9535       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9536                                 &ShufMask[0]);
9537       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9538                        DAG.getIntPtrConstant(0));
9539       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9540     }
9541
9542     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9543                                DAG.getIntPtrConstant(0));
9544
9545     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9546                                DAG.getIntPtrConstant(4));
9547
9548     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9549     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9550
9551     // The PSHUFB mask:
9552     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9553                                    -1, -1, -1, -1, -1, -1, -1, -1};
9554
9555     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9556     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9557     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9558
9559     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9560     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9561
9562     // The MOVLHPS Mask:
9563     static const int ShufMask2[] = {0, 1, 4, 5};
9564     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9565     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9566   }
9567
9568   // Handle truncation of V256 to V128 using shuffles.
9569   if (!VT.is128BitVector() || !InVT.is256BitVector())
9570     return SDValue();
9571
9572   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9573
9574   unsigned NumElems = VT.getVectorNumElements();
9575   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9576
9577   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9578   // Prepare truncation shuffle mask
9579   for (unsigned i = 0; i != NumElems; ++i)
9580     MaskVec[i] = i * 2;
9581   SDValue V = DAG.getVectorShuffle(NVT, DL,
9582                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9583                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9584   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9585                      DAG.getIntPtrConstant(0));
9586 }
9587
9588 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9589                                            SelectionDAG &DAG) const {
9590   assert(!Op.getSimpleValueType().isVector());
9591
9592   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9593     /*IsSigned=*/ true, /*IsReplace=*/ false);
9594   SDValue FIST = Vals.first, StackSlot = Vals.second;
9595   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9596   if (!FIST.getNode()) return Op;
9597
9598   if (StackSlot.getNode())
9599     // Load the result.
9600     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9601                        FIST, StackSlot, MachinePointerInfo(),
9602                        false, false, false, 0);
9603
9604   // The node is the result.
9605   return FIST;
9606 }
9607
9608 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9609                                            SelectionDAG &DAG) const {
9610   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9611     /*IsSigned=*/ false, /*IsReplace=*/ false);
9612   SDValue FIST = Vals.first, StackSlot = Vals.second;
9613   assert(FIST.getNode() && "Unexpected failure");
9614
9615   if (StackSlot.getNode())
9616     // Load the result.
9617     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9618                        FIST, StackSlot, MachinePointerInfo(),
9619                        false, false, false, 0);
9620
9621   // The node is the result.
9622   return FIST;
9623 }
9624
9625 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9626   SDLoc DL(Op);
9627   MVT VT = Op.getSimpleValueType();
9628   SDValue In = Op.getOperand(0);
9629   MVT SVT = In.getSimpleValueType();
9630
9631   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9632
9633   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9634                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9635                                  In, DAG.getUNDEF(SVT)));
9636 }
9637
9638 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9639   LLVMContext *Context = DAG.getContext();
9640   SDLoc dl(Op);
9641   MVT VT = Op.getSimpleValueType();
9642   MVT EltVT = VT;
9643   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9644   if (VT.isVector()) {
9645     EltVT = VT.getVectorElementType();
9646     NumElts = VT.getVectorNumElements();
9647   }
9648   Constant *C;
9649   if (EltVT == MVT::f64)
9650     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9651                                           APInt(64, ~(1ULL << 63))));
9652   else
9653     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9654                                           APInt(32, ~(1U << 31))));
9655   C = ConstantVector::getSplat(NumElts, C);
9656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9657   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9658   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9659   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9660                              MachinePointerInfo::getConstantPool(),
9661                              false, false, false, Alignment);
9662   if (VT.isVector()) {
9663     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9664     return DAG.getNode(ISD::BITCAST, dl, VT,
9665                        DAG.getNode(ISD::AND, dl, ANDVT,
9666                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9667                                                Op.getOperand(0)),
9668                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9669   }
9670   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9671 }
9672
9673 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9674   LLVMContext *Context = DAG.getContext();
9675   SDLoc dl(Op);
9676   MVT VT = Op.getSimpleValueType();
9677   MVT EltVT = VT;
9678   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9679   if (VT.isVector()) {
9680     EltVT = VT.getVectorElementType();
9681     NumElts = VT.getVectorNumElements();
9682   }
9683   Constant *C;
9684   if (EltVT == MVT::f64)
9685     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9686                                           APInt(64, 1ULL << 63)));
9687   else
9688     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9689                                           APInt(32, 1U << 31)));
9690   C = ConstantVector::getSplat(NumElts, C);
9691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9692   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9693   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9694   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9695                              MachinePointerInfo::getConstantPool(),
9696                              false, false, false, Alignment);
9697   if (VT.isVector()) {
9698     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9699     return DAG.getNode(ISD::BITCAST, dl, VT,
9700                        DAG.getNode(ISD::XOR, dl, XORVT,
9701                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9702                                                Op.getOperand(0)),
9703                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9704   }
9705
9706   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9707 }
9708
9709 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9711   LLVMContext *Context = DAG.getContext();
9712   SDValue Op0 = Op.getOperand(0);
9713   SDValue Op1 = Op.getOperand(1);
9714   SDLoc dl(Op);
9715   MVT VT = Op.getSimpleValueType();
9716   MVT SrcVT = Op1.getSimpleValueType();
9717
9718   // If second operand is smaller, extend it first.
9719   if (SrcVT.bitsLT(VT)) {
9720     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9721     SrcVT = VT;
9722   }
9723   // And if it is bigger, shrink it first.
9724   if (SrcVT.bitsGT(VT)) {
9725     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9726     SrcVT = VT;
9727   }
9728
9729   // At this point the operands and the result should have the same
9730   // type, and that won't be f80 since that is not custom lowered.
9731
9732   // First get the sign bit of second operand.
9733   SmallVector<Constant*,4> CV;
9734   if (SrcVT == MVT::f64) {
9735     const fltSemantics &Sem = APFloat::IEEEdouble;
9736     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9737     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9738   } else {
9739     const fltSemantics &Sem = APFloat::IEEEsingle;
9740     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9741     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9742     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9743     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9744   }
9745   Constant *C = ConstantVector::get(CV);
9746   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9747   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9748                               MachinePointerInfo::getConstantPool(),
9749                               false, false, false, 16);
9750   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9751
9752   // Shift sign bit right or left if the two operands have different types.
9753   if (SrcVT.bitsGT(VT)) {
9754     // Op0 is MVT::f32, Op1 is MVT::f64.
9755     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9756     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9757                           DAG.getConstant(32, MVT::i32));
9758     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9759     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9760                           DAG.getIntPtrConstant(0));
9761   }
9762
9763   // Clear first operand sign bit.
9764   CV.clear();
9765   if (VT == MVT::f64) {
9766     const fltSemantics &Sem = APFloat::IEEEdouble;
9767     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9768                                                    APInt(64, ~(1ULL << 63)))));
9769     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9770   } else {
9771     const fltSemantics &Sem = APFloat::IEEEsingle;
9772     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9773                                                    APInt(32, ~(1U << 31)))));
9774     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9775     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9776     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9777   }
9778   C = ConstantVector::get(CV);
9779   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9780   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9781                               MachinePointerInfo::getConstantPool(),
9782                               false, false, false, 16);
9783   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9784
9785   // Or the value with the sign bit.
9786   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9787 }
9788
9789 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9790   SDValue N0 = Op.getOperand(0);
9791   SDLoc dl(Op);
9792   MVT VT = Op.getSimpleValueType();
9793
9794   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9795   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9796                                   DAG.getConstant(1, VT));
9797   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9798 }
9799
9800 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9801 //
9802 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9803                                       SelectionDAG &DAG) {
9804   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9805
9806   if (!Subtarget->hasSSE41())
9807     return SDValue();
9808
9809   if (!Op->hasOneUse())
9810     return SDValue();
9811
9812   SDNode *N = Op.getNode();
9813   SDLoc DL(N);
9814
9815   SmallVector<SDValue, 8> Opnds;
9816   DenseMap<SDValue, unsigned> VecInMap;
9817   SmallVector<SDValue, 8> VecIns;
9818   EVT VT = MVT::Other;
9819
9820   // Recognize a special case where a vector is casted into wide integer to
9821   // test all 0s.
9822   Opnds.push_back(N->getOperand(0));
9823   Opnds.push_back(N->getOperand(1));
9824
9825   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9826     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9827     // BFS traverse all OR'd operands.
9828     if (I->getOpcode() == ISD::OR) {
9829       Opnds.push_back(I->getOperand(0));
9830       Opnds.push_back(I->getOperand(1));
9831       // Re-evaluate the number of nodes to be traversed.
9832       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9833       continue;
9834     }
9835
9836     // Quit if a non-EXTRACT_VECTOR_ELT
9837     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9838       return SDValue();
9839
9840     // Quit if without a constant index.
9841     SDValue Idx = I->getOperand(1);
9842     if (!isa<ConstantSDNode>(Idx))
9843       return SDValue();
9844
9845     SDValue ExtractedFromVec = I->getOperand(0);
9846     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9847     if (M == VecInMap.end()) {
9848       VT = ExtractedFromVec.getValueType();
9849       // Quit if not 128/256-bit vector.
9850       if (!VT.is128BitVector() && !VT.is256BitVector())
9851         return SDValue();
9852       // Quit if not the same type.
9853       if (VecInMap.begin() != VecInMap.end() &&
9854           VT != VecInMap.begin()->first.getValueType())
9855         return SDValue();
9856       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9857       VecIns.push_back(ExtractedFromVec);
9858     }
9859     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9860   }
9861
9862   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9863          "Not extracted from 128-/256-bit vector.");
9864
9865   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9866
9867   for (DenseMap<SDValue, unsigned>::const_iterator
9868         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9869     // Quit if not all elements are used.
9870     if (I->second != FullMask)
9871       return SDValue();
9872   }
9873
9874   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9875
9876   // Cast all vectors into TestVT for PTEST.
9877   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9878     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9879
9880   // If more than one full vectors are evaluated, OR them first before PTEST.
9881   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9882     // Each iteration will OR 2 nodes and append the result until there is only
9883     // 1 node left, i.e. the final OR'd value of all vectors.
9884     SDValue LHS = VecIns[Slot];
9885     SDValue RHS = VecIns[Slot + 1];
9886     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9887   }
9888
9889   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9890                      VecIns.back(), VecIns.back());
9891 }
9892
9893 /// \brief return true if \c Op has a use that doesn't just read flags.
9894 static bool hasNonFlagsUse(SDValue Op) {
9895   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9896        ++UI) {
9897     SDNode *User = *UI;
9898     unsigned UOpNo = UI.getOperandNo();
9899     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9900       // Look pass truncate.
9901       UOpNo = User->use_begin().getOperandNo();
9902       User = *User->use_begin();
9903     }
9904
9905     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9906         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9907       return true;
9908   }
9909   return false;
9910 }
9911
9912 /// Emit nodes that will be selected as "test Op0,Op0", or something
9913 /// equivalent.
9914 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9915                                     SelectionDAG &DAG) const {
9916   if (Op.getValueType() == MVT::i1)
9917     // KORTEST instruction should be selected
9918     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9919                        DAG.getConstant(0, Op.getValueType()));
9920
9921   // CF and OF aren't always set the way we want. Determine which
9922   // of these we need.
9923   bool NeedCF = false;
9924   bool NeedOF = false;
9925   switch (X86CC) {
9926   default: break;
9927   case X86::COND_A: case X86::COND_AE:
9928   case X86::COND_B: case X86::COND_BE:
9929     NeedCF = true;
9930     break;
9931   case X86::COND_G: case X86::COND_GE:
9932   case X86::COND_L: case X86::COND_LE:
9933   case X86::COND_O: case X86::COND_NO:
9934     NeedOF = true;
9935     break;
9936   }
9937   // See if we can use the EFLAGS value from the operand instead of
9938   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9939   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9940   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9941     // Emit a CMP with 0, which is the TEST pattern.
9942     //if (Op.getValueType() == MVT::i1)
9943     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9944     //                     DAG.getConstant(0, MVT::i1));
9945     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9946                        DAG.getConstant(0, Op.getValueType()));
9947   }
9948   unsigned Opcode = 0;
9949   unsigned NumOperands = 0;
9950
9951   // Truncate operations may prevent the merge of the SETCC instruction
9952   // and the arithmetic instruction before it. Attempt to truncate the operands
9953   // of the arithmetic instruction and use a reduced bit-width instruction.
9954   bool NeedTruncation = false;
9955   SDValue ArithOp = Op;
9956   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9957     SDValue Arith = Op->getOperand(0);
9958     // Both the trunc and the arithmetic op need to have one user each.
9959     if (Arith->hasOneUse())
9960       switch (Arith.getOpcode()) {
9961         default: break;
9962         case ISD::ADD:
9963         case ISD::SUB:
9964         case ISD::AND:
9965         case ISD::OR:
9966         case ISD::XOR: {
9967           NeedTruncation = true;
9968           ArithOp = Arith;
9969         }
9970       }
9971   }
9972
9973   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9974   // which may be the result of a CAST.  We use the variable 'Op', which is the
9975   // non-casted variable when we check for possible users.
9976   switch (ArithOp.getOpcode()) {
9977   case ISD::ADD:
9978     // Due to an isel shortcoming, be conservative if this add is likely to be
9979     // selected as part of a load-modify-store instruction. When the root node
9980     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9981     // uses of other nodes in the match, such as the ADD in this case. This
9982     // leads to the ADD being left around and reselected, with the result being
9983     // two adds in the output.  Alas, even if none our users are stores, that
9984     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9985     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9986     // climbing the DAG back to the root, and it doesn't seem to be worth the
9987     // effort.
9988     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9989          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9990       if (UI->getOpcode() != ISD::CopyToReg &&
9991           UI->getOpcode() != ISD::SETCC &&
9992           UI->getOpcode() != ISD::STORE)
9993         goto default_case;
9994
9995     if (ConstantSDNode *C =
9996         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9997       // An add of one will be selected as an INC.
9998       if (C->getAPIntValue() == 1) {
9999         Opcode = X86ISD::INC;
10000         NumOperands = 1;
10001         break;
10002       }
10003
10004       // An add of negative one (subtract of one) will be selected as a DEC.
10005       if (C->getAPIntValue().isAllOnesValue()) {
10006         Opcode = X86ISD::DEC;
10007         NumOperands = 1;
10008         break;
10009       }
10010     }
10011
10012     // Otherwise use a regular EFLAGS-setting add.
10013     Opcode = X86ISD::ADD;
10014     NumOperands = 2;
10015     break;
10016   case ISD::SHL:
10017   case ISD::SRL:
10018     // If we have a constant logical shift that's only used in a comparison
10019     // against zero turn it into an equivalent AND. This allows turning it into
10020     // a TEST instruction later.
10021     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10022         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10023       EVT VT = Op.getValueType();
10024       unsigned BitWidth = VT.getSizeInBits();
10025       unsigned ShAmt = Op->getConstantOperandVal(1);
10026       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10027         break;
10028       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10029                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10030                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10031       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10032         break;
10033       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10034                                 DAG.getConstant(Mask, VT));
10035       DAG.ReplaceAllUsesWith(Op, New);
10036       Op = New;
10037     }
10038     break;
10039
10040   case ISD::AND:
10041     // If the primary and result isn't used, don't bother using X86ISD::AND,
10042     // because a TEST instruction will be better.
10043     if (!hasNonFlagsUse(Op))
10044       break;
10045     // FALL THROUGH
10046   case ISD::SUB:
10047   case ISD::OR:
10048   case ISD::XOR:
10049     // Due to the ISEL shortcoming noted above, be conservative if this op is
10050     // likely to be selected as part of a load-modify-store instruction.
10051     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10052            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10053       if (UI->getOpcode() == ISD::STORE)
10054         goto default_case;
10055
10056     // Otherwise use a regular EFLAGS-setting instruction.
10057     switch (ArithOp.getOpcode()) {
10058     default: llvm_unreachable("unexpected operator!");
10059     case ISD::SUB: Opcode = X86ISD::SUB; break;
10060     case ISD::XOR: Opcode = X86ISD::XOR; break;
10061     case ISD::AND: Opcode = X86ISD::AND; break;
10062     case ISD::OR: {
10063       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10064         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10065         if (EFLAGS.getNode())
10066           return EFLAGS;
10067       }
10068       Opcode = X86ISD::OR;
10069       break;
10070     }
10071     }
10072
10073     NumOperands = 2;
10074     break;
10075   case X86ISD::ADD:
10076   case X86ISD::SUB:
10077   case X86ISD::INC:
10078   case X86ISD::DEC:
10079   case X86ISD::OR:
10080   case X86ISD::XOR:
10081   case X86ISD::AND:
10082     return SDValue(Op.getNode(), 1);
10083   default:
10084   default_case:
10085     break;
10086   }
10087
10088   // If we found that truncation is beneficial, perform the truncation and
10089   // update 'Op'.
10090   if (NeedTruncation) {
10091     EVT VT = Op.getValueType();
10092     SDValue WideVal = Op->getOperand(0);
10093     EVT WideVT = WideVal.getValueType();
10094     unsigned ConvertedOp = 0;
10095     // Use a target machine opcode to prevent further DAGCombine
10096     // optimizations that may separate the arithmetic operations
10097     // from the setcc node.
10098     switch (WideVal.getOpcode()) {
10099       default: break;
10100       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10101       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10102       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10103       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10104       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10105     }
10106
10107     if (ConvertedOp) {
10108       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10109       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10110         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10111         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10112         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10113       }
10114     }
10115   }
10116
10117   if (Opcode == 0)
10118     // Emit a CMP with 0, which is the TEST pattern.
10119     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10120                        DAG.getConstant(0, Op.getValueType()));
10121
10122   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10123   SmallVector<SDValue, 4> Ops;
10124   for (unsigned i = 0; i != NumOperands; ++i)
10125     Ops.push_back(Op.getOperand(i));
10126
10127   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10128   DAG.ReplaceAllUsesWith(Op, New);
10129   return SDValue(New.getNode(), 1);
10130 }
10131
10132 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10133 /// equivalent.
10134 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10135                                    SDLoc dl, SelectionDAG &DAG) const {
10136   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10137     if (C->getAPIntValue() == 0)
10138       return EmitTest(Op0, X86CC, dl, DAG);
10139
10140      if (Op0.getValueType() == MVT::i1)
10141        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10142   }
10143  
10144   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10145        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10146     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10147     // This avoids subregister aliasing issues. Keep the smaller reference 
10148     // if we're optimizing for size, however, as that'll allow better folding 
10149     // of memory operations.
10150     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10151         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10152              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10153         !Subtarget->isAtom()) {
10154       unsigned ExtendOp =
10155           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10156       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10157       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10158     }
10159     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10160     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10161     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10162                               Op0, Op1);
10163     return SDValue(Sub.getNode(), 1);
10164   }
10165   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10166 }
10167
10168 /// Convert a comparison if required by the subtarget.
10169 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10170                                                  SelectionDAG &DAG) const {
10171   // If the subtarget does not support the FUCOMI instruction, floating-point
10172   // comparisons have to be converted.
10173   if (Subtarget->hasCMov() ||
10174       Cmp.getOpcode() != X86ISD::CMP ||
10175       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10176       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10177     return Cmp;
10178
10179   // The instruction selector will select an FUCOM instruction instead of
10180   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10181   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10182   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10183   SDLoc dl(Cmp);
10184   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10185   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10186   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10187                             DAG.getConstant(8, MVT::i8));
10188   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10189   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10190 }
10191
10192 static bool isAllOnes(SDValue V) {
10193   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10194   return C && C->isAllOnesValue();
10195 }
10196
10197 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10198 /// if it's possible.
10199 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10200                                      SDLoc dl, SelectionDAG &DAG) const {
10201   SDValue Op0 = And.getOperand(0);
10202   SDValue Op1 = And.getOperand(1);
10203   if (Op0.getOpcode() == ISD::TRUNCATE)
10204     Op0 = Op0.getOperand(0);
10205   if (Op1.getOpcode() == ISD::TRUNCATE)
10206     Op1 = Op1.getOperand(0);
10207
10208   SDValue LHS, RHS;
10209   if (Op1.getOpcode() == ISD::SHL)
10210     std::swap(Op0, Op1);
10211   if (Op0.getOpcode() == ISD::SHL) {
10212     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10213       if (And00C->getZExtValue() == 1) {
10214         // If we looked past a truncate, check that it's only truncating away
10215         // known zeros.
10216         unsigned BitWidth = Op0.getValueSizeInBits();
10217         unsigned AndBitWidth = And.getValueSizeInBits();
10218         if (BitWidth > AndBitWidth) {
10219           APInt Zeros, Ones;
10220           DAG.computeKnownBits(Op0, Zeros, Ones);
10221           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10222             return SDValue();
10223         }
10224         LHS = Op1;
10225         RHS = Op0.getOperand(1);
10226       }
10227   } else if (Op1.getOpcode() == ISD::Constant) {
10228     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10229     uint64_t AndRHSVal = AndRHS->getZExtValue();
10230     SDValue AndLHS = Op0;
10231
10232     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10233       LHS = AndLHS.getOperand(0);
10234       RHS = AndLHS.getOperand(1);
10235     }
10236
10237     // Use BT if the immediate can't be encoded in a TEST instruction.
10238     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10239       LHS = AndLHS;
10240       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10241     }
10242   }
10243
10244   if (LHS.getNode()) {
10245     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10246     // instruction.  Since the shift amount is in-range-or-undefined, we know
10247     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10248     // the encoding for the i16 version is larger than the i32 version.
10249     // Also promote i16 to i32 for performance / code size reason.
10250     if (LHS.getValueType() == MVT::i8 ||
10251         LHS.getValueType() == MVT::i16)
10252       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10253
10254     // If the operand types disagree, extend the shift amount to match.  Since
10255     // BT ignores high bits (like shifts) we can use anyextend.
10256     if (LHS.getValueType() != RHS.getValueType())
10257       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10258
10259     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10260     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10261     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10262                        DAG.getConstant(Cond, MVT::i8), BT);
10263   }
10264
10265   return SDValue();
10266 }
10267
10268 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10269 /// mask CMPs.
10270 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10271                               SDValue &Op1) {
10272   unsigned SSECC;
10273   bool Swap = false;
10274
10275   // SSE Condition code mapping:
10276   //  0 - EQ
10277   //  1 - LT
10278   //  2 - LE
10279   //  3 - UNORD
10280   //  4 - NEQ
10281   //  5 - NLT
10282   //  6 - NLE
10283   //  7 - ORD
10284   switch (SetCCOpcode) {
10285   default: llvm_unreachable("Unexpected SETCC condition");
10286   case ISD::SETOEQ:
10287   case ISD::SETEQ:  SSECC = 0; break;
10288   case ISD::SETOGT:
10289   case ISD::SETGT:  Swap = true; // Fallthrough
10290   case ISD::SETLT:
10291   case ISD::SETOLT: SSECC = 1; break;
10292   case ISD::SETOGE:
10293   case ISD::SETGE:  Swap = true; // Fallthrough
10294   case ISD::SETLE:
10295   case ISD::SETOLE: SSECC = 2; break;
10296   case ISD::SETUO:  SSECC = 3; break;
10297   case ISD::SETUNE:
10298   case ISD::SETNE:  SSECC = 4; break;
10299   case ISD::SETULE: Swap = true; // Fallthrough
10300   case ISD::SETUGE: SSECC = 5; break;
10301   case ISD::SETULT: Swap = true; // Fallthrough
10302   case ISD::SETUGT: SSECC = 6; break;
10303   case ISD::SETO:   SSECC = 7; break;
10304   case ISD::SETUEQ:
10305   case ISD::SETONE: SSECC = 8; break;
10306   }
10307   if (Swap)
10308     std::swap(Op0, Op1);
10309
10310   return SSECC;
10311 }
10312
10313 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10314 // ones, and then concatenate the result back.
10315 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10316   MVT VT = Op.getSimpleValueType();
10317
10318   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10319          "Unsupported value type for operation");
10320
10321   unsigned NumElems = VT.getVectorNumElements();
10322   SDLoc dl(Op);
10323   SDValue CC = Op.getOperand(2);
10324
10325   // Extract the LHS vectors
10326   SDValue LHS = Op.getOperand(0);
10327   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10328   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10329
10330   // Extract the RHS vectors
10331   SDValue RHS = Op.getOperand(1);
10332   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10333   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10334
10335   // Issue the operation on the smaller types and concatenate the result back
10336   MVT EltVT = VT.getVectorElementType();
10337   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10338   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10339                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10340                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10341 }
10342
10343 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10344                                      const X86Subtarget *Subtarget) {
10345   SDValue Op0 = Op.getOperand(0);
10346   SDValue Op1 = Op.getOperand(1);
10347   SDValue CC = Op.getOperand(2);
10348   MVT VT = Op.getSimpleValueType();
10349   SDLoc dl(Op);
10350
10351   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10352          Op.getValueType().getScalarType() == MVT::i1 &&
10353          "Cannot set masked compare for this operation");
10354
10355   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10356   unsigned  Opc = 0;
10357   bool Unsigned = false;
10358   bool Swap = false;
10359   unsigned SSECC;
10360   switch (SetCCOpcode) {
10361   default: llvm_unreachable("Unexpected SETCC condition");
10362   case ISD::SETNE:  SSECC = 4; break;
10363   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10364   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10365   case ISD::SETLT:  Swap = true; //fall-through
10366   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10367   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10368   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10369   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10370   case ISD::SETULE: Unsigned = true; //fall-through
10371   case ISD::SETLE:  SSECC = 2; break;
10372   }
10373
10374   if (Swap)
10375     std::swap(Op0, Op1);
10376   if (Opc)
10377     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10378   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10379   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10380                      DAG.getConstant(SSECC, MVT::i8));
10381 }
10382
10383 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10384 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10385 /// return an empty value.
10386 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10387 {
10388   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10389   if (!BV)
10390     return SDValue();
10391
10392   MVT VT = Op1.getSimpleValueType();
10393   MVT EVT = VT.getVectorElementType();
10394   unsigned n = VT.getVectorNumElements();
10395   SmallVector<SDValue, 8> ULTOp1;
10396
10397   for (unsigned i = 0; i < n; ++i) {
10398     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10399     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10400       return SDValue();
10401
10402     // Avoid underflow.
10403     APInt Val = Elt->getAPIntValue();
10404     if (Val == 0)
10405       return SDValue();
10406
10407     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10408   }
10409
10410   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10411 }
10412
10413 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10414                            SelectionDAG &DAG) {
10415   SDValue Op0 = Op.getOperand(0);
10416   SDValue Op1 = Op.getOperand(1);
10417   SDValue CC = Op.getOperand(2);
10418   MVT VT = Op.getSimpleValueType();
10419   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10420   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10421   SDLoc dl(Op);
10422
10423   if (isFP) {
10424 #ifndef NDEBUG
10425     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10426     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10427 #endif
10428
10429     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10430     unsigned Opc = X86ISD::CMPP;
10431     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10432       assert(VT.getVectorNumElements() <= 16);
10433       Opc = X86ISD::CMPM;
10434     }
10435     // In the two special cases we can't handle, emit two comparisons.
10436     if (SSECC == 8) {
10437       unsigned CC0, CC1;
10438       unsigned CombineOpc;
10439       if (SetCCOpcode == ISD::SETUEQ) {
10440         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10441       } else {
10442         assert(SetCCOpcode == ISD::SETONE);
10443         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10444       }
10445
10446       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10447                                  DAG.getConstant(CC0, MVT::i8));
10448       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10449                                  DAG.getConstant(CC1, MVT::i8));
10450       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10451     }
10452     // Handle all other FP comparisons here.
10453     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10454                        DAG.getConstant(SSECC, MVT::i8));
10455   }
10456
10457   // Break 256-bit integer vector compare into smaller ones.
10458   if (VT.is256BitVector() && !Subtarget->hasInt256())
10459     return Lower256IntVSETCC(Op, DAG);
10460
10461   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10462   EVT OpVT = Op1.getValueType();
10463   if (Subtarget->hasAVX512()) {
10464     if (Op1.getValueType().is512BitVector() ||
10465         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10466       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10467
10468     // In AVX-512 architecture setcc returns mask with i1 elements,
10469     // But there is no compare instruction for i8 and i16 elements.
10470     // We are not talking about 512-bit operands in this case, these
10471     // types are illegal.
10472     if (MaskResult &&
10473         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10474          OpVT.getVectorElementType().getSizeInBits() >= 8))
10475       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10476                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10477   }
10478
10479   // We are handling one of the integer comparisons here.  Since SSE only has
10480   // GT and EQ comparisons for integer, swapping operands and multiple
10481   // operations may be required for some comparisons.
10482   unsigned Opc;
10483   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10484   bool Subus = false;
10485
10486   switch (SetCCOpcode) {
10487   default: llvm_unreachable("Unexpected SETCC condition");
10488   case ISD::SETNE:  Invert = true;
10489   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10490   case ISD::SETLT:  Swap = true;
10491   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10492   case ISD::SETGE:  Swap = true;
10493   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10494                     Invert = true; break;
10495   case ISD::SETULT: Swap = true;
10496   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10497                     FlipSigns = true; break;
10498   case ISD::SETUGE: Swap = true;
10499   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10500                     FlipSigns = true; Invert = true; break;
10501   }
10502
10503   // Special case: Use min/max operations for SETULE/SETUGE
10504   MVT VET = VT.getVectorElementType();
10505   bool hasMinMax =
10506        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10507     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10508
10509   if (hasMinMax) {
10510     switch (SetCCOpcode) {
10511     default: break;
10512     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10513     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10514     }
10515
10516     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10517   }
10518
10519   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10520   if (!MinMax && hasSubus) {
10521     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10522     // Op0 u<= Op1:
10523     //   t = psubus Op0, Op1
10524     //   pcmpeq t, <0..0>
10525     switch (SetCCOpcode) {
10526     default: break;
10527     case ISD::SETULT: {
10528       // If the comparison is against a constant we can turn this into a
10529       // setule.  With psubus, setule does not require a swap.  This is
10530       // beneficial because the constant in the register is no longer
10531       // destructed as the destination so it can be hoisted out of a loop.
10532       // Only do this pre-AVX since vpcmp* is no longer destructive.
10533       if (Subtarget->hasAVX())
10534         break;
10535       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10536       if (ULEOp1.getNode()) {
10537         Op1 = ULEOp1;
10538         Subus = true; Invert = false; Swap = false;
10539       }
10540       break;
10541     }
10542     // Psubus is better than flip-sign because it requires no inversion.
10543     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10544     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10545     }
10546
10547     if (Subus) {
10548       Opc = X86ISD::SUBUS;
10549       FlipSigns = false;
10550     }
10551   }
10552
10553   if (Swap)
10554     std::swap(Op0, Op1);
10555
10556   // Check that the operation in question is available (most are plain SSE2,
10557   // but PCMPGTQ and PCMPEQQ have different requirements).
10558   if (VT == MVT::v2i64) {
10559     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10560       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10561
10562       // First cast everything to the right type.
10563       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10564       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10565
10566       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10567       // bits of the inputs before performing those operations. The lower
10568       // compare is always unsigned.
10569       SDValue SB;
10570       if (FlipSigns) {
10571         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10572       } else {
10573         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10574         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10575         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10576                          Sign, Zero, Sign, Zero);
10577       }
10578       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10579       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10580
10581       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10582       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10583       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10584
10585       // Create masks for only the low parts/high parts of the 64 bit integers.
10586       static const int MaskHi[] = { 1, 1, 3, 3 };
10587       static const int MaskLo[] = { 0, 0, 2, 2 };
10588       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10589       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10590       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10591
10592       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10593       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10594
10595       if (Invert)
10596         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10597
10598       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10599     }
10600
10601     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10602       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10603       // pcmpeqd + pshufd + pand.
10604       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10605
10606       // First cast everything to the right type.
10607       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10608       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10609
10610       // Do the compare.
10611       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10612
10613       // Make sure the lower and upper halves are both all-ones.
10614       static const int Mask[] = { 1, 0, 3, 2 };
10615       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10616       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10617
10618       if (Invert)
10619         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10620
10621       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10622     }
10623   }
10624
10625   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10626   // bits of the inputs before performing those operations.
10627   if (FlipSigns) {
10628     EVT EltVT = VT.getVectorElementType();
10629     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10630     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10631     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10632   }
10633
10634   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10635
10636   // If the logical-not of the result is required, perform that now.
10637   if (Invert)
10638     Result = DAG.getNOT(dl, Result, VT);
10639
10640   if (MinMax)
10641     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10642
10643   if (Subus)
10644     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10645                          getZeroVector(VT, Subtarget, DAG, dl));
10646
10647   return Result;
10648 }
10649
10650 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10651
10652   MVT VT = Op.getSimpleValueType();
10653
10654   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10655
10656   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10657          && "SetCC type must be 8-bit or 1-bit integer");
10658   SDValue Op0 = Op.getOperand(0);
10659   SDValue Op1 = Op.getOperand(1);
10660   SDLoc dl(Op);
10661   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10662
10663   // Optimize to BT if possible.
10664   // Lower (X & (1 << N)) == 0 to BT(X, N).
10665   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10666   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10667   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10668       Op1.getOpcode() == ISD::Constant &&
10669       cast<ConstantSDNode>(Op1)->isNullValue() &&
10670       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10671     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10672     if (NewSetCC.getNode())
10673       return NewSetCC;
10674   }
10675
10676   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10677   // these.
10678   if (Op1.getOpcode() == ISD::Constant &&
10679       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10680        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10681       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10682
10683     // If the input is a setcc, then reuse the input setcc or use a new one with
10684     // the inverted condition.
10685     if (Op0.getOpcode() == X86ISD::SETCC) {
10686       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10687       bool Invert = (CC == ISD::SETNE) ^
10688         cast<ConstantSDNode>(Op1)->isNullValue();
10689       if (!Invert)
10690         return Op0;
10691
10692       CCode = X86::GetOppositeBranchCondition(CCode);
10693       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10694                                   DAG.getConstant(CCode, MVT::i8),
10695                                   Op0.getOperand(1));
10696       if (VT == MVT::i1)
10697         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10698       return SetCC;
10699     }
10700   }
10701   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10702       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10703       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10704
10705     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10706     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10707   }
10708
10709   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10710   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10711   if (X86CC == X86::COND_INVALID)
10712     return SDValue();
10713
10714   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10715   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10716   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10717                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10718   if (VT == MVT::i1)
10719     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10720   return SetCC;
10721 }
10722
10723 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10724 static bool isX86LogicalCmp(SDValue Op) {
10725   unsigned Opc = Op.getNode()->getOpcode();
10726   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10727       Opc == X86ISD::SAHF)
10728     return true;
10729   if (Op.getResNo() == 1 &&
10730       (Opc == X86ISD::ADD ||
10731        Opc == X86ISD::SUB ||
10732        Opc == X86ISD::ADC ||
10733        Opc == X86ISD::SBB ||
10734        Opc == X86ISD::SMUL ||
10735        Opc == X86ISD::UMUL ||
10736        Opc == X86ISD::INC ||
10737        Opc == X86ISD::DEC ||
10738        Opc == X86ISD::OR ||
10739        Opc == X86ISD::XOR ||
10740        Opc == X86ISD::AND))
10741     return true;
10742
10743   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10744     return true;
10745
10746   return false;
10747 }
10748
10749 static bool isZero(SDValue V) {
10750   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10751   return C && C->isNullValue();
10752 }
10753
10754 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10755   if (V.getOpcode() != ISD::TRUNCATE)
10756     return false;
10757
10758   SDValue VOp0 = V.getOperand(0);
10759   unsigned InBits = VOp0.getValueSizeInBits();
10760   unsigned Bits = V.getValueSizeInBits();
10761   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10762 }
10763
10764 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10765   bool addTest = true;
10766   SDValue Cond  = Op.getOperand(0);
10767   SDValue Op1 = Op.getOperand(1);
10768   SDValue Op2 = Op.getOperand(2);
10769   SDLoc DL(Op);
10770   EVT VT = Op1.getValueType();
10771   SDValue CC;
10772
10773   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10774   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10775   // sequence later on.
10776   if (Cond.getOpcode() == ISD::SETCC &&
10777       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10778        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10779       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10780     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10781     int SSECC = translateX86FSETCC(
10782         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10783
10784     if (SSECC != 8) {
10785       if (Subtarget->hasAVX512()) {
10786         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10787                                   DAG.getConstant(SSECC, MVT::i8));
10788         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10789       }
10790       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10791                                 DAG.getConstant(SSECC, MVT::i8));
10792       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10793       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10794       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10795     }
10796   }
10797
10798   if (Cond.getOpcode() == ISD::SETCC) {
10799     SDValue NewCond = LowerSETCC(Cond, DAG);
10800     if (NewCond.getNode())
10801       Cond = NewCond;
10802   }
10803
10804   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10805   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10806   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10807   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10808   if (Cond.getOpcode() == X86ISD::SETCC &&
10809       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10810       isZero(Cond.getOperand(1).getOperand(1))) {
10811     SDValue Cmp = Cond.getOperand(1);
10812
10813     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10814
10815     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10816         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10817       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10818
10819       SDValue CmpOp0 = Cmp.getOperand(0);
10820       // Apply further optimizations for special cases
10821       // (select (x != 0), -1, 0) -> neg & sbb
10822       // (select (x == 0), 0, -1) -> neg & sbb
10823       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10824         if (YC->isNullValue() &&
10825             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10826           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10827           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10828                                     DAG.getConstant(0, CmpOp0.getValueType()),
10829                                     CmpOp0);
10830           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10831                                     DAG.getConstant(X86::COND_B, MVT::i8),
10832                                     SDValue(Neg.getNode(), 1));
10833           return Res;
10834         }
10835
10836       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10837                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10838       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10839
10840       SDValue Res =   // Res = 0 or -1.
10841         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10842                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10843
10844       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10845         Res = DAG.getNOT(DL, Res, Res.getValueType());
10846
10847       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10848       if (!N2C || !N2C->isNullValue())
10849         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10850       return Res;
10851     }
10852   }
10853
10854   // Look past (and (setcc_carry (cmp ...)), 1).
10855   if (Cond.getOpcode() == ISD::AND &&
10856       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10857     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10858     if (C && C->getAPIntValue() == 1)
10859       Cond = Cond.getOperand(0);
10860   }
10861
10862   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10863   // setting operand in place of the X86ISD::SETCC.
10864   unsigned CondOpcode = Cond.getOpcode();
10865   if (CondOpcode == X86ISD::SETCC ||
10866       CondOpcode == X86ISD::SETCC_CARRY) {
10867     CC = Cond.getOperand(0);
10868
10869     SDValue Cmp = Cond.getOperand(1);
10870     unsigned Opc = Cmp.getOpcode();
10871     MVT VT = Op.getSimpleValueType();
10872
10873     bool IllegalFPCMov = false;
10874     if (VT.isFloatingPoint() && !VT.isVector() &&
10875         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10876       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10877
10878     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10879         Opc == X86ISD::BT) { // FIXME
10880       Cond = Cmp;
10881       addTest = false;
10882     }
10883   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10884              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10885              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10886               Cond.getOperand(0).getValueType() != MVT::i8)) {
10887     SDValue LHS = Cond.getOperand(0);
10888     SDValue RHS = Cond.getOperand(1);
10889     unsigned X86Opcode;
10890     unsigned X86Cond;
10891     SDVTList VTs;
10892     switch (CondOpcode) {
10893     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10894     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10895     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10896     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10897     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10898     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10899     default: llvm_unreachable("unexpected overflowing operator");
10900     }
10901     if (CondOpcode == ISD::UMULO)
10902       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10903                           MVT::i32);
10904     else
10905       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10906
10907     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10908
10909     if (CondOpcode == ISD::UMULO)
10910       Cond = X86Op.getValue(2);
10911     else
10912       Cond = X86Op.getValue(1);
10913
10914     CC = DAG.getConstant(X86Cond, MVT::i8);
10915     addTest = false;
10916   }
10917
10918   if (addTest) {
10919     // Look pass the truncate if the high bits are known zero.
10920     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10921         Cond = Cond.getOperand(0);
10922
10923     // We know the result of AND is compared against zero. Try to match
10924     // it to BT.
10925     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10926       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10927       if (NewSetCC.getNode()) {
10928         CC = NewSetCC.getOperand(0);
10929         Cond = NewSetCC.getOperand(1);
10930         addTest = false;
10931       }
10932     }
10933   }
10934
10935   if (addTest) {
10936     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10937     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10938   }
10939
10940   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10941   // a <  b ?  0 : -1 -> RES = setcc_carry
10942   // a >= b ? -1 :  0 -> RES = setcc_carry
10943   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10944   if (Cond.getOpcode() == X86ISD::SUB) {
10945     Cond = ConvertCmpIfNecessary(Cond, DAG);
10946     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10947
10948     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10949         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10950       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10951                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10952       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10953         return DAG.getNOT(DL, Res, Res.getValueType());
10954       return Res;
10955     }
10956   }
10957
10958   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10959   // widen the cmov and push the truncate through. This avoids introducing a new
10960   // branch during isel and doesn't add any extensions.
10961   if (Op.getValueType() == MVT::i8 &&
10962       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10963     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10964     if (T1.getValueType() == T2.getValueType() &&
10965         // Blacklist CopyFromReg to avoid partial register stalls.
10966         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10967       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10968       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10969       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10970     }
10971   }
10972
10973   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10974   // condition is true.
10975   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10976   SDValue Ops[] = { Op2, Op1, CC, Cond };
10977   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10978 }
10979
10980 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10981   MVT VT = Op->getSimpleValueType(0);
10982   SDValue In = Op->getOperand(0);
10983   MVT InVT = In.getSimpleValueType();
10984   SDLoc dl(Op);
10985
10986   unsigned int NumElts = VT.getVectorNumElements();
10987   if (NumElts != 8 && NumElts != 16)
10988     return SDValue();
10989
10990   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10991     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10992
10993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10994   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10995
10996   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10997   Constant *C = ConstantInt::get(*DAG.getContext(),
10998     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10999
11000   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11001   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11002   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11003                           MachinePointerInfo::getConstantPool(),
11004                           false, false, false, Alignment);
11005   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11006   if (VT.is512BitVector())
11007     return Brcst;
11008   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11009 }
11010
11011 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11012                                 SelectionDAG &DAG) {
11013   MVT VT = Op->getSimpleValueType(0);
11014   SDValue In = Op->getOperand(0);
11015   MVT InVT = In.getSimpleValueType();
11016   SDLoc dl(Op);
11017
11018   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11019     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11020
11021   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11022       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11023       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11024     return SDValue();
11025
11026   if (Subtarget->hasInt256())
11027     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11028
11029   // Optimize vectors in AVX mode
11030   // Sign extend  v8i16 to v8i32 and
11031   //              v4i32 to v4i64
11032   //
11033   // Divide input vector into two parts
11034   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11035   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11036   // concat the vectors to original VT
11037
11038   unsigned NumElems = InVT.getVectorNumElements();
11039   SDValue Undef = DAG.getUNDEF(InVT);
11040
11041   SmallVector<int,8> ShufMask1(NumElems, -1);
11042   for (unsigned i = 0; i != NumElems/2; ++i)
11043     ShufMask1[i] = i;
11044
11045   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11046
11047   SmallVector<int,8> ShufMask2(NumElems, -1);
11048   for (unsigned i = 0; i != NumElems/2; ++i)
11049     ShufMask2[i] = i + NumElems/2;
11050
11051   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11052
11053   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11054                                 VT.getVectorNumElements()/2);
11055
11056   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11057   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11058
11059   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11060 }
11061
11062 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11063 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11064 // from the AND / OR.
11065 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11066   Opc = Op.getOpcode();
11067   if (Opc != ISD::OR && Opc != ISD::AND)
11068     return false;
11069   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11070           Op.getOperand(0).hasOneUse() &&
11071           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11072           Op.getOperand(1).hasOneUse());
11073 }
11074
11075 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11076 // 1 and that the SETCC node has a single use.
11077 static bool isXor1OfSetCC(SDValue Op) {
11078   if (Op.getOpcode() != ISD::XOR)
11079     return false;
11080   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11081   if (N1C && N1C->getAPIntValue() == 1) {
11082     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11083       Op.getOperand(0).hasOneUse();
11084   }
11085   return false;
11086 }
11087
11088 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11089   bool addTest = true;
11090   SDValue Chain = Op.getOperand(0);
11091   SDValue Cond  = Op.getOperand(1);
11092   SDValue Dest  = Op.getOperand(2);
11093   SDLoc dl(Op);
11094   SDValue CC;
11095   bool Inverted = false;
11096
11097   if (Cond.getOpcode() == ISD::SETCC) {
11098     // Check for setcc([su]{add,sub,mul}o == 0).
11099     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11100         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11101         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11102         Cond.getOperand(0).getResNo() == 1 &&
11103         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11104          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11105          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11106          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11107          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11108          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11109       Inverted = true;
11110       Cond = Cond.getOperand(0);
11111     } else {
11112       SDValue NewCond = LowerSETCC(Cond, DAG);
11113       if (NewCond.getNode())
11114         Cond = NewCond;
11115     }
11116   }
11117 #if 0
11118   // FIXME: LowerXALUO doesn't handle these!!
11119   else if (Cond.getOpcode() == X86ISD::ADD  ||
11120            Cond.getOpcode() == X86ISD::SUB  ||
11121            Cond.getOpcode() == X86ISD::SMUL ||
11122            Cond.getOpcode() == X86ISD::UMUL)
11123     Cond = LowerXALUO(Cond, DAG);
11124 #endif
11125
11126   // Look pass (and (setcc_carry (cmp ...)), 1).
11127   if (Cond.getOpcode() == ISD::AND &&
11128       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11129     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11130     if (C && C->getAPIntValue() == 1)
11131       Cond = Cond.getOperand(0);
11132   }
11133
11134   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11135   // setting operand in place of the X86ISD::SETCC.
11136   unsigned CondOpcode = Cond.getOpcode();
11137   if (CondOpcode == X86ISD::SETCC ||
11138       CondOpcode == X86ISD::SETCC_CARRY) {
11139     CC = Cond.getOperand(0);
11140
11141     SDValue Cmp = Cond.getOperand(1);
11142     unsigned Opc = Cmp.getOpcode();
11143     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11144     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11145       Cond = Cmp;
11146       addTest = false;
11147     } else {
11148       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11149       default: break;
11150       case X86::COND_O:
11151       case X86::COND_B:
11152         // These can only come from an arithmetic instruction with overflow,
11153         // e.g. SADDO, UADDO.
11154         Cond = Cond.getNode()->getOperand(1);
11155         addTest = false;
11156         break;
11157       }
11158     }
11159   }
11160   CondOpcode = Cond.getOpcode();
11161   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11162       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11163       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11164        Cond.getOperand(0).getValueType() != MVT::i8)) {
11165     SDValue LHS = Cond.getOperand(0);
11166     SDValue RHS = Cond.getOperand(1);
11167     unsigned X86Opcode;
11168     unsigned X86Cond;
11169     SDVTList VTs;
11170     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11171     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11172     // X86ISD::INC).
11173     switch (CondOpcode) {
11174     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11175     case ISD::SADDO:
11176       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11177         if (C->isOne()) {
11178           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11179           break;
11180         }
11181       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11182     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11183     case ISD::SSUBO:
11184       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11185         if (C->isOne()) {
11186           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11187           break;
11188         }
11189       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11190     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11191     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11192     default: llvm_unreachable("unexpected overflowing operator");
11193     }
11194     if (Inverted)
11195       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11196     if (CondOpcode == ISD::UMULO)
11197       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11198                           MVT::i32);
11199     else
11200       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11201
11202     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11203
11204     if (CondOpcode == ISD::UMULO)
11205       Cond = X86Op.getValue(2);
11206     else
11207       Cond = X86Op.getValue(1);
11208
11209     CC = DAG.getConstant(X86Cond, MVT::i8);
11210     addTest = false;
11211   } else {
11212     unsigned CondOpc;
11213     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11214       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11215       if (CondOpc == ISD::OR) {
11216         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11217         // two branches instead of an explicit OR instruction with a
11218         // separate test.
11219         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11220             isX86LogicalCmp(Cmp)) {
11221           CC = Cond.getOperand(0).getOperand(0);
11222           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11223                               Chain, Dest, CC, Cmp);
11224           CC = Cond.getOperand(1).getOperand(0);
11225           Cond = Cmp;
11226           addTest = false;
11227         }
11228       } else { // ISD::AND
11229         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11230         // two branches instead of an explicit AND instruction with a
11231         // separate test. However, we only do this if this block doesn't
11232         // have a fall-through edge, because this requires an explicit
11233         // jmp when the condition is false.
11234         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11235             isX86LogicalCmp(Cmp) &&
11236             Op.getNode()->hasOneUse()) {
11237           X86::CondCode CCode =
11238             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11239           CCode = X86::GetOppositeBranchCondition(CCode);
11240           CC = DAG.getConstant(CCode, MVT::i8);
11241           SDNode *User = *Op.getNode()->use_begin();
11242           // Look for an unconditional branch following this conditional branch.
11243           // We need this because we need to reverse the successors in order
11244           // to implement FCMP_OEQ.
11245           if (User->getOpcode() == ISD::BR) {
11246             SDValue FalseBB = User->getOperand(1);
11247             SDNode *NewBR =
11248               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11249             assert(NewBR == User);
11250             (void)NewBR;
11251             Dest = FalseBB;
11252
11253             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11254                                 Chain, Dest, CC, Cmp);
11255             X86::CondCode CCode =
11256               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11257             CCode = X86::GetOppositeBranchCondition(CCode);
11258             CC = DAG.getConstant(CCode, MVT::i8);
11259             Cond = Cmp;
11260             addTest = false;
11261           }
11262         }
11263       }
11264     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11265       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11266       // It should be transformed during dag combiner except when the condition
11267       // is set by a arithmetics with overflow node.
11268       X86::CondCode CCode =
11269         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11270       CCode = X86::GetOppositeBranchCondition(CCode);
11271       CC = DAG.getConstant(CCode, MVT::i8);
11272       Cond = Cond.getOperand(0).getOperand(1);
11273       addTest = false;
11274     } else if (Cond.getOpcode() == ISD::SETCC &&
11275                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11276       // For FCMP_OEQ, we can emit
11277       // two branches instead of an explicit AND instruction with a
11278       // separate test. However, we only do this if this block doesn't
11279       // have a fall-through edge, because this requires an explicit
11280       // jmp when the condition is false.
11281       if (Op.getNode()->hasOneUse()) {
11282         SDNode *User = *Op.getNode()->use_begin();
11283         // Look for an unconditional branch following this conditional branch.
11284         // We need this because we need to reverse the successors in order
11285         // to implement FCMP_OEQ.
11286         if (User->getOpcode() == ISD::BR) {
11287           SDValue FalseBB = User->getOperand(1);
11288           SDNode *NewBR =
11289             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11290           assert(NewBR == User);
11291           (void)NewBR;
11292           Dest = FalseBB;
11293
11294           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11295                                     Cond.getOperand(0), Cond.getOperand(1));
11296           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11297           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11298           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11299                               Chain, Dest, CC, Cmp);
11300           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11301           Cond = Cmp;
11302           addTest = false;
11303         }
11304       }
11305     } else if (Cond.getOpcode() == ISD::SETCC &&
11306                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11307       // For FCMP_UNE, we can emit
11308       // two branches instead of an explicit AND instruction with a
11309       // separate test. However, we only do this if this block doesn't
11310       // have a fall-through edge, because this requires an explicit
11311       // jmp when the condition is false.
11312       if (Op.getNode()->hasOneUse()) {
11313         SDNode *User = *Op.getNode()->use_begin();
11314         // Look for an unconditional branch following this conditional branch.
11315         // We need this because we need to reverse the successors in order
11316         // to implement FCMP_UNE.
11317         if (User->getOpcode() == ISD::BR) {
11318           SDValue FalseBB = User->getOperand(1);
11319           SDNode *NewBR =
11320             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11321           assert(NewBR == User);
11322           (void)NewBR;
11323
11324           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11325                                     Cond.getOperand(0), Cond.getOperand(1));
11326           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11327           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11328           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11329                               Chain, Dest, CC, Cmp);
11330           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11331           Cond = Cmp;
11332           addTest = false;
11333           Dest = FalseBB;
11334         }
11335       }
11336     }
11337   }
11338
11339   if (addTest) {
11340     // Look pass the truncate if the high bits are known zero.
11341     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11342         Cond = Cond.getOperand(0);
11343
11344     // We know the result of AND is compared against zero. Try to match
11345     // it to BT.
11346     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11347       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11348       if (NewSetCC.getNode()) {
11349         CC = NewSetCC.getOperand(0);
11350         Cond = NewSetCC.getOperand(1);
11351         addTest = false;
11352       }
11353     }
11354   }
11355
11356   if (addTest) {
11357     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11358     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11359   }
11360   Cond = ConvertCmpIfNecessary(Cond, DAG);
11361   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11362                      Chain, Dest, CC, Cond);
11363 }
11364
11365 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11366 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11367 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11368 // that the guard pages used by the OS virtual memory manager are allocated in
11369 // correct sequence.
11370 SDValue
11371 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11372                                            SelectionDAG &DAG) const {
11373   MachineFunction &MF = DAG.getMachineFunction();
11374   bool SplitStack = MF.shouldSplitStack();
11375   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11376                SplitStack;
11377   SDLoc dl(Op);
11378
11379   if (!Lower) {
11380     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11381     SDNode* Node = Op.getNode();
11382
11383     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11384     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11385         " not tell us which reg is the stack pointer!");
11386     EVT VT = Node->getValueType(0);
11387     SDValue Tmp1 = SDValue(Node, 0);
11388     SDValue Tmp2 = SDValue(Node, 1);
11389     SDValue Tmp3 = Node->getOperand(2);
11390     SDValue Chain = Tmp1.getOperand(0);
11391
11392     // Chain the dynamic stack allocation so that it doesn't modify the stack
11393     // pointer when other instructions are using the stack.
11394     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11395         SDLoc(Node));
11396
11397     SDValue Size = Tmp2.getOperand(1);
11398     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11399     Chain = SP.getValue(1);
11400     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11401     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11402     unsigned StackAlign = TFI.getStackAlignment();
11403     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11404     if (Align > StackAlign)
11405       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11406           DAG.getConstant(-(uint64_t)Align, VT));
11407     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11408
11409     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11410         DAG.getIntPtrConstant(0, true), SDValue(),
11411         SDLoc(Node));
11412
11413     SDValue Ops[2] = { Tmp1, Tmp2 };
11414     return DAG.getMergeValues(Ops, dl);
11415   }
11416
11417   // Get the inputs.
11418   SDValue Chain = Op.getOperand(0);
11419   SDValue Size  = Op.getOperand(1);
11420   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11421   EVT VT = Op.getNode()->getValueType(0);
11422
11423   bool Is64Bit = Subtarget->is64Bit();
11424   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11425
11426   if (SplitStack) {
11427     MachineRegisterInfo &MRI = MF.getRegInfo();
11428
11429     if (Is64Bit) {
11430       // The 64 bit implementation of segmented stacks needs to clobber both r10
11431       // r11. This makes it impossible to use it along with nested parameters.
11432       const Function *F = MF.getFunction();
11433
11434       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11435            I != E; ++I)
11436         if (I->hasNestAttr())
11437           report_fatal_error("Cannot use segmented stacks with functions that "
11438                              "have nested arguments.");
11439     }
11440
11441     const TargetRegisterClass *AddrRegClass =
11442       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11443     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11444     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11445     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11446                                 DAG.getRegister(Vreg, SPTy));
11447     SDValue Ops1[2] = { Value, Chain };
11448     return DAG.getMergeValues(Ops1, dl);
11449   } else {
11450     SDValue Flag;
11451     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11452
11453     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11454     Flag = Chain.getValue(1);
11455     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11456
11457     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11458
11459     const X86RegisterInfo *RegInfo =
11460       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11461     unsigned SPReg = RegInfo->getStackRegister();
11462     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11463     Chain = SP.getValue(1);
11464
11465     if (Align) {
11466       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11467                        DAG.getConstant(-(uint64_t)Align, VT));
11468       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11469     }
11470
11471     SDValue Ops1[2] = { SP, Chain };
11472     return DAG.getMergeValues(Ops1, dl);
11473   }
11474 }
11475
11476 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11477   MachineFunction &MF = DAG.getMachineFunction();
11478   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11479
11480   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11481   SDLoc DL(Op);
11482
11483   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11484     // vastart just stores the address of the VarArgsFrameIndex slot into the
11485     // memory location argument.
11486     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11487                                    getPointerTy());
11488     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11489                         MachinePointerInfo(SV), false, false, 0);
11490   }
11491
11492   // __va_list_tag:
11493   //   gp_offset         (0 - 6 * 8)
11494   //   fp_offset         (48 - 48 + 8 * 16)
11495   //   overflow_arg_area (point to parameters coming in memory).
11496   //   reg_save_area
11497   SmallVector<SDValue, 8> MemOps;
11498   SDValue FIN = Op.getOperand(1);
11499   // Store gp_offset
11500   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11501                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11502                                                MVT::i32),
11503                                FIN, MachinePointerInfo(SV), false, false, 0);
11504   MemOps.push_back(Store);
11505
11506   // Store fp_offset
11507   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11508                     FIN, DAG.getIntPtrConstant(4));
11509   Store = DAG.getStore(Op.getOperand(0), DL,
11510                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11511                                        MVT::i32),
11512                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11513   MemOps.push_back(Store);
11514
11515   // Store ptr to overflow_arg_area
11516   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11517                     FIN, DAG.getIntPtrConstant(4));
11518   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11519                                     getPointerTy());
11520   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11521                        MachinePointerInfo(SV, 8),
11522                        false, false, 0);
11523   MemOps.push_back(Store);
11524
11525   // Store ptr to reg_save_area.
11526   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11527                     FIN, DAG.getIntPtrConstant(8));
11528   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11529                                     getPointerTy());
11530   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11531                        MachinePointerInfo(SV, 16), false, false, 0);
11532   MemOps.push_back(Store);
11533   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11534 }
11535
11536 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11537   assert(Subtarget->is64Bit() &&
11538          "LowerVAARG only handles 64-bit va_arg!");
11539   assert((Subtarget->isTargetLinux() ||
11540           Subtarget->isTargetDarwin()) &&
11541           "Unhandled target in LowerVAARG");
11542   assert(Op.getNode()->getNumOperands() == 4);
11543   SDValue Chain = Op.getOperand(0);
11544   SDValue SrcPtr = Op.getOperand(1);
11545   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11546   unsigned Align = Op.getConstantOperandVal(3);
11547   SDLoc dl(Op);
11548
11549   EVT ArgVT = Op.getNode()->getValueType(0);
11550   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11551   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11552   uint8_t ArgMode;
11553
11554   // Decide which area this value should be read from.
11555   // TODO: Implement the AMD64 ABI in its entirety. This simple
11556   // selection mechanism works only for the basic types.
11557   if (ArgVT == MVT::f80) {
11558     llvm_unreachable("va_arg for f80 not yet implemented");
11559   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11560     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11561   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11562     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11563   } else {
11564     llvm_unreachable("Unhandled argument type in LowerVAARG");
11565   }
11566
11567   if (ArgMode == 2) {
11568     // Sanity Check: Make sure using fp_offset makes sense.
11569     assert(!getTargetMachine().Options.UseSoftFloat &&
11570            !(DAG.getMachineFunction()
11571                 .getFunction()->getAttributes()
11572                 .hasAttribute(AttributeSet::FunctionIndex,
11573                               Attribute::NoImplicitFloat)) &&
11574            Subtarget->hasSSE1());
11575   }
11576
11577   // Insert VAARG_64 node into the DAG
11578   // VAARG_64 returns two values: Variable Argument Address, Chain
11579   SmallVector<SDValue, 11> InstOps;
11580   InstOps.push_back(Chain);
11581   InstOps.push_back(SrcPtr);
11582   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11583   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11584   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11585   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11586   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11587                                           VTs, InstOps, MVT::i64,
11588                                           MachinePointerInfo(SV),
11589                                           /*Align=*/0,
11590                                           /*Volatile=*/false,
11591                                           /*ReadMem=*/true,
11592                                           /*WriteMem=*/true);
11593   Chain = VAARG.getValue(1);
11594
11595   // Load the next argument and return it
11596   return DAG.getLoad(ArgVT, dl,
11597                      Chain,
11598                      VAARG,
11599                      MachinePointerInfo(),
11600                      false, false, false, 0);
11601 }
11602
11603 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11604                            SelectionDAG &DAG) {
11605   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11606   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11607   SDValue Chain = Op.getOperand(0);
11608   SDValue DstPtr = Op.getOperand(1);
11609   SDValue SrcPtr = Op.getOperand(2);
11610   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11611   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11612   SDLoc DL(Op);
11613
11614   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11615                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11616                        false,
11617                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11618 }
11619
11620 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11621 // amount is a constant. Takes immediate version of shift as input.
11622 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11623                                           SDValue SrcOp, uint64_t ShiftAmt,
11624                                           SelectionDAG &DAG) {
11625   MVT ElementType = VT.getVectorElementType();
11626
11627   // Fold this packed shift into its first operand if ShiftAmt is 0.
11628   if (ShiftAmt == 0)
11629     return SrcOp;
11630
11631   // Check for ShiftAmt >= element width
11632   if (ShiftAmt >= ElementType.getSizeInBits()) {
11633     if (Opc == X86ISD::VSRAI)
11634       ShiftAmt = ElementType.getSizeInBits() - 1;
11635     else
11636       return DAG.getConstant(0, VT);
11637   }
11638
11639   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11640          && "Unknown target vector shift-by-constant node");
11641
11642   // Fold this packed vector shift into a build vector if SrcOp is a
11643   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11644   if (VT == SrcOp.getSimpleValueType() &&
11645       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11646     SmallVector<SDValue, 8> Elts;
11647     unsigned NumElts = SrcOp->getNumOperands();
11648     ConstantSDNode *ND;
11649
11650     switch(Opc) {
11651     default: llvm_unreachable(nullptr);
11652     case X86ISD::VSHLI:
11653       for (unsigned i=0; i!=NumElts; ++i) {
11654         SDValue CurrentOp = SrcOp->getOperand(i);
11655         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11656           Elts.push_back(CurrentOp);
11657           continue;
11658         }
11659         ND = cast<ConstantSDNode>(CurrentOp);
11660         const APInt &C = ND->getAPIntValue();
11661         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11662       }
11663       break;
11664     case X86ISD::VSRLI:
11665       for (unsigned i=0; i!=NumElts; ++i) {
11666         SDValue CurrentOp = SrcOp->getOperand(i);
11667         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11668           Elts.push_back(CurrentOp);
11669           continue;
11670         }
11671         ND = cast<ConstantSDNode>(CurrentOp);
11672         const APInt &C = ND->getAPIntValue();
11673         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11674       }
11675       break;
11676     case X86ISD::VSRAI:
11677       for (unsigned i=0; i!=NumElts; ++i) {
11678         SDValue CurrentOp = SrcOp->getOperand(i);
11679         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11680           Elts.push_back(CurrentOp);
11681           continue;
11682         }
11683         ND = cast<ConstantSDNode>(CurrentOp);
11684         const APInt &C = ND->getAPIntValue();
11685         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11686       }
11687       break;
11688     }
11689
11690     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11691   }
11692
11693   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11694 }
11695
11696 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11697 // may or may not be a constant. Takes immediate version of shift as input.
11698 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11699                                    SDValue SrcOp, SDValue ShAmt,
11700                                    SelectionDAG &DAG) {
11701   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11702
11703   // Catch shift-by-constant.
11704   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11705     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11706                                       CShAmt->getZExtValue(), DAG);
11707
11708   // Change opcode to non-immediate version
11709   switch (Opc) {
11710     default: llvm_unreachable("Unknown target vector shift node");
11711     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11712     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11713     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11714   }
11715
11716   // Need to build a vector containing shift amount
11717   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11718   SDValue ShOps[4];
11719   ShOps[0] = ShAmt;
11720   ShOps[1] = DAG.getConstant(0, MVT::i32);
11721   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11722   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11723
11724   // The return type has to be a 128-bit type with the same element
11725   // type as the input type.
11726   MVT EltVT = VT.getVectorElementType();
11727   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11728
11729   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11730   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11731 }
11732
11733 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11734   SDLoc dl(Op);
11735   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11736   switch (IntNo) {
11737   default: return SDValue();    // Don't custom lower most intrinsics.
11738   // Comparison intrinsics.
11739   case Intrinsic::x86_sse_comieq_ss:
11740   case Intrinsic::x86_sse_comilt_ss:
11741   case Intrinsic::x86_sse_comile_ss:
11742   case Intrinsic::x86_sse_comigt_ss:
11743   case Intrinsic::x86_sse_comige_ss:
11744   case Intrinsic::x86_sse_comineq_ss:
11745   case Intrinsic::x86_sse_ucomieq_ss:
11746   case Intrinsic::x86_sse_ucomilt_ss:
11747   case Intrinsic::x86_sse_ucomile_ss:
11748   case Intrinsic::x86_sse_ucomigt_ss:
11749   case Intrinsic::x86_sse_ucomige_ss:
11750   case Intrinsic::x86_sse_ucomineq_ss:
11751   case Intrinsic::x86_sse2_comieq_sd:
11752   case Intrinsic::x86_sse2_comilt_sd:
11753   case Intrinsic::x86_sse2_comile_sd:
11754   case Intrinsic::x86_sse2_comigt_sd:
11755   case Intrinsic::x86_sse2_comige_sd:
11756   case Intrinsic::x86_sse2_comineq_sd:
11757   case Intrinsic::x86_sse2_ucomieq_sd:
11758   case Intrinsic::x86_sse2_ucomilt_sd:
11759   case Intrinsic::x86_sse2_ucomile_sd:
11760   case Intrinsic::x86_sse2_ucomigt_sd:
11761   case Intrinsic::x86_sse2_ucomige_sd:
11762   case Intrinsic::x86_sse2_ucomineq_sd: {
11763     unsigned Opc;
11764     ISD::CondCode CC;
11765     switch (IntNo) {
11766     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11767     case Intrinsic::x86_sse_comieq_ss:
11768     case Intrinsic::x86_sse2_comieq_sd:
11769       Opc = X86ISD::COMI;
11770       CC = ISD::SETEQ;
11771       break;
11772     case Intrinsic::x86_sse_comilt_ss:
11773     case Intrinsic::x86_sse2_comilt_sd:
11774       Opc = X86ISD::COMI;
11775       CC = ISD::SETLT;
11776       break;
11777     case Intrinsic::x86_sse_comile_ss:
11778     case Intrinsic::x86_sse2_comile_sd:
11779       Opc = X86ISD::COMI;
11780       CC = ISD::SETLE;
11781       break;
11782     case Intrinsic::x86_sse_comigt_ss:
11783     case Intrinsic::x86_sse2_comigt_sd:
11784       Opc = X86ISD::COMI;
11785       CC = ISD::SETGT;
11786       break;
11787     case Intrinsic::x86_sse_comige_ss:
11788     case Intrinsic::x86_sse2_comige_sd:
11789       Opc = X86ISD::COMI;
11790       CC = ISD::SETGE;
11791       break;
11792     case Intrinsic::x86_sse_comineq_ss:
11793     case Intrinsic::x86_sse2_comineq_sd:
11794       Opc = X86ISD::COMI;
11795       CC = ISD::SETNE;
11796       break;
11797     case Intrinsic::x86_sse_ucomieq_ss:
11798     case Intrinsic::x86_sse2_ucomieq_sd:
11799       Opc = X86ISD::UCOMI;
11800       CC = ISD::SETEQ;
11801       break;
11802     case Intrinsic::x86_sse_ucomilt_ss:
11803     case Intrinsic::x86_sse2_ucomilt_sd:
11804       Opc = X86ISD::UCOMI;
11805       CC = ISD::SETLT;
11806       break;
11807     case Intrinsic::x86_sse_ucomile_ss:
11808     case Intrinsic::x86_sse2_ucomile_sd:
11809       Opc = X86ISD::UCOMI;
11810       CC = ISD::SETLE;
11811       break;
11812     case Intrinsic::x86_sse_ucomigt_ss:
11813     case Intrinsic::x86_sse2_ucomigt_sd:
11814       Opc = X86ISD::UCOMI;
11815       CC = ISD::SETGT;
11816       break;
11817     case Intrinsic::x86_sse_ucomige_ss:
11818     case Intrinsic::x86_sse2_ucomige_sd:
11819       Opc = X86ISD::UCOMI;
11820       CC = ISD::SETGE;
11821       break;
11822     case Intrinsic::x86_sse_ucomineq_ss:
11823     case Intrinsic::x86_sse2_ucomineq_sd:
11824       Opc = X86ISD::UCOMI;
11825       CC = ISD::SETNE;
11826       break;
11827     }
11828
11829     SDValue LHS = Op.getOperand(1);
11830     SDValue RHS = Op.getOperand(2);
11831     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11832     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11833     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11834     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11835                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11836     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11837   }
11838
11839   // Arithmetic intrinsics.
11840   case Intrinsic::x86_sse2_pmulu_dq:
11841   case Intrinsic::x86_avx2_pmulu_dq:
11842     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11843                        Op.getOperand(1), Op.getOperand(2));
11844
11845   case Intrinsic::x86_sse41_pmuldq:
11846   case Intrinsic::x86_avx2_pmul_dq:
11847     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11848                        Op.getOperand(1), Op.getOperand(2));
11849
11850   case Intrinsic::x86_sse2_pmulhu_w:
11851   case Intrinsic::x86_avx2_pmulhu_w:
11852     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11853                        Op.getOperand(1), Op.getOperand(2));
11854
11855   case Intrinsic::x86_sse2_pmulh_w:
11856   case Intrinsic::x86_avx2_pmulh_w:
11857     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11858                        Op.getOperand(1), Op.getOperand(2));
11859
11860   // SSE2/AVX2 sub with unsigned saturation intrinsics
11861   case Intrinsic::x86_sse2_psubus_b:
11862   case Intrinsic::x86_sse2_psubus_w:
11863   case Intrinsic::x86_avx2_psubus_b:
11864   case Intrinsic::x86_avx2_psubus_w:
11865     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11866                        Op.getOperand(1), Op.getOperand(2));
11867
11868   // SSE3/AVX horizontal add/sub intrinsics
11869   case Intrinsic::x86_sse3_hadd_ps:
11870   case Intrinsic::x86_sse3_hadd_pd:
11871   case Intrinsic::x86_avx_hadd_ps_256:
11872   case Intrinsic::x86_avx_hadd_pd_256:
11873   case Intrinsic::x86_sse3_hsub_ps:
11874   case Intrinsic::x86_sse3_hsub_pd:
11875   case Intrinsic::x86_avx_hsub_ps_256:
11876   case Intrinsic::x86_avx_hsub_pd_256:
11877   case Intrinsic::x86_ssse3_phadd_w_128:
11878   case Intrinsic::x86_ssse3_phadd_d_128:
11879   case Intrinsic::x86_avx2_phadd_w:
11880   case Intrinsic::x86_avx2_phadd_d:
11881   case Intrinsic::x86_ssse3_phsub_w_128:
11882   case Intrinsic::x86_ssse3_phsub_d_128:
11883   case Intrinsic::x86_avx2_phsub_w:
11884   case Intrinsic::x86_avx2_phsub_d: {
11885     unsigned Opcode;
11886     switch (IntNo) {
11887     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11888     case Intrinsic::x86_sse3_hadd_ps:
11889     case Intrinsic::x86_sse3_hadd_pd:
11890     case Intrinsic::x86_avx_hadd_ps_256:
11891     case Intrinsic::x86_avx_hadd_pd_256:
11892       Opcode = X86ISD::FHADD;
11893       break;
11894     case Intrinsic::x86_sse3_hsub_ps:
11895     case Intrinsic::x86_sse3_hsub_pd:
11896     case Intrinsic::x86_avx_hsub_ps_256:
11897     case Intrinsic::x86_avx_hsub_pd_256:
11898       Opcode = X86ISD::FHSUB;
11899       break;
11900     case Intrinsic::x86_ssse3_phadd_w_128:
11901     case Intrinsic::x86_ssse3_phadd_d_128:
11902     case Intrinsic::x86_avx2_phadd_w:
11903     case Intrinsic::x86_avx2_phadd_d:
11904       Opcode = X86ISD::HADD;
11905       break;
11906     case Intrinsic::x86_ssse3_phsub_w_128:
11907     case Intrinsic::x86_ssse3_phsub_d_128:
11908     case Intrinsic::x86_avx2_phsub_w:
11909     case Intrinsic::x86_avx2_phsub_d:
11910       Opcode = X86ISD::HSUB;
11911       break;
11912     }
11913     return DAG.getNode(Opcode, dl, Op.getValueType(),
11914                        Op.getOperand(1), Op.getOperand(2));
11915   }
11916
11917   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11918   case Intrinsic::x86_sse2_pmaxu_b:
11919   case Intrinsic::x86_sse41_pmaxuw:
11920   case Intrinsic::x86_sse41_pmaxud:
11921   case Intrinsic::x86_avx2_pmaxu_b:
11922   case Intrinsic::x86_avx2_pmaxu_w:
11923   case Intrinsic::x86_avx2_pmaxu_d:
11924   case Intrinsic::x86_sse2_pminu_b:
11925   case Intrinsic::x86_sse41_pminuw:
11926   case Intrinsic::x86_sse41_pminud:
11927   case Intrinsic::x86_avx2_pminu_b:
11928   case Intrinsic::x86_avx2_pminu_w:
11929   case Intrinsic::x86_avx2_pminu_d:
11930   case Intrinsic::x86_sse41_pmaxsb:
11931   case Intrinsic::x86_sse2_pmaxs_w:
11932   case Intrinsic::x86_sse41_pmaxsd:
11933   case Intrinsic::x86_avx2_pmaxs_b:
11934   case Intrinsic::x86_avx2_pmaxs_w:
11935   case Intrinsic::x86_avx2_pmaxs_d:
11936   case Intrinsic::x86_sse41_pminsb:
11937   case Intrinsic::x86_sse2_pmins_w:
11938   case Intrinsic::x86_sse41_pminsd:
11939   case Intrinsic::x86_avx2_pmins_b:
11940   case Intrinsic::x86_avx2_pmins_w:
11941   case Intrinsic::x86_avx2_pmins_d: {
11942     unsigned Opcode;
11943     switch (IntNo) {
11944     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11945     case Intrinsic::x86_sse2_pmaxu_b:
11946     case Intrinsic::x86_sse41_pmaxuw:
11947     case Intrinsic::x86_sse41_pmaxud:
11948     case Intrinsic::x86_avx2_pmaxu_b:
11949     case Intrinsic::x86_avx2_pmaxu_w:
11950     case Intrinsic::x86_avx2_pmaxu_d:
11951       Opcode = X86ISD::UMAX;
11952       break;
11953     case Intrinsic::x86_sse2_pminu_b:
11954     case Intrinsic::x86_sse41_pminuw:
11955     case Intrinsic::x86_sse41_pminud:
11956     case Intrinsic::x86_avx2_pminu_b:
11957     case Intrinsic::x86_avx2_pminu_w:
11958     case Intrinsic::x86_avx2_pminu_d:
11959       Opcode = X86ISD::UMIN;
11960       break;
11961     case Intrinsic::x86_sse41_pmaxsb:
11962     case Intrinsic::x86_sse2_pmaxs_w:
11963     case Intrinsic::x86_sse41_pmaxsd:
11964     case Intrinsic::x86_avx2_pmaxs_b:
11965     case Intrinsic::x86_avx2_pmaxs_w:
11966     case Intrinsic::x86_avx2_pmaxs_d:
11967       Opcode = X86ISD::SMAX;
11968       break;
11969     case Intrinsic::x86_sse41_pminsb:
11970     case Intrinsic::x86_sse2_pmins_w:
11971     case Intrinsic::x86_sse41_pminsd:
11972     case Intrinsic::x86_avx2_pmins_b:
11973     case Intrinsic::x86_avx2_pmins_w:
11974     case Intrinsic::x86_avx2_pmins_d:
11975       Opcode = X86ISD::SMIN;
11976       break;
11977     }
11978     return DAG.getNode(Opcode, dl, Op.getValueType(),
11979                        Op.getOperand(1), Op.getOperand(2));
11980   }
11981
11982   // SSE/SSE2/AVX floating point max/min intrinsics.
11983   case Intrinsic::x86_sse_max_ps:
11984   case Intrinsic::x86_sse2_max_pd:
11985   case Intrinsic::x86_avx_max_ps_256:
11986   case Intrinsic::x86_avx_max_pd_256:
11987   case Intrinsic::x86_sse_min_ps:
11988   case Intrinsic::x86_sse2_min_pd:
11989   case Intrinsic::x86_avx_min_ps_256:
11990   case Intrinsic::x86_avx_min_pd_256: {
11991     unsigned Opcode;
11992     switch (IntNo) {
11993     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11994     case Intrinsic::x86_sse_max_ps:
11995     case Intrinsic::x86_sse2_max_pd:
11996     case Intrinsic::x86_avx_max_ps_256:
11997     case Intrinsic::x86_avx_max_pd_256:
11998       Opcode = X86ISD::FMAX;
11999       break;
12000     case Intrinsic::x86_sse_min_ps:
12001     case Intrinsic::x86_sse2_min_pd:
12002     case Intrinsic::x86_avx_min_ps_256:
12003     case Intrinsic::x86_avx_min_pd_256:
12004       Opcode = X86ISD::FMIN;
12005       break;
12006     }
12007     return DAG.getNode(Opcode, dl, Op.getValueType(),
12008                        Op.getOperand(1), Op.getOperand(2));
12009   }
12010
12011   // AVX2 variable shift intrinsics
12012   case Intrinsic::x86_avx2_psllv_d:
12013   case Intrinsic::x86_avx2_psllv_q:
12014   case Intrinsic::x86_avx2_psllv_d_256:
12015   case Intrinsic::x86_avx2_psllv_q_256:
12016   case Intrinsic::x86_avx2_psrlv_d:
12017   case Intrinsic::x86_avx2_psrlv_q:
12018   case Intrinsic::x86_avx2_psrlv_d_256:
12019   case Intrinsic::x86_avx2_psrlv_q_256:
12020   case Intrinsic::x86_avx2_psrav_d:
12021   case Intrinsic::x86_avx2_psrav_d_256: {
12022     unsigned Opcode;
12023     switch (IntNo) {
12024     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12025     case Intrinsic::x86_avx2_psllv_d:
12026     case Intrinsic::x86_avx2_psllv_q:
12027     case Intrinsic::x86_avx2_psllv_d_256:
12028     case Intrinsic::x86_avx2_psllv_q_256:
12029       Opcode = ISD::SHL;
12030       break;
12031     case Intrinsic::x86_avx2_psrlv_d:
12032     case Intrinsic::x86_avx2_psrlv_q:
12033     case Intrinsic::x86_avx2_psrlv_d_256:
12034     case Intrinsic::x86_avx2_psrlv_q_256:
12035       Opcode = ISD::SRL;
12036       break;
12037     case Intrinsic::x86_avx2_psrav_d:
12038     case Intrinsic::x86_avx2_psrav_d_256:
12039       Opcode = ISD::SRA;
12040       break;
12041     }
12042     return DAG.getNode(Opcode, dl, Op.getValueType(),
12043                        Op.getOperand(1), Op.getOperand(2));
12044   }
12045
12046   case Intrinsic::x86_ssse3_pshuf_b_128:
12047   case Intrinsic::x86_avx2_pshuf_b:
12048     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12049                        Op.getOperand(1), Op.getOperand(2));
12050
12051   case Intrinsic::x86_ssse3_psign_b_128:
12052   case Intrinsic::x86_ssse3_psign_w_128:
12053   case Intrinsic::x86_ssse3_psign_d_128:
12054   case Intrinsic::x86_avx2_psign_b:
12055   case Intrinsic::x86_avx2_psign_w:
12056   case Intrinsic::x86_avx2_psign_d:
12057     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12058                        Op.getOperand(1), Op.getOperand(2));
12059
12060   case Intrinsic::x86_sse41_insertps:
12061     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12062                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12063
12064   case Intrinsic::x86_avx_vperm2f128_ps_256:
12065   case Intrinsic::x86_avx_vperm2f128_pd_256:
12066   case Intrinsic::x86_avx_vperm2f128_si_256:
12067   case Intrinsic::x86_avx2_vperm2i128:
12068     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12069                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12070
12071   case Intrinsic::x86_avx2_permd:
12072   case Intrinsic::x86_avx2_permps:
12073     // Operands intentionally swapped. Mask is last operand to intrinsic,
12074     // but second operand for node/instruction.
12075     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12076                        Op.getOperand(2), Op.getOperand(1));
12077
12078   case Intrinsic::x86_sse_sqrt_ps:
12079   case Intrinsic::x86_sse2_sqrt_pd:
12080   case Intrinsic::x86_avx_sqrt_ps_256:
12081   case Intrinsic::x86_avx_sqrt_pd_256:
12082     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12083
12084   // ptest and testp intrinsics. The intrinsic these come from are designed to
12085   // return an integer value, not just an instruction so lower it to the ptest
12086   // or testp pattern and a setcc for the result.
12087   case Intrinsic::x86_sse41_ptestz:
12088   case Intrinsic::x86_sse41_ptestc:
12089   case Intrinsic::x86_sse41_ptestnzc:
12090   case Intrinsic::x86_avx_ptestz_256:
12091   case Intrinsic::x86_avx_ptestc_256:
12092   case Intrinsic::x86_avx_ptestnzc_256:
12093   case Intrinsic::x86_avx_vtestz_ps:
12094   case Intrinsic::x86_avx_vtestc_ps:
12095   case Intrinsic::x86_avx_vtestnzc_ps:
12096   case Intrinsic::x86_avx_vtestz_pd:
12097   case Intrinsic::x86_avx_vtestc_pd:
12098   case Intrinsic::x86_avx_vtestnzc_pd:
12099   case Intrinsic::x86_avx_vtestz_ps_256:
12100   case Intrinsic::x86_avx_vtestc_ps_256:
12101   case Intrinsic::x86_avx_vtestnzc_ps_256:
12102   case Intrinsic::x86_avx_vtestz_pd_256:
12103   case Intrinsic::x86_avx_vtestc_pd_256:
12104   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12105     bool IsTestPacked = false;
12106     unsigned X86CC;
12107     switch (IntNo) {
12108     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12109     case Intrinsic::x86_avx_vtestz_ps:
12110     case Intrinsic::x86_avx_vtestz_pd:
12111     case Intrinsic::x86_avx_vtestz_ps_256:
12112     case Intrinsic::x86_avx_vtestz_pd_256:
12113       IsTestPacked = true; // Fallthrough
12114     case Intrinsic::x86_sse41_ptestz:
12115     case Intrinsic::x86_avx_ptestz_256:
12116       // ZF = 1
12117       X86CC = X86::COND_E;
12118       break;
12119     case Intrinsic::x86_avx_vtestc_ps:
12120     case Intrinsic::x86_avx_vtestc_pd:
12121     case Intrinsic::x86_avx_vtestc_ps_256:
12122     case Intrinsic::x86_avx_vtestc_pd_256:
12123       IsTestPacked = true; // Fallthrough
12124     case Intrinsic::x86_sse41_ptestc:
12125     case Intrinsic::x86_avx_ptestc_256:
12126       // CF = 1
12127       X86CC = X86::COND_B;
12128       break;
12129     case Intrinsic::x86_avx_vtestnzc_ps:
12130     case Intrinsic::x86_avx_vtestnzc_pd:
12131     case Intrinsic::x86_avx_vtestnzc_ps_256:
12132     case Intrinsic::x86_avx_vtestnzc_pd_256:
12133       IsTestPacked = true; // Fallthrough
12134     case Intrinsic::x86_sse41_ptestnzc:
12135     case Intrinsic::x86_avx_ptestnzc_256:
12136       // ZF and CF = 0
12137       X86CC = X86::COND_A;
12138       break;
12139     }
12140
12141     SDValue LHS = Op.getOperand(1);
12142     SDValue RHS = Op.getOperand(2);
12143     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12144     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12145     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12146     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12147     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12148   }
12149   case Intrinsic::x86_avx512_kortestz_w:
12150   case Intrinsic::x86_avx512_kortestc_w: {
12151     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12152     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12153     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12154     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12155     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12156     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12157     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12158   }
12159
12160   // SSE/AVX shift intrinsics
12161   case Intrinsic::x86_sse2_psll_w:
12162   case Intrinsic::x86_sse2_psll_d:
12163   case Intrinsic::x86_sse2_psll_q:
12164   case Intrinsic::x86_avx2_psll_w:
12165   case Intrinsic::x86_avx2_psll_d:
12166   case Intrinsic::x86_avx2_psll_q:
12167   case Intrinsic::x86_sse2_psrl_w:
12168   case Intrinsic::x86_sse2_psrl_d:
12169   case Intrinsic::x86_sse2_psrl_q:
12170   case Intrinsic::x86_avx2_psrl_w:
12171   case Intrinsic::x86_avx2_psrl_d:
12172   case Intrinsic::x86_avx2_psrl_q:
12173   case Intrinsic::x86_sse2_psra_w:
12174   case Intrinsic::x86_sse2_psra_d:
12175   case Intrinsic::x86_avx2_psra_w:
12176   case Intrinsic::x86_avx2_psra_d: {
12177     unsigned Opcode;
12178     switch (IntNo) {
12179     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12180     case Intrinsic::x86_sse2_psll_w:
12181     case Intrinsic::x86_sse2_psll_d:
12182     case Intrinsic::x86_sse2_psll_q:
12183     case Intrinsic::x86_avx2_psll_w:
12184     case Intrinsic::x86_avx2_psll_d:
12185     case Intrinsic::x86_avx2_psll_q:
12186       Opcode = X86ISD::VSHL;
12187       break;
12188     case Intrinsic::x86_sse2_psrl_w:
12189     case Intrinsic::x86_sse2_psrl_d:
12190     case Intrinsic::x86_sse2_psrl_q:
12191     case Intrinsic::x86_avx2_psrl_w:
12192     case Intrinsic::x86_avx2_psrl_d:
12193     case Intrinsic::x86_avx2_psrl_q:
12194       Opcode = X86ISD::VSRL;
12195       break;
12196     case Intrinsic::x86_sse2_psra_w:
12197     case Intrinsic::x86_sse2_psra_d:
12198     case Intrinsic::x86_avx2_psra_w:
12199     case Intrinsic::x86_avx2_psra_d:
12200       Opcode = X86ISD::VSRA;
12201       break;
12202     }
12203     return DAG.getNode(Opcode, dl, Op.getValueType(),
12204                        Op.getOperand(1), Op.getOperand(2));
12205   }
12206
12207   // SSE/AVX immediate shift intrinsics
12208   case Intrinsic::x86_sse2_pslli_w:
12209   case Intrinsic::x86_sse2_pslli_d:
12210   case Intrinsic::x86_sse2_pslli_q:
12211   case Intrinsic::x86_avx2_pslli_w:
12212   case Intrinsic::x86_avx2_pslli_d:
12213   case Intrinsic::x86_avx2_pslli_q:
12214   case Intrinsic::x86_sse2_psrli_w:
12215   case Intrinsic::x86_sse2_psrli_d:
12216   case Intrinsic::x86_sse2_psrli_q:
12217   case Intrinsic::x86_avx2_psrli_w:
12218   case Intrinsic::x86_avx2_psrli_d:
12219   case Intrinsic::x86_avx2_psrli_q:
12220   case Intrinsic::x86_sse2_psrai_w:
12221   case Intrinsic::x86_sse2_psrai_d:
12222   case Intrinsic::x86_avx2_psrai_w:
12223   case Intrinsic::x86_avx2_psrai_d: {
12224     unsigned Opcode;
12225     switch (IntNo) {
12226     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12227     case Intrinsic::x86_sse2_pslli_w:
12228     case Intrinsic::x86_sse2_pslli_d:
12229     case Intrinsic::x86_sse2_pslli_q:
12230     case Intrinsic::x86_avx2_pslli_w:
12231     case Intrinsic::x86_avx2_pslli_d:
12232     case Intrinsic::x86_avx2_pslli_q:
12233       Opcode = X86ISD::VSHLI;
12234       break;
12235     case Intrinsic::x86_sse2_psrli_w:
12236     case Intrinsic::x86_sse2_psrli_d:
12237     case Intrinsic::x86_sse2_psrli_q:
12238     case Intrinsic::x86_avx2_psrli_w:
12239     case Intrinsic::x86_avx2_psrli_d:
12240     case Intrinsic::x86_avx2_psrli_q:
12241       Opcode = X86ISD::VSRLI;
12242       break;
12243     case Intrinsic::x86_sse2_psrai_w:
12244     case Intrinsic::x86_sse2_psrai_d:
12245     case Intrinsic::x86_avx2_psrai_w:
12246     case Intrinsic::x86_avx2_psrai_d:
12247       Opcode = X86ISD::VSRAI;
12248       break;
12249     }
12250     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12251                                Op.getOperand(1), Op.getOperand(2), DAG);
12252   }
12253
12254   case Intrinsic::x86_sse42_pcmpistria128:
12255   case Intrinsic::x86_sse42_pcmpestria128:
12256   case Intrinsic::x86_sse42_pcmpistric128:
12257   case Intrinsic::x86_sse42_pcmpestric128:
12258   case Intrinsic::x86_sse42_pcmpistrio128:
12259   case Intrinsic::x86_sse42_pcmpestrio128:
12260   case Intrinsic::x86_sse42_pcmpistris128:
12261   case Intrinsic::x86_sse42_pcmpestris128:
12262   case Intrinsic::x86_sse42_pcmpistriz128:
12263   case Intrinsic::x86_sse42_pcmpestriz128: {
12264     unsigned Opcode;
12265     unsigned X86CC;
12266     switch (IntNo) {
12267     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12268     case Intrinsic::x86_sse42_pcmpistria128:
12269       Opcode = X86ISD::PCMPISTRI;
12270       X86CC = X86::COND_A;
12271       break;
12272     case Intrinsic::x86_sse42_pcmpestria128:
12273       Opcode = X86ISD::PCMPESTRI;
12274       X86CC = X86::COND_A;
12275       break;
12276     case Intrinsic::x86_sse42_pcmpistric128:
12277       Opcode = X86ISD::PCMPISTRI;
12278       X86CC = X86::COND_B;
12279       break;
12280     case Intrinsic::x86_sse42_pcmpestric128:
12281       Opcode = X86ISD::PCMPESTRI;
12282       X86CC = X86::COND_B;
12283       break;
12284     case Intrinsic::x86_sse42_pcmpistrio128:
12285       Opcode = X86ISD::PCMPISTRI;
12286       X86CC = X86::COND_O;
12287       break;
12288     case Intrinsic::x86_sse42_pcmpestrio128:
12289       Opcode = X86ISD::PCMPESTRI;
12290       X86CC = X86::COND_O;
12291       break;
12292     case Intrinsic::x86_sse42_pcmpistris128:
12293       Opcode = X86ISD::PCMPISTRI;
12294       X86CC = X86::COND_S;
12295       break;
12296     case Intrinsic::x86_sse42_pcmpestris128:
12297       Opcode = X86ISD::PCMPESTRI;
12298       X86CC = X86::COND_S;
12299       break;
12300     case Intrinsic::x86_sse42_pcmpistriz128:
12301       Opcode = X86ISD::PCMPISTRI;
12302       X86CC = X86::COND_E;
12303       break;
12304     case Intrinsic::x86_sse42_pcmpestriz128:
12305       Opcode = X86ISD::PCMPESTRI;
12306       X86CC = X86::COND_E;
12307       break;
12308     }
12309     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12310     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12311     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12312     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12313                                 DAG.getConstant(X86CC, MVT::i8),
12314                                 SDValue(PCMP.getNode(), 1));
12315     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12316   }
12317
12318   case Intrinsic::x86_sse42_pcmpistri128:
12319   case Intrinsic::x86_sse42_pcmpestri128: {
12320     unsigned Opcode;
12321     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12322       Opcode = X86ISD::PCMPISTRI;
12323     else
12324       Opcode = X86ISD::PCMPESTRI;
12325
12326     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12327     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12328     return DAG.getNode(Opcode, dl, VTs, NewOps);
12329   }
12330   case Intrinsic::x86_fma_vfmadd_ps:
12331   case Intrinsic::x86_fma_vfmadd_pd:
12332   case Intrinsic::x86_fma_vfmsub_ps:
12333   case Intrinsic::x86_fma_vfmsub_pd:
12334   case Intrinsic::x86_fma_vfnmadd_ps:
12335   case Intrinsic::x86_fma_vfnmadd_pd:
12336   case Intrinsic::x86_fma_vfnmsub_ps:
12337   case Intrinsic::x86_fma_vfnmsub_pd:
12338   case Intrinsic::x86_fma_vfmaddsub_ps:
12339   case Intrinsic::x86_fma_vfmaddsub_pd:
12340   case Intrinsic::x86_fma_vfmsubadd_ps:
12341   case Intrinsic::x86_fma_vfmsubadd_pd:
12342   case Intrinsic::x86_fma_vfmadd_ps_256:
12343   case Intrinsic::x86_fma_vfmadd_pd_256:
12344   case Intrinsic::x86_fma_vfmsub_ps_256:
12345   case Intrinsic::x86_fma_vfmsub_pd_256:
12346   case Intrinsic::x86_fma_vfnmadd_ps_256:
12347   case Intrinsic::x86_fma_vfnmadd_pd_256:
12348   case Intrinsic::x86_fma_vfnmsub_ps_256:
12349   case Intrinsic::x86_fma_vfnmsub_pd_256:
12350   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12351   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12352   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12353   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12354   case Intrinsic::x86_fma_vfmadd_ps_512:
12355   case Intrinsic::x86_fma_vfmadd_pd_512:
12356   case Intrinsic::x86_fma_vfmsub_ps_512:
12357   case Intrinsic::x86_fma_vfmsub_pd_512:
12358   case Intrinsic::x86_fma_vfnmadd_ps_512:
12359   case Intrinsic::x86_fma_vfnmadd_pd_512:
12360   case Intrinsic::x86_fma_vfnmsub_ps_512:
12361   case Intrinsic::x86_fma_vfnmsub_pd_512:
12362   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12363   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12364   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12365   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12366     unsigned Opc;
12367     switch (IntNo) {
12368     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12369     case Intrinsic::x86_fma_vfmadd_ps:
12370     case Intrinsic::x86_fma_vfmadd_pd:
12371     case Intrinsic::x86_fma_vfmadd_ps_256:
12372     case Intrinsic::x86_fma_vfmadd_pd_256:
12373     case Intrinsic::x86_fma_vfmadd_ps_512:
12374     case Intrinsic::x86_fma_vfmadd_pd_512:
12375       Opc = X86ISD::FMADD;
12376       break;
12377     case Intrinsic::x86_fma_vfmsub_ps:
12378     case Intrinsic::x86_fma_vfmsub_pd:
12379     case Intrinsic::x86_fma_vfmsub_ps_256:
12380     case Intrinsic::x86_fma_vfmsub_pd_256:
12381     case Intrinsic::x86_fma_vfmsub_ps_512:
12382     case Intrinsic::x86_fma_vfmsub_pd_512:
12383       Opc = X86ISD::FMSUB;
12384       break;
12385     case Intrinsic::x86_fma_vfnmadd_ps:
12386     case Intrinsic::x86_fma_vfnmadd_pd:
12387     case Intrinsic::x86_fma_vfnmadd_ps_256:
12388     case Intrinsic::x86_fma_vfnmadd_pd_256:
12389     case Intrinsic::x86_fma_vfnmadd_ps_512:
12390     case Intrinsic::x86_fma_vfnmadd_pd_512:
12391       Opc = X86ISD::FNMADD;
12392       break;
12393     case Intrinsic::x86_fma_vfnmsub_ps:
12394     case Intrinsic::x86_fma_vfnmsub_pd:
12395     case Intrinsic::x86_fma_vfnmsub_ps_256:
12396     case Intrinsic::x86_fma_vfnmsub_pd_256:
12397     case Intrinsic::x86_fma_vfnmsub_ps_512:
12398     case Intrinsic::x86_fma_vfnmsub_pd_512:
12399       Opc = X86ISD::FNMSUB;
12400       break;
12401     case Intrinsic::x86_fma_vfmaddsub_ps:
12402     case Intrinsic::x86_fma_vfmaddsub_pd:
12403     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12404     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12405     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12406     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12407       Opc = X86ISD::FMADDSUB;
12408       break;
12409     case Intrinsic::x86_fma_vfmsubadd_ps:
12410     case Intrinsic::x86_fma_vfmsubadd_pd:
12411     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12412     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12413     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12414     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12415       Opc = X86ISD::FMSUBADD;
12416       break;
12417     }
12418
12419     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12420                        Op.getOperand(2), Op.getOperand(3));
12421   }
12422   }
12423 }
12424
12425 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12426                               SDValue Src, SDValue Mask, SDValue Base,
12427                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12428                               const X86Subtarget * Subtarget) {
12429   SDLoc dl(Op);
12430   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12431   assert(C && "Invalid scale type");
12432   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12433   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12434                              Index.getSimpleValueType().getVectorNumElements());
12435   SDValue MaskInReg;
12436   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12437   if (MaskC)
12438     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12439   else
12440     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12441   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12442   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12443   SDValue Segment = DAG.getRegister(0, MVT::i32);
12444   if (Src.getOpcode() == ISD::UNDEF)
12445     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12446   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12447   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12448   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12449   return DAG.getMergeValues(RetOps, dl);
12450 }
12451
12452 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12453                                SDValue Src, SDValue Mask, SDValue Base,
12454                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12455   SDLoc dl(Op);
12456   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12457   assert(C && "Invalid scale type");
12458   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12459   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12460   SDValue Segment = DAG.getRegister(0, MVT::i32);
12461   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12462                              Index.getSimpleValueType().getVectorNumElements());
12463   SDValue MaskInReg;
12464   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12465   if (MaskC)
12466     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12467   else
12468     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12469   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12470   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12471   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12472   return SDValue(Res, 1);
12473 }
12474
12475 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12476                                SDValue Mask, SDValue Base, SDValue Index,
12477                                SDValue ScaleOp, SDValue Chain) {
12478   SDLoc dl(Op);
12479   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12480   assert(C && "Invalid scale type");
12481   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12482   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12483   SDValue Segment = DAG.getRegister(0, MVT::i32);
12484   EVT MaskVT =
12485     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12486   SDValue MaskInReg;
12487   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12488   if (MaskC)
12489     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12490   else
12491     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12492   //SDVTList VTs = DAG.getVTList(MVT::Other);
12493   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12494   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12495   return SDValue(Res, 0);
12496 }
12497
12498 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12499 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12500 // also used to custom lower READCYCLECOUNTER nodes.
12501 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12502                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12503                               SmallVectorImpl<SDValue> &Results) {
12504   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12505   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12506   SDValue LO, HI;
12507
12508   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12509   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12510   // and the EAX register is loaded with the low-order 32 bits.
12511   if (Subtarget->is64Bit()) {
12512     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12513     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12514                             LO.getValue(2));
12515   } else {
12516     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12517     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12518                             LO.getValue(2));
12519   }
12520   SDValue Chain = HI.getValue(1);
12521
12522   if (Opcode == X86ISD::RDTSCP_DAG) {
12523     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12524
12525     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12526     // the ECX register. Add 'ecx' explicitly to the chain.
12527     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12528                                      HI.getValue(2));
12529     // Explicitly store the content of ECX at the location passed in input
12530     // to the 'rdtscp' intrinsic.
12531     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12532                          MachinePointerInfo(), false, false, 0);
12533   }
12534
12535   if (Subtarget->is64Bit()) {
12536     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12537     // the EAX register is loaded with the low-order 32 bits.
12538     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12539                               DAG.getConstant(32, MVT::i8));
12540     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12541     Results.push_back(Chain);
12542     return;
12543   }
12544
12545   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12546   SDValue Ops[] = { LO, HI };
12547   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12548   Results.push_back(Pair);
12549   Results.push_back(Chain);
12550 }
12551
12552 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12553                                      SelectionDAG &DAG) {
12554   SmallVector<SDValue, 2> Results;
12555   SDLoc DL(Op);
12556   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12557                           Results);
12558   return DAG.getMergeValues(Results, DL);
12559 }
12560
12561 enum IntrinsicType {
12562   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12563 };
12564
12565 struct IntrinsicData {
12566   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12567     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12568   IntrinsicType Type;
12569   unsigned      Opc0;
12570   unsigned      Opc1;
12571 };
12572
12573 std::map < unsigned, IntrinsicData> IntrMap;
12574 static void InitIntinsicsMap() {
12575   static bool Initialized = false;
12576   if (Initialized) 
12577     return;
12578   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12579                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12580   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12581                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12582   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12583                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12584   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12585                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12586   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12587                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12588   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12589                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12590   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12591                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12592   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12593                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12594   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12595                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12596
12597   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12598                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12599   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12600                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12601   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12602                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12603   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12604                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12605   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12606                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12607   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12608                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12609   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12610                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12611   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12612                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12613    
12614   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12615                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12616                                                         X86::VGATHERPF1QPSm)));
12617   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12618                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12619                                                         X86::VGATHERPF1QPDm)));
12620   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12621                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12622                                                         X86::VGATHERPF1DPDm)));
12623   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12624                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12625                                                         X86::VGATHERPF1DPSm)));
12626   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12627                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12628                                                         X86::VSCATTERPF1QPSm)));
12629   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12630                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12631                                                         X86::VSCATTERPF1QPDm)));
12632   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12633                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12634                                                         X86::VSCATTERPF1DPDm)));
12635   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12636                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12637                                                         X86::VSCATTERPF1DPSm)));
12638   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12639                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12640   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12641                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12642   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12643                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12644   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12645                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12646   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12647                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12648   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12649                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12650   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12651                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12652   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12653                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12654   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12655                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12656   Initialized = true;
12657 }
12658
12659 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12660                                       SelectionDAG &DAG) {
12661   InitIntinsicsMap();
12662   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12663   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12664   if (itr == IntrMap.end())
12665     return SDValue();
12666
12667   SDLoc dl(Op);
12668   IntrinsicData Intr = itr->second;
12669   switch(Intr.Type) {
12670   case RDSEED:
12671   case RDRAND: {
12672     // Emit the node with the right value type.
12673     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12674     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12675
12676     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12677     // Otherwise return the value from Rand, which is always 0, casted to i32.
12678     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12679                       DAG.getConstant(1, Op->getValueType(1)),
12680                       DAG.getConstant(X86::COND_B, MVT::i32),
12681                       SDValue(Result.getNode(), 1) };
12682     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12683                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12684                                   Ops);
12685
12686     // Return { result, isValid, chain }.
12687     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12688                        SDValue(Result.getNode(), 2));
12689   }
12690   case GATHER: {
12691   //gather(v1, mask, index, base, scale);
12692     SDValue Chain = Op.getOperand(0);
12693     SDValue Src   = Op.getOperand(2);
12694     SDValue Base  = Op.getOperand(3);
12695     SDValue Index = Op.getOperand(4);
12696     SDValue Mask  = Op.getOperand(5);
12697     SDValue Scale = Op.getOperand(6);
12698     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12699                           Subtarget);
12700   }
12701   case SCATTER: {
12702   //scatter(base, mask, index, v1, scale);
12703     SDValue Chain = Op.getOperand(0);
12704     SDValue Base  = Op.getOperand(2);
12705     SDValue Mask  = Op.getOperand(3);
12706     SDValue Index = Op.getOperand(4);
12707     SDValue Src   = Op.getOperand(5);
12708     SDValue Scale = Op.getOperand(6);
12709     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12710   }
12711   case PREFETCH: {
12712     SDValue Hint = Op.getOperand(6);
12713     unsigned HintVal;
12714     if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12715         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12716       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12717     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12718     SDValue Chain = Op.getOperand(0);
12719     SDValue Mask  = Op.getOperand(2);
12720     SDValue Index = Op.getOperand(3);
12721     SDValue Base  = Op.getOperand(4);
12722     SDValue Scale = Op.getOperand(5);
12723     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12724   }
12725   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12726   case RDTSC: {
12727     SmallVector<SDValue, 2> Results;
12728     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12729     return DAG.getMergeValues(Results, dl);
12730   }
12731   // XTEST intrinsics.
12732   case XTEST: {
12733     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12734     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12735     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12736                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12737                                 InTrans);
12738     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12739     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12740                        Ret, SDValue(InTrans.getNode(), 1));
12741   }
12742   }
12743   llvm_unreachable("Unknown Intrinsic Type");
12744 }
12745
12746 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12747                                            SelectionDAG &DAG) const {
12748   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12749   MFI->setReturnAddressIsTaken(true);
12750
12751   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12752     return SDValue();
12753
12754   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12755   SDLoc dl(Op);
12756   EVT PtrVT = getPointerTy();
12757
12758   if (Depth > 0) {
12759     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12760     const X86RegisterInfo *RegInfo =
12761       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12762     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12763     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12764                        DAG.getNode(ISD::ADD, dl, PtrVT,
12765                                    FrameAddr, Offset),
12766                        MachinePointerInfo(), false, false, false, 0);
12767   }
12768
12769   // Just load the return address.
12770   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12771   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12772                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12773 }
12774
12775 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12776   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12777   MFI->setFrameAddressIsTaken(true);
12778
12779   EVT VT = Op.getValueType();
12780   SDLoc dl(Op);  // FIXME probably not meaningful
12781   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12782   const X86RegisterInfo *RegInfo =
12783     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12784   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12785   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12786           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12787          "Invalid Frame Register!");
12788   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12789   while (Depth--)
12790     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12791                             MachinePointerInfo(),
12792                             false, false, false, 0);
12793   return FrameAddr;
12794 }
12795
12796 // FIXME? Maybe this could be a TableGen attribute on some registers and
12797 // this table could be generated automatically from RegInfo.
12798 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12799                                               EVT VT) const {
12800   unsigned Reg = StringSwitch<unsigned>(RegName)
12801                        .Case("esp", X86::ESP)
12802                        .Case("rsp", X86::RSP)
12803                        .Default(0);
12804   if (Reg)
12805     return Reg;
12806   report_fatal_error("Invalid register name global variable");
12807 }
12808
12809 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12810                                                      SelectionDAG &DAG) const {
12811   const X86RegisterInfo *RegInfo =
12812     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12813   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12814 }
12815
12816 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12817   SDValue Chain     = Op.getOperand(0);
12818   SDValue Offset    = Op.getOperand(1);
12819   SDValue Handler   = Op.getOperand(2);
12820   SDLoc dl      (Op);
12821
12822   EVT PtrVT = getPointerTy();
12823   const X86RegisterInfo *RegInfo =
12824     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12825   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12826   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12827           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12828          "Invalid Frame Register!");
12829   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12830   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12831
12832   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12833                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12834   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12835   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12836                        false, false, 0);
12837   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12838
12839   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12840                      DAG.getRegister(StoreAddrReg, PtrVT));
12841 }
12842
12843 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12844                                                SelectionDAG &DAG) const {
12845   SDLoc DL(Op);
12846   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12847                      DAG.getVTList(MVT::i32, MVT::Other),
12848                      Op.getOperand(0), Op.getOperand(1));
12849 }
12850
12851 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12852                                                 SelectionDAG &DAG) const {
12853   SDLoc DL(Op);
12854   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12855                      Op.getOperand(0), Op.getOperand(1));
12856 }
12857
12858 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12859   return Op.getOperand(0);
12860 }
12861
12862 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12863                                                 SelectionDAG &DAG) const {
12864   SDValue Root = Op.getOperand(0);
12865   SDValue Trmp = Op.getOperand(1); // trampoline
12866   SDValue FPtr = Op.getOperand(2); // nested function
12867   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12868   SDLoc dl (Op);
12869
12870   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12871   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12872
12873   if (Subtarget->is64Bit()) {
12874     SDValue OutChains[6];
12875
12876     // Large code-model.
12877     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12878     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12879
12880     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12881     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12882
12883     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12884
12885     // Load the pointer to the nested function into R11.
12886     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12887     SDValue Addr = Trmp;
12888     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12889                                 Addr, MachinePointerInfo(TrmpAddr),
12890                                 false, false, 0);
12891
12892     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12893                        DAG.getConstant(2, MVT::i64));
12894     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12895                                 MachinePointerInfo(TrmpAddr, 2),
12896                                 false, false, 2);
12897
12898     // Load the 'nest' parameter value into R10.
12899     // R10 is specified in X86CallingConv.td
12900     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12901     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12902                        DAG.getConstant(10, MVT::i64));
12903     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12904                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12905                                 false, false, 0);
12906
12907     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12908                        DAG.getConstant(12, MVT::i64));
12909     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12910                                 MachinePointerInfo(TrmpAddr, 12),
12911                                 false, false, 2);
12912
12913     // Jump to the nested function.
12914     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12915     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12916                        DAG.getConstant(20, MVT::i64));
12917     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12918                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12919                                 false, false, 0);
12920
12921     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12922     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12923                        DAG.getConstant(22, MVT::i64));
12924     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12925                                 MachinePointerInfo(TrmpAddr, 22),
12926                                 false, false, 0);
12927
12928     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12929   } else {
12930     const Function *Func =
12931       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12932     CallingConv::ID CC = Func->getCallingConv();
12933     unsigned NestReg;
12934
12935     switch (CC) {
12936     default:
12937       llvm_unreachable("Unsupported calling convention");
12938     case CallingConv::C:
12939     case CallingConv::X86_StdCall: {
12940       // Pass 'nest' parameter in ECX.
12941       // Must be kept in sync with X86CallingConv.td
12942       NestReg = X86::ECX;
12943
12944       // Check that ECX wasn't needed by an 'inreg' parameter.
12945       FunctionType *FTy = Func->getFunctionType();
12946       const AttributeSet &Attrs = Func->getAttributes();
12947
12948       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12949         unsigned InRegCount = 0;
12950         unsigned Idx = 1;
12951
12952         for (FunctionType::param_iterator I = FTy->param_begin(),
12953              E = FTy->param_end(); I != E; ++I, ++Idx)
12954           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12955             // FIXME: should only count parameters that are lowered to integers.
12956             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12957
12958         if (InRegCount > 2) {
12959           report_fatal_error("Nest register in use - reduce number of inreg"
12960                              " parameters!");
12961         }
12962       }
12963       break;
12964     }
12965     case CallingConv::X86_FastCall:
12966     case CallingConv::X86_ThisCall:
12967     case CallingConv::Fast:
12968       // Pass 'nest' parameter in EAX.
12969       // Must be kept in sync with X86CallingConv.td
12970       NestReg = X86::EAX;
12971       break;
12972     }
12973
12974     SDValue OutChains[4];
12975     SDValue Addr, Disp;
12976
12977     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12978                        DAG.getConstant(10, MVT::i32));
12979     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12980
12981     // This is storing the opcode for MOV32ri.
12982     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12983     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12984     OutChains[0] = DAG.getStore(Root, dl,
12985                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12986                                 Trmp, MachinePointerInfo(TrmpAddr),
12987                                 false, false, 0);
12988
12989     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12990                        DAG.getConstant(1, MVT::i32));
12991     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12992                                 MachinePointerInfo(TrmpAddr, 1),
12993                                 false, false, 1);
12994
12995     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12996     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12997                        DAG.getConstant(5, MVT::i32));
12998     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12999                                 MachinePointerInfo(TrmpAddr, 5),
13000                                 false, false, 1);
13001
13002     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13003                        DAG.getConstant(6, MVT::i32));
13004     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13005                                 MachinePointerInfo(TrmpAddr, 6),
13006                                 false, false, 1);
13007
13008     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13009   }
13010 }
13011
13012 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13013                                             SelectionDAG &DAG) const {
13014   /*
13015    The rounding mode is in bits 11:10 of FPSR, and has the following
13016    settings:
13017      00 Round to nearest
13018      01 Round to -inf
13019      10 Round to +inf
13020      11 Round to 0
13021
13022   FLT_ROUNDS, on the other hand, expects the following:
13023     -1 Undefined
13024      0 Round to 0
13025      1 Round to nearest
13026      2 Round to +inf
13027      3 Round to -inf
13028
13029   To perform the conversion, we do:
13030     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13031   */
13032
13033   MachineFunction &MF = DAG.getMachineFunction();
13034   const TargetMachine &TM = MF.getTarget();
13035   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13036   unsigned StackAlignment = TFI.getStackAlignment();
13037   MVT VT = Op.getSimpleValueType();
13038   SDLoc DL(Op);
13039
13040   // Save FP Control Word to stack slot
13041   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13042   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13043
13044   MachineMemOperand *MMO =
13045    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13046                            MachineMemOperand::MOStore, 2, 2);
13047
13048   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13049   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13050                                           DAG.getVTList(MVT::Other),
13051                                           Ops, MVT::i16, MMO);
13052
13053   // Load FP Control Word from stack slot
13054   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13055                             MachinePointerInfo(), false, false, false, 0);
13056
13057   // Transform as necessary
13058   SDValue CWD1 =
13059     DAG.getNode(ISD::SRL, DL, MVT::i16,
13060                 DAG.getNode(ISD::AND, DL, MVT::i16,
13061                             CWD, DAG.getConstant(0x800, MVT::i16)),
13062                 DAG.getConstant(11, MVT::i8));
13063   SDValue CWD2 =
13064     DAG.getNode(ISD::SRL, DL, MVT::i16,
13065                 DAG.getNode(ISD::AND, DL, MVT::i16,
13066                             CWD, DAG.getConstant(0x400, MVT::i16)),
13067                 DAG.getConstant(9, MVT::i8));
13068
13069   SDValue RetVal =
13070     DAG.getNode(ISD::AND, DL, MVT::i16,
13071                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13072                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13073                             DAG.getConstant(1, MVT::i16)),
13074                 DAG.getConstant(3, MVT::i16));
13075
13076   return DAG.getNode((VT.getSizeInBits() < 16 ?
13077                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13078 }
13079
13080 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13081   MVT VT = Op.getSimpleValueType();
13082   EVT OpVT = VT;
13083   unsigned NumBits = VT.getSizeInBits();
13084   SDLoc dl(Op);
13085
13086   Op = Op.getOperand(0);
13087   if (VT == MVT::i8) {
13088     // Zero extend to i32 since there is not an i8 bsr.
13089     OpVT = MVT::i32;
13090     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13091   }
13092
13093   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13094   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13095   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13096
13097   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13098   SDValue Ops[] = {
13099     Op,
13100     DAG.getConstant(NumBits+NumBits-1, OpVT),
13101     DAG.getConstant(X86::COND_E, MVT::i8),
13102     Op.getValue(1)
13103   };
13104   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13105
13106   // Finally xor with NumBits-1.
13107   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13108
13109   if (VT == MVT::i8)
13110     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13111   return Op;
13112 }
13113
13114 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13115   MVT VT = Op.getSimpleValueType();
13116   EVT OpVT = VT;
13117   unsigned NumBits = VT.getSizeInBits();
13118   SDLoc dl(Op);
13119
13120   Op = Op.getOperand(0);
13121   if (VT == MVT::i8) {
13122     // Zero extend to i32 since there is not an i8 bsr.
13123     OpVT = MVT::i32;
13124     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13125   }
13126
13127   // Issue a bsr (scan bits in reverse).
13128   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13129   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13130
13131   // And xor with NumBits-1.
13132   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13133
13134   if (VT == MVT::i8)
13135     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13136   return Op;
13137 }
13138
13139 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13140   MVT VT = Op.getSimpleValueType();
13141   unsigned NumBits = VT.getSizeInBits();
13142   SDLoc dl(Op);
13143   Op = Op.getOperand(0);
13144
13145   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13146   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13147   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13148
13149   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13150   SDValue Ops[] = {
13151     Op,
13152     DAG.getConstant(NumBits, VT),
13153     DAG.getConstant(X86::COND_E, MVT::i8),
13154     Op.getValue(1)
13155   };
13156   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13157 }
13158
13159 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13160 // ones, and then concatenate the result back.
13161 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13162   MVT VT = Op.getSimpleValueType();
13163
13164   assert(VT.is256BitVector() && VT.isInteger() &&
13165          "Unsupported value type for operation");
13166
13167   unsigned NumElems = VT.getVectorNumElements();
13168   SDLoc dl(Op);
13169
13170   // Extract the LHS vectors
13171   SDValue LHS = Op.getOperand(0);
13172   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13173   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13174
13175   // Extract the RHS vectors
13176   SDValue RHS = Op.getOperand(1);
13177   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13178   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13179
13180   MVT EltVT = VT.getVectorElementType();
13181   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13182
13183   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13184                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13185                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13186 }
13187
13188 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13189   assert(Op.getSimpleValueType().is256BitVector() &&
13190          Op.getSimpleValueType().isInteger() &&
13191          "Only handle AVX 256-bit vector integer operation");
13192   return Lower256IntArith(Op, DAG);
13193 }
13194
13195 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13196   assert(Op.getSimpleValueType().is256BitVector() &&
13197          Op.getSimpleValueType().isInteger() &&
13198          "Only handle AVX 256-bit vector integer operation");
13199   return Lower256IntArith(Op, DAG);
13200 }
13201
13202 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13203                         SelectionDAG &DAG) {
13204   SDLoc dl(Op);
13205   MVT VT = Op.getSimpleValueType();
13206
13207   // Decompose 256-bit ops into smaller 128-bit ops.
13208   if (VT.is256BitVector() && !Subtarget->hasInt256())
13209     return Lower256IntArith(Op, DAG);
13210
13211   SDValue A = Op.getOperand(0);
13212   SDValue B = Op.getOperand(1);
13213
13214   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13215   if (VT == MVT::v4i32) {
13216     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13217            "Should not custom lower when pmuldq is available!");
13218
13219     // Extract the odd parts.
13220     static const int UnpackMask[] = { 1, -1, 3, -1 };
13221     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13222     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13223
13224     // Multiply the even parts.
13225     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13226     // Now multiply odd parts.
13227     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13228
13229     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13230     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13231
13232     // Merge the two vectors back together with a shuffle. This expands into 2
13233     // shuffles.
13234     static const int ShufMask[] = { 0, 4, 2, 6 };
13235     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13236   }
13237
13238   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13239          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13240
13241   //  Ahi = psrlqi(a, 32);
13242   //  Bhi = psrlqi(b, 32);
13243   //
13244   //  AloBlo = pmuludq(a, b);
13245   //  AloBhi = pmuludq(a, Bhi);
13246   //  AhiBlo = pmuludq(Ahi, b);
13247
13248   //  AloBhi = psllqi(AloBhi, 32);
13249   //  AhiBlo = psllqi(AhiBlo, 32);
13250   //  return AloBlo + AloBhi + AhiBlo;
13251
13252   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13253   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13254
13255   // Bit cast to 32-bit vectors for MULUDQ
13256   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13257                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13258   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13259   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13260   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13261   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13262
13263   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13264   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13265   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13266
13267   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13268   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13269
13270   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13271   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13272 }
13273
13274 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13275   assert(Subtarget->isTargetWin64() && "Unexpected target");
13276   EVT VT = Op.getValueType();
13277   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13278          "Unexpected return type for lowering");
13279
13280   RTLIB::Libcall LC;
13281   bool isSigned;
13282   switch (Op->getOpcode()) {
13283   default: llvm_unreachable("Unexpected request for libcall!");
13284   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13285   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13286   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13287   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13288   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13289   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13290   }
13291
13292   SDLoc dl(Op);
13293   SDValue InChain = DAG.getEntryNode();
13294
13295   TargetLowering::ArgListTy Args;
13296   TargetLowering::ArgListEntry Entry;
13297   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13298     EVT ArgVT = Op->getOperand(i).getValueType();
13299     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13300            "Unexpected argument type for lowering");
13301     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13302     Entry.Node = StackPtr;
13303     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13304                            false, false, 16);
13305     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13306     Entry.Ty = PointerType::get(ArgTy,0);
13307     Entry.isSExt = false;
13308     Entry.isZExt = false;
13309     Args.push_back(Entry);
13310   }
13311
13312   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13313                                          getPointerTy());
13314
13315   TargetLowering::CallLoweringInfo CLI(
13316       InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13317       isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13318       /*isTailCall=*/false,
13319       /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13320       dl);
13321   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13322
13323   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13324 }
13325
13326 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13327                              SelectionDAG &DAG) {
13328   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13329   EVT VT = Op0.getValueType();
13330   SDLoc dl(Op);
13331
13332   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13333          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13334
13335   // Get the high parts.
13336   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13337   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13338   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13339
13340   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13341   // ints.
13342   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13343   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13344   unsigned Opcode =
13345       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13346   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13347                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13348   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13349                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13350
13351   // Shuffle it back into the right order.
13352   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13353   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13354   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13355   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13356
13357   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13358   // unsigned multiply.
13359   if (IsSigned && !Subtarget->hasSSE41()) {
13360     SDValue ShAmt =
13361         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13362     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13363                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13364     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13365                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13366
13367     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13368     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13369   }
13370
13371   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13372 }
13373
13374 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13375                                          const X86Subtarget *Subtarget) {
13376   MVT VT = Op.getSimpleValueType();
13377   SDLoc dl(Op);
13378   SDValue R = Op.getOperand(0);
13379   SDValue Amt = Op.getOperand(1);
13380
13381   // Optimize shl/srl/sra with constant shift amount.
13382   if (isSplatVector(Amt.getNode())) {
13383     SDValue SclrAmt = Amt->getOperand(0);
13384     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13385       uint64_t ShiftAmt = C->getZExtValue();
13386
13387       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13388           (Subtarget->hasInt256() &&
13389            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13390           (Subtarget->hasAVX512() &&
13391            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13392         if (Op.getOpcode() == ISD::SHL)
13393           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13394                                             DAG);
13395         if (Op.getOpcode() == ISD::SRL)
13396           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13397                                             DAG);
13398         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13399           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13400                                             DAG);
13401       }
13402
13403       if (VT == MVT::v16i8) {
13404         if (Op.getOpcode() == ISD::SHL) {
13405           // Make a large shift.
13406           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13407                                                    MVT::v8i16, R, ShiftAmt,
13408                                                    DAG);
13409           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13410           // Zero out the rightmost bits.
13411           SmallVector<SDValue, 16> V(16,
13412                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13413                                                      MVT::i8));
13414           return DAG.getNode(ISD::AND, dl, VT, SHL,
13415                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13416         }
13417         if (Op.getOpcode() == ISD::SRL) {
13418           // Make a large shift.
13419           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13420                                                    MVT::v8i16, R, ShiftAmt,
13421                                                    DAG);
13422           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13423           // Zero out the leftmost bits.
13424           SmallVector<SDValue, 16> V(16,
13425                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13426                                                      MVT::i8));
13427           return DAG.getNode(ISD::AND, dl, VT, SRL,
13428                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13429         }
13430         if (Op.getOpcode() == ISD::SRA) {
13431           if (ShiftAmt == 7) {
13432             // R s>> 7  ===  R s< 0
13433             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13434             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13435           }
13436
13437           // R s>> a === ((R u>> a) ^ m) - m
13438           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13439           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13440                                                          MVT::i8));
13441           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13442           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13443           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13444           return Res;
13445         }
13446         llvm_unreachable("Unknown shift opcode.");
13447       }
13448
13449       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13450         if (Op.getOpcode() == ISD::SHL) {
13451           // Make a large shift.
13452           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13453                                                    MVT::v16i16, R, ShiftAmt,
13454                                                    DAG);
13455           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13456           // Zero out the rightmost bits.
13457           SmallVector<SDValue, 32> V(32,
13458                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13459                                                      MVT::i8));
13460           return DAG.getNode(ISD::AND, dl, VT, SHL,
13461                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13462         }
13463         if (Op.getOpcode() == ISD::SRL) {
13464           // Make a large shift.
13465           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13466                                                    MVT::v16i16, R, ShiftAmt,
13467                                                    DAG);
13468           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13469           // Zero out the leftmost bits.
13470           SmallVector<SDValue, 32> V(32,
13471                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13472                                                      MVT::i8));
13473           return DAG.getNode(ISD::AND, dl, VT, SRL,
13474                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13475         }
13476         if (Op.getOpcode() == ISD::SRA) {
13477           if (ShiftAmt == 7) {
13478             // R s>> 7  ===  R s< 0
13479             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13480             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13481           }
13482
13483           // R s>> a === ((R u>> a) ^ m) - m
13484           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13485           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13486                                                          MVT::i8));
13487           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13488           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13489           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13490           return Res;
13491         }
13492         llvm_unreachable("Unknown shift opcode.");
13493       }
13494     }
13495   }
13496
13497   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13498   if (!Subtarget->is64Bit() &&
13499       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13500       Amt.getOpcode() == ISD::BITCAST &&
13501       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13502     Amt = Amt.getOperand(0);
13503     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13504                      VT.getVectorNumElements();
13505     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13506     uint64_t ShiftAmt = 0;
13507     for (unsigned i = 0; i != Ratio; ++i) {
13508       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13509       if (!C)
13510         return SDValue();
13511       // 6 == Log2(64)
13512       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13513     }
13514     // Check remaining shift amounts.
13515     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13516       uint64_t ShAmt = 0;
13517       for (unsigned j = 0; j != Ratio; ++j) {
13518         ConstantSDNode *C =
13519           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13520         if (!C)
13521           return SDValue();
13522         // 6 == Log2(64)
13523         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13524       }
13525       if (ShAmt != ShiftAmt)
13526         return SDValue();
13527     }
13528     switch (Op.getOpcode()) {
13529     default:
13530       llvm_unreachable("Unknown shift opcode!");
13531     case ISD::SHL:
13532       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13533                                         DAG);
13534     case ISD::SRL:
13535       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13536                                         DAG);
13537     case ISD::SRA:
13538       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13539                                         DAG);
13540     }
13541   }
13542
13543   return SDValue();
13544 }
13545
13546 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13547                                         const X86Subtarget* Subtarget) {
13548   MVT VT = Op.getSimpleValueType();
13549   SDLoc dl(Op);
13550   SDValue R = Op.getOperand(0);
13551   SDValue Amt = Op.getOperand(1);
13552
13553   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13554       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13555       (Subtarget->hasInt256() &&
13556        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13557         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13558        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13559     SDValue BaseShAmt;
13560     EVT EltVT = VT.getVectorElementType();
13561
13562     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13563       unsigned NumElts = VT.getVectorNumElements();
13564       unsigned i, j;
13565       for (i = 0; i != NumElts; ++i) {
13566         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13567           continue;
13568         break;
13569       }
13570       for (j = i; j != NumElts; ++j) {
13571         SDValue Arg = Amt.getOperand(j);
13572         if (Arg.getOpcode() == ISD::UNDEF) continue;
13573         if (Arg != Amt.getOperand(i))
13574           break;
13575       }
13576       if (i != NumElts && j == NumElts)
13577         BaseShAmt = Amt.getOperand(i);
13578     } else {
13579       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13580         Amt = Amt.getOperand(0);
13581       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13582                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13583         SDValue InVec = Amt.getOperand(0);
13584         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13585           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13586           unsigned i = 0;
13587           for (; i != NumElts; ++i) {
13588             SDValue Arg = InVec.getOperand(i);
13589             if (Arg.getOpcode() == ISD::UNDEF) continue;
13590             BaseShAmt = Arg;
13591             break;
13592           }
13593         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13594            if (ConstantSDNode *C =
13595                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13596              unsigned SplatIdx =
13597                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13598              if (C->getZExtValue() == SplatIdx)
13599                BaseShAmt = InVec.getOperand(1);
13600            }
13601         }
13602         if (!BaseShAmt.getNode())
13603           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13604                                   DAG.getIntPtrConstant(0));
13605       }
13606     }
13607
13608     if (BaseShAmt.getNode()) {
13609       if (EltVT.bitsGT(MVT::i32))
13610         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13611       else if (EltVT.bitsLT(MVT::i32))
13612         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13613
13614       switch (Op.getOpcode()) {
13615       default:
13616         llvm_unreachable("Unknown shift opcode!");
13617       case ISD::SHL:
13618         switch (VT.SimpleTy) {
13619         default: return SDValue();
13620         case MVT::v2i64:
13621         case MVT::v4i32:
13622         case MVT::v8i16:
13623         case MVT::v4i64:
13624         case MVT::v8i32:
13625         case MVT::v16i16:
13626         case MVT::v16i32:
13627         case MVT::v8i64:
13628           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13629         }
13630       case ISD::SRA:
13631         switch (VT.SimpleTy) {
13632         default: return SDValue();
13633         case MVT::v4i32:
13634         case MVT::v8i16:
13635         case MVT::v8i32:
13636         case MVT::v16i16:
13637         case MVT::v16i32:
13638         case MVT::v8i64:
13639           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13640         }
13641       case ISD::SRL:
13642         switch (VT.SimpleTy) {
13643         default: return SDValue();
13644         case MVT::v2i64:
13645         case MVT::v4i32:
13646         case MVT::v8i16:
13647         case MVT::v4i64:
13648         case MVT::v8i32:
13649         case MVT::v16i16:
13650         case MVT::v16i32:
13651         case MVT::v8i64:
13652           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13653         }
13654       }
13655     }
13656   }
13657
13658   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13659   if (!Subtarget->is64Bit() &&
13660       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13661       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13662       Amt.getOpcode() == ISD::BITCAST &&
13663       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13664     Amt = Amt.getOperand(0);
13665     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13666                      VT.getVectorNumElements();
13667     std::vector<SDValue> Vals(Ratio);
13668     for (unsigned i = 0; i != Ratio; ++i)
13669       Vals[i] = Amt.getOperand(i);
13670     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13671       for (unsigned j = 0; j != Ratio; ++j)
13672         if (Vals[j] != Amt.getOperand(i + j))
13673           return SDValue();
13674     }
13675     switch (Op.getOpcode()) {
13676     default:
13677       llvm_unreachable("Unknown shift opcode!");
13678     case ISD::SHL:
13679       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13680     case ISD::SRL:
13681       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13682     case ISD::SRA:
13683       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13684     }
13685   }
13686
13687   return SDValue();
13688 }
13689
13690 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13691                           SelectionDAG &DAG) {
13692
13693   MVT VT = Op.getSimpleValueType();
13694   SDLoc dl(Op);
13695   SDValue R = Op.getOperand(0);
13696   SDValue Amt = Op.getOperand(1);
13697   SDValue V;
13698
13699   if (!Subtarget->hasSSE2())
13700     return SDValue();
13701
13702   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13703   if (V.getNode())
13704     return V;
13705
13706   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13707   if (V.getNode())
13708       return V;
13709
13710   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13711     return Op;
13712   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13713   if (Subtarget->hasInt256()) {
13714     if (Op.getOpcode() == ISD::SRL &&
13715         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13716          VT == MVT::v4i64 || VT == MVT::v8i32))
13717       return Op;
13718     if (Op.getOpcode() == ISD::SHL &&
13719         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13720          VT == MVT::v4i64 || VT == MVT::v8i32))
13721       return Op;
13722     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13723       return Op;
13724   }
13725
13726   // If possible, lower this packed shift into a vector multiply instead of
13727   // expanding it into a sequence of scalar shifts.
13728   // Do this only if the vector shift count is a constant build_vector.
13729   if (Op.getOpcode() == ISD::SHL && 
13730       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13731        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13732       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13733     SmallVector<SDValue, 8> Elts;
13734     EVT SVT = VT.getScalarType();
13735     unsigned SVTBits = SVT.getSizeInBits();
13736     const APInt &One = APInt(SVTBits, 1);
13737     unsigned NumElems = VT.getVectorNumElements();
13738
13739     for (unsigned i=0; i !=NumElems; ++i) {
13740       SDValue Op = Amt->getOperand(i);
13741       if (Op->getOpcode() == ISD::UNDEF) {
13742         Elts.push_back(Op);
13743         continue;
13744       }
13745
13746       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13747       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13748       uint64_t ShAmt = C.getZExtValue();
13749       if (ShAmt >= SVTBits) {
13750         Elts.push_back(DAG.getUNDEF(SVT));
13751         continue;
13752       }
13753       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13754     }
13755     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13756     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13757   }
13758
13759   // Lower SHL with variable shift amount.
13760   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13761     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13762
13763     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13764     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13765     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13766     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13767   }
13768
13769   // If possible, lower this shift as a sequence of two shifts by
13770   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13771   // Example:
13772   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13773   //
13774   // Could be rewritten as:
13775   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13776   //
13777   // The advantage is that the two shifts from the example would be
13778   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13779   // the vector shift into four scalar shifts plus four pairs of vector
13780   // insert/extract.
13781   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13782       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13783     unsigned TargetOpcode = X86ISD::MOVSS;
13784     bool CanBeSimplified;
13785     // The splat value for the first packed shift (the 'X' from the example).
13786     SDValue Amt1 = Amt->getOperand(0);
13787     // The splat value for the second packed shift (the 'Y' from the example).
13788     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13789                                         Amt->getOperand(2);
13790
13791     // See if it is possible to replace this node with a sequence of
13792     // two shifts followed by a MOVSS/MOVSD
13793     if (VT == MVT::v4i32) {
13794       // Check if it is legal to use a MOVSS.
13795       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13796                         Amt2 == Amt->getOperand(3);
13797       if (!CanBeSimplified) {
13798         // Otherwise, check if we can still simplify this node using a MOVSD.
13799         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13800                           Amt->getOperand(2) == Amt->getOperand(3);
13801         TargetOpcode = X86ISD::MOVSD;
13802         Amt2 = Amt->getOperand(2);
13803       }
13804     } else {
13805       // Do similar checks for the case where the machine value type
13806       // is MVT::v8i16.
13807       CanBeSimplified = Amt1 == Amt->getOperand(1);
13808       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13809         CanBeSimplified = Amt2 == Amt->getOperand(i);
13810
13811       if (!CanBeSimplified) {
13812         TargetOpcode = X86ISD::MOVSD;
13813         CanBeSimplified = true;
13814         Amt2 = Amt->getOperand(4);
13815         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13816           CanBeSimplified = Amt1 == Amt->getOperand(i);
13817         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13818           CanBeSimplified = Amt2 == Amt->getOperand(j);
13819       }
13820     }
13821     
13822     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13823         isa<ConstantSDNode>(Amt2)) {
13824       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13825       EVT CastVT = MVT::v4i32;
13826       SDValue Splat1 = 
13827         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13828       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13829       SDValue Splat2 = 
13830         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13831       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13832       if (TargetOpcode == X86ISD::MOVSD)
13833         CastVT = MVT::v2i64;
13834       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13835       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13836       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13837                                             BitCast1, DAG);
13838       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13839     }
13840   }
13841
13842   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13843     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13844
13845     // a = a << 5;
13846     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13847     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13848
13849     // Turn 'a' into a mask suitable for VSELECT
13850     SDValue VSelM = DAG.getConstant(0x80, VT);
13851     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13852     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13853
13854     SDValue CM1 = DAG.getConstant(0x0f, VT);
13855     SDValue CM2 = DAG.getConstant(0x3f, VT);
13856
13857     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13858     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13859     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13860     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13861     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13862
13863     // a += a
13864     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13865     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13866     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13867
13868     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13869     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13870     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13871     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13872     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13873
13874     // a += a
13875     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13876     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13877     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13878
13879     // return VSELECT(r, r+r, a);
13880     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13881                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13882     return R;
13883   }
13884
13885   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13886   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13887   // solution better.
13888   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13889     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13890     unsigned ExtOpc =
13891         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13892     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13893     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13894     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13895                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13896     }
13897
13898   // Decompose 256-bit shifts into smaller 128-bit shifts.
13899   if (VT.is256BitVector()) {
13900     unsigned NumElems = VT.getVectorNumElements();
13901     MVT EltVT = VT.getVectorElementType();
13902     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13903
13904     // Extract the two vectors
13905     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13906     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13907
13908     // Recreate the shift amount vectors
13909     SDValue Amt1, Amt2;
13910     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13911       // Constant shift amount
13912       SmallVector<SDValue, 4> Amt1Csts;
13913       SmallVector<SDValue, 4> Amt2Csts;
13914       for (unsigned i = 0; i != NumElems/2; ++i)
13915         Amt1Csts.push_back(Amt->getOperand(i));
13916       for (unsigned i = NumElems/2; i != NumElems; ++i)
13917         Amt2Csts.push_back(Amt->getOperand(i));
13918
13919       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13920       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13921     } else {
13922       // Variable shift amount
13923       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13924       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13925     }
13926
13927     // Issue new vector shifts for the smaller types
13928     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13929     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13930
13931     // Concatenate the result back
13932     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13933   }
13934
13935   return SDValue();
13936 }
13937
13938 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13939   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13940   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13941   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13942   // has only one use.
13943   SDNode *N = Op.getNode();
13944   SDValue LHS = N->getOperand(0);
13945   SDValue RHS = N->getOperand(1);
13946   unsigned BaseOp = 0;
13947   unsigned Cond = 0;
13948   SDLoc DL(Op);
13949   switch (Op.getOpcode()) {
13950   default: llvm_unreachable("Unknown ovf instruction!");
13951   case ISD::SADDO:
13952     // A subtract of one will be selected as a INC. Note that INC doesn't
13953     // set CF, so we can't do this for UADDO.
13954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13955       if (C->isOne()) {
13956         BaseOp = X86ISD::INC;
13957         Cond = X86::COND_O;
13958         break;
13959       }
13960     BaseOp = X86ISD::ADD;
13961     Cond = X86::COND_O;
13962     break;
13963   case ISD::UADDO:
13964     BaseOp = X86ISD::ADD;
13965     Cond = X86::COND_B;
13966     break;
13967   case ISD::SSUBO:
13968     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13969     // set CF, so we can't do this for USUBO.
13970     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13971       if (C->isOne()) {
13972         BaseOp = X86ISD::DEC;
13973         Cond = X86::COND_O;
13974         break;
13975       }
13976     BaseOp = X86ISD::SUB;
13977     Cond = X86::COND_O;
13978     break;
13979   case ISD::USUBO:
13980     BaseOp = X86ISD::SUB;
13981     Cond = X86::COND_B;
13982     break;
13983   case ISD::SMULO:
13984     BaseOp = X86ISD::SMUL;
13985     Cond = X86::COND_O;
13986     break;
13987   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13988     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13989                                  MVT::i32);
13990     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13991
13992     SDValue SetCC =
13993       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13994                   DAG.getConstant(X86::COND_O, MVT::i32),
13995                   SDValue(Sum.getNode(), 2));
13996
13997     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13998   }
13999   }
14000
14001   // Also sets EFLAGS.
14002   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14003   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14004
14005   SDValue SetCC =
14006     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14007                 DAG.getConstant(Cond, MVT::i32),
14008                 SDValue(Sum.getNode(), 1));
14009
14010   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14011 }
14012
14013 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14014                                                   SelectionDAG &DAG) const {
14015   SDLoc dl(Op);
14016   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14017   MVT VT = Op.getSimpleValueType();
14018
14019   if (!Subtarget->hasSSE2() || !VT.isVector())
14020     return SDValue();
14021
14022   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14023                       ExtraVT.getScalarType().getSizeInBits();
14024
14025   switch (VT.SimpleTy) {
14026     default: return SDValue();
14027     case MVT::v8i32:
14028     case MVT::v16i16:
14029       if (!Subtarget->hasFp256())
14030         return SDValue();
14031       if (!Subtarget->hasInt256()) {
14032         // needs to be split
14033         unsigned NumElems = VT.getVectorNumElements();
14034
14035         // Extract the LHS vectors
14036         SDValue LHS = Op.getOperand(0);
14037         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14038         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14039
14040         MVT EltVT = VT.getVectorElementType();
14041         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14042
14043         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14044         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14045         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14046                                    ExtraNumElems/2);
14047         SDValue Extra = DAG.getValueType(ExtraVT);
14048
14049         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14050         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14051
14052         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14053       }
14054       // fall through
14055     case MVT::v4i32:
14056     case MVT::v8i16: {
14057       SDValue Op0 = Op.getOperand(0);
14058       SDValue Op00 = Op0.getOperand(0);
14059       SDValue Tmp1;
14060       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14061       if (Op0.getOpcode() == ISD::BITCAST &&
14062           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14063         // (sext (vzext x)) -> (vsext x)
14064         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14065         if (Tmp1.getNode()) {
14066           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14067           // This folding is only valid when the in-reg type is a vector of i8,
14068           // i16, or i32.
14069           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14070               ExtraEltVT == MVT::i32) {
14071             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14072             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14073                    "This optimization is invalid without a VZEXT.");
14074             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14075           }
14076           Op0 = Tmp1;
14077         }
14078       }
14079
14080       // If the above didn't work, then just use Shift-Left + Shift-Right.
14081       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14082                                         DAG);
14083       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14084                                         DAG);
14085     }
14086   }
14087 }
14088
14089 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14090                                  SelectionDAG &DAG) {
14091   SDLoc dl(Op);
14092   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14093     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14094   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14095     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14096
14097   // The only fence that needs an instruction is a sequentially-consistent
14098   // cross-thread fence.
14099   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14100     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14101     // no-sse2). There isn't any reason to disable it if the target processor
14102     // supports it.
14103     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14104       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14105
14106     SDValue Chain = Op.getOperand(0);
14107     SDValue Zero = DAG.getConstant(0, MVT::i32);
14108     SDValue Ops[] = {
14109       DAG.getRegister(X86::ESP, MVT::i32), // Base
14110       DAG.getTargetConstant(1, MVT::i8),   // Scale
14111       DAG.getRegister(0, MVT::i32),        // Index
14112       DAG.getTargetConstant(0, MVT::i32),  // Disp
14113       DAG.getRegister(0, MVT::i32),        // Segment.
14114       Zero,
14115       Chain
14116     };
14117     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14118     return SDValue(Res, 0);
14119   }
14120
14121   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14122   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14123 }
14124
14125 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14126                              SelectionDAG &DAG) {
14127   MVT T = Op.getSimpleValueType();
14128   SDLoc DL(Op);
14129   unsigned Reg = 0;
14130   unsigned size = 0;
14131   switch(T.SimpleTy) {
14132   default: llvm_unreachable("Invalid value type!");
14133   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14134   case MVT::i16: Reg = X86::AX;  size = 2; break;
14135   case MVT::i32: Reg = X86::EAX; size = 4; break;
14136   case MVT::i64:
14137     assert(Subtarget->is64Bit() && "Node not type legal!");
14138     Reg = X86::RAX; size = 8;
14139     break;
14140   }
14141   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14142                                     Op.getOperand(2), SDValue());
14143   SDValue Ops[] = { cpIn.getValue(0),
14144                     Op.getOperand(1),
14145                     Op.getOperand(3),
14146                     DAG.getTargetConstant(size, MVT::i8),
14147                     cpIn.getValue(1) };
14148   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14149   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14150   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14151                                            Ops, T, MMO);
14152   SDValue cpOut =
14153     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14154   return cpOut;
14155 }
14156
14157 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14158                             SelectionDAG &DAG) {
14159   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14160   MVT DstVT = Op.getSimpleValueType();
14161
14162   if (SrcVT == MVT::v2i32) {
14163     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14164     if (DstVT != MVT::f64)
14165       // This conversion needs to be expanded.
14166       return SDValue();
14167
14168     SDLoc dl(Op);
14169     SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14170                                Op->getOperand(0), DAG.getIntPtrConstant(0));
14171     SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14172                                Op->getOperand(0), DAG.getIntPtrConstant(1));
14173     SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14174     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14175     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14176     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14177                        DAG.getIntPtrConstant(0));
14178   }
14179
14180   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14181          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14182   assert((DstVT == MVT::i64 ||
14183           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14184          "Unexpected custom BITCAST");
14185   // i64 <=> MMX conversions are Legal.
14186   if (SrcVT==MVT::i64 && DstVT.isVector())
14187     return Op;
14188   if (DstVT==MVT::i64 && SrcVT.isVector())
14189     return Op;
14190   // MMX <=> MMX conversions are Legal.
14191   if (SrcVT.isVector() && DstVT.isVector())
14192     return Op;
14193   // All other conversions need to be expanded.
14194   return SDValue();
14195 }
14196
14197 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14198   SDNode *Node = Op.getNode();
14199   SDLoc dl(Node);
14200   EVT T = Node->getValueType(0);
14201   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14202                               DAG.getConstant(0, T), Node->getOperand(2));
14203   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14204                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14205                        Node->getOperand(0),
14206                        Node->getOperand(1), negOp,
14207                        cast<AtomicSDNode>(Node)->getMemOperand(),
14208                        cast<AtomicSDNode>(Node)->getOrdering(),
14209                        cast<AtomicSDNode>(Node)->getSynchScope());
14210 }
14211
14212 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14213   SDNode *Node = Op.getNode();
14214   SDLoc dl(Node);
14215   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14216
14217   // Convert seq_cst store -> xchg
14218   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14219   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14220   //        (The only way to get a 16-byte store is cmpxchg16b)
14221   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14222   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14223       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14224     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14225                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14226                                  Node->getOperand(0),
14227                                  Node->getOperand(1), Node->getOperand(2),
14228                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14229                                  cast<AtomicSDNode>(Node)->getOrdering(),
14230                                  cast<AtomicSDNode>(Node)->getSynchScope());
14231     return Swap.getValue(1);
14232   }
14233   // Other atomic stores have a simple pattern.
14234   return Op;
14235 }
14236
14237 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14238   EVT VT = Op.getNode()->getSimpleValueType(0);
14239
14240   // Let legalize expand this if it isn't a legal type yet.
14241   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14242     return SDValue();
14243
14244   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14245
14246   unsigned Opc;
14247   bool ExtraOp = false;
14248   switch (Op.getOpcode()) {
14249   default: llvm_unreachable("Invalid code");
14250   case ISD::ADDC: Opc = X86ISD::ADD; break;
14251   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14252   case ISD::SUBC: Opc = X86ISD::SUB; break;
14253   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14254   }
14255
14256   if (!ExtraOp)
14257     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14258                        Op.getOperand(1));
14259   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14260                      Op.getOperand(1), Op.getOperand(2));
14261 }
14262
14263 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14264                             SelectionDAG &DAG) {
14265   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14266
14267   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14268   // which returns the values as { float, float } (in XMM0) or
14269   // { double, double } (which is returned in XMM0, XMM1).
14270   SDLoc dl(Op);
14271   SDValue Arg = Op.getOperand(0);
14272   EVT ArgVT = Arg.getValueType();
14273   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14274
14275   TargetLowering::ArgListTy Args;
14276   TargetLowering::ArgListEntry Entry;
14277
14278   Entry.Node = Arg;
14279   Entry.Ty = ArgTy;
14280   Entry.isSExt = false;
14281   Entry.isZExt = false;
14282   Args.push_back(Entry);
14283
14284   bool isF64 = ArgVT == MVT::f64;
14285   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14286   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14287   // the results are returned via SRet in memory.
14288   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14290   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14291
14292   Type *RetTy = isF64
14293     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14294     : (Type*)VectorType::get(ArgTy, 4);
14295   TargetLowering::
14296     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14297                          false, false, false, false, 0,
14298                          CallingConv::C, /*isTaillCall=*/false,
14299                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14300                          Callee, Args, DAG, dl);
14301   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14302
14303   if (isF64)
14304     // Returned in xmm0 and xmm1.
14305     return CallResult.first;
14306
14307   // Returned in bits 0:31 and 32:64 xmm0.
14308   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14309                                CallResult.first, DAG.getIntPtrConstant(0));
14310   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14311                                CallResult.first, DAG.getIntPtrConstant(1));
14312   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14313   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14314 }
14315
14316 /// LowerOperation - Provide custom lowering hooks for some operations.
14317 ///
14318 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14319   switch (Op.getOpcode()) {
14320   default: llvm_unreachable("Should not custom lower this!");
14321   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14322   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14323   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14324   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14325   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14326   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14327   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14328   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14329   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14330   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14331   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14332   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14333   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14334   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14335   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14336   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14337   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14338   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14339   case ISD::SHL_PARTS:
14340   case ISD::SRA_PARTS:
14341   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14342   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14343   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14344   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14345   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14346   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14347   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14348   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14349   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14350   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14351   case ISD::FABS:               return LowerFABS(Op, DAG);
14352   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14353   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14354   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14355   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14356   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14357   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14358   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14359   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14360   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14361   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14362   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14363   case ISD::INTRINSIC_VOID:
14364   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14365   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14366   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14367   case ISD::FRAME_TO_ARGS_OFFSET:
14368                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14369   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14370   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14371   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14372   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14373   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14374   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14375   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14376   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14377   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14378   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14379   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14380   case ISD::UMUL_LOHI:
14381   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14382   case ISD::SRA:
14383   case ISD::SRL:
14384   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14385   case ISD::SADDO:
14386   case ISD::UADDO:
14387   case ISD::SSUBO:
14388   case ISD::USUBO:
14389   case ISD::SMULO:
14390   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14391   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14392   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14393   case ISD::ADDC:
14394   case ISD::ADDE:
14395   case ISD::SUBC:
14396   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14397   case ISD::ADD:                return LowerADD(Op, DAG);
14398   case ISD::SUB:                return LowerSUB(Op, DAG);
14399   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14400   }
14401 }
14402
14403 static void ReplaceATOMIC_LOAD(SDNode *Node,
14404                                   SmallVectorImpl<SDValue> &Results,
14405                                   SelectionDAG &DAG) {
14406   SDLoc dl(Node);
14407   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14408
14409   // Convert wide load -> cmpxchg8b/cmpxchg16b
14410   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14411   //        (The only way to get a 16-byte load is cmpxchg16b)
14412   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14413   SDValue Zero = DAG.getConstant(0, VT);
14414   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14415                                Node->getOperand(0),
14416                                Node->getOperand(1), Zero, Zero,
14417                                cast<AtomicSDNode>(Node)->getMemOperand(),
14418                                cast<AtomicSDNode>(Node)->getOrdering(),
14419                                cast<AtomicSDNode>(Node)->getOrdering(),
14420                                cast<AtomicSDNode>(Node)->getSynchScope());
14421   Results.push_back(Swap.getValue(0));
14422   Results.push_back(Swap.getValue(1));
14423 }
14424
14425 static void
14426 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14427                         SelectionDAG &DAG, unsigned NewOp) {
14428   SDLoc dl(Node);
14429   assert (Node->getValueType(0) == MVT::i64 &&
14430           "Only know how to expand i64 atomics");
14431
14432   SDValue Chain = Node->getOperand(0);
14433   SDValue In1 = Node->getOperand(1);
14434   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14435                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14436   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14437                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14438   SDValue Ops[] = { Chain, In1, In2L, In2H };
14439   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14440   SDValue Result =
14441     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14442                             cast<MemSDNode>(Node)->getMemOperand());
14443   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14444   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14445   Results.push_back(Result.getValue(2));
14446 }
14447
14448 /// ReplaceNodeResults - Replace a node with an illegal result type
14449 /// with a new node built out of custom code.
14450 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14451                                            SmallVectorImpl<SDValue>&Results,
14452                                            SelectionDAG &DAG) const {
14453   SDLoc dl(N);
14454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14455   switch (N->getOpcode()) {
14456   default:
14457     llvm_unreachable("Do not know how to custom type legalize this operation!");
14458   case ISD::SIGN_EXTEND_INREG:
14459   case ISD::ADDC:
14460   case ISD::ADDE:
14461   case ISD::SUBC:
14462   case ISD::SUBE:
14463     // We don't want to expand or promote these.
14464     return;
14465   case ISD::SDIV:
14466   case ISD::UDIV:
14467   case ISD::SREM:
14468   case ISD::UREM:
14469   case ISD::SDIVREM:
14470   case ISD::UDIVREM: {
14471     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14472     Results.push_back(V);
14473     return;
14474   }
14475   case ISD::FP_TO_SINT:
14476   case ISD::FP_TO_UINT: {
14477     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14478
14479     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14480       return;
14481
14482     std::pair<SDValue,SDValue> Vals =
14483         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14484     SDValue FIST = Vals.first, StackSlot = Vals.second;
14485     if (FIST.getNode()) {
14486       EVT VT = N->getValueType(0);
14487       // Return a load from the stack slot.
14488       if (StackSlot.getNode())
14489         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14490                                       MachinePointerInfo(),
14491                                       false, false, false, 0));
14492       else
14493         Results.push_back(FIST);
14494     }
14495     return;
14496   }
14497   case ISD::UINT_TO_FP: {
14498     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14499     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14500         N->getValueType(0) != MVT::v2f32)
14501       return;
14502     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14503                                  N->getOperand(0));
14504     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14505                                      MVT::f64);
14506     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14507     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14508                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14509     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14510     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14511     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14512     return;
14513   }
14514   case ISD::FP_ROUND: {
14515     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14516         return;
14517     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14518     Results.push_back(V);
14519     return;
14520   }
14521   case ISD::INTRINSIC_W_CHAIN: {
14522     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14523     switch (IntNo) {
14524     default : llvm_unreachable("Do not know how to custom type "
14525                                "legalize this intrinsic operation!");
14526     case Intrinsic::x86_rdtsc:
14527       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14528                                      Results);
14529     case Intrinsic::x86_rdtscp:
14530       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14531                                      Results);
14532     }
14533   }
14534   case ISD::READCYCLECOUNTER: {
14535     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14536                                    Results);
14537   }
14538   case ISD::ATOMIC_CMP_SWAP: {
14539     EVT T = N->getValueType(0);
14540     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14541     bool Regs64bit = T == MVT::i128;
14542     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14543     SDValue cpInL, cpInH;
14544     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14545                         DAG.getConstant(0, HalfT));
14546     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14547                         DAG.getConstant(1, HalfT));
14548     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14549                              Regs64bit ? X86::RAX : X86::EAX,
14550                              cpInL, SDValue());
14551     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14552                              Regs64bit ? X86::RDX : X86::EDX,
14553                              cpInH, cpInL.getValue(1));
14554     SDValue swapInL, swapInH;
14555     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14556                           DAG.getConstant(0, HalfT));
14557     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14558                           DAG.getConstant(1, HalfT));
14559     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14560                                Regs64bit ? X86::RBX : X86::EBX,
14561                                swapInL, cpInH.getValue(1));
14562     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14563                                Regs64bit ? X86::RCX : X86::ECX,
14564                                swapInH, swapInL.getValue(1));
14565     SDValue Ops[] = { swapInH.getValue(0),
14566                       N->getOperand(1),
14567                       swapInH.getValue(1) };
14568     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14569     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14570     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14571                                   X86ISD::LCMPXCHG8_DAG;
14572     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14573     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14574                                         Regs64bit ? X86::RAX : X86::EAX,
14575                                         HalfT, Result.getValue(1));
14576     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14577                                         Regs64bit ? X86::RDX : X86::EDX,
14578                                         HalfT, cpOutL.getValue(2));
14579     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14580     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14581     Results.push_back(cpOutH.getValue(1));
14582     return;
14583   }
14584   case ISD::ATOMIC_LOAD_ADD:
14585   case ISD::ATOMIC_LOAD_AND:
14586   case ISD::ATOMIC_LOAD_NAND:
14587   case ISD::ATOMIC_LOAD_OR:
14588   case ISD::ATOMIC_LOAD_SUB:
14589   case ISD::ATOMIC_LOAD_XOR:
14590   case ISD::ATOMIC_LOAD_MAX:
14591   case ISD::ATOMIC_LOAD_MIN:
14592   case ISD::ATOMIC_LOAD_UMAX:
14593   case ISD::ATOMIC_LOAD_UMIN:
14594   case ISD::ATOMIC_SWAP: {
14595     unsigned Opc;
14596     switch (N->getOpcode()) {
14597     default: llvm_unreachable("Unexpected opcode");
14598     case ISD::ATOMIC_LOAD_ADD:
14599       Opc = X86ISD::ATOMADD64_DAG;
14600       break;
14601     case ISD::ATOMIC_LOAD_AND:
14602       Opc = X86ISD::ATOMAND64_DAG;
14603       break;
14604     case ISD::ATOMIC_LOAD_NAND:
14605       Opc = X86ISD::ATOMNAND64_DAG;
14606       break;
14607     case ISD::ATOMIC_LOAD_OR:
14608       Opc = X86ISD::ATOMOR64_DAG;
14609       break;
14610     case ISD::ATOMIC_LOAD_SUB:
14611       Opc = X86ISD::ATOMSUB64_DAG;
14612       break;
14613     case ISD::ATOMIC_LOAD_XOR:
14614       Opc = X86ISD::ATOMXOR64_DAG;
14615       break;
14616     case ISD::ATOMIC_LOAD_MAX:
14617       Opc = X86ISD::ATOMMAX64_DAG;
14618       break;
14619     case ISD::ATOMIC_LOAD_MIN:
14620       Opc = X86ISD::ATOMMIN64_DAG;
14621       break;
14622     case ISD::ATOMIC_LOAD_UMAX:
14623       Opc = X86ISD::ATOMUMAX64_DAG;
14624       break;
14625     case ISD::ATOMIC_LOAD_UMIN:
14626       Opc = X86ISD::ATOMUMIN64_DAG;
14627       break;
14628     case ISD::ATOMIC_SWAP:
14629       Opc = X86ISD::ATOMSWAP64_DAG;
14630       break;
14631     }
14632     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14633     return;
14634   }
14635   case ISD::ATOMIC_LOAD: {
14636     ReplaceATOMIC_LOAD(N, Results, DAG);
14637     return;
14638   }
14639   case ISD::BITCAST: {
14640     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14641     EVT DstVT = N->getValueType(0);
14642     EVT SrcVT = N->getOperand(0)->getValueType(0);
14643
14644     if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14645       SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14646                                      MVT::v2f64, N->getOperand(0));
14647       SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14648       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14649                                  ToV4I32, DAG.getIntPtrConstant(0));
14650       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14651                                  ToV4I32, DAG.getIntPtrConstant(1));
14652       SDValue Elts[] = {Elt0, Elt1};
14653       Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14654     }
14655   }
14656   }
14657 }
14658
14659 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14660   switch (Opcode) {
14661   default: return nullptr;
14662   case X86ISD::BSF:                return "X86ISD::BSF";
14663   case X86ISD::BSR:                return "X86ISD::BSR";
14664   case X86ISD::SHLD:               return "X86ISD::SHLD";
14665   case X86ISD::SHRD:               return "X86ISD::SHRD";
14666   case X86ISD::FAND:               return "X86ISD::FAND";
14667   case X86ISD::FANDN:              return "X86ISD::FANDN";
14668   case X86ISD::FOR:                return "X86ISD::FOR";
14669   case X86ISD::FXOR:               return "X86ISD::FXOR";
14670   case X86ISD::FSRL:               return "X86ISD::FSRL";
14671   case X86ISD::FILD:               return "X86ISD::FILD";
14672   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14673   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14674   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14675   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14676   case X86ISD::FLD:                return "X86ISD::FLD";
14677   case X86ISD::FST:                return "X86ISD::FST";
14678   case X86ISD::CALL:               return "X86ISD::CALL";
14679   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14680   case X86ISD::BT:                 return "X86ISD::BT";
14681   case X86ISD::CMP:                return "X86ISD::CMP";
14682   case X86ISD::COMI:               return "X86ISD::COMI";
14683   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14684   case X86ISD::CMPM:               return "X86ISD::CMPM";
14685   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14686   case X86ISD::SETCC:              return "X86ISD::SETCC";
14687   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14688   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14689   case X86ISD::CMOV:               return "X86ISD::CMOV";
14690   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14691   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14692   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14693   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14694   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14695   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14696   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14697   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14698   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14699   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14700   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14701   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14702   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14703   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14704   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14705   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14706   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14707   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14708   case X86ISD::HADD:               return "X86ISD::HADD";
14709   case X86ISD::HSUB:               return "X86ISD::HSUB";
14710   case X86ISD::FHADD:              return "X86ISD::FHADD";
14711   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14712   case X86ISD::UMAX:               return "X86ISD::UMAX";
14713   case X86ISD::UMIN:               return "X86ISD::UMIN";
14714   case X86ISD::SMAX:               return "X86ISD::SMAX";
14715   case X86ISD::SMIN:               return "X86ISD::SMIN";
14716   case X86ISD::FMAX:               return "X86ISD::FMAX";
14717   case X86ISD::FMIN:               return "X86ISD::FMIN";
14718   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14719   case X86ISD::FMINC:              return "X86ISD::FMINC";
14720   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14721   case X86ISD::FRCP:               return "X86ISD::FRCP";
14722   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14723   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14724   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14725   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14726   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14727   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14728   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14729   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14730   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14731   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14732   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14733   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14734   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14735   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14736   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14737   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14738   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14739   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14740   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14741   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14742   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14743   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14744   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14745   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14746   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14747   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14748   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14749   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14750   case X86ISD::VSHL:               return "X86ISD::VSHL";
14751   case X86ISD::VSRL:               return "X86ISD::VSRL";
14752   case X86ISD::VSRA:               return "X86ISD::VSRA";
14753   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14754   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14755   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14756   case X86ISD::CMPP:               return "X86ISD::CMPP";
14757   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14758   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14759   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14760   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14761   case X86ISD::ADD:                return "X86ISD::ADD";
14762   case X86ISD::SUB:                return "X86ISD::SUB";
14763   case X86ISD::ADC:                return "X86ISD::ADC";
14764   case X86ISD::SBB:                return "X86ISD::SBB";
14765   case X86ISD::SMUL:               return "X86ISD::SMUL";
14766   case X86ISD::UMUL:               return "X86ISD::UMUL";
14767   case X86ISD::INC:                return "X86ISD::INC";
14768   case X86ISD::DEC:                return "X86ISD::DEC";
14769   case X86ISD::OR:                 return "X86ISD::OR";
14770   case X86ISD::XOR:                return "X86ISD::XOR";
14771   case X86ISD::AND:                return "X86ISD::AND";
14772   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14773   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14774   case X86ISD::PTEST:              return "X86ISD::PTEST";
14775   case X86ISD::TESTP:              return "X86ISD::TESTP";
14776   case X86ISD::TESTM:              return "X86ISD::TESTM";
14777   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14778   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14779   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14780   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14781   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14782   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14783   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14784   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14785   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14786   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14787   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14788   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14789   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14790   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14791   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14792   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14793   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14794   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14795   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14796   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14797   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14798   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14799   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14800   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14801   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14802   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14803   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14804   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14805   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14806   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14807   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14808   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14809   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14810   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14811   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14812   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14813   case X86ISD::SAHF:               return "X86ISD::SAHF";
14814   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14815   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14816   case X86ISD::FMADD:              return "X86ISD::FMADD";
14817   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14818   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14819   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14820   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14821   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14822   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14823   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14824   case X86ISD::XTEST:              return "X86ISD::XTEST";
14825   }
14826 }
14827
14828 // isLegalAddressingMode - Return true if the addressing mode represented
14829 // by AM is legal for this target, for a load/store of the specified type.
14830 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14831                                               Type *Ty) const {
14832   // X86 supports extremely general addressing modes.
14833   CodeModel::Model M = getTargetMachine().getCodeModel();
14834   Reloc::Model R = getTargetMachine().getRelocationModel();
14835
14836   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14837   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14838     return false;
14839
14840   if (AM.BaseGV) {
14841     unsigned GVFlags =
14842       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14843
14844     // If a reference to this global requires an extra load, we can't fold it.
14845     if (isGlobalStubReference(GVFlags))
14846       return false;
14847
14848     // If BaseGV requires a register for the PIC base, we cannot also have a
14849     // BaseReg specified.
14850     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14851       return false;
14852
14853     // If lower 4G is not available, then we must use rip-relative addressing.
14854     if ((M != CodeModel::Small || R != Reloc::Static) &&
14855         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14856       return false;
14857   }
14858
14859   switch (AM.Scale) {
14860   case 0:
14861   case 1:
14862   case 2:
14863   case 4:
14864   case 8:
14865     // These scales always work.
14866     break;
14867   case 3:
14868   case 5:
14869   case 9:
14870     // These scales are formed with basereg+scalereg.  Only accept if there is
14871     // no basereg yet.
14872     if (AM.HasBaseReg)
14873       return false;
14874     break;
14875   default:  // Other stuff never works.
14876     return false;
14877   }
14878
14879   return true;
14880 }
14881
14882 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14883   unsigned Bits = Ty->getScalarSizeInBits();
14884
14885   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14886   // particularly cheaper than those without.
14887   if (Bits == 8)
14888     return false;
14889
14890   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14891   // variable shifts just as cheap as scalar ones.
14892   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14893     return false;
14894
14895   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14896   // fully general vector.
14897   return true;
14898 }
14899
14900 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14901   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14902     return false;
14903   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14904   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14905   return NumBits1 > NumBits2;
14906 }
14907
14908 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14909   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14910     return false;
14911
14912   if (!isTypeLegal(EVT::getEVT(Ty1)))
14913     return false;
14914
14915   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14916
14917   // Assuming the caller doesn't have a zeroext or signext return parameter,
14918   // truncation all the way down to i1 is valid.
14919   return true;
14920 }
14921
14922 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14923   return isInt<32>(Imm);
14924 }
14925
14926 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14927   // Can also use sub to handle negated immediates.
14928   return isInt<32>(Imm);
14929 }
14930
14931 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14932   if (!VT1.isInteger() || !VT2.isInteger())
14933     return false;
14934   unsigned NumBits1 = VT1.getSizeInBits();
14935   unsigned NumBits2 = VT2.getSizeInBits();
14936   return NumBits1 > NumBits2;
14937 }
14938
14939 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14940   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14941   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14942 }
14943
14944 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14945   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14946   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14947 }
14948
14949 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14950   EVT VT1 = Val.getValueType();
14951   if (isZExtFree(VT1, VT2))
14952     return true;
14953
14954   if (Val.getOpcode() != ISD::LOAD)
14955     return false;
14956
14957   if (!VT1.isSimple() || !VT1.isInteger() ||
14958       !VT2.isSimple() || !VT2.isInteger())
14959     return false;
14960
14961   switch (VT1.getSimpleVT().SimpleTy) {
14962   default: break;
14963   case MVT::i8:
14964   case MVT::i16:
14965   case MVT::i32:
14966     // X86 has 8, 16, and 32-bit zero-extending loads.
14967     return true;
14968   }
14969
14970   return false;
14971 }
14972
14973 bool
14974 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14975   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14976     return false;
14977
14978   VT = VT.getScalarType();
14979
14980   if (!VT.isSimple())
14981     return false;
14982
14983   switch (VT.getSimpleVT().SimpleTy) {
14984   case MVT::f32:
14985   case MVT::f64:
14986     return true;
14987   default:
14988     break;
14989   }
14990
14991   return false;
14992 }
14993
14994 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14995   // i16 instructions are longer (0x66 prefix) and potentially slower.
14996   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14997 }
14998
14999 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15000 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15001 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15002 /// are assumed to be legal.
15003 bool
15004 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15005                                       EVT VT) const {
15006   if (!VT.isSimple())
15007     return false;
15008
15009   MVT SVT = VT.getSimpleVT();
15010
15011   // Very little shuffling can be done for 64-bit vectors right now.
15012   if (VT.getSizeInBits() == 64)
15013     return false;
15014
15015   // FIXME: pshufb, blends, shifts.
15016   return (SVT.getVectorNumElements() == 2 ||
15017           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15018           isMOVLMask(M, SVT) ||
15019           isSHUFPMask(M, SVT) ||
15020           isPSHUFDMask(M, SVT) ||
15021           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15022           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15023           isPALIGNRMask(M, SVT, Subtarget) ||
15024           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15025           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15026           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15027           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15028 }
15029
15030 bool
15031 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15032                                           EVT VT) const {
15033   if (!VT.isSimple())
15034     return false;
15035
15036   MVT SVT = VT.getSimpleVT();
15037   unsigned NumElts = SVT.getVectorNumElements();
15038   // FIXME: This collection of masks seems suspect.
15039   if (NumElts == 2)
15040     return true;
15041   if (NumElts == 4 && SVT.is128BitVector()) {
15042     return (isMOVLMask(Mask, SVT)  ||
15043             isCommutedMOVLMask(Mask, SVT, true) ||
15044             isSHUFPMask(Mask, SVT) ||
15045             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15046   }
15047   return false;
15048 }
15049
15050 //===----------------------------------------------------------------------===//
15051 //                           X86 Scheduler Hooks
15052 //===----------------------------------------------------------------------===//
15053
15054 /// Utility function to emit xbegin specifying the start of an RTM region.
15055 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15056                                      const TargetInstrInfo *TII) {
15057   DebugLoc DL = MI->getDebugLoc();
15058
15059   const BasicBlock *BB = MBB->getBasicBlock();
15060   MachineFunction::iterator I = MBB;
15061   ++I;
15062
15063   // For the v = xbegin(), we generate
15064   //
15065   // thisMBB:
15066   //  xbegin sinkMBB
15067   //
15068   // mainMBB:
15069   //  eax = -1
15070   //
15071   // sinkMBB:
15072   //  v = eax
15073
15074   MachineBasicBlock *thisMBB = MBB;
15075   MachineFunction *MF = MBB->getParent();
15076   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15077   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15078   MF->insert(I, mainMBB);
15079   MF->insert(I, sinkMBB);
15080
15081   // Transfer the remainder of BB and its successor edges to sinkMBB.
15082   sinkMBB->splice(sinkMBB->begin(), MBB,
15083                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15084   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15085
15086   // thisMBB:
15087   //  xbegin sinkMBB
15088   //  # fallthrough to mainMBB
15089   //  # abortion to sinkMBB
15090   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15091   thisMBB->addSuccessor(mainMBB);
15092   thisMBB->addSuccessor(sinkMBB);
15093
15094   // mainMBB:
15095   //  EAX = -1
15096   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15097   mainMBB->addSuccessor(sinkMBB);
15098
15099   // sinkMBB:
15100   // EAX is live into the sinkMBB
15101   sinkMBB->addLiveIn(X86::EAX);
15102   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15103           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15104     .addReg(X86::EAX);
15105
15106   MI->eraseFromParent();
15107   return sinkMBB;
15108 }
15109
15110 // Get CMPXCHG opcode for the specified data type.
15111 static unsigned getCmpXChgOpcode(EVT VT) {
15112   switch (VT.getSimpleVT().SimpleTy) {
15113   case MVT::i8:  return X86::LCMPXCHG8;
15114   case MVT::i16: return X86::LCMPXCHG16;
15115   case MVT::i32: return X86::LCMPXCHG32;
15116   case MVT::i64: return X86::LCMPXCHG64;
15117   default:
15118     break;
15119   }
15120   llvm_unreachable("Invalid operand size!");
15121 }
15122
15123 // Get LOAD opcode for the specified data type.
15124 static unsigned getLoadOpcode(EVT VT) {
15125   switch (VT.getSimpleVT().SimpleTy) {
15126   case MVT::i8:  return X86::MOV8rm;
15127   case MVT::i16: return X86::MOV16rm;
15128   case MVT::i32: return X86::MOV32rm;
15129   case MVT::i64: return X86::MOV64rm;
15130   default:
15131     break;
15132   }
15133   llvm_unreachable("Invalid operand size!");
15134 }
15135
15136 // Get opcode of the non-atomic one from the specified atomic instruction.
15137 static unsigned getNonAtomicOpcode(unsigned Opc) {
15138   switch (Opc) {
15139   case X86::ATOMAND8:  return X86::AND8rr;
15140   case X86::ATOMAND16: return X86::AND16rr;
15141   case X86::ATOMAND32: return X86::AND32rr;
15142   case X86::ATOMAND64: return X86::AND64rr;
15143   case X86::ATOMOR8:   return X86::OR8rr;
15144   case X86::ATOMOR16:  return X86::OR16rr;
15145   case X86::ATOMOR32:  return X86::OR32rr;
15146   case X86::ATOMOR64:  return X86::OR64rr;
15147   case X86::ATOMXOR8:  return X86::XOR8rr;
15148   case X86::ATOMXOR16: return X86::XOR16rr;
15149   case X86::ATOMXOR32: return X86::XOR32rr;
15150   case X86::ATOMXOR64: return X86::XOR64rr;
15151   }
15152   llvm_unreachable("Unhandled atomic-load-op opcode!");
15153 }
15154
15155 // Get opcode of the non-atomic one from the specified atomic instruction with
15156 // extra opcode.
15157 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15158                                                unsigned &ExtraOpc) {
15159   switch (Opc) {
15160   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15161   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15162   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15163   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15164   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15165   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15166   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15167   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15168   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15169   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15170   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15171   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15172   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15173   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15174   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15175   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15176   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15177   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15178   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15179   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15180   }
15181   llvm_unreachable("Unhandled atomic-load-op opcode!");
15182 }
15183
15184 // Get opcode of the non-atomic one from the specified atomic instruction for
15185 // 64-bit data type on 32-bit target.
15186 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15187   switch (Opc) {
15188   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15189   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15190   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15191   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15192   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15193   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15194   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15195   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15196   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15197   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15198   }
15199   llvm_unreachable("Unhandled atomic-load-op opcode!");
15200 }
15201
15202 // Get opcode of the non-atomic one from the specified atomic instruction for
15203 // 64-bit data type on 32-bit target with extra opcode.
15204 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15205                                                    unsigned &HiOpc,
15206                                                    unsigned &ExtraOpc) {
15207   switch (Opc) {
15208   case X86::ATOMNAND6432:
15209     ExtraOpc = X86::NOT32r;
15210     HiOpc = X86::AND32rr;
15211     return X86::AND32rr;
15212   }
15213   llvm_unreachable("Unhandled atomic-load-op opcode!");
15214 }
15215
15216 // Get pseudo CMOV opcode from the specified data type.
15217 static unsigned getPseudoCMOVOpc(EVT VT) {
15218   switch (VT.getSimpleVT().SimpleTy) {
15219   case MVT::i8:  return X86::CMOV_GR8;
15220   case MVT::i16: return X86::CMOV_GR16;
15221   case MVT::i32: return X86::CMOV_GR32;
15222   default:
15223     break;
15224   }
15225   llvm_unreachable("Unknown CMOV opcode!");
15226 }
15227
15228 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15229 // They will be translated into a spin-loop or compare-exchange loop from
15230 //
15231 //    ...
15232 //    dst = atomic-fetch-op MI.addr, MI.val
15233 //    ...
15234 //
15235 // to
15236 //
15237 //    ...
15238 //    t1 = LOAD MI.addr
15239 // loop:
15240 //    t4 = phi(t1, t3 / loop)
15241 //    t2 = OP MI.val, t4
15242 //    EAX = t4
15243 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15244 //    t3 = EAX
15245 //    JNE loop
15246 // sink:
15247 //    dst = t3
15248 //    ...
15249 MachineBasicBlock *
15250 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15251                                        MachineBasicBlock *MBB) const {
15252   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15253   DebugLoc DL = MI->getDebugLoc();
15254
15255   MachineFunction *MF = MBB->getParent();
15256   MachineRegisterInfo &MRI = MF->getRegInfo();
15257
15258   const BasicBlock *BB = MBB->getBasicBlock();
15259   MachineFunction::iterator I = MBB;
15260   ++I;
15261
15262   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15263          "Unexpected number of operands");
15264
15265   assert(MI->hasOneMemOperand() &&
15266          "Expected atomic-load-op to have one memoperand");
15267
15268   // Memory Reference
15269   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15270   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15271
15272   unsigned DstReg, SrcReg;
15273   unsigned MemOpndSlot;
15274
15275   unsigned CurOp = 0;
15276
15277   DstReg = MI->getOperand(CurOp++).getReg();
15278   MemOpndSlot = CurOp;
15279   CurOp += X86::AddrNumOperands;
15280   SrcReg = MI->getOperand(CurOp++).getReg();
15281
15282   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15283   MVT::SimpleValueType VT = *RC->vt_begin();
15284   unsigned t1 = MRI.createVirtualRegister(RC);
15285   unsigned t2 = MRI.createVirtualRegister(RC);
15286   unsigned t3 = MRI.createVirtualRegister(RC);
15287   unsigned t4 = MRI.createVirtualRegister(RC);
15288   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15289
15290   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15291   unsigned LOADOpc = getLoadOpcode(VT);
15292
15293   // For the atomic load-arith operator, we generate
15294   //
15295   //  thisMBB:
15296   //    t1 = LOAD [MI.addr]
15297   //  mainMBB:
15298   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15299   //    t1 = OP MI.val, EAX
15300   //    EAX = t4
15301   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15302   //    t3 = EAX
15303   //    JNE mainMBB
15304   //  sinkMBB:
15305   //    dst = t3
15306
15307   MachineBasicBlock *thisMBB = MBB;
15308   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15309   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15310   MF->insert(I, mainMBB);
15311   MF->insert(I, sinkMBB);
15312
15313   MachineInstrBuilder MIB;
15314
15315   // Transfer the remainder of BB and its successor edges to sinkMBB.
15316   sinkMBB->splice(sinkMBB->begin(), MBB,
15317                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15318   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15319
15320   // thisMBB:
15321   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15322   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15323     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15324     if (NewMO.isReg())
15325       NewMO.setIsKill(false);
15326     MIB.addOperand(NewMO);
15327   }
15328   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15329     unsigned flags = (*MMOI)->getFlags();
15330     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15331     MachineMemOperand *MMO =
15332       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15333                                (*MMOI)->getSize(),
15334                                (*MMOI)->getBaseAlignment(),
15335                                (*MMOI)->getTBAAInfo(),
15336                                (*MMOI)->getRanges());
15337     MIB.addMemOperand(MMO);
15338   }
15339
15340   thisMBB->addSuccessor(mainMBB);
15341
15342   // mainMBB:
15343   MachineBasicBlock *origMainMBB = mainMBB;
15344
15345   // Add a PHI.
15346   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15347                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15348
15349   unsigned Opc = MI->getOpcode();
15350   switch (Opc) {
15351   default:
15352     llvm_unreachable("Unhandled atomic-load-op opcode!");
15353   case X86::ATOMAND8:
15354   case X86::ATOMAND16:
15355   case X86::ATOMAND32:
15356   case X86::ATOMAND64:
15357   case X86::ATOMOR8:
15358   case X86::ATOMOR16:
15359   case X86::ATOMOR32:
15360   case X86::ATOMOR64:
15361   case X86::ATOMXOR8:
15362   case X86::ATOMXOR16:
15363   case X86::ATOMXOR32:
15364   case X86::ATOMXOR64: {
15365     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15366     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15367       .addReg(t4);
15368     break;
15369   }
15370   case X86::ATOMNAND8:
15371   case X86::ATOMNAND16:
15372   case X86::ATOMNAND32:
15373   case X86::ATOMNAND64: {
15374     unsigned Tmp = MRI.createVirtualRegister(RC);
15375     unsigned NOTOpc;
15376     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15377     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15378       .addReg(t4);
15379     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15380     break;
15381   }
15382   case X86::ATOMMAX8:
15383   case X86::ATOMMAX16:
15384   case X86::ATOMMAX32:
15385   case X86::ATOMMAX64:
15386   case X86::ATOMMIN8:
15387   case X86::ATOMMIN16:
15388   case X86::ATOMMIN32:
15389   case X86::ATOMMIN64:
15390   case X86::ATOMUMAX8:
15391   case X86::ATOMUMAX16:
15392   case X86::ATOMUMAX32:
15393   case X86::ATOMUMAX64:
15394   case X86::ATOMUMIN8:
15395   case X86::ATOMUMIN16:
15396   case X86::ATOMUMIN32:
15397   case X86::ATOMUMIN64: {
15398     unsigned CMPOpc;
15399     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15400
15401     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15402       .addReg(SrcReg)
15403       .addReg(t4);
15404
15405     if (Subtarget->hasCMov()) {
15406       if (VT != MVT::i8) {
15407         // Native support
15408         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15409           .addReg(SrcReg)
15410           .addReg(t4);
15411       } else {
15412         // Promote i8 to i32 to use CMOV32
15413         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15414         const TargetRegisterClass *RC32 =
15415           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15416         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15417         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15418         unsigned Tmp = MRI.createVirtualRegister(RC32);
15419
15420         unsigned Undef = MRI.createVirtualRegister(RC32);
15421         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15422
15423         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15424           .addReg(Undef)
15425           .addReg(SrcReg)
15426           .addImm(X86::sub_8bit);
15427         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15428           .addReg(Undef)
15429           .addReg(t4)
15430           .addImm(X86::sub_8bit);
15431
15432         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15433           .addReg(SrcReg32)
15434           .addReg(AccReg32);
15435
15436         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15437           .addReg(Tmp, 0, X86::sub_8bit);
15438       }
15439     } else {
15440       // Use pseudo select and lower them.
15441       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15442              "Invalid atomic-load-op transformation!");
15443       unsigned SelOpc = getPseudoCMOVOpc(VT);
15444       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15445       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15446       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15447               .addReg(SrcReg).addReg(t4)
15448               .addImm(CC);
15449       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15450       // Replace the original PHI node as mainMBB is changed after CMOV
15451       // lowering.
15452       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15453         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15454       Phi->eraseFromParent();
15455     }
15456     break;
15457   }
15458   }
15459
15460   // Copy PhyReg back from virtual register.
15461   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15462     .addReg(t4);
15463
15464   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15465   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15466     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15467     if (NewMO.isReg())
15468       NewMO.setIsKill(false);
15469     MIB.addOperand(NewMO);
15470   }
15471   MIB.addReg(t2);
15472   MIB.setMemRefs(MMOBegin, MMOEnd);
15473
15474   // Copy PhyReg back to virtual register.
15475   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15476     .addReg(PhyReg);
15477
15478   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15479
15480   mainMBB->addSuccessor(origMainMBB);
15481   mainMBB->addSuccessor(sinkMBB);
15482
15483   // sinkMBB:
15484   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15485           TII->get(TargetOpcode::COPY), DstReg)
15486     .addReg(t3);
15487
15488   MI->eraseFromParent();
15489   return sinkMBB;
15490 }
15491
15492 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15493 // instructions. They will be translated into a spin-loop or compare-exchange
15494 // loop from
15495 //
15496 //    ...
15497 //    dst = atomic-fetch-op MI.addr, MI.val
15498 //    ...
15499 //
15500 // to
15501 //
15502 //    ...
15503 //    t1L = LOAD [MI.addr + 0]
15504 //    t1H = LOAD [MI.addr + 4]
15505 // loop:
15506 //    t4L = phi(t1L, t3L / loop)
15507 //    t4H = phi(t1H, t3H / loop)
15508 //    t2L = OP MI.val.lo, t4L
15509 //    t2H = OP MI.val.hi, t4H
15510 //    EAX = t4L
15511 //    EDX = t4H
15512 //    EBX = t2L
15513 //    ECX = t2H
15514 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15515 //    t3L = EAX
15516 //    t3H = EDX
15517 //    JNE loop
15518 // sink:
15519 //    dstL = t3L
15520 //    dstH = t3H
15521 //    ...
15522 MachineBasicBlock *
15523 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15524                                            MachineBasicBlock *MBB) const {
15525   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15526   DebugLoc DL = MI->getDebugLoc();
15527
15528   MachineFunction *MF = MBB->getParent();
15529   MachineRegisterInfo &MRI = MF->getRegInfo();
15530
15531   const BasicBlock *BB = MBB->getBasicBlock();
15532   MachineFunction::iterator I = MBB;
15533   ++I;
15534
15535   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15536          "Unexpected number of operands");
15537
15538   assert(MI->hasOneMemOperand() &&
15539          "Expected atomic-load-op32 to have one memoperand");
15540
15541   // Memory Reference
15542   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15543   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15544
15545   unsigned DstLoReg, DstHiReg;
15546   unsigned SrcLoReg, SrcHiReg;
15547   unsigned MemOpndSlot;
15548
15549   unsigned CurOp = 0;
15550
15551   DstLoReg = MI->getOperand(CurOp++).getReg();
15552   DstHiReg = MI->getOperand(CurOp++).getReg();
15553   MemOpndSlot = CurOp;
15554   CurOp += X86::AddrNumOperands;
15555   SrcLoReg = MI->getOperand(CurOp++).getReg();
15556   SrcHiReg = MI->getOperand(CurOp++).getReg();
15557
15558   const TargetRegisterClass *RC = &X86::GR32RegClass;
15559   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15560
15561   unsigned t1L = MRI.createVirtualRegister(RC);
15562   unsigned t1H = MRI.createVirtualRegister(RC);
15563   unsigned t2L = MRI.createVirtualRegister(RC);
15564   unsigned t2H = MRI.createVirtualRegister(RC);
15565   unsigned t3L = MRI.createVirtualRegister(RC);
15566   unsigned t3H = MRI.createVirtualRegister(RC);
15567   unsigned t4L = MRI.createVirtualRegister(RC);
15568   unsigned t4H = MRI.createVirtualRegister(RC);
15569
15570   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15571   unsigned LOADOpc = X86::MOV32rm;
15572
15573   // For the atomic load-arith operator, we generate
15574   //
15575   //  thisMBB:
15576   //    t1L = LOAD [MI.addr + 0]
15577   //    t1H = LOAD [MI.addr + 4]
15578   //  mainMBB:
15579   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15580   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15581   //    t2L = OP MI.val.lo, t4L
15582   //    t2H = OP MI.val.hi, t4H
15583   //    EBX = t2L
15584   //    ECX = t2H
15585   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15586   //    t3L = EAX
15587   //    t3H = EDX
15588   //    JNE loop
15589   //  sinkMBB:
15590   //    dstL = t3L
15591   //    dstH = t3H
15592
15593   MachineBasicBlock *thisMBB = MBB;
15594   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15595   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15596   MF->insert(I, mainMBB);
15597   MF->insert(I, sinkMBB);
15598
15599   MachineInstrBuilder MIB;
15600
15601   // Transfer the remainder of BB and its successor edges to sinkMBB.
15602   sinkMBB->splice(sinkMBB->begin(), MBB,
15603                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15604   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15605
15606   // thisMBB:
15607   // Lo
15608   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15609   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15610     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15611     if (NewMO.isReg())
15612       NewMO.setIsKill(false);
15613     MIB.addOperand(NewMO);
15614   }
15615   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15616     unsigned flags = (*MMOI)->getFlags();
15617     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15618     MachineMemOperand *MMO =
15619       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15620                                (*MMOI)->getSize(),
15621                                (*MMOI)->getBaseAlignment(),
15622                                (*MMOI)->getTBAAInfo(),
15623                                (*MMOI)->getRanges());
15624     MIB.addMemOperand(MMO);
15625   };
15626   MachineInstr *LowMI = MIB;
15627
15628   // Hi
15629   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15630   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15631     if (i == X86::AddrDisp) {
15632       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15633     } else {
15634       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15635       if (NewMO.isReg())
15636         NewMO.setIsKill(false);
15637       MIB.addOperand(NewMO);
15638     }
15639   }
15640   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15641
15642   thisMBB->addSuccessor(mainMBB);
15643
15644   // mainMBB:
15645   MachineBasicBlock *origMainMBB = mainMBB;
15646
15647   // Add PHIs.
15648   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15649                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15650   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15651                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15652
15653   unsigned Opc = MI->getOpcode();
15654   switch (Opc) {
15655   default:
15656     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15657   case X86::ATOMAND6432:
15658   case X86::ATOMOR6432:
15659   case X86::ATOMXOR6432:
15660   case X86::ATOMADD6432:
15661   case X86::ATOMSUB6432: {
15662     unsigned HiOpc;
15663     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15664     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15665       .addReg(SrcLoReg);
15666     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15667       .addReg(SrcHiReg);
15668     break;
15669   }
15670   case X86::ATOMNAND6432: {
15671     unsigned HiOpc, NOTOpc;
15672     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15673     unsigned TmpL = MRI.createVirtualRegister(RC);
15674     unsigned TmpH = MRI.createVirtualRegister(RC);
15675     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15676       .addReg(t4L);
15677     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15678       .addReg(t4H);
15679     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15680     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15681     break;
15682   }
15683   case X86::ATOMMAX6432:
15684   case X86::ATOMMIN6432:
15685   case X86::ATOMUMAX6432:
15686   case X86::ATOMUMIN6432: {
15687     unsigned HiOpc;
15688     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15689     unsigned cL = MRI.createVirtualRegister(RC8);
15690     unsigned cH = MRI.createVirtualRegister(RC8);
15691     unsigned cL32 = MRI.createVirtualRegister(RC);
15692     unsigned cH32 = MRI.createVirtualRegister(RC);
15693     unsigned cc = MRI.createVirtualRegister(RC);
15694     // cl := cmp src_lo, lo
15695     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15696       .addReg(SrcLoReg).addReg(t4L);
15697     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15698     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15699     // ch := cmp src_hi, hi
15700     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15701       .addReg(SrcHiReg).addReg(t4H);
15702     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15703     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15704     // cc := if (src_hi == hi) ? cl : ch;
15705     if (Subtarget->hasCMov()) {
15706       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15707         .addReg(cH32).addReg(cL32);
15708     } else {
15709       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15710               .addReg(cH32).addReg(cL32)
15711               .addImm(X86::COND_E);
15712       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15713     }
15714     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15715     if (Subtarget->hasCMov()) {
15716       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15717         .addReg(SrcLoReg).addReg(t4L);
15718       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15719         .addReg(SrcHiReg).addReg(t4H);
15720     } else {
15721       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15722               .addReg(SrcLoReg).addReg(t4L)
15723               .addImm(X86::COND_NE);
15724       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15725       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15726       // 2nd CMOV lowering.
15727       mainMBB->addLiveIn(X86::EFLAGS);
15728       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15729               .addReg(SrcHiReg).addReg(t4H)
15730               .addImm(X86::COND_NE);
15731       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15732       // Replace the original PHI node as mainMBB is changed after CMOV
15733       // lowering.
15734       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15735         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15736       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15737         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15738       PhiL->eraseFromParent();
15739       PhiH->eraseFromParent();
15740     }
15741     break;
15742   }
15743   case X86::ATOMSWAP6432: {
15744     unsigned HiOpc;
15745     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15746     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15747     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15748     break;
15749   }
15750   }
15751
15752   // Copy EDX:EAX back from HiReg:LoReg
15753   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15754   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15755   // Copy ECX:EBX from t1H:t1L
15756   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15757   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15758
15759   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15760   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15761     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15762     if (NewMO.isReg())
15763       NewMO.setIsKill(false);
15764     MIB.addOperand(NewMO);
15765   }
15766   MIB.setMemRefs(MMOBegin, MMOEnd);
15767
15768   // Copy EDX:EAX back to t3H:t3L
15769   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15770   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15771
15772   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15773
15774   mainMBB->addSuccessor(origMainMBB);
15775   mainMBB->addSuccessor(sinkMBB);
15776
15777   // sinkMBB:
15778   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15779           TII->get(TargetOpcode::COPY), DstLoReg)
15780     .addReg(t3L);
15781   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15782           TII->get(TargetOpcode::COPY), DstHiReg)
15783     .addReg(t3H);
15784
15785   MI->eraseFromParent();
15786   return sinkMBB;
15787 }
15788
15789 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15790 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15791 // in the .td file.
15792 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15793                                        const TargetInstrInfo *TII) {
15794   unsigned Opc;
15795   switch (MI->getOpcode()) {
15796   default: llvm_unreachable("illegal opcode!");
15797   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15798   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15799   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15800   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15801   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15802   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15803   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15804   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15805   }
15806
15807   DebugLoc dl = MI->getDebugLoc();
15808   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15809
15810   unsigned NumArgs = MI->getNumOperands();
15811   for (unsigned i = 1; i < NumArgs; ++i) {
15812     MachineOperand &Op = MI->getOperand(i);
15813     if (!(Op.isReg() && Op.isImplicit()))
15814       MIB.addOperand(Op);
15815   }
15816   if (MI->hasOneMemOperand())
15817     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15818
15819   BuildMI(*BB, MI, dl,
15820     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15821     .addReg(X86::XMM0);
15822
15823   MI->eraseFromParent();
15824   return BB;
15825 }
15826
15827 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15828 // defs in an instruction pattern
15829 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15830                                        const TargetInstrInfo *TII) {
15831   unsigned Opc;
15832   switch (MI->getOpcode()) {
15833   default: llvm_unreachable("illegal opcode!");
15834   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15835   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15836   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15837   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15838   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15839   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15840   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15841   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15842   }
15843
15844   DebugLoc dl = MI->getDebugLoc();
15845   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15846
15847   unsigned NumArgs = MI->getNumOperands(); // remove the results
15848   for (unsigned i = 1; i < NumArgs; ++i) {
15849     MachineOperand &Op = MI->getOperand(i);
15850     if (!(Op.isReg() && Op.isImplicit()))
15851       MIB.addOperand(Op);
15852   }
15853   if (MI->hasOneMemOperand())
15854     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15855
15856   BuildMI(*BB, MI, dl,
15857     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15858     .addReg(X86::ECX);
15859
15860   MI->eraseFromParent();
15861   return BB;
15862 }
15863
15864 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15865                                        const TargetInstrInfo *TII,
15866                                        const X86Subtarget* Subtarget) {
15867   DebugLoc dl = MI->getDebugLoc();
15868
15869   // Address into RAX/EAX, other two args into ECX, EDX.
15870   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15871   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15872   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15873   for (int i = 0; i < X86::AddrNumOperands; ++i)
15874     MIB.addOperand(MI->getOperand(i));
15875
15876   unsigned ValOps = X86::AddrNumOperands;
15877   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15878     .addReg(MI->getOperand(ValOps).getReg());
15879   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15880     .addReg(MI->getOperand(ValOps+1).getReg());
15881
15882   // The instruction doesn't actually take any operands though.
15883   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15884
15885   MI->eraseFromParent(); // The pseudo is gone now.
15886   return BB;
15887 }
15888
15889 MachineBasicBlock *
15890 X86TargetLowering::EmitVAARG64WithCustomInserter(
15891                    MachineInstr *MI,
15892                    MachineBasicBlock *MBB) const {
15893   // Emit va_arg instruction on X86-64.
15894
15895   // Operands to this pseudo-instruction:
15896   // 0  ) Output        : destination address (reg)
15897   // 1-5) Input         : va_list address (addr, i64mem)
15898   // 6  ) ArgSize       : Size (in bytes) of vararg type
15899   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15900   // 8  ) Align         : Alignment of type
15901   // 9  ) EFLAGS (implicit-def)
15902
15903   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15904   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15905
15906   unsigned DestReg = MI->getOperand(0).getReg();
15907   MachineOperand &Base = MI->getOperand(1);
15908   MachineOperand &Scale = MI->getOperand(2);
15909   MachineOperand &Index = MI->getOperand(3);
15910   MachineOperand &Disp = MI->getOperand(4);
15911   MachineOperand &Segment = MI->getOperand(5);
15912   unsigned ArgSize = MI->getOperand(6).getImm();
15913   unsigned ArgMode = MI->getOperand(7).getImm();
15914   unsigned Align = MI->getOperand(8).getImm();
15915
15916   // Memory Reference
15917   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15918   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15919   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15920
15921   // Machine Information
15922   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15923   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15924   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15925   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15926   DebugLoc DL = MI->getDebugLoc();
15927
15928   // struct va_list {
15929   //   i32   gp_offset
15930   //   i32   fp_offset
15931   //   i64   overflow_area (address)
15932   //   i64   reg_save_area (address)
15933   // }
15934   // sizeof(va_list) = 24
15935   // alignment(va_list) = 8
15936
15937   unsigned TotalNumIntRegs = 6;
15938   unsigned TotalNumXMMRegs = 8;
15939   bool UseGPOffset = (ArgMode == 1);
15940   bool UseFPOffset = (ArgMode == 2);
15941   unsigned MaxOffset = TotalNumIntRegs * 8 +
15942                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15943
15944   /* Align ArgSize to a multiple of 8 */
15945   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15946   bool NeedsAlign = (Align > 8);
15947
15948   MachineBasicBlock *thisMBB = MBB;
15949   MachineBasicBlock *overflowMBB;
15950   MachineBasicBlock *offsetMBB;
15951   MachineBasicBlock *endMBB;
15952
15953   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15954   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15955   unsigned OffsetReg = 0;
15956
15957   if (!UseGPOffset && !UseFPOffset) {
15958     // If we only pull from the overflow region, we don't create a branch.
15959     // We don't need to alter control flow.
15960     OffsetDestReg = 0; // unused
15961     OverflowDestReg = DestReg;
15962
15963     offsetMBB = nullptr;
15964     overflowMBB = thisMBB;
15965     endMBB = thisMBB;
15966   } else {
15967     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15968     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15969     // If not, pull from overflow_area. (branch to overflowMBB)
15970     //
15971     //       thisMBB
15972     //         |     .
15973     //         |        .
15974     //     offsetMBB   overflowMBB
15975     //         |        .
15976     //         |     .
15977     //        endMBB
15978
15979     // Registers for the PHI in endMBB
15980     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15981     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15982
15983     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15984     MachineFunction *MF = MBB->getParent();
15985     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15986     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15987     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15988
15989     MachineFunction::iterator MBBIter = MBB;
15990     ++MBBIter;
15991
15992     // Insert the new basic blocks
15993     MF->insert(MBBIter, offsetMBB);
15994     MF->insert(MBBIter, overflowMBB);
15995     MF->insert(MBBIter, endMBB);
15996
15997     // Transfer the remainder of MBB and its successor edges to endMBB.
15998     endMBB->splice(endMBB->begin(), thisMBB,
15999                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16000     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16001
16002     // Make offsetMBB and overflowMBB successors of thisMBB
16003     thisMBB->addSuccessor(offsetMBB);
16004     thisMBB->addSuccessor(overflowMBB);
16005
16006     // endMBB is a successor of both offsetMBB and overflowMBB
16007     offsetMBB->addSuccessor(endMBB);
16008     overflowMBB->addSuccessor(endMBB);
16009
16010     // Load the offset value into a register
16011     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16012     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16013       .addOperand(Base)
16014       .addOperand(Scale)
16015       .addOperand(Index)
16016       .addDisp(Disp, UseFPOffset ? 4 : 0)
16017       .addOperand(Segment)
16018       .setMemRefs(MMOBegin, MMOEnd);
16019
16020     // Check if there is enough room left to pull this argument.
16021     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16022       .addReg(OffsetReg)
16023       .addImm(MaxOffset + 8 - ArgSizeA8);
16024
16025     // Branch to "overflowMBB" if offset >= max
16026     // Fall through to "offsetMBB" otherwise
16027     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16028       .addMBB(overflowMBB);
16029   }
16030
16031   // In offsetMBB, emit code to use the reg_save_area.
16032   if (offsetMBB) {
16033     assert(OffsetReg != 0);
16034
16035     // Read the reg_save_area address.
16036     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16037     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16038       .addOperand(Base)
16039       .addOperand(Scale)
16040       .addOperand(Index)
16041       .addDisp(Disp, 16)
16042       .addOperand(Segment)
16043       .setMemRefs(MMOBegin, MMOEnd);
16044
16045     // Zero-extend the offset
16046     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16047       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16048         .addImm(0)
16049         .addReg(OffsetReg)
16050         .addImm(X86::sub_32bit);
16051
16052     // Add the offset to the reg_save_area to get the final address.
16053     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16054       .addReg(OffsetReg64)
16055       .addReg(RegSaveReg);
16056
16057     // Compute the offset for the next argument
16058     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16059     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16060       .addReg(OffsetReg)
16061       .addImm(UseFPOffset ? 16 : 8);
16062
16063     // Store it back into the va_list.
16064     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16065       .addOperand(Base)
16066       .addOperand(Scale)
16067       .addOperand(Index)
16068       .addDisp(Disp, UseFPOffset ? 4 : 0)
16069       .addOperand(Segment)
16070       .addReg(NextOffsetReg)
16071       .setMemRefs(MMOBegin, MMOEnd);
16072
16073     // Jump to endMBB
16074     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16075       .addMBB(endMBB);
16076   }
16077
16078   //
16079   // Emit code to use overflow area
16080   //
16081
16082   // Load the overflow_area address into a register.
16083   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16084   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16085     .addOperand(Base)
16086     .addOperand(Scale)
16087     .addOperand(Index)
16088     .addDisp(Disp, 8)
16089     .addOperand(Segment)
16090     .setMemRefs(MMOBegin, MMOEnd);
16091
16092   // If we need to align it, do so. Otherwise, just copy the address
16093   // to OverflowDestReg.
16094   if (NeedsAlign) {
16095     // Align the overflow address
16096     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16097     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16098
16099     // aligned_addr = (addr + (align-1)) & ~(align-1)
16100     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16101       .addReg(OverflowAddrReg)
16102       .addImm(Align-1);
16103
16104     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16105       .addReg(TmpReg)
16106       .addImm(~(uint64_t)(Align-1));
16107   } else {
16108     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16109       .addReg(OverflowAddrReg);
16110   }
16111
16112   // Compute the next overflow address after this argument.
16113   // (the overflow address should be kept 8-byte aligned)
16114   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16115   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16116     .addReg(OverflowDestReg)
16117     .addImm(ArgSizeA8);
16118
16119   // Store the new overflow address.
16120   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16121     .addOperand(Base)
16122     .addOperand(Scale)
16123     .addOperand(Index)
16124     .addDisp(Disp, 8)
16125     .addOperand(Segment)
16126     .addReg(NextAddrReg)
16127     .setMemRefs(MMOBegin, MMOEnd);
16128
16129   // If we branched, emit the PHI to the front of endMBB.
16130   if (offsetMBB) {
16131     BuildMI(*endMBB, endMBB->begin(), DL,
16132             TII->get(X86::PHI), DestReg)
16133       .addReg(OffsetDestReg).addMBB(offsetMBB)
16134       .addReg(OverflowDestReg).addMBB(overflowMBB);
16135   }
16136
16137   // Erase the pseudo instruction
16138   MI->eraseFromParent();
16139
16140   return endMBB;
16141 }
16142
16143 MachineBasicBlock *
16144 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16145                                                  MachineInstr *MI,
16146                                                  MachineBasicBlock *MBB) const {
16147   // Emit code to save XMM registers to the stack. The ABI says that the
16148   // number of registers to save is given in %al, so it's theoretically
16149   // possible to do an indirect jump trick to avoid saving all of them,
16150   // however this code takes a simpler approach and just executes all
16151   // of the stores if %al is non-zero. It's less code, and it's probably
16152   // easier on the hardware branch predictor, and stores aren't all that
16153   // expensive anyway.
16154
16155   // Create the new basic blocks. One block contains all the XMM stores,
16156   // and one block is the final destination regardless of whether any
16157   // stores were performed.
16158   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16159   MachineFunction *F = MBB->getParent();
16160   MachineFunction::iterator MBBIter = MBB;
16161   ++MBBIter;
16162   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16163   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16164   F->insert(MBBIter, XMMSaveMBB);
16165   F->insert(MBBIter, EndMBB);
16166
16167   // Transfer the remainder of MBB and its successor edges to EndMBB.
16168   EndMBB->splice(EndMBB->begin(), MBB,
16169                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16170   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16171
16172   // The original block will now fall through to the XMM save block.
16173   MBB->addSuccessor(XMMSaveMBB);
16174   // The XMMSaveMBB will fall through to the end block.
16175   XMMSaveMBB->addSuccessor(EndMBB);
16176
16177   // Now add the instructions.
16178   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16179   DebugLoc DL = MI->getDebugLoc();
16180
16181   unsigned CountReg = MI->getOperand(0).getReg();
16182   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16183   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16184
16185   if (!Subtarget->isTargetWin64()) {
16186     // If %al is 0, branch around the XMM save block.
16187     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16188     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16189     MBB->addSuccessor(EndMBB);
16190   }
16191
16192   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16193   // that was just emitted, but clearly shouldn't be "saved".
16194   assert((MI->getNumOperands() <= 3 ||
16195           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16196           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16197          && "Expected last argument to be EFLAGS");
16198   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16199   // In the XMM save block, save all the XMM argument registers.
16200   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16201     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16202     MachineMemOperand *MMO =
16203       F->getMachineMemOperand(
16204           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16205         MachineMemOperand::MOStore,
16206         /*Size=*/16, /*Align=*/16);
16207     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16208       .addFrameIndex(RegSaveFrameIndex)
16209       .addImm(/*Scale=*/1)
16210       .addReg(/*IndexReg=*/0)
16211       .addImm(/*Disp=*/Offset)
16212       .addReg(/*Segment=*/0)
16213       .addReg(MI->getOperand(i).getReg())
16214       .addMemOperand(MMO);
16215   }
16216
16217   MI->eraseFromParent();   // The pseudo instruction is gone now.
16218
16219   return EndMBB;
16220 }
16221
16222 // The EFLAGS operand of SelectItr might be missing a kill marker
16223 // because there were multiple uses of EFLAGS, and ISel didn't know
16224 // which to mark. Figure out whether SelectItr should have had a
16225 // kill marker, and set it if it should. Returns the correct kill
16226 // marker value.
16227 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16228                                      MachineBasicBlock* BB,
16229                                      const TargetRegisterInfo* TRI) {
16230   // Scan forward through BB for a use/def of EFLAGS.
16231   MachineBasicBlock::iterator miI(std::next(SelectItr));
16232   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16233     const MachineInstr& mi = *miI;
16234     if (mi.readsRegister(X86::EFLAGS))
16235       return false;
16236     if (mi.definesRegister(X86::EFLAGS))
16237       break; // Should have kill-flag - update below.
16238   }
16239
16240   // If we hit the end of the block, check whether EFLAGS is live into a
16241   // successor.
16242   if (miI == BB->end()) {
16243     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16244                                           sEnd = BB->succ_end();
16245          sItr != sEnd; ++sItr) {
16246       MachineBasicBlock* succ = *sItr;
16247       if (succ->isLiveIn(X86::EFLAGS))
16248         return false;
16249     }
16250   }
16251
16252   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16253   // out. SelectMI should have a kill flag on EFLAGS.
16254   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16255   return true;
16256 }
16257
16258 MachineBasicBlock *
16259 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16260                                      MachineBasicBlock *BB) const {
16261   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16262   DebugLoc DL = MI->getDebugLoc();
16263
16264   // To "insert" a SELECT_CC instruction, we actually have to insert the
16265   // diamond control-flow pattern.  The incoming instruction knows the
16266   // destination vreg to set, the condition code register to branch on, the
16267   // true/false values to select between, and a branch opcode to use.
16268   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16269   MachineFunction::iterator It = BB;
16270   ++It;
16271
16272   //  thisMBB:
16273   //  ...
16274   //   TrueVal = ...
16275   //   cmpTY ccX, r1, r2
16276   //   bCC copy1MBB
16277   //   fallthrough --> copy0MBB
16278   MachineBasicBlock *thisMBB = BB;
16279   MachineFunction *F = BB->getParent();
16280   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16281   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16282   F->insert(It, copy0MBB);
16283   F->insert(It, sinkMBB);
16284
16285   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16286   // live into the sink and copy blocks.
16287   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16288   if (!MI->killsRegister(X86::EFLAGS) &&
16289       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16290     copy0MBB->addLiveIn(X86::EFLAGS);
16291     sinkMBB->addLiveIn(X86::EFLAGS);
16292   }
16293
16294   // Transfer the remainder of BB and its successor edges to sinkMBB.
16295   sinkMBB->splice(sinkMBB->begin(), BB,
16296                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16297   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16298
16299   // Add the true and fallthrough blocks as its successors.
16300   BB->addSuccessor(copy0MBB);
16301   BB->addSuccessor(sinkMBB);
16302
16303   // Create the conditional branch instruction.
16304   unsigned Opc =
16305     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16306   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16307
16308   //  copy0MBB:
16309   //   %FalseValue = ...
16310   //   # fallthrough to sinkMBB
16311   copy0MBB->addSuccessor(sinkMBB);
16312
16313   //  sinkMBB:
16314   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16315   //  ...
16316   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16317           TII->get(X86::PHI), MI->getOperand(0).getReg())
16318     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16319     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16320
16321   MI->eraseFromParent();   // The pseudo instruction is gone now.
16322   return sinkMBB;
16323 }
16324
16325 MachineBasicBlock *
16326 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16327                                         bool Is64Bit) const {
16328   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16329   DebugLoc DL = MI->getDebugLoc();
16330   MachineFunction *MF = BB->getParent();
16331   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16332
16333   assert(MF->shouldSplitStack());
16334
16335   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16336   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16337
16338   // BB:
16339   //  ... [Till the alloca]
16340   // If stacklet is not large enough, jump to mallocMBB
16341   //
16342   // bumpMBB:
16343   //  Allocate by subtracting from RSP
16344   //  Jump to continueMBB
16345   //
16346   // mallocMBB:
16347   //  Allocate by call to runtime
16348   //
16349   // continueMBB:
16350   //  ...
16351   //  [rest of original BB]
16352   //
16353
16354   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16355   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16356   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16357
16358   MachineRegisterInfo &MRI = MF->getRegInfo();
16359   const TargetRegisterClass *AddrRegClass =
16360     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16361
16362   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16363     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16364     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16365     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16366     sizeVReg = MI->getOperand(1).getReg(),
16367     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16368
16369   MachineFunction::iterator MBBIter = BB;
16370   ++MBBIter;
16371
16372   MF->insert(MBBIter, bumpMBB);
16373   MF->insert(MBBIter, mallocMBB);
16374   MF->insert(MBBIter, continueMBB);
16375
16376   continueMBB->splice(continueMBB->begin(), BB,
16377                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16378   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16379
16380   // Add code to the main basic block to check if the stack limit has been hit,
16381   // and if so, jump to mallocMBB otherwise to bumpMBB.
16382   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16383   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16384     .addReg(tmpSPVReg).addReg(sizeVReg);
16385   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16386     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16387     .addReg(SPLimitVReg);
16388   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16389
16390   // bumpMBB simply decreases the stack pointer, since we know the current
16391   // stacklet has enough space.
16392   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16393     .addReg(SPLimitVReg);
16394   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16395     .addReg(SPLimitVReg);
16396   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16397
16398   // Calls into a routine in libgcc to allocate more space from the heap.
16399   const uint32_t *RegMask =
16400     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16401   if (Is64Bit) {
16402     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16403       .addReg(sizeVReg);
16404     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16405       .addExternalSymbol("__morestack_allocate_stack_space")
16406       .addRegMask(RegMask)
16407       .addReg(X86::RDI, RegState::Implicit)
16408       .addReg(X86::RAX, RegState::ImplicitDefine);
16409   } else {
16410     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16411       .addImm(12);
16412     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16413     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16414       .addExternalSymbol("__morestack_allocate_stack_space")
16415       .addRegMask(RegMask)
16416       .addReg(X86::EAX, RegState::ImplicitDefine);
16417   }
16418
16419   if (!Is64Bit)
16420     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16421       .addImm(16);
16422
16423   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16424     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16425   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16426
16427   // Set up the CFG correctly.
16428   BB->addSuccessor(bumpMBB);
16429   BB->addSuccessor(mallocMBB);
16430   mallocMBB->addSuccessor(continueMBB);
16431   bumpMBB->addSuccessor(continueMBB);
16432
16433   // Take care of the PHI nodes.
16434   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16435           MI->getOperand(0).getReg())
16436     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16437     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16438
16439   // Delete the original pseudo instruction.
16440   MI->eraseFromParent();
16441
16442   // And we're done.
16443   return continueMBB;
16444 }
16445
16446 MachineBasicBlock *
16447 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16448                                           MachineBasicBlock *BB) const {
16449   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16450   DebugLoc DL = MI->getDebugLoc();
16451
16452   assert(!Subtarget->isTargetMacho());
16453
16454   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16455   // non-trivial part is impdef of ESP.
16456
16457   if (Subtarget->isTargetWin64()) {
16458     if (Subtarget->isTargetCygMing()) {
16459       // ___chkstk(Mingw64):
16460       // Clobbers R10, R11, RAX and EFLAGS.
16461       // Updates RSP.
16462       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16463         .addExternalSymbol("___chkstk")
16464         .addReg(X86::RAX, RegState::Implicit)
16465         .addReg(X86::RSP, RegState::Implicit)
16466         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16467         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16468         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16469     } else {
16470       // __chkstk(MSVCRT): does not update stack pointer.
16471       // Clobbers R10, R11 and EFLAGS.
16472       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16473         .addExternalSymbol("__chkstk")
16474         .addReg(X86::RAX, RegState::Implicit)
16475         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16476       // RAX has the offset to be subtracted from RSP.
16477       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16478         .addReg(X86::RSP)
16479         .addReg(X86::RAX);
16480     }
16481   } else {
16482     const char *StackProbeSymbol =
16483       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16484
16485     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16486       .addExternalSymbol(StackProbeSymbol)
16487       .addReg(X86::EAX, RegState::Implicit)
16488       .addReg(X86::ESP, RegState::Implicit)
16489       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16490       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16491       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16492   }
16493
16494   MI->eraseFromParent();   // The pseudo instruction is gone now.
16495   return BB;
16496 }
16497
16498 MachineBasicBlock *
16499 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16500                                       MachineBasicBlock *BB) const {
16501   // This is pretty easy.  We're taking the value that we received from
16502   // our load from the relocation, sticking it in either RDI (x86-64)
16503   // or EAX and doing an indirect call.  The return value will then
16504   // be in the normal return register.
16505   const X86InstrInfo *TII
16506     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16507   DebugLoc DL = MI->getDebugLoc();
16508   MachineFunction *F = BB->getParent();
16509
16510   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16511   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16512
16513   // Get a register mask for the lowered call.
16514   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16515   // proper register mask.
16516   const uint32_t *RegMask =
16517     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16518   if (Subtarget->is64Bit()) {
16519     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16520                                       TII->get(X86::MOV64rm), X86::RDI)
16521     .addReg(X86::RIP)
16522     .addImm(0).addReg(0)
16523     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16524                       MI->getOperand(3).getTargetFlags())
16525     .addReg(0);
16526     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16527     addDirectMem(MIB, X86::RDI);
16528     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16529   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16530     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16531                                       TII->get(X86::MOV32rm), X86::EAX)
16532     .addReg(0)
16533     .addImm(0).addReg(0)
16534     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16535                       MI->getOperand(3).getTargetFlags())
16536     .addReg(0);
16537     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16538     addDirectMem(MIB, X86::EAX);
16539     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16540   } else {
16541     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16542                                       TII->get(X86::MOV32rm), X86::EAX)
16543     .addReg(TII->getGlobalBaseReg(F))
16544     .addImm(0).addReg(0)
16545     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16546                       MI->getOperand(3).getTargetFlags())
16547     .addReg(0);
16548     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16549     addDirectMem(MIB, X86::EAX);
16550     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16551   }
16552
16553   MI->eraseFromParent(); // The pseudo instruction is gone now.
16554   return BB;
16555 }
16556
16557 MachineBasicBlock *
16558 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16559                                     MachineBasicBlock *MBB) const {
16560   DebugLoc DL = MI->getDebugLoc();
16561   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16562
16563   MachineFunction *MF = MBB->getParent();
16564   MachineRegisterInfo &MRI = MF->getRegInfo();
16565
16566   const BasicBlock *BB = MBB->getBasicBlock();
16567   MachineFunction::iterator I = MBB;
16568   ++I;
16569
16570   // Memory Reference
16571   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16572   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16573
16574   unsigned DstReg;
16575   unsigned MemOpndSlot = 0;
16576
16577   unsigned CurOp = 0;
16578
16579   DstReg = MI->getOperand(CurOp++).getReg();
16580   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16581   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16582   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16583   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16584
16585   MemOpndSlot = CurOp;
16586
16587   MVT PVT = getPointerTy();
16588   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16589          "Invalid Pointer Size!");
16590
16591   // For v = setjmp(buf), we generate
16592   //
16593   // thisMBB:
16594   //  buf[LabelOffset] = restoreMBB
16595   //  SjLjSetup restoreMBB
16596   //
16597   // mainMBB:
16598   //  v_main = 0
16599   //
16600   // sinkMBB:
16601   //  v = phi(main, restore)
16602   //
16603   // restoreMBB:
16604   //  v_restore = 1
16605
16606   MachineBasicBlock *thisMBB = MBB;
16607   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16608   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16609   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16610   MF->insert(I, mainMBB);
16611   MF->insert(I, sinkMBB);
16612   MF->push_back(restoreMBB);
16613
16614   MachineInstrBuilder MIB;
16615
16616   // Transfer the remainder of BB and its successor edges to sinkMBB.
16617   sinkMBB->splice(sinkMBB->begin(), MBB,
16618                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16619   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16620
16621   // thisMBB:
16622   unsigned PtrStoreOpc = 0;
16623   unsigned LabelReg = 0;
16624   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16625   Reloc::Model RM = getTargetMachine().getRelocationModel();
16626   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16627                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16628
16629   // Prepare IP either in reg or imm.
16630   if (!UseImmLabel) {
16631     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16632     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16633     LabelReg = MRI.createVirtualRegister(PtrRC);
16634     if (Subtarget->is64Bit()) {
16635       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16636               .addReg(X86::RIP)
16637               .addImm(0)
16638               .addReg(0)
16639               .addMBB(restoreMBB)
16640               .addReg(0);
16641     } else {
16642       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16643       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16644               .addReg(XII->getGlobalBaseReg(MF))
16645               .addImm(0)
16646               .addReg(0)
16647               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16648               .addReg(0);
16649     }
16650   } else
16651     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16652   // Store IP
16653   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16654   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16655     if (i == X86::AddrDisp)
16656       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16657     else
16658       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16659   }
16660   if (!UseImmLabel)
16661     MIB.addReg(LabelReg);
16662   else
16663     MIB.addMBB(restoreMBB);
16664   MIB.setMemRefs(MMOBegin, MMOEnd);
16665   // Setup
16666   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16667           .addMBB(restoreMBB);
16668
16669   const X86RegisterInfo *RegInfo =
16670     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16671   MIB.addRegMask(RegInfo->getNoPreservedMask());
16672   thisMBB->addSuccessor(mainMBB);
16673   thisMBB->addSuccessor(restoreMBB);
16674
16675   // mainMBB:
16676   //  EAX = 0
16677   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16678   mainMBB->addSuccessor(sinkMBB);
16679
16680   // sinkMBB:
16681   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16682           TII->get(X86::PHI), DstReg)
16683     .addReg(mainDstReg).addMBB(mainMBB)
16684     .addReg(restoreDstReg).addMBB(restoreMBB);
16685
16686   // restoreMBB:
16687   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16688   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16689   restoreMBB->addSuccessor(sinkMBB);
16690
16691   MI->eraseFromParent();
16692   return sinkMBB;
16693 }
16694
16695 MachineBasicBlock *
16696 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16697                                      MachineBasicBlock *MBB) const {
16698   DebugLoc DL = MI->getDebugLoc();
16699   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16700
16701   MachineFunction *MF = MBB->getParent();
16702   MachineRegisterInfo &MRI = MF->getRegInfo();
16703
16704   // Memory Reference
16705   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16706   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16707
16708   MVT PVT = getPointerTy();
16709   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16710          "Invalid Pointer Size!");
16711
16712   const TargetRegisterClass *RC =
16713     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16714   unsigned Tmp = MRI.createVirtualRegister(RC);
16715   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16716   const X86RegisterInfo *RegInfo =
16717     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16718   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16719   unsigned SP = RegInfo->getStackRegister();
16720
16721   MachineInstrBuilder MIB;
16722
16723   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16724   const int64_t SPOffset = 2 * PVT.getStoreSize();
16725
16726   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16727   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16728
16729   // Reload FP
16730   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16731   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16732     MIB.addOperand(MI->getOperand(i));
16733   MIB.setMemRefs(MMOBegin, MMOEnd);
16734   // Reload IP
16735   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16736   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16737     if (i == X86::AddrDisp)
16738       MIB.addDisp(MI->getOperand(i), LabelOffset);
16739     else
16740       MIB.addOperand(MI->getOperand(i));
16741   }
16742   MIB.setMemRefs(MMOBegin, MMOEnd);
16743   // Reload SP
16744   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16745   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16746     if (i == X86::AddrDisp)
16747       MIB.addDisp(MI->getOperand(i), SPOffset);
16748     else
16749       MIB.addOperand(MI->getOperand(i));
16750   }
16751   MIB.setMemRefs(MMOBegin, MMOEnd);
16752   // Jump
16753   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16754
16755   MI->eraseFromParent();
16756   return MBB;
16757 }
16758
16759 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16760 // accumulator loops. Writing back to the accumulator allows the coalescer
16761 // to remove extra copies in the loop.   
16762 MachineBasicBlock *
16763 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16764                                  MachineBasicBlock *MBB) const {
16765   MachineOperand &AddendOp = MI->getOperand(3);
16766
16767   // Bail out early if the addend isn't a register - we can't switch these.
16768   if (!AddendOp.isReg())
16769     return MBB;
16770
16771   MachineFunction &MF = *MBB->getParent();
16772   MachineRegisterInfo &MRI = MF.getRegInfo();
16773
16774   // Check whether the addend is defined by a PHI:
16775   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16776   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16777   if (!AddendDef.isPHI())
16778     return MBB;
16779
16780   // Look for the following pattern:
16781   // loop:
16782   //   %addend = phi [%entry, 0], [%loop, %result]
16783   //   ...
16784   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16785
16786   // Replace with:
16787   //   loop:
16788   //   %addend = phi [%entry, 0], [%loop, %result]
16789   //   ...
16790   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16791
16792   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16793     assert(AddendDef.getOperand(i).isReg());
16794     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16795     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16796     if (&PHISrcInst == MI) {
16797       // Found a matching instruction.
16798       unsigned NewFMAOpc = 0;
16799       switch (MI->getOpcode()) {
16800         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16801         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16802         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16803         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16804         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16805         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16806         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16807         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16808         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16809         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16810         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16811         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16812         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16813         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16814         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16815         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16816         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16817         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16818         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16819         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16820         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16821         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16822         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16823         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16824         default: llvm_unreachable("Unrecognized FMA variant.");
16825       }
16826
16827       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16828       MachineInstrBuilder MIB =
16829         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16830         .addOperand(MI->getOperand(0))
16831         .addOperand(MI->getOperand(3))
16832         .addOperand(MI->getOperand(2))
16833         .addOperand(MI->getOperand(1));
16834       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16835       MI->eraseFromParent();
16836     }
16837   }
16838
16839   return MBB;
16840 }
16841
16842 MachineBasicBlock *
16843 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16844                                                MachineBasicBlock *BB) const {
16845   switch (MI->getOpcode()) {
16846   default: llvm_unreachable("Unexpected instr type to insert");
16847   case X86::TAILJMPd64:
16848   case X86::TAILJMPr64:
16849   case X86::TAILJMPm64:
16850     llvm_unreachable("TAILJMP64 would not be touched here.");
16851   case X86::TCRETURNdi64:
16852   case X86::TCRETURNri64:
16853   case X86::TCRETURNmi64:
16854     return BB;
16855   case X86::WIN_ALLOCA:
16856     return EmitLoweredWinAlloca(MI, BB);
16857   case X86::SEG_ALLOCA_32:
16858     return EmitLoweredSegAlloca(MI, BB, false);
16859   case X86::SEG_ALLOCA_64:
16860     return EmitLoweredSegAlloca(MI, BB, true);
16861   case X86::TLSCall_32:
16862   case X86::TLSCall_64:
16863     return EmitLoweredTLSCall(MI, BB);
16864   case X86::CMOV_GR8:
16865   case X86::CMOV_FR32:
16866   case X86::CMOV_FR64:
16867   case X86::CMOV_V4F32:
16868   case X86::CMOV_V2F64:
16869   case X86::CMOV_V2I64:
16870   case X86::CMOV_V8F32:
16871   case X86::CMOV_V4F64:
16872   case X86::CMOV_V4I64:
16873   case X86::CMOV_V16F32:
16874   case X86::CMOV_V8F64:
16875   case X86::CMOV_V8I64:
16876   case X86::CMOV_GR16:
16877   case X86::CMOV_GR32:
16878   case X86::CMOV_RFP32:
16879   case X86::CMOV_RFP64:
16880   case X86::CMOV_RFP80:
16881     return EmitLoweredSelect(MI, BB);
16882
16883   case X86::FP32_TO_INT16_IN_MEM:
16884   case X86::FP32_TO_INT32_IN_MEM:
16885   case X86::FP32_TO_INT64_IN_MEM:
16886   case X86::FP64_TO_INT16_IN_MEM:
16887   case X86::FP64_TO_INT32_IN_MEM:
16888   case X86::FP64_TO_INT64_IN_MEM:
16889   case X86::FP80_TO_INT16_IN_MEM:
16890   case X86::FP80_TO_INT32_IN_MEM:
16891   case X86::FP80_TO_INT64_IN_MEM: {
16892     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16893     DebugLoc DL = MI->getDebugLoc();
16894
16895     // Change the floating point control register to use "round towards zero"
16896     // mode when truncating to an integer value.
16897     MachineFunction *F = BB->getParent();
16898     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16899     addFrameReference(BuildMI(*BB, MI, DL,
16900                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16901
16902     // Load the old value of the high byte of the control word...
16903     unsigned OldCW =
16904       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16905     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16906                       CWFrameIdx);
16907
16908     // Set the high part to be round to zero...
16909     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16910       .addImm(0xC7F);
16911
16912     // Reload the modified control word now...
16913     addFrameReference(BuildMI(*BB, MI, DL,
16914                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16915
16916     // Restore the memory image of control word to original value
16917     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16918       .addReg(OldCW);
16919
16920     // Get the X86 opcode to use.
16921     unsigned Opc;
16922     switch (MI->getOpcode()) {
16923     default: llvm_unreachable("illegal opcode!");
16924     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16925     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16926     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16927     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16928     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16929     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16930     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16931     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16932     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16933     }
16934
16935     X86AddressMode AM;
16936     MachineOperand &Op = MI->getOperand(0);
16937     if (Op.isReg()) {
16938       AM.BaseType = X86AddressMode::RegBase;
16939       AM.Base.Reg = Op.getReg();
16940     } else {
16941       AM.BaseType = X86AddressMode::FrameIndexBase;
16942       AM.Base.FrameIndex = Op.getIndex();
16943     }
16944     Op = MI->getOperand(1);
16945     if (Op.isImm())
16946       AM.Scale = Op.getImm();
16947     Op = MI->getOperand(2);
16948     if (Op.isImm())
16949       AM.IndexReg = Op.getImm();
16950     Op = MI->getOperand(3);
16951     if (Op.isGlobal()) {
16952       AM.GV = Op.getGlobal();
16953     } else {
16954       AM.Disp = Op.getImm();
16955     }
16956     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16957                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16958
16959     // Reload the original control word now.
16960     addFrameReference(BuildMI(*BB, MI, DL,
16961                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16962
16963     MI->eraseFromParent();   // The pseudo instruction is gone now.
16964     return BB;
16965   }
16966     // String/text processing lowering.
16967   case X86::PCMPISTRM128REG:
16968   case X86::VPCMPISTRM128REG:
16969   case X86::PCMPISTRM128MEM:
16970   case X86::VPCMPISTRM128MEM:
16971   case X86::PCMPESTRM128REG:
16972   case X86::VPCMPESTRM128REG:
16973   case X86::PCMPESTRM128MEM:
16974   case X86::VPCMPESTRM128MEM:
16975     assert(Subtarget->hasSSE42() &&
16976            "Target must have SSE4.2 or AVX features enabled");
16977     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16978
16979   // String/text processing lowering.
16980   case X86::PCMPISTRIREG:
16981   case X86::VPCMPISTRIREG:
16982   case X86::PCMPISTRIMEM:
16983   case X86::VPCMPISTRIMEM:
16984   case X86::PCMPESTRIREG:
16985   case X86::VPCMPESTRIREG:
16986   case X86::PCMPESTRIMEM:
16987   case X86::VPCMPESTRIMEM:
16988     assert(Subtarget->hasSSE42() &&
16989            "Target must have SSE4.2 or AVX features enabled");
16990     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16991
16992   // Thread synchronization.
16993   case X86::MONITOR:
16994     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16995
16996   // xbegin
16997   case X86::XBEGIN:
16998     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16999
17000   // Atomic Lowering.
17001   case X86::ATOMAND8:
17002   case X86::ATOMAND16:
17003   case X86::ATOMAND32:
17004   case X86::ATOMAND64:
17005     // Fall through
17006   case X86::ATOMOR8:
17007   case X86::ATOMOR16:
17008   case X86::ATOMOR32:
17009   case X86::ATOMOR64:
17010     // Fall through
17011   case X86::ATOMXOR16:
17012   case X86::ATOMXOR8:
17013   case X86::ATOMXOR32:
17014   case X86::ATOMXOR64:
17015     // Fall through
17016   case X86::ATOMNAND8:
17017   case X86::ATOMNAND16:
17018   case X86::ATOMNAND32:
17019   case X86::ATOMNAND64:
17020     // Fall through
17021   case X86::ATOMMAX8:
17022   case X86::ATOMMAX16:
17023   case X86::ATOMMAX32:
17024   case X86::ATOMMAX64:
17025     // Fall through
17026   case X86::ATOMMIN8:
17027   case X86::ATOMMIN16:
17028   case X86::ATOMMIN32:
17029   case X86::ATOMMIN64:
17030     // Fall through
17031   case X86::ATOMUMAX8:
17032   case X86::ATOMUMAX16:
17033   case X86::ATOMUMAX32:
17034   case X86::ATOMUMAX64:
17035     // Fall through
17036   case X86::ATOMUMIN8:
17037   case X86::ATOMUMIN16:
17038   case X86::ATOMUMIN32:
17039   case X86::ATOMUMIN64:
17040     return EmitAtomicLoadArith(MI, BB);
17041
17042   // This group does 64-bit operations on a 32-bit host.
17043   case X86::ATOMAND6432:
17044   case X86::ATOMOR6432:
17045   case X86::ATOMXOR6432:
17046   case X86::ATOMNAND6432:
17047   case X86::ATOMADD6432:
17048   case X86::ATOMSUB6432:
17049   case X86::ATOMMAX6432:
17050   case X86::ATOMMIN6432:
17051   case X86::ATOMUMAX6432:
17052   case X86::ATOMUMIN6432:
17053   case X86::ATOMSWAP6432:
17054     return EmitAtomicLoadArith6432(MI, BB);
17055
17056   case X86::VASTART_SAVE_XMM_REGS:
17057     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17058
17059   case X86::VAARG_64:
17060     return EmitVAARG64WithCustomInserter(MI, BB);
17061
17062   case X86::EH_SjLj_SetJmp32:
17063   case X86::EH_SjLj_SetJmp64:
17064     return emitEHSjLjSetJmp(MI, BB);
17065
17066   case X86::EH_SjLj_LongJmp32:
17067   case X86::EH_SjLj_LongJmp64:
17068     return emitEHSjLjLongJmp(MI, BB);
17069
17070   case TargetOpcode::STACKMAP:
17071   case TargetOpcode::PATCHPOINT:
17072     return emitPatchPoint(MI, BB);
17073
17074   case X86::VFMADDPDr213r:
17075   case X86::VFMADDPSr213r:
17076   case X86::VFMADDSDr213r:
17077   case X86::VFMADDSSr213r:
17078   case X86::VFMSUBPDr213r:
17079   case X86::VFMSUBPSr213r:
17080   case X86::VFMSUBSDr213r:
17081   case X86::VFMSUBSSr213r:
17082   case X86::VFNMADDPDr213r:
17083   case X86::VFNMADDPSr213r:
17084   case X86::VFNMADDSDr213r:
17085   case X86::VFNMADDSSr213r:
17086   case X86::VFNMSUBPDr213r:
17087   case X86::VFNMSUBPSr213r:
17088   case X86::VFNMSUBSDr213r:
17089   case X86::VFNMSUBSSr213r:
17090   case X86::VFMADDPDr213rY:
17091   case X86::VFMADDPSr213rY:
17092   case X86::VFMSUBPDr213rY:
17093   case X86::VFMSUBPSr213rY:
17094   case X86::VFNMADDPDr213rY:
17095   case X86::VFNMADDPSr213rY:
17096   case X86::VFNMSUBPDr213rY:
17097   case X86::VFNMSUBPSr213rY:
17098     return emitFMA3Instr(MI, BB);
17099   }
17100 }
17101
17102 //===----------------------------------------------------------------------===//
17103 //                           X86 Optimization Hooks
17104 //===----------------------------------------------------------------------===//
17105
17106 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17107                                                       APInt &KnownZero,
17108                                                       APInt &KnownOne,
17109                                                       const SelectionDAG &DAG,
17110                                                       unsigned Depth) const {
17111   unsigned BitWidth = KnownZero.getBitWidth();
17112   unsigned Opc = Op.getOpcode();
17113   assert((Opc >= ISD::BUILTIN_OP_END ||
17114           Opc == ISD::INTRINSIC_WO_CHAIN ||
17115           Opc == ISD::INTRINSIC_W_CHAIN ||
17116           Opc == ISD::INTRINSIC_VOID) &&
17117          "Should use MaskedValueIsZero if you don't know whether Op"
17118          " is a target node!");
17119
17120   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17121   switch (Opc) {
17122   default: break;
17123   case X86ISD::ADD:
17124   case X86ISD::SUB:
17125   case X86ISD::ADC:
17126   case X86ISD::SBB:
17127   case X86ISD::SMUL:
17128   case X86ISD::UMUL:
17129   case X86ISD::INC:
17130   case X86ISD::DEC:
17131   case X86ISD::OR:
17132   case X86ISD::XOR:
17133   case X86ISD::AND:
17134     // These nodes' second result is a boolean.
17135     if (Op.getResNo() == 0)
17136       break;
17137     // Fallthrough
17138   case X86ISD::SETCC:
17139     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17140     break;
17141   case ISD::INTRINSIC_WO_CHAIN: {
17142     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17143     unsigned NumLoBits = 0;
17144     switch (IntId) {
17145     default: break;
17146     case Intrinsic::x86_sse_movmsk_ps:
17147     case Intrinsic::x86_avx_movmsk_ps_256:
17148     case Intrinsic::x86_sse2_movmsk_pd:
17149     case Intrinsic::x86_avx_movmsk_pd_256:
17150     case Intrinsic::x86_mmx_pmovmskb:
17151     case Intrinsic::x86_sse2_pmovmskb_128:
17152     case Intrinsic::x86_avx2_pmovmskb: {
17153       // High bits of movmskp{s|d}, pmovmskb are known zero.
17154       switch (IntId) {
17155         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17156         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17157         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17158         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17159         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17160         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17161         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17162         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17163       }
17164       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17165       break;
17166     }
17167     }
17168     break;
17169   }
17170   }
17171 }
17172
17173 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17174   SDValue Op,
17175   const SelectionDAG &,
17176   unsigned Depth) const {
17177   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17178   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17179     return Op.getValueType().getScalarType().getSizeInBits();
17180
17181   // Fallback case.
17182   return 1;
17183 }
17184
17185 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17186 /// node is a GlobalAddress + offset.
17187 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17188                                        const GlobalValue* &GA,
17189                                        int64_t &Offset) const {
17190   if (N->getOpcode() == X86ISD::Wrapper) {
17191     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17192       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17193       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17194       return true;
17195     }
17196   }
17197   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17198 }
17199
17200 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17201 /// same as extracting the high 128-bit part of 256-bit vector and then
17202 /// inserting the result into the low part of a new 256-bit vector
17203 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17204   EVT VT = SVOp->getValueType(0);
17205   unsigned NumElems = VT.getVectorNumElements();
17206
17207   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17208   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17209     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17210         SVOp->getMaskElt(j) >= 0)
17211       return false;
17212
17213   return true;
17214 }
17215
17216 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17217 /// same as extracting the low 128-bit part of 256-bit vector and then
17218 /// inserting the result into the high part of a new 256-bit vector
17219 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17220   EVT VT = SVOp->getValueType(0);
17221   unsigned NumElems = VT.getVectorNumElements();
17222
17223   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17224   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17225     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17226         SVOp->getMaskElt(j) >= 0)
17227       return false;
17228
17229   return true;
17230 }
17231
17232 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17233 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17234                                         TargetLowering::DAGCombinerInfo &DCI,
17235                                         const X86Subtarget* Subtarget) {
17236   SDLoc dl(N);
17237   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17238   SDValue V1 = SVOp->getOperand(0);
17239   SDValue V2 = SVOp->getOperand(1);
17240   EVT VT = SVOp->getValueType(0);
17241   unsigned NumElems = VT.getVectorNumElements();
17242
17243   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17244       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17245     //
17246     //                   0,0,0,...
17247     //                      |
17248     //    V      UNDEF    BUILD_VECTOR    UNDEF
17249     //     \      /           \           /
17250     //  CONCAT_VECTOR         CONCAT_VECTOR
17251     //         \                  /
17252     //          \                /
17253     //          RESULT: V + zero extended
17254     //
17255     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17256         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17257         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17258       return SDValue();
17259
17260     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17261       return SDValue();
17262
17263     // To match the shuffle mask, the first half of the mask should
17264     // be exactly the first vector, and all the rest a splat with the
17265     // first element of the second one.
17266     for (unsigned i = 0; i != NumElems/2; ++i)
17267       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17268           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17269         return SDValue();
17270
17271     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17272     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17273       if (Ld->hasNUsesOfValue(1, 0)) {
17274         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17275         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17276         SDValue ResNode =
17277           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17278                                   Ld->getMemoryVT(),
17279                                   Ld->getPointerInfo(),
17280                                   Ld->getAlignment(),
17281                                   false/*isVolatile*/, true/*ReadMem*/,
17282                                   false/*WriteMem*/);
17283
17284         // Make sure the newly-created LOAD is in the same position as Ld in
17285         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17286         // and update uses of Ld's output chain to use the TokenFactor.
17287         if (Ld->hasAnyUseOfValue(1)) {
17288           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17289                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17290           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17291           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17292                                  SDValue(ResNode.getNode(), 1));
17293         }
17294
17295         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17296       }
17297     }
17298
17299     // Emit a zeroed vector and insert the desired subvector on its
17300     // first half.
17301     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17302     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17303     return DCI.CombineTo(N, InsV);
17304   }
17305
17306   //===--------------------------------------------------------------------===//
17307   // Combine some shuffles into subvector extracts and inserts:
17308   //
17309
17310   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17311   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17312     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17313     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17314     return DCI.CombineTo(N, InsV);
17315   }
17316
17317   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17318   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17319     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17320     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17321     return DCI.CombineTo(N, InsV);
17322   }
17323
17324   return SDValue();
17325 }
17326
17327 /// PerformShuffleCombine - Performs several different shuffle combines.
17328 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17329                                      TargetLowering::DAGCombinerInfo &DCI,
17330                                      const X86Subtarget *Subtarget) {
17331   SDLoc dl(N);
17332   EVT VT = N->getValueType(0);
17333
17334   // Don't create instructions with illegal types after legalize types has run.
17335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17336   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17337     return SDValue();
17338
17339   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17340   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17341       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17342     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17343
17344   // Only handle 128 wide vector from here on.
17345   if (!VT.is128BitVector())
17346     return SDValue();
17347
17348   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17349   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17350   // consecutive, non-overlapping, and in the right order.
17351   SmallVector<SDValue, 16> Elts;
17352   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17353     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17354
17355   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17356 }
17357
17358 /// PerformTruncateCombine - Converts truncate operation to
17359 /// a sequence of vector shuffle operations.
17360 /// It is possible when we truncate 256-bit vector to 128-bit vector
17361 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17362                                       TargetLowering::DAGCombinerInfo &DCI,
17363                                       const X86Subtarget *Subtarget)  {
17364   return SDValue();
17365 }
17366
17367 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17368 /// specific shuffle of a load can be folded into a single element load.
17369 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17370 /// shuffles have been customed lowered so we need to handle those here.
17371 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17372                                          TargetLowering::DAGCombinerInfo &DCI) {
17373   if (DCI.isBeforeLegalizeOps())
17374     return SDValue();
17375
17376   SDValue InVec = N->getOperand(0);
17377   SDValue EltNo = N->getOperand(1);
17378
17379   if (!isa<ConstantSDNode>(EltNo))
17380     return SDValue();
17381
17382   EVT VT = InVec.getValueType();
17383
17384   bool HasShuffleIntoBitcast = false;
17385   if (InVec.getOpcode() == ISD::BITCAST) {
17386     // Don't duplicate a load with other uses.
17387     if (!InVec.hasOneUse())
17388       return SDValue();
17389     EVT BCVT = InVec.getOperand(0).getValueType();
17390     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17391       return SDValue();
17392     InVec = InVec.getOperand(0);
17393     HasShuffleIntoBitcast = true;
17394   }
17395
17396   if (!isTargetShuffle(InVec.getOpcode()))
17397     return SDValue();
17398
17399   // Don't duplicate a load with other uses.
17400   if (!InVec.hasOneUse())
17401     return SDValue();
17402
17403   SmallVector<int, 16> ShuffleMask;
17404   bool UnaryShuffle;
17405   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17406                             UnaryShuffle))
17407     return SDValue();
17408
17409   // Select the input vector, guarding against out of range extract vector.
17410   unsigned NumElems = VT.getVectorNumElements();
17411   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17412   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17413   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17414                                          : InVec.getOperand(1);
17415
17416   // If inputs to shuffle are the same for both ops, then allow 2 uses
17417   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17418
17419   if (LdNode.getOpcode() == ISD::BITCAST) {
17420     // Don't duplicate a load with other uses.
17421     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17422       return SDValue();
17423
17424     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17425     LdNode = LdNode.getOperand(0);
17426   }
17427
17428   if (!ISD::isNormalLoad(LdNode.getNode()))
17429     return SDValue();
17430
17431   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17432
17433   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17434     return SDValue();
17435
17436   if (HasShuffleIntoBitcast) {
17437     // If there's a bitcast before the shuffle, check if the load type and
17438     // alignment is valid.
17439     unsigned Align = LN0->getAlignment();
17440     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17441     unsigned NewAlign = TLI.getDataLayout()->
17442       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17443
17444     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17445       return SDValue();
17446   }
17447
17448   // All checks match so transform back to vector_shuffle so that DAG combiner
17449   // can finish the job
17450   SDLoc dl(N);
17451
17452   // Create shuffle node taking into account the case that its a unary shuffle
17453   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17454   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17455                                  InVec.getOperand(0), Shuffle,
17456                                  &ShuffleMask[0]);
17457   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17458   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17459                      EltNo);
17460 }
17461
17462 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17463 /// generation and convert it from being a bunch of shuffles and extracts
17464 /// to a simple store and scalar loads to extract the elements.
17465 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17466                                          TargetLowering::DAGCombinerInfo &DCI) {
17467   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17468   if (NewOp.getNode())
17469     return NewOp;
17470
17471   SDValue InputVector = N->getOperand(0);
17472
17473   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17474   // from mmx to v2i32 has a single usage.
17475   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17476       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17477       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17478     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17479                        N->getValueType(0),
17480                        InputVector.getNode()->getOperand(0));
17481
17482   // Only operate on vectors of 4 elements, where the alternative shuffling
17483   // gets to be more expensive.
17484   if (InputVector.getValueType() != MVT::v4i32)
17485     return SDValue();
17486
17487   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17488   // single use which is a sign-extend or zero-extend, and all elements are
17489   // used.
17490   SmallVector<SDNode *, 4> Uses;
17491   unsigned ExtractedElements = 0;
17492   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17493        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17494     if (UI.getUse().getResNo() != InputVector.getResNo())
17495       return SDValue();
17496
17497     SDNode *Extract = *UI;
17498     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17499       return SDValue();
17500
17501     if (Extract->getValueType(0) != MVT::i32)
17502       return SDValue();
17503     if (!Extract->hasOneUse())
17504       return SDValue();
17505     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17506         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17507       return SDValue();
17508     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17509       return SDValue();
17510
17511     // Record which element was extracted.
17512     ExtractedElements |=
17513       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17514
17515     Uses.push_back(Extract);
17516   }
17517
17518   // If not all the elements were used, this may not be worthwhile.
17519   if (ExtractedElements != 15)
17520     return SDValue();
17521
17522   // Ok, we've now decided to do the transformation.
17523   SDLoc dl(InputVector);
17524
17525   // Store the value to a temporary stack slot.
17526   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17527   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17528                             MachinePointerInfo(), false, false, 0);
17529
17530   // Replace each use (extract) with a load of the appropriate element.
17531   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17532        UE = Uses.end(); UI != UE; ++UI) {
17533     SDNode *Extract = *UI;
17534
17535     // cOMpute the element's address.
17536     SDValue Idx = Extract->getOperand(1);
17537     unsigned EltSize =
17538         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17539     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17540     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17541     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17542
17543     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17544                                      StackPtr, OffsetVal);
17545
17546     // Load the scalar.
17547     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17548                                      ScalarAddr, MachinePointerInfo(),
17549                                      false, false, false, 0);
17550
17551     // Replace the exact with the load.
17552     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17553   }
17554
17555   // The replacement was made in place; don't return anything.
17556   return SDValue();
17557 }
17558
17559 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17560 static std::pair<unsigned, bool>
17561 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17562                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17563   if (!VT.isVector())
17564     return std::make_pair(0, false);
17565
17566   bool NeedSplit = false;
17567   switch (VT.getSimpleVT().SimpleTy) {
17568   default: return std::make_pair(0, false);
17569   case MVT::v32i8:
17570   case MVT::v16i16:
17571   case MVT::v8i32:
17572     if (!Subtarget->hasAVX2())
17573       NeedSplit = true;
17574     if (!Subtarget->hasAVX())
17575       return std::make_pair(0, false);
17576     break;
17577   case MVT::v16i8:
17578   case MVT::v8i16:
17579   case MVT::v4i32:
17580     if (!Subtarget->hasSSE2())
17581       return std::make_pair(0, false);
17582   }
17583
17584   // SSE2 has only a small subset of the operations.
17585   bool hasUnsigned = Subtarget->hasSSE41() ||
17586                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17587   bool hasSigned = Subtarget->hasSSE41() ||
17588                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17589
17590   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17591
17592   unsigned Opc = 0;
17593   // Check for x CC y ? x : y.
17594   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17595       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17596     switch (CC) {
17597     default: break;
17598     case ISD::SETULT:
17599     case ISD::SETULE:
17600       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17601     case ISD::SETUGT:
17602     case ISD::SETUGE:
17603       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17604     case ISD::SETLT:
17605     case ISD::SETLE:
17606       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17607     case ISD::SETGT:
17608     case ISD::SETGE:
17609       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17610     }
17611   // Check for x CC y ? y : x -- a min/max with reversed arms.
17612   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17613              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17614     switch (CC) {
17615     default: break;
17616     case ISD::SETULT:
17617     case ISD::SETULE:
17618       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17619     case ISD::SETUGT:
17620     case ISD::SETUGE:
17621       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17622     case ISD::SETLT:
17623     case ISD::SETLE:
17624       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17625     case ISD::SETGT:
17626     case ISD::SETGE:
17627       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17628     }
17629   }
17630
17631   return std::make_pair(Opc, NeedSplit);
17632 }
17633
17634 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17635 /// nodes.
17636 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17637                                     TargetLowering::DAGCombinerInfo &DCI,
17638                                     const X86Subtarget *Subtarget) {
17639   SDLoc DL(N);
17640   SDValue Cond = N->getOperand(0);
17641   // Get the LHS/RHS of the select.
17642   SDValue LHS = N->getOperand(1);
17643   SDValue RHS = N->getOperand(2);
17644   EVT VT = LHS.getValueType();
17645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17646
17647   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17648   // instructions match the semantics of the common C idiom x<y?x:y but not
17649   // x<=y?x:y, because of how they handle negative zero (which can be
17650   // ignored in unsafe-math mode).
17651   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17652       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17653       (Subtarget->hasSSE2() ||
17654        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17655     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17656
17657     unsigned Opcode = 0;
17658     // Check for x CC y ? x : y.
17659     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17660         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17661       switch (CC) {
17662       default: break;
17663       case ISD::SETULT:
17664         // Converting this to a min would handle NaNs incorrectly, and swapping
17665         // the operands would cause it to handle comparisons between positive
17666         // and negative zero incorrectly.
17667         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17668           if (!DAG.getTarget().Options.UnsafeFPMath &&
17669               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17670             break;
17671           std::swap(LHS, RHS);
17672         }
17673         Opcode = X86ISD::FMIN;
17674         break;
17675       case ISD::SETOLE:
17676         // Converting this to a min would handle comparisons between positive
17677         // and negative zero incorrectly.
17678         if (!DAG.getTarget().Options.UnsafeFPMath &&
17679             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17680           break;
17681         Opcode = X86ISD::FMIN;
17682         break;
17683       case ISD::SETULE:
17684         // Converting this to a min would handle both negative zeros and NaNs
17685         // incorrectly, but we can swap the operands to fix both.
17686         std::swap(LHS, RHS);
17687       case ISD::SETOLT:
17688       case ISD::SETLT:
17689       case ISD::SETLE:
17690         Opcode = X86ISD::FMIN;
17691         break;
17692
17693       case ISD::SETOGE:
17694         // Converting this to a max would handle comparisons between positive
17695         // and negative zero incorrectly.
17696         if (!DAG.getTarget().Options.UnsafeFPMath &&
17697             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17698           break;
17699         Opcode = X86ISD::FMAX;
17700         break;
17701       case ISD::SETUGT:
17702         // Converting this to a max would handle NaNs incorrectly, and swapping
17703         // the operands would cause it to handle comparisons between positive
17704         // and negative zero incorrectly.
17705         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17706           if (!DAG.getTarget().Options.UnsafeFPMath &&
17707               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17708             break;
17709           std::swap(LHS, RHS);
17710         }
17711         Opcode = X86ISD::FMAX;
17712         break;
17713       case ISD::SETUGE:
17714         // Converting this to a max would handle both negative zeros and NaNs
17715         // incorrectly, but we can swap the operands to fix both.
17716         std::swap(LHS, RHS);
17717       case ISD::SETOGT:
17718       case ISD::SETGT:
17719       case ISD::SETGE:
17720         Opcode = X86ISD::FMAX;
17721         break;
17722       }
17723     // Check for x CC y ? y : x -- a min/max with reversed arms.
17724     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17725                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17726       switch (CC) {
17727       default: break;
17728       case ISD::SETOGE:
17729         // Converting this to a min would handle comparisons between positive
17730         // and negative zero incorrectly, and swapping the operands would
17731         // cause it to handle NaNs incorrectly.
17732         if (!DAG.getTarget().Options.UnsafeFPMath &&
17733             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17734           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17735             break;
17736           std::swap(LHS, RHS);
17737         }
17738         Opcode = X86ISD::FMIN;
17739         break;
17740       case ISD::SETUGT:
17741         // Converting this to a min would handle NaNs incorrectly.
17742         if (!DAG.getTarget().Options.UnsafeFPMath &&
17743             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17744           break;
17745         Opcode = X86ISD::FMIN;
17746         break;
17747       case ISD::SETUGE:
17748         // Converting this to a min would handle both negative zeros and NaNs
17749         // incorrectly, but we can swap the operands to fix both.
17750         std::swap(LHS, RHS);
17751       case ISD::SETOGT:
17752       case ISD::SETGT:
17753       case ISD::SETGE:
17754         Opcode = X86ISD::FMIN;
17755         break;
17756
17757       case ISD::SETULT:
17758         // Converting this to a max would handle NaNs incorrectly.
17759         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17760           break;
17761         Opcode = X86ISD::FMAX;
17762         break;
17763       case ISD::SETOLE:
17764         // Converting this to a max would handle comparisons between positive
17765         // and negative zero incorrectly, and swapping the operands would
17766         // cause it to handle NaNs incorrectly.
17767         if (!DAG.getTarget().Options.UnsafeFPMath &&
17768             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17769           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17770             break;
17771           std::swap(LHS, RHS);
17772         }
17773         Opcode = X86ISD::FMAX;
17774         break;
17775       case ISD::SETULE:
17776         // Converting this to a max would handle both negative zeros and NaNs
17777         // incorrectly, but we can swap the operands to fix both.
17778         std::swap(LHS, RHS);
17779       case ISD::SETOLT:
17780       case ISD::SETLT:
17781       case ISD::SETLE:
17782         Opcode = X86ISD::FMAX;
17783         break;
17784       }
17785     }
17786
17787     if (Opcode)
17788       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17789   }
17790
17791   EVT CondVT = Cond.getValueType();
17792   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17793       CondVT.getVectorElementType() == MVT::i1) {
17794     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17795     // lowering on AVX-512. In this case we convert it to
17796     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17797     // The same situation for all 128 and 256-bit vectors of i8 and i16
17798     EVT OpVT = LHS.getValueType();
17799     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17800         (OpVT.getVectorElementType() == MVT::i8 ||
17801          OpVT.getVectorElementType() == MVT::i16)) {
17802       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17803       DCI.AddToWorklist(Cond.getNode());
17804       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17805     }
17806   }
17807   // If this is a select between two integer constants, try to do some
17808   // optimizations.
17809   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17810     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17811       // Don't do this for crazy integer types.
17812       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17813         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17814         // so that TrueC (the true value) is larger than FalseC.
17815         bool NeedsCondInvert = false;
17816
17817         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17818             // Efficiently invertible.
17819             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17820              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17821               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17822           NeedsCondInvert = true;
17823           std::swap(TrueC, FalseC);
17824         }
17825
17826         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17827         if (FalseC->getAPIntValue() == 0 &&
17828             TrueC->getAPIntValue().isPowerOf2()) {
17829           if (NeedsCondInvert) // Invert the condition if needed.
17830             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17831                                DAG.getConstant(1, Cond.getValueType()));
17832
17833           // Zero extend the condition if needed.
17834           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17835
17836           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17837           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17838                              DAG.getConstant(ShAmt, MVT::i8));
17839         }
17840
17841         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17842         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17843           if (NeedsCondInvert) // Invert the condition if needed.
17844             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17845                                DAG.getConstant(1, Cond.getValueType()));
17846
17847           // Zero extend the condition if needed.
17848           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17849                              FalseC->getValueType(0), Cond);
17850           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17851                              SDValue(FalseC, 0));
17852         }
17853
17854         // Optimize cases that will turn into an LEA instruction.  This requires
17855         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17856         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17857           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17858           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17859
17860           bool isFastMultiplier = false;
17861           if (Diff < 10) {
17862             switch ((unsigned char)Diff) {
17863               default: break;
17864               case 1:  // result = add base, cond
17865               case 2:  // result = lea base(    , cond*2)
17866               case 3:  // result = lea base(cond, cond*2)
17867               case 4:  // result = lea base(    , cond*4)
17868               case 5:  // result = lea base(cond, cond*4)
17869               case 8:  // result = lea base(    , cond*8)
17870               case 9:  // result = lea base(cond, cond*8)
17871                 isFastMultiplier = true;
17872                 break;
17873             }
17874           }
17875
17876           if (isFastMultiplier) {
17877             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17878             if (NeedsCondInvert) // Invert the condition if needed.
17879               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17880                                  DAG.getConstant(1, Cond.getValueType()));
17881
17882             // Zero extend the condition if needed.
17883             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17884                                Cond);
17885             // Scale the condition by the difference.
17886             if (Diff != 1)
17887               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17888                                  DAG.getConstant(Diff, Cond.getValueType()));
17889
17890             // Add the base if non-zero.
17891             if (FalseC->getAPIntValue() != 0)
17892               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17893                                  SDValue(FalseC, 0));
17894             return Cond;
17895           }
17896         }
17897       }
17898   }
17899
17900   // Canonicalize max and min:
17901   // (x > y) ? x : y -> (x >= y) ? x : y
17902   // (x < y) ? x : y -> (x <= y) ? x : y
17903   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17904   // the need for an extra compare
17905   // against zero. e.g.
17906   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17907   // subl   %esi, %edi
17908   // testl  %edi, %edi
17909   // movl   $0, %eax
17910   // cmovgl %edi, %eax
17911   // =>
17912   // xorl   %eax, %eax
17913   // subl   %esi, $edi
17914   // cmovsl %eax, %edi
17915   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17916       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17917       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17918     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17919     switch (CC) {
17920     default: break;
17921     case ISD::SETLT:
17922     case ISD::SETGT: {
17923       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17924       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17925                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17926       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17927     }
17928     }
17929   }
17930
17931   // Early exit check
17932   if (!TLI.isTypeLegal(VT))
17933     return SDValue();
17934
17935   // Match VSELECTs into subs with unsigned saturation.
17936   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17937       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17938       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17939        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17940     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17941
17942     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17943     // left side invert the predicate to simplify logic below.
17944     SDValue Other;
17945     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17946       Other = RHS;
17947       CC = ISD::getSetCCInverse(CC, true);
17948     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17949       Other = LHS;
17950     }
17951
17952     if (Other.getNode() && Other->getNumOperands() == 2 &&
17953         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17954       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17955       SDValue CondRHS = Cond->getOperand(1);
17956
17957       // Look for a general sub with unsigned saturation first.
17958       // x >= y ? x-y : 0 --> subus x, y
17959       // x >  y ? x-y : 0 --> subus x, y
17960       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17961           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17962         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17963
17964       // If the RHS is a constant we have to reverse the const canonicalization.
17965       // x > C-1 ? x+-C : 0 --> subus x, C
17966       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17967           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17968         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17969         if (CondRHS.getConstantOperandVal(0) == -A-1)
17970           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17971                              DAG.getConstant(-A, VT));
17972       }
17973
17974       // Another special case: If C was a sign bit, the sub has been
17975       // canonicalized into a xor.
17976       // FIXME: Would it be better to use computeKnownBits to determine whether
17977       //        it's safe to decanonicalize the xor?
17978       // x s< 0 ? x^C : 0 --> subus x, C
17979       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17980           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17981           isSplatVector(OpRHS.getNode())) {
17982         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17983         if (A.isSignBit())
17984           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17985       }
17986     }
17987   }
17988
17989   // Try to match a min/max vector operation.
17990   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17991     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17992     unsigned Opc = ret.first;
17993     bool NeedSplit = ret.second;
17994
17995     if (Opc && NeedSplit) {
17996       unsigned NumElems = VT.getVectorNumElements();
17997       // Extract the LHS vectors
17998       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17999       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18000
18001       // Extract the RHS vectors
18002       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18003       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18004
18005       // Create min/max for each subvector
18006       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18007       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18008
18009       // Merge the result
18010       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18011     } else if (Opc)
18012       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18013   }
18014
18015   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18016   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18017       // Check if SETCC has already been promoted
18018       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18019       // Check that condition value type matches vselect operand type
18020       CondVT == VT) { 
18021
18022     assert(Cond.getValueType().isVector() &&
18023            "vector select expects a vector selector!");
18024
18025     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18026     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18027
18028     if (!TValIsAllOnes && !FValIsAllZeros) {
18029       // Try invert the condition if true value is not all 1s and false value
18030       // is not all 0s.
18031       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18032       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18033
18034       if (TValIsAllZeros || FValIsAllOnes) {
18035         SDValue CC = Cond.getOperand(2);
18036         ISD::CondCode NewCC =
18037           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18038                                Cond.getOperand(0).getValueType().isInteger());
18039         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18040         std::swap(LHS, RHS);
18041         TValIsAllOnes = FValIsAllOnes;
18042         FValIsAllZeros = TValIsAllZeros;
18043       }
18044     }
18045
18046     if (TValIsAllOnes || FValIsAllZeros) {
18047       SDValue Ret;
18048
18049       if (TValIsAllOnes && FValIsAllZeros)
18050         Ret = Cond;
18051       else if (TValIsAllOnes)
18052         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18053                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18054       else if (FValIsAllZeros)
18055         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18056                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18057
18058       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18059     }
18060   }
18061
18062   // Try to fold this VSELECT into a MOVSS/MOVSD
18063   if (N->getOpcode() == ISD::VSELECT &&
18064       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18065     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18066         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18067       bool CanFold = false;
18068       unsigned NumElems = Cond.getNumOperands();
18069       SDValue A = LHS;
18070       SDValue B = RHS;
18071       
18072       if (isZero(Cond.getOperand(0))) {
18073         CanFold = true;
18074
18075         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18076         // fold (vselect <0,-1> -> (movsd A, B)
18077         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18078           CanFold = isAllOnes(Cond.getOperand(i));
18079       } else if (isAllOnes(Cond.getOperand(0))) {
18080         CanFold = true;
18081         std::swap(A, B);
18082
18083         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18084         // fold (vselect <-1,0> -> (movsd B, A)
18085         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18086           CanFold = isZero(Cond.getOperand(i));
18087       }
18088
18089       if (CanFold) {
18090         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18091           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18092         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18093       }
18094
18095       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18096         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18097         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18098         //                             (v2i64 (bitcast B)))))
18099         //
18100         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18101         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18102         //                             (v2f64 (bitcast B)))))
18103         //
18104         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18105         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18106         //                             (v2i64 (bitcast A)))))
18107         //
18108         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18109         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18110         //                             (v2f64 (bitcast A)))))
18111
18112         CanFold = (isZero(Cond.getOperand(0)) &&
18113                    isZero(Cond.getOperand(1)) &&
18114                    isAllOnes(Cond.getOperand(2)) &&
18115                    isAllOnes(Cond.getOperand(3)));
18116
18117         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18118             isAllOnes(Cond.getOperand(1)) &&
18119             isZero(Cond.getOperand(2)) &&
18120             isZero(Cond.getOperand(3))) {
18121           CanFold = true;
18122           std::swap(LHS, RHS);
18123         }
18124
18125         if (CanFold) {
18126           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18127           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18128           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18129           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18130                                                 NewB, DAG);
18131           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18132         }
18133       }
18134     }
18135   }
18136
18137   // If we know that this node is legal then we know that it is going to be
18138   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18139   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18140   // to simplify previous instructions.
18141   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18142       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18143     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18144
18145     // Don't optimize vector selects that map to mask-registers.
18146     if (BitWidth == 1)
18147       return SDValue();
18148
18149     // Check all uses of that condition operand to check whether it will be
18150     // consumed by non-BLEND instructions, which may depend on all bits are set
18151     // properly.
18152     for (SDNode::use_iterator I = Cond->use_begin(),
18153                               E = Cond->use_end(); I != E; ++I)
18154       if (I->getOpcode() != ISD::VSELECT)
18155         // TODO: Add other opcodes eventually lowered into BLEND.
18156         return SDValue();
18157
18158     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18159     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18160
18161     APInt KnownZero, KnownOne;
18162     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18163                                           DCI.isBeforeLegalizeOps());
18164     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18165         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18166       DCI.CommitTargetLoweringOpt(TLO);
18167   }
18168
18169   return SDValue();
18170 }
18171
18172 // Check whether a boolean test is testing a boolean value generated by
18173 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18174 // code.
18175 //
18176 // Simplify the following patterns:
18177 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18178 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18179 // to (Op EFLAGS Cond)
18180 //
18181 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18182 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18183 // to (Op EFLAGS !Cond)
18184 //
18185 // where Op could be BRCOND or CMOV.
18186 //
18187 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18188   // Quit if not CMP and SUB with its value result used.
18189   if (Cmp.getOpcode() != X86ISD::CMP &&
18190       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18191       return SDValue();
18192
18193   // Quit if not used as a boolean value.
18194   if (CC != X86::COND_E && CC != X86::COND_NE)
18195     return SDValue();
18196
18197   // Check CMP operands. One of them should be 0 or 1 and the other should be
18198   // an SetCC or extended from it.
18199   SDValue Op1 = Cmp.getOperand(0);
18200   SDValue Op2 = Cmp.getOperand(1);
18201
18202   SDValue SetCC;
18203   const ConstantSDNode* C = nullptr;
18204   bool needOppositeCond = (CC == X86::COND_E);
18205   bool checkAgainstTrue = false; // Is it a comparison against 1?
18206
18207   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18208     SetCC = Op2;
18209   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18210     SetCC = Op1;
18211   else // Quit if all operands are not constants.
18212     return SDValue();
18213
18214   if (C->getZExtValue() == 1) {
18215     needOppositeCond = !needOppositeCond;
18216     checkAgainstTrue = true;
18217   } else if (C->getZExtValue() != 0)
18218     // Quit if the constant is neither 0 or 1.
18219     return SDValue();
18220
18221   bool truncatedToBoolWithAnd = false;
18222   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18223   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18224          SetCC.getOpcode() == ISD::TRUNCATE ||
18225          SetCC.getOpcode() == ISD::AND) {
18226     if (SetCC.getOpcode() == ISD::AND) {
18227       int OpIdx = -1;
18228       ConstantSDNode *CS;
18229       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18230           CS->getZExtValue() == 1)
18231         OpIdx = 1;
18232       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18233           CS->getZExtValue() == 1)
18234         OpIdx = 0;
18235       if (OpIdx == -1)
18236         break;
18237       SetCC = SetCC.getOperand(OpIdx);
18238       truncatedToBoolWithAnd = true;
18239     } else
18240       SetCC = SetCC.getOperand(0);
18241   }
18242
18243   switch (SetCC.getOpcode()) {
18244   case X86ISD::SETCC_CARRY:
18245     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18246     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18247     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18248     // truncated to i1 using 'and'.
18249     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18250       break;
18251     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18252            "Invalid use of SETCC_CARRY!");
18253     // FALL THROUGH
18254   case X86ISD::SETCC:
18255     // Set the condition code or opposite one if necessary.
18256     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18257     if (needOppositeCond)
18258       CC = X86::GetOppositeBranchCondition(CC);
18259     return SetCC.getOperand(1);
18260   case X86ISD::CMOV: {
18261     // Check whether false/true value has canonical one, i.e. 0 or 1.
18262     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18263     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18264     // Quit if true value is not a constant.
18265     if (!TVal)
18266       return SDValue();
18267     // Quit if false value is not a constant.
18268     if (!FVal) {
18269       SDValue Op = SetCC.getOperand(0);
18270       // Skip 'zext' or 'trunc' node.
18271       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18272           Op.getOpcode() == ISD::TRUNCATE)
18273         Op = Op.getOperand(0);
18274       // A special case for rdrand/rdseed, where 0 is set if false cond is
18275       // found.
18276       if ((Op.getOpcode() != X86ISD::RDRAND &&
18277            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18278         return SDValue();
18279     }
18280     // Quit if false value is not the constant 0 or 1.
18281     bool FValIsFalse = true;
18282     if (FVal && FVal->getZExtValue() != 0) {
18283       if (FVal->getZExtValue() != 1)
18284         return SDValue();
18285       // If FVal is 1, opposite cond is needed.
18286       needOppositeCond = !needOppositeCond;
18287       FValIsFalse = false;
18288     }
18289     // Quit if TVal is not the constant opposite of FVal.
18290     if (FValIsFalse && TVal->getZExtValue() != 1)
18291       return SDValue();
18292     if (!FValIsFalse && TVal->getZExtValue() != 0)
18293       return SDValue();
18294     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18295     if (needOppositeCond)
18296       CC = X86::GetOppositeBranchCondition(CC);
18297     return SetCC.getOperand(3);
18298   }
18299   }
18300
18301   return SDValue();
18302 }
18303
18304 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18305 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18306                                   TargetLowering::DAGCombinerInfo &DCI,
18307                                   const X86Subtarget *Subtarget) {
18308   SDLoc DL(N);
18309
18310   // If the flag operand isn't dead, don't touch this CMOV.
18311   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18312     return SDValue();
18313
18314   SDValue FalseOp = N->getOperand(0);
18315   SDValue TrueOp = N->getOperand(1);
18316   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18317   SDValue Cond = N->getOperand(3);
18318
18319   if (CC == X86::COND_E || CC == X86::COND_NE) {
18320     switch (Cond.getOpcode()) {
18321     default: break;
18322     case X86ISD::BSR:
18323     case X86ISD::BSF:
18324       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18325       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18326         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18327     }
18328   }
18329
18330   SDValue Flags;
18331
18332   Flags = checkBoolTestSetCCCombine(Cond, CC);
18333   if (Flags.getNode() &&
18334       // Extra check as FCMOV only supports a subset of X86 cond.
18335       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18336     SDValue Ops[] = { FalseOp, TrueOp,
18337                       DAG.getConstant(CC, MVT::i8), Flags };
18338     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18339   }
18340
18341   // If this is a select between two integer constants, try to do some
18342   // optimizations.  Note that the operands are ordered the opposite of SELECT
18343   // operands.
18344   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18345     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18346       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18347       // larger than FalseC (the false value).
18348       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18349         CC = X86::GetOppositeBranchCondition(CC);
18350         std::swap(TrueC, FalseC);
18351         std::swap(TrueOp, FalseOp);
18352       }
18353
18354       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18355       // This is efficient for any integer data type (including i8/i16) and
18356       // shift amount.
18357       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18358         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18359                            DAG.getConstant(CC, MVT::i8), Cond);
18360
18361         // Zero extend the condition if needed.
18362         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18363
18364         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18365         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18366                            DAG.getConstant(ShAmt, MVT::i8));
18367         if (N->getNumValues() == 2)  // Dead flag value?
18368           return DCI.CombineTo(N, Cond, SDValue());
18369         return Cond;
18370       }
18371
18372       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18373       // for any integer data type, including i8/i16.
18374       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18375         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18376                            DAG.getConstant(CC, MVT::i8), Cond);
18377
18378         // Zero extend the condition if needed.
18379         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18380                            FalseC->getValueType(0), Cond);
18381         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18382                            SDValue(FalseC, 0));
18383
18384         if (N->getNumValues() == 2)  // Dead flag value?
18385           return DCI.CombineTo(N, Cond, SDValue());
18386         return Cond;
18387       }
18388
18389       // Optimize cases that will turn into an LEA instruction.  This requires
18390       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18391       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18392         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18393         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18394
18395         bool isFastMultiplier = false;
18396         if (Diff < 10) {
18397           switch ((unsigned char)Diff) {
18398           default: break;
18399           case 1:  // result = add base, cond
18400           case 2:  // result = lea base(    , cond*2)
18401           case 3:  // result = lea base(cond, cond*2)
18402           case 4:  // result = lea base(    , cond*4)
18403           case 5:  // result = lea base(cond, cond*4)
18404           case 8:  // result = lea base(    , cond*8)
18405           case 9:  // result = lea base(cond, cond*8)
18406             isFastMultiplier = true;
18407             break;
18408           }
18409         }
18410
18411         if (isFastMultiplier) {
18412           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18413           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18414                              DAG.getConstant(CC, MVT::i8), Cond);
18415           // Zero extend the condition if needed.
18416           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18417                              Cond);
18418           // Scale the condition by the difference.
18419           if (Diff != 1)
18420             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18421                                DAG.getConstant(Diff, Cond.getValueType()));
18422
18423           // Add the base if non-zero.
18424           if (FalseC->getAPIntValue() != 0)
18425             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18426                                SDValue(FalseC, 0));
18427           if (N->getNumValues() == 2)  // Dead flag value?
18428             return DCI.CombineTo(N, Cond, SDValue());
18429           return Cond;
18430         }
18431       }
18432     }
18433   }
18434
18435   // Handle these cases:
18436   //   (select (x != c), e, c) -> select (x != c), e, x),
18437   //   (select (x == c), c, e) -> select (x == c), x, e)
18438   // where the c is an integer constant, and the "select" is the combination
18439   // of CMOV and CMP.
18440   //
18441   // The rationale for this change is that the conditional-move from a constant
18442   // needs two instructions, however, conditional-move from a register needs
18443   // only one instruction.
18444   //
18445   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18446   //  some instruction-combining opportunities. This opt needs to be
18447   //  postponed as late as possible.
18448   //
18449   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18450     // the DCI.xxxx conditions are provided to postpone the optimization as
18451     // late as possible.
18452
18453     ConstantSDNode *CmpAgainst = nullptr;
18454     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18455         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18456         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18457
18458       if (CC == X86::COND_NE &&
18459           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18460         CC = X86::GetOppositeBranchCondition(CC);
18461         std::swap(TrueOp, FalseOp);
18462       }
18463
18464       if (CC == X86::COND_E &&
18465           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18466         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18467                           DAG.getConstant(CC, MVT::i8), Cond };
18468         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18469       }
18470     }
18471   }
18472
18473   return SDValue();
18474 }
18475
18476 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18477                                                 const X86Subtarget *Subtarget) {
18478   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18479   switch (IntNo) {
18480   default: return SDValue();
18481   // SSE/AVX/AVX2 blend intrinsics.
18482   case Intrinsic::x86_avx2_pblendvb:
18483   case Intrinsic::x86_avx2_pblendw:
18484   case Intrinsic::x86_avx2_pblendd_128:
18485   case Intrinsic::x86_avx2_pblendd_256:
18486     // Don't try to simplify this intrinsic if we don't have AVX2.
18487     if (!Subtarget->hasAVX2())
18488       return SDValue();
18489     // FALL-THROUGH
18490   case Intrinsic::x86_avx_blend_pd_256:
18491   case Intrinsic::x86_avx_blend_ps_256:
18492   case Intrinsic::x86_avx_blendv_pd_256:
18493   case Intrinsic::x86_avx_blendv_ps_256:
18494     // Don't try to simplify this intrinsic if we don't have AVX.
18495     if (!Subtarget->hasAVX())
18496       return SDValue();
18497     // FALL-THROUGH
18498   case Intrinsic::x86_sse41_pblendw:
18499   case Intrinsic::x86_sse41_blendpd:
18500   case Intrinsic::x86_sse41_blendps:
18501   case Intrinsic::x86_sse41_blendvps:
18502   case Intrinsic::x86_sse41_blendvpd:
18503   case Intrinsic::x86_sse41_pblendvb: {
18504     SDValue Op0 = N->getOperand(1);
18505     SDValue Op1 = N->getOperand(2);
18506     SDValue Mask = N->getOperand(3);
18507
18508     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18509     if (!Subtarget->hasSSE41())
18510       return SDValue();
18511
18512     // fold (blend A, A, Mask) -> A
18513     if (Op0 == Op1)
18514       return Op0;
18515     // fold (blend A, B, allZeros) -> A
18516     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18517       return Op0;
18518     // fold (blend A, B, allOnes) -> B
18519     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18520       return Op1;
18521     
18522     // Simplify the case where the mask is a constant i32 value.
18523     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18524       if (C->isNullValue())
18525         return Op0;
18526       if (C->isAllOnesValue())
18527         return Op1;
18528     }
18529   }
18530
18531   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18532   case Intrinsic::x86_sse2_psrai_w:
18533   case Intrinsic::x86_sse2_psrai_d:
18534   case Intrinsic::x86_avx2_psrai_w:
18535   case Intrinsic::x86_avx2_psrai_d:
18536   case Intrinsic::x86_sse2_psra_w:
18537   case Intrinsic::x86_sse2_psra_d:
18538   case Intrinsic::x86_avx2_psra_w:
18539   case Intrinsic::x86_avx2_psra_d: {
18540     SDValue Op0 = N->getOperand(1);
18541     SDValue Op1 = N->getOperand(2);
18542     EVT VT = Op0.getValueType();
18543     assert(VT.isVector() && "Expected a vector type!");
18544
18545     if (isa<BuildVectorSDNode>(Op1))
18546       Op1 = Op1.getOperand(0);
18547
18548     if (!isa<ConstantSDNode>(Op1))
18549       return SDValue();
18550
18551     EVT SVT = VT.getVectorElementType();
18552     unsigned SVTBits = SVT.getSizeInBits();
18553
18554     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18555     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18556     uint64_t ShAmt = C.getZExtValue();
18557
18558     // Don't try to convert this shift into a ISD::SRA if the shift
18559     // count is bigger than or equal to the element size.
18560     if (ShAmt >= SVTBits)
18561       return SDValue();
18562
18563     // Trivial case: if the shift count is zero, then fold this
18564     // into the first operand.
18565     if (ShAmt == 0)
18566       return Op0;
18567
18568     // Replace this packed shift intrinsic with a target independent
18569     // shift dag node.
18570     SDValue Splat = DAG.getConstant(C, VT);
18571     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18572   }
18573   }
18574 }
18575
18576 /// PerformMulCombine - Optimize a single multiply with constant into two
18577 /// in order to implement it with two cheaper instructions, e.g.
18578 /// LEA + SHL, LEA + LEA.
18579 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18580                                  TargetLowering::DAGCombinerInfo &DCI) {
18581   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18582     return SDValue();
18583
18584   EVT VT = N->getValueType(0);
18585   if (VT != MVT::i64)
18586     return SDValue();
18587
18588   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18589   if (!C)
18590     return SDValue();
18591   uint64_t MulAmt = C->getZExtValue();
18592   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18593     return SDValue();
18594
18595   uint64_t MulAmt1 = 0;
18596   uint64_t MulAmt2 = 0;
18597   if ((MulAmt % 9) == 0) {
18598     MulAmt1 = 9;
18599     MulAmt2 = MulAmt / 9;
18600   } else if ((MulAmt % 5) == 0) {
18601     MulAmt1 = 5;
18602     MulAmt2 = MulAmt / 5;
18603   } else if ((MulAmt % 3) == 0) {
18604     MulAmt1 = 3;
18605     MulAmt2 = MulAmt / 3;
18606   }
18607   if (MulAmt2 &&
18608       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18609     SDLoc DL(N);
18610
18611     if (isPowerOf2_64(MulAmt2) &&
18612         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18613       // If second multiplifer is pow2, issue it first. We want the multiply by
18614       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18615       // is an add.
18616       std::swap(MulAmt1, MulAmt2);
18617
18618     SDValue NewMul;
18619     if (isPowerOf2_64(MulAmt1))
18620       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18621                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18622     else
18623       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18624                            DAG.getConstant(MulAmt1, VT));
18625
18626     if (isPowerOf2_64(MulAmt2))
18627       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18628                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18629     else
18630       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18631                            DAG.getConstant(MulAmt2, VT));
18632
18633     // Do not add new nodes to DAG combiner worklist.
18634     DCI.CombineTo(N, NewMul, false);
18635   }
18636   return SDValue();
18637 }
18638
18639 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18640   SDValue N0 = N->getOperand(0);
18641   SDValue N1 = N->getOperand(1);
18642   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18643   EVT VT = N0.getValueType();
18644
18645   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18646   // since the result of setcc_c is all zero's or all ones.
18647   if (VT.isInteger() && !VT.isVector() &&
18648       N1C && N0.getOpcode() == ISD::AND &&
18649       N0.getOperand(1).getOpcode() == ISD::Constant) {
18650     SDValue N00 = N0.getOperand(0);
18651     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18652         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18653           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18654          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18655       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18656       APInt ShAmt = N1C->getAPIntValue();
18657       Mask = Mask.shl(ShAmt);
18658       if (Mask != 0)
18659         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18660                            N00, DAG.getConstant(Mask, VT));
18661     }
18662   }
18663
18664   // Hardware support for vector shifts is sparse which makes us scalarize the
18665   // vector operations in many cases. Also, on sandybridge ADD is faster than
18666   // shl.
18667   // (shl V, 1) -> add V,V
18668   if (isSplatVector(N1.getNode())) {
18669     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18670     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18671     // We shift all of the values by one. In many cases we do not have
18672     // hardware support for this operation. This is better expressed as an ADD
18673     // of two values.
18674     if (N1C && (1 == N1C->getZExtValue())) {
18675       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18676     }
18677   }
18678
18679   return SDValue();
18680 }
18681
18682 /// \brief Returns a vector of 0s if the node in input is a vector logical
18683 /// shift by a constant amount which is known to be bigger than or equal
18684 /// to the vector element size in bits.
18685 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18686                                       const X86Subtarget *Subtarget) {
18687   EVT VT = N->getValueType(0);
18688
18689   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18690       (!Subtarget->hasInt256() ||
18691        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18692     return SDValue();
18693
18694   SDValue Amt = N->getOperand(1);
18695   SDLoc DL(N);
18696   if (isSplatVector(Amt.getNode())) {
18697     SDValue SclrAmt = Amt->getOperand(0);
18698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18699       APInt ShiftAmt = C->getAPIntValue();
18700       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18701
18702       // SSE2/AVX2 logical shifts always return a vector of 0s
18703       // if the shift amount is bigger than or equal to
18704       // the element size. The constant shift amount will be
18705       // encoded as a 8-bit immediate.
18706       if (ShiftAmt.trunc(8).uge(MaxAmount))
18707         return getZeroVector(VT, Subtarget, DAG, DL);
18708     }
18709   }
18710
18711   return SDValue();
18712 }
18713
18714 /// PerformShiftCombine - Combine shifts.
18715 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18716                                    TargetLowering::DAGCombinerInfo &DCI,
18717                                    const X86Subtarget *Subtarget) {
18718   if (N->getOpcode() == ISD::SHL) {
18719     SDValue V = PerformSHLCombine(N, DAG);
18720     if (V.getNode()) return V;
18721   }
18722
18723   if (N->getOpcode() != ISD::SRA) {
18724     // Try to fold this logical shift into a zero vector.
18725     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18726     if (V.getNode()) return V;
18727   }
18728
18729   return SDValue();
18730 }
18731
18732 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18733 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18734 // and friends.  Likewise for OR -> CMPNEQSS.
18735 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18736                             TargetLowering::DAGCombinerInfo &DCI,
18737                             const X86Subtarget *Subtarget) {
18738   unsigned opcode;
18739
18740   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18741   // we're requiring SSE2 for both.
18742   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18743     SDValue N0 = N->getOperand(0);
18744     SDValue N1 = N->getOperand(1);
18745     SDValue CMP0 = N0->getOperand(1);
18746     SDValue CMP1 = N1->getOperand(1);
18747     SDLoc DL(N);
18748
18749     // The SETCCs should both refer to the same CMP.
18750     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18751       return SDValue();
18752
18753     SDValue CMP00 = CMP0->getOperand(0);
18754     SDValue CMP01 = CMP0->getOperand(1);
18755     EVT     VT    = CMP00.getValueType();
18756
18757     if (VT == MVT::f32 || VT == MVT::f64) {
18758       bool ExpectingFlags = false;
18759       // Check for any users that want flags:
18760       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18761            !ExpectingFlags && UI != UE; ++UI)
18762         switch (UI->getOpcode()) {
18763         default:
18764         case ISD::BR_CC:
18765         case ISD::BRCOND:
18766         case ISD::SELECT:
18767           ExpectingFlags = true;
18768           break;
18769         case ISD::CopyToReg:
18770         case ISD::SIGN_EXTEND:
18771         case ISD::ZERO_EXTEND:
18772         case ISD::ANY_EXTEND:
18773           break;
18774         }
18775
18776       if (!ExpectingFlags) {
18777         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18778         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18779
18780         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18781           X86::CondCode tmp = cc0;
18782           cc0 = cc1;
18783           cc1 = tmp;
18784         }
18785
18786         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18787             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18788           // FIXME: need symbolic constants for these magic numbers.
18789           // See X86ATTInstPrinter.cpp:printSSECC().
18790           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18791           if (Subtarget->hasAVX512()) {
18792             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18793                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18794             if (N->getValueType(0) != MVT::i1)
18795               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18796                                  FSetCC);
18797             return FSetCC;
18798           }
18799           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18800                                               CMP00.getValueType(), CMP00, CMP01,
18801                                               DAG.getConstant(x86cc, MVT::i8));
18802
18803           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18804           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18805
18806           if (is64BitFP && !Subtarget->is64Bit()) {
18807             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18808             // 64-bit integer, since that's not a legal type. Since
18809             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18810             // bits, but can do this little dance to extract the lowest 32 bits
18811             // and work with those going forward.
18812             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18813                                            OnesOrZeroesF);
18814             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18815                                            Vector64);
18816             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18817                                         Vector32, DAG.getIntPtrConstant(0));
18818             IntVT = MVT::i32;
18819           }
18820
18821           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18822           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18823                                       DAG.getConstant(1, IntVT));
18824           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18825           return OneBitOfTruth;
18826         }
18827       }
18828     }
18829   }
18830   return SDValue();
18831 }
18832
18833 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18834 /// so it can be folded inside ANDNP.
18835 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18836   EVT VT = N->getValueType(0);
18837
18838   // Match direct AllOnes for 128 and 256-bit vectors
18839   if (ISD::isBuildVectorAllOnes(N))
18840     return true;
18841
18842   // Look through a bit convert.
18843   if (N->getOpcode() == ISD::BITCAST)
18844     N = N->getOperand(0).getNode();
18845
18846   // Sometimes the operand may come from a insert_subvector building a 256-bit
18847   // allones vector
18848   if (VT.is256BitVector() &&
18849       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18850     SDValue V1 = N->getOperand(0);
18851     SDValue V2 = N->getOperand(1);
18852
18853     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18854         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18855         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18856         ISD::isBuildVectorAllOnes(V2.getNode()))
18857       return true;
18858   }
18859
18860   return false;
18861 }
18862
18863 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18864 // register. In most cases we actually compare or select YMM-sized registers
18865 // and mixing the two types creates horrible code. This method optimizes
18866 // some of the transition sequences.
18867 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18868                                  TargetLowering::DAGCombinerInfo &DCI,
18869                                  const X86Subtarget *Subtarget) {
18870   EVT VT = N->getValueType(0);
18871   if (!VT.is256BitVector())
18872     return SDValue();
18873
18874   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18875           N->getOpcode() == ISD::ZERO_EXTEND ||
18876           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18877
18878   SDValue Narrow = N->getOperand(0);
18879   EVT NarrowVT = Narrow->getValueType(0);
18880   if (!NarrowVT.is128BitVector())
18881     return SDValue();
18882
18883   if (Narrow->getOpcode() != ISD::XOR &&
18884       Narrow->getOpcode() != ISD::AND &&
18885       Narrow->getOpcode() != ISD::OR)
18886     return SDValue();
18887
18888   SDValue N0  = Narrow->getOperand(0);
18889   SDValue N1  = Narrow->getOperand(1);
18890   SDLoc DL(Narrow);
18891
18892   // The Left side has to be a trunc.
18893   if (N0.getOpcode() != ISD::TRUNCATE)
18894     return SDValue();
18895
18896   // The type of the truncated inputs.
18897   EVT WideVT = N0->getOperand(0)->getValueType(0);
18898   if (WideVT != VT)
18899     return SDValue();
18900
18901   // The right side has to be a 'trunc' or a constant vector.
18902   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18903   bool RHSConst = (isSplatVector(N1.getNode()) &&
18904                    isa<ConstantSDNode>(N1->getOperand(0)));
18905   if (!RHSTrunc && !RHSConst)
18906     return SDValue();
18907
18908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18909
18910   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18911     return SDValue();
18912
18913   // Set N0 and N1 to hold the inputs to the new wide operation.
18914   N0 = N0->getOperand(0);
18915   if (RHSConst) {
18916     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18917                      N1->getOperand(0));
18918     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18919     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18920   } else if (RHSTrunc) {
18921     N1 = N1->getOperand(0);
18922   }
18923
18924   // Generate the wide operation.
18925   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18926   unsigned Opcode = N->getOpcode();
18927   switch (Opcode) {
18928   case ISD::ANY_EXTEND:
18929     return Op;
18930   case ISD::ZERO_EXTEND: {
18931     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18932     APInt Mask = APInt::getAllOnesValue(InBits);
18933     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18934     return DAG.getNode(ISD::AND, DL, VT,
18935                        Op, DAG.getConstant(Mask, VT));
18936   }
18937   case ISD::SIGN_EXTEND:
18938     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18939                        Op, DAG.getValueType(NarrowVT));
18940   default:
18941     llvm_unreachable("Unexpected opcode");
18942   }
18943 }
18944
18945 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18946                                  TargetLowering::DAGCombinerInfo &DCI,
18947                                  const X86Subtarget *Subtarget) {
18948   EVT VT = N->getValueType(0);
18949   if (DCI.isBeforeLegalizeOps())
18950     return SDValue();
18951
18952   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18953   if (R.getNode())
18954     return R;
18955
18956   // Create BEXTR instructions
18957   // BEXTR is ((X >> imm) & (2**size-1))
18958   if (VT == MVT::i32 || VT == MVT::i64) {
18959     SDValue N0 = N->getOperand(0);
18960     SDValue N1 = N->getOperand(1);
18961     SDLoc DL(N);
18962
18963     // Check for BEXTR.
18964     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18965         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18966       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18967       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18968       if (MaskNode && ShiftNode) {
18969         uint64_t Mask = MaskNode->getZExtValue();
18970         uint64_t Shift = ShiftNode->getZExtValue();
18971         if (isMask_64(Mask)) {
18972           uint64_t MaskSize = CountPopulation_64(Mask);
18973           if (Shift + MaskSize <= VT.getSizeInBits())
18974             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18975                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18976         }
18977       }
18978     } // BEXTR
18979
18980     return SDValue();
18981   }
18982
18983   // Want to form ANDNP nodes:
18984   // 1) In the hopes of then easily combining them with OR and AND nodes
18985   //    to form PBLEND/PSIGN.
18986   // 2) To match ANDN packed intrinsics
18987   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18988     return SDValue();
18989
18990   SDValue N0 = N->getOperand(0);
18991   SDValue N1 = N->getOperand(1);
18992   SDLoc DL(N);
18993
18994   // Check LHS for vnot
18995   if (N0.getOpcode() == ISD::XOR &&
18996       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18997       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18998     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18999
19000   // Check RHS for vnot
19001   if (N1.getOpcode() == ISD::XOR &&
19002       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19003       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19004     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19005
19006   return SDValue();
19007 }
19008
19009 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19010                                 TargetLowering::DAGCombinerInfo &DCI,
19011                                 const X86Subtarget *Subtarget) {
19012   if (DCI.isBeforeLegalizeOps())
19013     return SDValue();
19014
19015   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19016   if (R.getNode())
19017     return R;
19018
19019   SDValue N0 = N->getOperand(0);
19020   SDValue N1 = N->getOperand(1);
19021   EVT VT = N->getValueType(0);
19022
19023   // look for psign/blend
19024   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19025     if (!Subtarget->hasSSSE3() ||
19026         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19027       return SDValue();
19028
19029     // Canonicalize pandn to RHS
19030     if (N0.getOpcode() == X86ISD::ANDNP)
19031       std::swap(N0, N1);
19032     // or (and (m, y), (pandn m, x))
19033     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19034       SDValue Mask = N1.getOperand(0);
19035       SDValue X    = N1.getOperand(1);
19036       SDValue Y;
19037       if (N0.getOperand(0) == Mask)
19038         Y = N0.getOperand(1);
19039       if (N0.getOperand(1) == Mask)
19040         Y = N0.getOperand(0);
19041
19042       // Check to see if the mask appeared in both the AND and ANDNP and
19043       if (!Y.getNode())
19044         return SDValue();
19045
19046       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19047       // Look through mask bitcast.
19048       if (Mask.getOpcode() == ISD::BITCAST)
19049         Mask = Mask.getOperand(0);
19050       if (X.getOpcode() == ISD::BITCAST)
19051         X = X.getOperand(0);
19052       if (Y.getOpcode() == ISD::BITCAST)
19053         Y = Y.getOperand(0);
19054
19055       EVT MaskVT = Mask.getValueType();
19056
19057       // Validate that the Mask operand is a vector sra node.
19058       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19059       // there is no psrai.b
19060       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19061       unsigned SraAmt = ~0;
19062       if (Mask.getOpcode() == ISD::SRA) {
19063         SDValue Amt = Mask.getOperand(1);
19064         if (isSplatVector(Amt.getNode())) {
19065           SDValue SclrAmt = Amt->getOperand(0);
19066           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19067             SraAmt = C->getZExtValue();
19068         }
19069       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19070         SDValue SraC = Mask.getOperand(1);
19071         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19072       }
19073       if ((SraAmt + 1) != EltBits)
19074         return SDValue();
19075
19076       SDLoc DL(N);
19077
19078       // Now we know we at least have a plendvb with the mask val.  See if
19079       // we can form a psignb/w/d.
19080       // psign = x.type == y.type == mask.type && y = sub(0, x);
19081       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19082           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19083           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19084         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19085                "Unsupported VT for PSIGN");
19086         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19087         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19088       }
19089       // PBLENDVB only available on SSE 4.1
19090       if (!Subtarget->hasSSE41())
19091         return SDValue();
19092
19093       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19094
19095       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19096       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19097       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19098       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19099       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19100     }
19101   }
19102
19103   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19104     return SDValue();
19105
19106   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19107   MachineFunction &MF = DAG.getMachineFunction();
19108   bool OptForSize = MF.getFunction()->getAttributes().
19109     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19110
19111   // SHLD/SHRD instructions have lower register pressure, but on some
19112   // platforms they have higher latency than the equivalent
19113   // series of shifts/or that would otherwise be generated.
19114   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19115   // have higher latencies and we are not optimizing for size.
19116   if (!OptForSize && Subtarget->isSHLDSlow())
19117     return SDValue();
19118
19119   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19120     std::swap(N0, N1);
19121   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19122     return SDValue();
19123   if (!N0.hasOneUse() || !N1.hasOneUse())
19124     return SDValue();
19125
19126   SDValue ShAmt0 = N0.getOperand(1);
19127   if (ShAmt0.getValueType() != MVT::i8)
19128     return SDValue();
19129   SDValue ShAmt1 = N1.getOperand(1);
19130   if (ShAmt1.getValueType() != MVT::i8)
19131     return SDValue();
19132   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19133     ShAmt0 = ShAmt0.getOperand(0);
19134   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19135     ShAmt1 = ShAmt1.getOperand(0);
19136
19137   SDLoc DL(N);
19138   unsigned Opc = X86ISD::SHLD;
19139   SDValue Op0 = N0.getOperand(0);
19140   SDValue Op1 = N1.getOperand(0);
19141   if (ShAmt0.getOpcode() == ISD::SUB) {
19142     Opc = X86ISD::SHRD;
19143     std::swap(Op0, Op1);
19144     std::swap(ShAmt0, ShAmt1);
19145   }
19146
19147   unsigned Bits = VT.getSizeInBits();
19148   if (ShAmt1.getOpcode() == ISD::SUB) {
19149     SDValue Sum = ShAmt1.getOperand(0);
19150     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19151       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19152       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19153         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19154       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19155         return DAG.getNode(Opc, DL, VT,
19156                            Op0, Op1,
19157                            DAG.getNode(ISD::TRUNCATE, DL,
19158                                        MVT::i8, ShAmt0));
19159     }
19160   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19161     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19162     if (ShAmt0C &&
19163         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19164       return DAG.getNode(Opc, DL, VT,
19165                          N0.getOperand(0), N1.getOperand(0),
19166                          DAG.getNode(ISD::TRUNCATE, DL,
19167                                        MVT::i8, ShAmt0));
19168   }
19169
19170   return SDValue();
19171 }
19172
19173 // Generate NEG and CMOV for integer abs.
19174 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19175   EVT VT = N->getValueType(0);
19176
19177   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19178   // 8-bit integer abs to NEG and CMOV.
19179   if (VT.isInteger() && VT.getSizeInBits() == 8)
19180     return SDValue();
19181
19182   SDValue N0 = N->getOperand(0);
19183   SDValue N1 = N->getOperand(1);
19184   SDLoc DL(N);
19185
19186   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19187   // and change it to SUB and CMOV.
19188   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19189       N0.getOpcode() == ISD::ADD &&
19190       N0.getOperand(1) == N1 &&
19191       N1.getOpcode() == ISD::SRA &&
19192       N1.getOperand(0) == N0.getOperand(0))
19193     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19194       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19195         // Generate SUB & CMOV.
19196         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19197                                   DAG.getConstant(0, VT), N0.getOperand(0));
19198
19199         SDValue Ops[] = { N0.getOperand(0), Neg,
19200                           DAG.getConstant(X86::COND_GE, MVT::i8),
19201                           SDValue(Neg.getNode(), 1) };
19202         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19203       }
19204   return SDValue();
19205 }
19206
19207 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19208 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19209                                  TargetLowering::DAGCombinerInfo &DCI,
19210                                  const X86Subtarget *Subtarget) {
19211   if (DCI.isBeforeLegalizeOps())
19212     return SDValue();
19213
19214   if (Subtarget->hasCMov()) {
19215     SDValue RV = performIntegerAbsCombine(N, DAG);
19216     if (RV.getNode())
19217       return RV;
19218   }
19219
19220   return SDValue();
19221 }
19222
19223 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19224 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19225                                   TargetLowering::DAGCombinerInfo &DCI,
19226                                   const X86Subtarget *Subtarget) {
19227   LoadSDNode *Ld = cast<LoadSDNode>(N);
19228   EVT RegVT = Ld->getValueType(0);
19229   EVT MemVT = Ld->getMemoryVT();
19230   SDLoc dl(Ld);
19231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19232   unsigned RegSz = RegVT.getSizeInBits();
19233
19234   // On Sandybridge unaligned 256bit loads are inefficient.
19235   ISD::LoadExtType Ext = Ld->getExtensionType();
19236   unsigned Alignment = Ld->getAlignment();
19237   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19238   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19239       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19240     unsigned NumElems = RegVT.getVectorNumElements();
19241     if (NumElems < 2)
19242       return SDValue();
19243
19244     SDValue Ptr = Ld->getBasePtr();
19245     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19246
19247     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19248                                   NumElems/2);
19249     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19250                                 Ld->getPointerInfo(), Ld->isVolatile(),
19251                                 Ld->isNonTemporal(), Ld->isInvariant(),
19252                                 Alignment);
19253     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19254     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19255                                 Ld->getPointerInfo(), Ld->isVolatile(),
19256                                 Ld->isNonTemporal(), Ld->isInvariant(),
19257                                 std::min(16U, Alignment));
19258     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19259                              Load1.getValue(1),
19260                              Load2.getValue(1));
19261
19262     SDValue NewVec = DAG.getUNDEF(RegVT);
19263     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19264     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19265     return DCI.CombineTo(N, NewVec, TF, true);
19266   }
19267
19268   // If this is a vector EXT Load then attempt to optimize it using a
19269   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19270   // expansion is still better than scalar code.
19271   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19272   // emit a shuffle and a arithmetic shift.
19273   // TODO: It is possible to support ZExt by zeroing the undef values
19274   // during the shuffle phase or after the shuffle.
19275   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19276       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19277     assert(MemVT != RegVT && "Cannot extend to the same type");
19278     assert(MemVT.isVector() && "Must load a vector from memory");
19279
19280     unsigned NumElems = RegVT.getVectorNumElements();
19281     unsigned MemSz = MemVT.getSizeInBits();
19282     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19283
19284     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19285       return SDValue();
19286
19287     // All sizes must be a power of two.
19288     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19289       return SDValue();
19290
19291     // Attempt to load the original value using scalar loads.
19292     // Find the largest scalar type that divides the total loaded size.
19293     MVT SclrLoadTy = MVT::i8;
19294     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19295          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19296       MVT Tp = (MVT::SimpleValueType)tp;
19297       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19298         SclrLoadTy = Tp;
19299       }
19300     }
19301
19302     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19303     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19304         (64 <= MemSz))
19305       SclrLoadTy = MVT::f64;
19306
19307     // Calculate the number of scalar loads that we need to perform
19308     // in order to load our vector from memory.
19309     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19310     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19311       return SDValue();
19312
19313     unsigned loadRegZize = RegSz;
19314     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19315       loadRegZize /= 2;
19316
19317     // Represent our vector as a sequence of elements which are the
19318     // largest scalar that we can load.
19319     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19320       loadRegZize/SclrLoadTy.getSizeInBits());
19321
19322     // Represent the data using the same element type that is stored in
19323     // memory. In practice, we ''widen'' MemVT.
19324     EVT WideVecVT =
19325           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19326                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19327
19328     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19329       "Invalid vector type");
19330
19331     // We can't shuffle using an illegal type.
19332     if (!TLI.isTypeLegal(WideVecVT))
19333       return SDValue();
19334
19335     SmallVector<SDValue, 8> Chains;
19336     SDValue Ptr = Ld->getBasePtr();
19337     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19338                                         TLI.getPointerTy());
19339     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19340
19341     for (unsigned i = 0; i < NumLoads; ++i) {
19342       // Perform a single load.
19343       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19344                                        Ptr, Ld->getPointerInfo(),
19345                                        Ld->isVolatile(), Ld->isNonTemporal(),
19346                                        Ld->isInvariant(), Ld->getAlignment());
19347       Chains.push_back(ScalarLoad.getValue(1));
19348       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19349       // another round of DAGCombining.
19350       if (i == 0)
19351         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19352       else
19353         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19354                           ScalarLoad, DAG.getIntPtrConstant(i));
19355
19356       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19357     }
19358
19359     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19360
19361     // Bitcast the loaded value to a vector of the original element type, in
19362     // the size of the target vector type.
19363     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19364     unsigned SizeRatio = RegSz/MemSz;
19365
19366     if (Ext == ISD::SEXTLOAD) {
19367       // If we have SSE4.1 we can directly emit a VSEXT node.
19368       if (Subtarget->hasSSE41()) {
19369         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19370         return DCI.CombineTo(N, Sext, TF, true);
19371       }
19372
19373       // Otherwise we'll shuffle the small elements in the high bits of the
19374       // larger type and perform an arithmetic shift. If the shift is not legal
19375       // it's better to scalarize.
19376       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19377         return SDValue();
19378
19379       // Redistribute the loaded elements into the different locations.
19380       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19381       for (unsigned i = 0; i != NumElems; ++i)
19382         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19383
19384       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19385                                            DAG.getUNDEF(WideVecVT),
19386                                            &ShuffleVec[0]);
19387
19388       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19389
19390       // Build the arithmetic shift.
19391       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19392                      MemVT.getVectorElementType().getSizeInBits();
19393       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19394                           DAG.getConstant(Amt, RegVT));
19395
19396       return DCI.CombineTo(N, Shuff, TF, true);
19397     }
19398
19399     // Redistribute the loaded elements into the different locations.
19400     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19401     for (unsigned i = 0; i != NumElems; ++i)
19402       ShuffleVec[i*SizeRatio] = i;
19403
19404     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19405                                          DAG.getUNDEF(WideVecVT),
19406                                          &ShuffleVec[0]);
19407
19408     // Bitcast to the requested type.
19409     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19410     // Replace the original load with the new sequence
19411     // and return the new chain.
19412     return DCI.CombineTo(N, Shuff, TF, true);
19413   }
19414
19415   return SDValue();
19416 }
19417
19418 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19419 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19420                                    const X86Subtarget *Subtarget) {
19421   StoreSDNode *St = cast<StoreSDNode>(N);
19422   EVT VT = St->getValue().getValueType();
19423   EVT StVT = St->getMemoryVT();
19424   SDLoc dl(St);
19425   SDValue StoredVal = St->getOperand(1);
19426   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19427
19428   // If we are saving a concatenation of two XMM registers, perform two stores.
19429   // On Sandy Bridge, 256-bit memory operations are executed by two
19430   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19431   // memory  operation.
19432   unsigned Alignment = St->getAlignment();
19433   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19434   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19435       StVT == VT && !IsAligned) {
19436     unsigned NumElems = VT.getVectorNumElements();
19437     if (NumElems < 2)
19438       return SDValue();
19439
19440     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19441     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19442
19443     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19444     SDValue Ptr0 = St->getBasePtr();
19445     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19446
19447     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19448                                 St->getPointerInfo(), St->isVolatile(),
19449                                 St->isNonTemporal(), Alignment);
19450     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19451                                 St->getPointerInfo(), St->isVolatile(),
19452                                 St->isNonTemporal(),
19453                                 std::min(16U, Alignment));
19454     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19455   }
19456
19457   // Optimize trunc store (of multiple scalars) to shuffle and store.
19458   // First, pack all of the elements in one place. Next, store to memory
19459   // in fewer chunks.
19460   if (St->isTruncatingStore() && VT.isVector()) {
19461     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19462     unsigned NumElems = VT.getVectorNumElements();
19463     assert(StVT != VT && "Cannot truncate to the same type");
19464     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19465     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19466
19467     // From, To sizes and ElemCount must be pow of two
19468     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19469     // We are going to use the original vector elt for storing.
19470     // Accumulated smaller vector elements must be a multiple of the store size.
19471     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19472
19473     unsigned SizeRatio  = FromSz / ToSz;
19474
19475     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19476
19477     // Create a type on which we perform the shuffle
19478     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19479             StVT.getScalarType(), NumElems*SizeRatio);
19480
19481     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19482
19483     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19484     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19485     for (unsigned i = 0; i != NumElems; ++i)
19486       ShuffleVec[i] = i * SizeRatio;
19487
19488     // Can't shuffle using an illegal type.
19489     if (!TLI.isTypeLegal(WideVecVT))
19490       return SDValue();
19491
19492     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19493                                          DAG.getUNDEF(WideVecVT),
19494                                          &ShuffleVec[0]);
19495     // At this point all of the data is stored at the bottom of the
19496     // register. We now need to save it to mem.
19497
19498     // Find the largest store unit
19499     MVT StoreType = MVT::i8;
19500     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19501          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19502       MVT Tp = (MVT::SimpleValueType)tp;
19503       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19504         StoreType = Tp;
19505     }
19506
19507     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19508     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19509         (64 <= NumElems * ToSz))
19510       StoreType = MVT::f64;
19511
19512     // Bitcast the original vector into a vector of store-size units
19513     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19514             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19515     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19516     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19517     SmallVector<SDValue, 8> Chains;
19518     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19519                                         TLI.getPointerTy());
19520     SDValue Ptr = St->getBasePtr();
19521
19522     // Perform one or more big stores into memory.
19523     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19524       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19525                                    StoreType, ShuffWide,
19526                                    DAG.getIntPtrConstant(i));
19527       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19528                                 St->getPointerInfo(), St->isVolatile(),
19529                                 St->isNonTemporal(), St->getAlignment());
19530       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19531       Chains.push_back(Ch);
19532     }
19533
19534     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19535   }
19536
19537   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19538   // the FP state in cases where an emms may be missing.
19539   // A preferable solution to the general problem is to figure out the right
19540   // places to insert EMMS.  This qualifies as a quick hack.
19541
19542   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19543   if (VT.getSizeInBits() != 64)
19544     return SDValue();
19545
19546   const Function *F = DAG.getMachineFunction().getFunction();
19547   bool NoImplicitFloatOps = F->getAttributes().
19548     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19549   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19550                      && Subtarget->hasSSE2();
19551   if ((VT.isVector() ||
19552        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19553       isa<LoadSDNode>(St->getValue()) &&
19554       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19555       St->getChain().hasOneUse() && !St->isVolatile()) {
19556     SDNode* LdVal = St->getValue().getNode();
19557     LoadSDNode *Ld = nullptr;
19558     int TokenFactorIndex = -1;
19559     SmallVector<SDValue, 8> Ops;
19560     SDNode* ChainVal = St->getChain().getNode();
19561     // Must be a store of a load.  We currently handle two cases:  the load
19562     // is a direct child, and it's under an intervening TokenFactor.  It is
19563     // possible to dig deeper under nested TokenFactors.
19564     if (ChainVal == LdVal)
19565       Ld = cast<LoadSDNode>(St->getChain());
19566     else if (St->getValue().hasOneUse() &&
19567              ChainVal->getOpcode() == ISD::TokenFactor) {
19568       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19569         if (ChainVal->getOperand(i).getNode() == LdVal) {
19570           TokenFactorIndex = i;
19571           Ld = cast<LoadSDNode>(St->getValue());
19572         } else
19573           Ops.push_back(ChainVal->getOperand(i));
19574       }
19575     }
19576
19577     if (!Ld || !ISD::isNormalLoad(Ld))
19578       return SDValue();
19579
19580     // If this is not the MMX case, i.e. we are just turning i64 load/store
19581     // into f64 load/store, avoid the transformation if there are multiple
19582     // uses of the loaded value.
19583     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19584       return SDValue();
19585
19586     SDLoc LdDL(Ld);
19587     SDLoc StDL(N);
19588     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19589     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19590     // pair instead.
19591     if (Subtarget->is64Bit() || F64IsLegal) {
19592       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19593       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19594                                   Ld->getPointerInfo(), Ld->isVolatile(),
19595                                   Ld->isNonTemporal(), Ld->isInvariant(),
19596                                   Ld->getAlignment());
19597       SDValue NewChain = NewLd.getValue(1);
19598       if (TokenFactorIndex != -1) {
19599         Ops.push_back(NewChain);
19600         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19601       }
19602       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19603                           St->getPointerInfo(),
19604                           St->isVolatile(), St->isNonTemporal(),
19605                           St->getAlignment());
19606     }
19607
19608     // Otherwise, lower to two pairs of 32-bit loads / stores.
19609     SDValue LoAddr = Ld->getBasePtr();
19610     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19611                                  DAG.getConstant(4, MVT::i32));
19612
19613     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19614                                Ld->getPointerInfo(),
19615                                Ld->isVolatile(), Ld->isNonTemporal(),
19616                                Ld->isInvariant(), Ld->getAlignment());
19617     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19618                                Ld->getPointerInfo().getWithOffset(4),
19619                                Ld->isVolatile(), Ld->isNonTemporal(),
19620                                Ld->isInvariant(),
19621                                MinAlign(Ld->getAlignment(), 4));
19622
19623     SDValue NewChain = LoLd.getValue(1);
19624     if (TokenFactorIndex != -1) {
19625       Ops.push_back(LoLd);
19626       Ops.push_back(HiLd);
19627       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19628     }
19629
19630     LoAddr = St->getBasePtr();
19631     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19632                          DAG.getConstant(4, MVT::i32));
19633
19634     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19635                                 St->getPointerInfo(),
19636                                 St->isVolatile(), St->isNonTemporal(),
19637                                 St->getAlignment());
19638     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19639                                 St->getPointerInfo().getWithOffset(4),
19640                                 St->isVolatile(),
19641                                 St->isNonTemporal(),
19642                                 MinAlign(St->getAlignment(), 4));
19643     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19644   }
19645   return SDValue();
19646 }
19647
19648 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19649 /// and return the operands for the horizontal operation in LHS and RHS.  A
19650 /// horizontal operation performs the binary operation on successive elements
19651 /// of its first operand, then on successive elements of its second operand,
19652 /// returning the resulting values in a vector.  For example, if
19653 ///   A = < float a0, float a1, float a2, float a3 >
19654 /// and
19655 ///   B = < float b0, float b1, float b2, float b3 >
19656 /// then the result of doing a horizontal operation on A and B is
19657 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19658 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19659 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19660 /// set to A, RHS to B, and the routine returns 'true'.
19661 /// Note that the binary operation should have the property that if one of the
19662 /// operands is UNDEF then the result is UNDEF.
19663 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19664   // Look for the following pattern: if
19665   //   A = < float a0, float a1, float a2, float a3 >
19666   //   B = < float b0, float b1, float b2, float b3 >
19667   // and
19668   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19669   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19670   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19671   // which is A horizontal-op B.
19672
19673   // At least one of the operands should be a vector shuffle.
19674   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19675       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19676     return false;
19677
19678   MVT VT = LHS.getSimpleValueType();
19679
19680   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19681          "Unsupported vector type for horizontal add/sub");
19682
19683   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19684   // operate independently on 128-bit lanes.
19685   unsigned NumElts = VT.getVectorNumElements();
19686   unsigned NumLanes = VT.getSizeInBits()/128;
19687   unsigned NumLaneElts = NumElts / NumLanes;
19688   assert((NumLaneElts % 2 == 0) &&
19689          "Vector type should have an even number of elements in each lane");
19690   unsigned HalfLaneElts = NumLaneElts/2;
19691
19692   // View LHS in the form
19693   //   LHS = VECTOR_SHUFFLE A, B, LMask
19694   // If LHS is not a shuffle then pretend it is the shuffle
19695   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19696   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19697   // type VT.
19698   SDValue A, B;
19699   SmallVector<int, 16> LMask(NumElts);
19700   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19701     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19702       A = LHS.getOperand(0);
19703     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19704       B = LHS.getOperand(1);
19705     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19706     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19707   } else {
19708     if (LHS.getOpcode() != ISD::UNDEF)
19709       A = LHS;
19710     for (unsigned i = 0; i != NumElts; ++i)
19711       LMask[i] = i;
19712   }
19713
19714   // Likewise, view RHS in the form
19715   //   RHS = VECTOR_SHUFFLE C, D, RMask
19716   SDValue C, D;
19717   SmallVector<int, 16> RMask(NumElts);
19718   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19719     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19720       C = RHS.getOperand(0);
19721     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19722       D = RHS.getOperand(1);
19723     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19724     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19725   } else {
19726     if (RHS.getOpcode() != ISD::UNDEF)
19727       C = RHS;
19728     for (unsigned i = 0; i != NumElts; ++i)
19729       RMask[i] = i;
19730   }
19731
19732   // Check that the shuffles are both shuffling the same vectors.
19733   if (!(A == C && B == D) && !(A == D && B == C))
19734     return false;
19735
19736   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19737   if (!A.getNode() && !B.getNode())
19738     return false;
19739
19740   // If A and B occur in reverse order in RHS, then "swap" them (which means
19741   // rewriting the mask).
19742   if (A != C)
19743     CommuteVectorShuffleMask(RMask, NumElts);
19744
19745   // At this point LHS and RHS are equivalent to
19746   //   LHS = VECTOR_SHUFFLE A, B, LMask
19747   //   RHS = VECTOR_SHUFFLE A, B, RMask
19748   // Check that the masks correspond to performing a horizontal operation.
19749   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19750     for (unsigned i = 0; i != NumLaneElts; ++i) {
19751       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19752
19753       // Ignore any UNDEF components.
19754       if (LIdx < 0 || RIdx < 0 ||
19755           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19756           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19757         continue;
19758
19759       // Check that successive elements are being operated on.  If not, this is
19760       // not a horizontal operation.
19761       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19762       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19763       if (!(LIdx == Index && RIdx == Index + 1) &&
19764           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19765         return false;
19766     }
19767   }
19768
19769   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19770   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19771   return true;
19772 }
19773
19774 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19775 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19776                                   const X86Subtarget *Subtarget) {
19777   EVT VT = N->getValueType(0);
19778   SDValue LHS = N->getOperand(0);
19779   SDValue RHS = N->getOperand(1);
19780
19781   // Try to synthesize horizontal adds from adds of shuffles.
19782   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19783        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19784       isHorizontalBinOp(LHS, RHS, true))
19785     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19786   return SDValue();
19787 }
19788
19789 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19790 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19791                                   const X86Subtarget *Subtarget) {
19792   EVT VT = N->getValueType(0);
19793   SDValue LHS = N->getOperand(0);
19794   SDValue RHS = N->getOperand(1);
19795
19796   // Try to synthesize horizontal subs from subs of shuffles.
19797   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19798        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19799       isHorizontalBinOp(LHS, RHS, false))
19800     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19801   return SDValue();
19802 }
19803
19804 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19805 /// X86ISD::FXOR nodes.
19806 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19807   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19808   // F[X]OR(0.0, x) -> x
19809   // F[X]OR(x, 0.0) -> x
19810   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19811     if (C->getValueAPF().isPosZero())
19812       return N->getOperand(1);
19813   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19814     if (C->getValueAPF().isPosZero())
19815       return N->getOperand(0);
19816   return SDValue();
19817 }
19818
19819 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19820 /// X86ISD::FMAX nodes.
19821 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19822   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19823
19824   // Only perform optimizations if UnsafeMath is used.
19825   if (!DAG.getTarget().Options.UnsafeFPMath)
19826     return SDValue();
19827
19828   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19829   // into FMINC and FMAXC, which are Commutative operations.
19830   unsigned NewOp = 0;
19831   switch (N->getOpcode()) {
19832     default: llvm_unreachable("unknown opcode");
19833     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19834     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19835   }
19836
19837   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19838                      N->getOperand(0), N->getOperand(1));
19839 }
19840
19841 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19842 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19843   // FAND(0.0, x) -> 0.0
19844   // FAND(x, 0.0) -> 0.0
19845   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19846     if (C->getValueAPF().isPosZero())
19847       return N->getOperand(0);
19848   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19849     if (C->getValueAPF().isPosZero())
19850       return N->getOperand(1);
19851   return SDValue();
19852 }
19853
19854 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19855 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19856   // FANDN(x, 0.0) -> 0.0
19857   // FANDN(0.0, x) -> x
19858   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19859     if (C->getValueAPF().isPosZero())
19860       return N->getOperand(1);
19861   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19862     if (C->getValueAPF().isPosZero())
19863       return N->getOperand(1);
19864   return SDValue();
19865 }
19866
19867 static SDValue PerformBTCombine(SDNode *N,
19868                                 SelectionDAG &DAG,
19869                                 TargetLowering::DAGCombinerInfo &DCI) {
19870   // BT ignores high bits in the bit index operand.
19871   SDValue Op1 = N->getOperand(1);
19872   if (Op1.hasOneUse()) {
19873     unsigned BitWidth = Op1.getValueSizeInBits();
19874     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19875     APInt KnownZero, KnownOne;
19876     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19877                                           !DCI.isBeforeLegalizeOps());
19878     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19879     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19880         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19881       DCI.CommitTargetLoweringOpt(TLO);
19882   }
19883   return SDValue();
19884 }
19885
19886 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19887   SDValue Op = N->getOperand(0);
19888   if (Op.getOpcode() == ISD::BITCAST)
19889     Op = Op.getOperand(0);
19890   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19891   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19892       VT.getVectorElementType().getSizeInBits() ==
19893       OpVT.getVectorElementType().getSizeInBits()) {
19894     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19895   }
19896   return SDValue();
19897 }
19898
19899 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19900                                                const X86Subtarget *Subtarget) {
19901   EVT VT = N->getValueType(0);
19902   if (!VT.isVector())
19903     return SDValue();
19904
19905   SDValue N0 = N->getOperand(0);
19906   SDValue N1 = N->getOperand(1);
19907   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19908   SDLoc dl(N);
19909
19910   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19911   // both SSE and AVX2 since there is no sign-extended shift right
19912   // operation on a vector with 64-bit elements.
19913   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19914   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19915   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19916       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19917     SDValue N00 = N0.getOperand(0);
19918
19919     // EXTLOAD has a better solution on AVX2,
19920     // it may be replaced with X86ISD::VSEXT node.
19921     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19922       if (!ISD::isNormalLoad(N00.getNode()))
19923         return SDValue();
19924
19925     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19926         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19927                                   N00, N1);
19928       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19929     }
19930   }
19931   return SDValue();
19932 }
19933
19934 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19935                                   TargetLowering::DAGCombinerInfo &DCI,
19936                                   const X86Subtarget *Subtarget) {
19937   if (!DCI.isBeforeLegalizeOps())
19938     return SDValue();
19939
19940   if (!Subtarget->hasFp256())
19941     return SDValue();
19942
19943   EVT VT = N->getValueType(0);
19944   if (VT.isVector() && VT.getSizeInBits() == 256) {
19945     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19946     if (R.getNode())
19947       return R;
19948   }
19949
19950   return SDValue();
19951 }
19952
19953 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19954                                  const X86Subtarget* Subtarget) {
19955   SDLoc dl(N);
19956   EVT VT = N->getValueType(0);
19957
19958   // Let legalize expand this if it isn't a legal type yet.
19959   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19960     return SDValue();
19961
19962   EVT ScalarVT = VT.getScalarType();
19963   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19964       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19965     return SDValue();
19966
19967   SDValue A = N->getOperand(0);
19968   SDValue B = N->getOperand(1);
19969   SDValue C = N->getOperand(2);
19970
19971   bool NegA = (A.getOpcode() == ISD::FNEG);
19972   bool NegB = (B.getOpcode() == ISD::FNEG);
19973   bool NegC = (C.getOpcode() == ISD::FNEG);
19974
19975   // Negative multiplication when NegA xor NegB
19976   bool NegMul = (NegA != NegB);
19977   if (NegA)
19978     A = A.getOperand(0);
19979   if (NegB)
19980     B = B.getOperand(0);
19981   if (NegC)
19982     C = C.getOperand(0);
19983
19984   unsigned Opcode;
19985   if (!NegMul)
19986     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19987   else
19988     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19989
19990   return DAG.getNode(Opcode, dl, VT, A, B, C);
19991 }
19992
19993 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19994                                   TargetLowering::DAGCombinerInfo &DCI,
19995                                   const X86Subtarget *Subtarget) {
19996   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19997   //           (and (i32 x86isd::setcc_carry), 1)
19998   // This eliminates the zext. This transformation is necessary because
19999   // ISD::SETCC is always legalized to i8.
20000   SDLoc dl(N);
20001   SDValue N0 = N->getOperand(0);
20002   EVT VT = N->getValueType(0);
20003
20004   if (N0.getOpcode() == ISD::AND &&
20005       N0.hasOneUse() &&
20006       N0.getOperand(0).hasOneUse()) {
20007     SDValue N00 = N0.getOperand(0);
20008     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20009       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20010       if (!C || C->getZExtValue() != 1)
20011         return SDValue();
20012       return DAG.getNode(ISD::AND, dl, VT,
20013                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20014                                      N00.getOperand(0), N00.getOperand(1)),
20015                          DAG.getConstant(1, VT));
20016     }
20017   }
20018
20019   if (N0.getOpcode() == ISD::TRUNCATE &&
20020       N0.hasOneUse() &&
20021       N0.getOperand(0).hasOneUse()) {
20022     SDValue N00 = N0.getOperand(0);
20023     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20024       return DAG.getNode(ISD::AND, dl, VT,
20025                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20026                                      N00.getOperand(0), N00.getOperand(1)),
20027                          DAG.getConstant(1, VT));
20028     }
20029   }
20030   if (VT.is256BitVector()) {
20031     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20032     if (R.getNode())
20033       return R;
20034   }
20035
20036   return SDValue();
20037 }
20038
20039 // Optimize x == -y --> x+y == 0
20040 //          x != -y --> x+y != 0
20041 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20042                                       const X86Subtarget* Subtarget) {
20043   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20044   SDValue LHS = N->getOperand(0);
20045   SDValue RHS = N->getOperand(1);
20046   EVT VT = N->getValueType(0);
20047   SDLoc DL(N);
20048
20049   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20051       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20052         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20053                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20054         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20055                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20056       }
20057   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20059       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20060         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20061                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20062         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20063                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20064       }
20065
20066   if (VT.getScalarType() == MVT::i1) {
20067     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20068       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20069     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20070     if (!IsSEXT0 && !IsVZero0)
20071       return SDValue();
20072     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20073       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20074     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20075
20076     if (!IsSEXT1 && !IsVZero1)
20077       return SDValue();
20078
20079     if (IsSEXT0 && IsVZero1) {
20080       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20081       if (CC == ISD::SETEQ)
20082         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20083       return LHS.getOperand(0);
20084     }
20085     if (IsSEXT1 && IsVZero0) {
20086       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20087       if (CC == ISD::SETEQ)
20088         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20089       return RHS.getOperand(0);
20090     }
20091   }
20092
20093   return SDValue();
20094 }
20095
20096 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20097 // as "sbb reg,reg", since it can be extended without zext and produces
20098 // an all-ones bit which is more useful than 0/1 in some cases.
20099 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20100                                MVT VT) {
20101   if (VT == MVT::i8)
20102     return DAG.getNode(ISD::AND, DL, VT,
20103                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20104                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20105                        DAG.getConstant(1, VT));
20106   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20107   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20108                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20109                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20110 }
20111
20112 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20113 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20114                                    TargetLowering::DAGCombinerInfo &DCI,
20115                                    const X86Subtarget *Subtarget) {
20116   SDLoc DL(N);
20117   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20118   SDValue EFLAGS = N->getOperand(1);
20119
20120   if (CC == X86::COND_A) {
20121     // Try to convert COND_A into COND_B in an attempt to facilitate
20122     // materializing "setb reg".
20123     //
20124     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20125     // cannot take an immediate as its first operand.
20126     //
20127     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20128         EFLAGS.getValueType().isInteger() &&
20129         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20130       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20131                                    EFLAGS.getNode()->getVTList(),
20132                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20133       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20134       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20135     }
20136   }
20137
20138   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20139   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20140   // cases.
20141   if (CC == X86::COND_B)
20142     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20143
20144   SDValue Flags;
20145
20146   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20147   if (Flags.getNode()) {
20148     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20149     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20150   }
20151
20152   return SDValue();
20153 }
20154
20155 // Optimize branch condition evaluation.
20156 //
20157 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20158                                     TargetLowering::DAGCombinerInfo &DCI,
20159                                     const X86Subtarget *Subtarget) {
20160   SDLoc DL(N);
20161   SDValue Chain = N->getOperand(0);
20162   SDValue Dest = N->getOperand(1);
20163   SDValue EFLAGS = N->getOperand(3);
20164   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20165
20166   SDValue Flags;
20167
20168   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20169   if (Flags.getNode()) {
20170     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20171     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20172                        Flags);
20173   }
20174
20175   return SDValue();
20176 }
20177
20178 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20179                                         const X86TargetLowering *XTLI) {
20180   SDValue Op0 = N->getOperand(0);
20181   EVT InVT = Op0->getValueType(0);
20182
20183   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20184   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20185     SDLoc dl(N);
20186     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20187     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20188     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20189   }
20190
20191   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20192   // a 32-bit target where SSE doesn't support i64->FP operations.
20193   if (Op0.getOpcode() == ISD::LOAD) {
20194     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20195     EVT VT = Ld->getValueType(0);
20196     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20197         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20198         !XTLI->getSubtarget()->is64Bit() &&
20199         VT == MVT::i64) {
20200       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20201                                           Ld->getChain(), Op0, DAG);
20202       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20203       return FILDChain;
20204     }
20205   }
20206   return SDValue();
20207 }
20208
20209 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20210 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20211                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20212   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20213   // the result is either zero or one (depending on the input carry bit).
20214   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20215   if (X86::isZeroNode(N->getOperand(0)) &&
20216       X86::isZeroNode(N->getOperand(1)) &&
20217       // We don't have a good way to replace an EFLAGS use, so only do this when
20218       // dead right now.
20219       SDValue(N, 1).use_empty()) {
20220     SDLoc DL(N);
20221     EVT VT = N->getValueType(0);
20222     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20223     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20224                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20225                                            DAG.getConstant(X86::COND_B,MVT::i8),
20226                                            N->getOperand(2)),
20227                                DAG.getConstant(1, VT));
20228     return DCI.CombineTo(N, Res1, CarryOut);
20229   }
20230
20231   return SDValue();
20232 }
20233
20234 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20235 //      (add Y, (setne X, 0)) -> sbb -1, Y
20236 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20237 //      (sub (setne X, 0), Y) -> adc -1, Y
20238 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20239   SDLoc DL(N);
20240
20241   // Look through ZExts.
20242   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20243   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20244     return SDValue();
20245
20246   SDValue SetCC = Ext.getOperand(0);
20247   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20248     return SDValue();
20249
20250   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20251   if (CC != X86::COND_E && CC != X86::COND_NE)
20252     return SDValue();
20253
20254   SDValue Cmp = SetCC.getOperand(1);
20255   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20256       !X86::isZeroNode(Cmp.getOperand(1)) ||
20257       !Cmp.getOperand(0).getValueType().isInteger())
20258     return SDValue();
20259
20260   SDValue CmpOp0 = Cmp.getOperand(0);
20261   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20262                                DAG.getConstant(1, CmpOp0.getValueType()));
20263
20264   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20265   if (CC == X86::COND_NE)
20266     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20267                        DL, OtherVal.getValueType(), OtherVal,
20268                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20269   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20270                      DL, OtherVal.getValueType(), OtherVal,
20271                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20272 }
20273
20274 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20275 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20276                                  const X86Subtarget *Subtarget) {
20277   EVT VT = N->getValueType(0);
20278   SDValue Op0 = N->getOperand(0);
20279   SDValue Op1 = N->getOperand(1);
20280
20281   // Try to synthesize horizontal adds from adds of shuffles.
20282   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20283        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20284       isHorizontalBinOp(Op0, Op1, true))
20285     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20286
20287   return OptimizeConditionalInDecrement(N, DAG);
20288 }
20289
20290 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20291                                  const X86Subtarget *Subtarget) {
20292   SDValue Op0 = N->getOperand(0);
20293   SDValue Op1 = N->getOperand(1);
20294
20295   // X86 can't encode an immediate LHS of a sub. See if we can push the
20296   // negation into a preceding instruction.
20297   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20298     // If the RHS of the sub is a XOR with one use and a constant, invert the
20299     // immediate. Then add one to the LHS of the sub so we can turn
20300     // X-Y -> X+~Y+1, saving one register.
20301     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20302         isa<ConstantSDNode>(Op1.getOperand(1))) {
20303       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20304       EVT VT = Op0.getValueType();
20305       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20306                                    Op1.getOperand(0),
20307                                    DAG.getConstant(~XorC, VT));
20308       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20309                          DAG.getConstant(C->getAPIntValue()+1, VT));
20310     }
20311   }
20312
20313   // Try to synthesize horizontal adds from adds of shuffles.
20314   EVT VT = N->getValueType(0);
20315   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20316        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20317       isHorizontalBinOp(Op0, Op1, true))
20318     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20319
20320   return OptimizeConditionalInDecrement(N, DAG);
20321 }
20322
20323 /// performVZEXTCombine - Performs build vector combines
20324 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20325                                         TargetLowering::DAGCombinerInfo &DCI,
20326                                         const X86Subtarget *Subtarget) {
20327   // (vzext (bitcast (vzext (x)) -> (vzext x)
20328   SDValue In = N->getOperand(0);
20329   while (In.getOpcode() == ISD::BITCAST)
20330     In = In.getOperand(0);
20331
20332   if (In.getOpcode() != X86ISD::VZEXT)
20333     return SDValue();
20334
20335   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20336                      In.getOperand(0));
20337 }
20338
20339 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20340                                              DAGCombinerInfo &DCI) const {
20341   SelectionDAG &DAG = DCI.DAG;
20342   switch (N->getOpcode()) {
20343   default: break;
20344   case ISD::EXTRACT_VECTOR_ELT:
20345     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20346   case ISD::VSELECT:
20347   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20348   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20349   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20350   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20351   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20352   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20353   case ISD::SHL:
20354   case ISD::SRA:
20355   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20356   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20357   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20358   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20359   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20360   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20361   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20362   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20363   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20364   case X86ISD::FXOR:
20365   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20366   case X86ISD::FMIN:
20367   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20368   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20369   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20370   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20371   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20372   case ISD::ANY_EXTEND:
20373   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20374   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20375   case ISD::SIGN_EXTEND_INREG:
20376     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20377   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20378   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20379   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20380   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20381   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20382   case X86ISD::SHUFP:       // Handle all target specific shuffles
20383   case X86ISD::PALIGNR:
20384   case X86ISD::UNPCKH:
20385   case X86ISD::UNPCKL:
20386   case X86ISD::MOVHLPS:
20387   case X86ISD::MOVLHPS:
20388   case X86ISD::PSHUFD:
20389   case X86ISD::PSHUFHW:
20390   case X86ISD::PSHUFLW:
20391   case X86ISD::MOVSS:
20392   case X86ISD::MOVSD:
20393   case X86ISD::VPERMILP:
20394   case X86ISD::VPERM2X128:
20395   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20396   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20397   case ISD::INTRINSIC_WO_CHAIN:
20398     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20399   }
20400
20401   return SDValue();
20402 }
20403
20404 /// isTypeDesirableForOp - Return true if the target has native support for
20405 /// the specified value type and it is 'desirable' to use the type for the
20406 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20407 /// instruction encodings are longer and some i16 instructions are slow.
20408 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20409   if (!isTypeLegal(VT))
20410     return false;
20411   if (VT != MVT::i16)
20412     return true;
20413
20414   switch (Opc) {
20415   default:
20416     return true;
20417   case ISD::LOAD:
20418   case ISD::SIGN_EXTEND:
20419   case ISD::ZERO_EXTEND:
20420   case ISD::ANY_EXTEND:
20421   case ISD::SHL:
20422   case ISD::SRL:
20423   case ISD::SUB:
20424   case ISD::ADD:
20425   case ISD::MUL:
20426   case ISD::AND:
20427   case ISD::OR:
20428   case ISD::XOR:
20429     return false;
20430   }
20431 }
20432
20433 /// IsDesirableToPromoteOp - This method query the target whether it is
20434 /// beneficial for dag combiner to promote the specified node. If true, it
20435 /// should return the desired promotion type by reference.
20436 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20437   EVT VT = Op.getValueType();
20438   if (VT != MVT::i16)
20439     return false;
20440
20441   bool Promote = false;
20442   bool Commute = false;
20443   switch (Op.getOpcode()) {
20444   default: break;
20445   case ISD::LOAD: {
20446     LoadSDNode *LD = cast<LoadSDNode>(Op);
20447     // If the non-extending load has a single use and it's not live out, then it
20448     // might be folded.
20449     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20450                                                      Op.hasOneUse()*/) {
20451       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20452              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20453         // The only case where we'd want to promote LOAD (rather then it being
20454         // promoted as an operand is when it's only use is liveout.
20455         if (UI->getOpcode() != ISD::CopyToReg)
20456           return false;
20457       }
20458     }
20459     Promote = true;
20460     break;
20461   }
20462   case ISD::SIGN_EXTEND:
20463   case ISD::ZERO_EXTEND:
20464   case ISD::ANY_EXTEND:
20465     Promote = true;
20466     break;
20467   case ISD::SHL:
20468   case ISD::SRL: {
20469     SDValue N0 = Op.getOperand(0);
20470     // Look out for (store (shl (load), x)).
20471     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20472       return false;
20473     Promote = true;
20474     break;
20475   }
20476   case ISD::ADD:
20477   case ISD::MUL:
20478   case ISD::AND:
20479   case ISD::OR:
20480   case ISD::XOR:
20481     Commute = true;
20482     // fallthrough
20483   case ISD::SUB: {
20484     SDValue N0 = Op.getOperand(0);
20485     SDValue N1 = Op.getOperand(1);
20486     if (!Commute && MayFoldLoad(N1))
20487       return false;
20488     // Avoid disabling potential load folding opportunities.
20489     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20490       return false;
20491     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20492       return false;
20493     Promote = true;
20494   }
20495   }
20496
20497   PVT = MVT::i32;
20498   return Promote;
20499 }
20500
20501 //===----------------------------------------------------------------------===//
20502 //                           X86 Inline Assembly Support
20503 //===----------------------------------------------------------------------===//
20504
20505 namespace {
20506   // Helper to match a string separated by whitespace.
20507   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20508     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20509
20510     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20511       StringRef piece(*args[i]);
20512       if (!s.startswith(piece)) // Check if the piece matches.
20513         return false;
20514
20515       s = s.substr(piece.size());
20516       StringRef::size_type pos = s.find_first_not_of(" \t");
20517       if (pos == 0) // We matched a prefix.
20518         return false;
20519
20520       s = s.substr(pos);
20521     }
20522
20523     return s.empty();
20524   }
20525   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20526 }
20527
20528 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20529
20530   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20531     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20532         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20533         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20534
20535       if (AsmPieces.size() == 3)
20536         return true;
20537       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20538         return true;
20539     }
20540   }
20541   return false;
20542 }
20543
20544 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20545   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20546
20547   std::string AsmStr = IA->getAsmString();
20548
20549   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20550   if (!Ty || Ty->getBitWidth() % 16 != 0)
20551     return false;
20552
20553   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20554   SmallVector<StringRef, 4> AsmPieces;
20555   SplitString(AsmStr, AsmPieces, ";\n");
20556
20557   switch (AsmPieces.size()) {
20558   default: return false;
20559   case 1:
20560     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20561     // we will turn this bswap into something that will be lowered to logical
20562     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20563     // lower so don't worry about this.
20564     // bswap $0
20565     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20566         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20567         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20568         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20569         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20570         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20571       // No need to check constraints, nothing other than the equivalent of
20572       // "=r,0" would be valid here.
20573       return IntrinsicLowering::LowerToByteSwap(CI);
20574     }
20575
20576     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20577     if (CI->getType()->isIntegerTy(16) &&
20578         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20579         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20580          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20581       AsmPieces.clear();
20582       const std::string &ConstraintsStr = IA->getConstraintString();
20583       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20584       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20585       if (clobbersFlagRegisters(AsmPieces))
20586         return IntrinsicLowering::LowerToByteSwap(CI);
20587     }
20588     break;
20589   case 3:
20590     if (CI->getType()->isIntegerTy(32) &&
20591         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20592         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20593         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20594         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20595       AsmPieces.clear();
20596       const std::string &ConstraintsStr = IA->getConstraintString();
20597       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20598       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20599       if (clobbersFlagRegisters(AsmPieces))
20600         return IntrinsicLowering::LowerToByteSwap(CI);
20601     }
20602
20603     if (CI->getType()->isIntegerTy(64)) {
20604       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20605       if (Constraints.size() >= 2 &&
20606           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20607           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20608         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20609         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20610             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20611             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20612           return IntrinsicLowering::LowerToByteSwap(CI);
20613       }
20614     }
20615     break;
20616   }
20617   return false;
20618 }
20619
20620 /// getConstraintType - Given a constraint letter, return the type of
20621 /// constraint it is for this target.
20622 X86TargetLowering::ConstraintType
20623 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20624   if (Constraint.size() == 1) {
20625     switch (Constraint[0]) {
20626     case 'R':
20627     case 'q':
20628     case 'Q':
20629     case 'f':
20630     case 't':
20631     case 'u':
20632     case 'y':
20633     case 'x':
20634     case 'Y':
20635     case 'l':
20636       return C_RegisterClass;
20637     case 'a':
20638     case 'b':
20639     case 'c':
20640     case 'd':
20641     case 'S':
20642     case 'D':
20643     case 'A':
20644       return C_Register;
20645     case 'I':
20646     case 'J':
20647     case 'K':
20648     case 'L':
20649     case 'M':
20650     case 'N':
20651     case 'G':
20652     case 'C':
20653     case 'e':
20654     case 'Z':
20655       return C_Other;
20656     default:
20657       break;
20658     }
20659   }
20660   return TargetLowering::getConstraintType(Constraint);
20661 }
20662
20663 /// Examine constraint type and operand type and determine a weight value.
20664 /// This object must already have been set up with the operand type
20665 /// and the current alternative constraint selected.
20666 TargetLowering::ConstraintWeight
20667   X86TargetLowering::getSingleConstraintMatchWeight(
20668     AsmOperandInfo &info, const char *constraint) const {
20669   ConstraintWeight weight = CW_Invalid;
20670   Value *CallOperandVal = info.CallOperandVal;
20671     // If we don't have a value, we can't do a match,
20672     // but allow it at the lowest weight.
20673   if (!CallOperandVal)
20674     return CW_Default;
20675   Type *type = CallOperandVal->getType();
20676   // Look at the constraint type.
20677   switch (*constraint) {
20678   default:
20679     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20680   case 'R':
20681   case 'q':
20682   case 'Q':
20683   case 'a':
20684   case 'b':
20685   case 'c':
20686   case 'd':
20687   case 'S':
20688   case 'D':
20689   case 'A':
20690     if (CallOperandVal->getType()->isIntegerTy())
20691       weight = CW_SpecificReg;
20692     break;
20693   case 'f':
20694   case 't':
20695   case 'u':
20696     if (type->isFloatingPointTy())
20697       weight = CW_SpecificReg;
20698     break;
20699   case 'y':
20700     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20701       weight = CW_SpecificReg;
20702     break;
20703   case 'x':
20704   case 'Y':
20705     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20706         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20707       weight = CW_Register;
20708     break;
20709   case 'I':
20710     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20711       if (C->getZExtValue() <= 31)
20712         weight = CW_Constant;
20713     }
20714     break;
20715   case 'J':
20716     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20717       if (C->getZExtValue() <= 63)
20718         weight = CW_Constant;
20719     }
20720     break;
20721   case 'K':
20722     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20723       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20724         weight = CW_Constant;
20725     }
20726     break;
20727   case 'L':
20728     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20729       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20730         weight = CW_Constant;
20731     }
20732     break;
20733   case 'M':
20734     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20735       if (C->getZExtValue() <= 3)
20736         weight = CW_Constant;
20737     }
20738     break;
20739   case 'N':
20740     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20741       if (C->getZExtValue() <= 0xff)
20742         weight = CW_Constant;
20743     }
20744     break;
20745   case 'G':
20746   case 'C':
20747     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20748       weight = CW_Constant;
20749     }
20750     break;
20751   case 'e':
20752     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20753       if ((C->getSExtValue() >= -0x80000000LL) &&
20754           (C->getSExtValue() <= 0x7fffffffLL))
20755         weight = CW_Constant;
20756     }
20757     break;
20758   case 'Z':
20759     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20760       if (C->getZExtValue() <= 0xffffffff)
20761         weight = CW_Constant;
20762     }
20763     break;
20764   }
20765   return weight;
20766 }
20767
20768 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20769 /// with another that has more specific requirements based on the type of the
20770 /// corresponding operand.
20771 const char *X86TargetLowering::
20772 LowerXConstraint(EVT ConstraintVT) const {
20773   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20774   // 'f' like normal targets.
20775   if (ConstraintVT.isFloatingPoint()) {
20776     if (Subtarget->hasSSE2())
20777       return "Y";
20778     if (Subtarget->hasSSE1())
20779       return "x";
20780   }
20781
20782   return TargetLowering::LowerXConstraint(ConstraintVT);
20783 }
20784
20785 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20786 /// vector.  If it is invalid, don't add anything to Ops.
20787 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20788                                                      std::string &Constraint,
20789                                                      std::vector<SDValue>&Ops,
20790                                                      SelectionDAG &DAG) const {
20791   SDValue Result;
20792
20793   // Only support length 1 constraints for now.
20794   if (Constraint.length() > 1) return;
20795
20796   char ConstraintLetter = Constraint[0];
20797   switch (ConstraintLetter) {
20798   default: break;
20799   case 'I':
20800     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20801       if (C->getZExtValue() <= 31) {
20802         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20803         break;
20804       }
20805     }
20806     return;
20807   case 'J':
20808     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20809       if (C->getZExtValue() <= 63) {
20810         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20811         break;
20812       }
20813     }
20814     return;
20815   case 'K':
20816     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20817       if (isInt<8>(C->getSExtValue())) {
20818         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20819         break;
20820       }
20821     }
20822     return;
20823   case 'N':
20824     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20825       if (C->getZExtValue() <= 255) {
20826         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20827         break;
20828       }
20829     }
20830     return;
20831   case 'e': {
20832     // 32-bit signed value
20833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20834       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20835                                            C->getSExtValue())) {
20836         // Widen to 64 bits here to get it sign extended.
20837         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20838         break;
20839       }
20840     // FIXME gcc accepts some relocatable values here too, but only in certain
20841     // memory models; it's complicated.
20842     }
20843     return;
20844   }
20845   case 'Z': {
20846     // 32-bit unsigned value
20847     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20848       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20849                                            C->getZExtValue())) {
20850         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20851         break;
20852       }
20853     }
20854     // FIXME gcc accepts some relocatable values here too, but only in certain
20855     // memory models; it's complicated.
20856     return;
20857   }
20858   case 'i': {
20859     // Literal immediates are always ok.
20860     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20861       // Widen to 64 bits here to get it sign extended.
20862       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20863       break;
20864     }
20865
20866     // In any sort of PIC mode addresses need to be computed at runtime by
20867     // adding in a register or some sort of table lookup.  These can't
20868     // be used as immediates.
20869     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20870       return;
20871
20872     // If we are in non-pic codegen mode, we allow the address of a global (with
20873     // an optional displacement) to be used with 'i'.
20874     GlobalAddressSDNode *GA = nullptr;
20875     int64_t Offset = 0;
20876
20877     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20878     while (1) {
20879       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20880         Offset += GA->getOffset();
20881         break;
20882       } else if (Op.getOpcode() == ISD::ADD) {
20883         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20884           Offset += C->getZExtValue();
20885           Op = Op.getOperand(0);
20886           continue;
20887         }
20888       } else if (Op.getOpcode() == ISD::SUB) {
20889         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20890           Offset += -C->getZExtValue();
20891           Op = Op.getOperand(0);
20892           continue;
20893         }
20894       }
20895
20896       // Otherwise, this isn't something we can handle, reject it.
20897       return;
20898     }
20899
20900     const GlobalValue *GV = GA->getGlobal();
20901     // If we require an extra load to get this address, as in PIC mode, we
20902     // can't accept it.
20903     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20904                                                         getTargetMachine())))
20905       return;
20906
20907     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20908                                         GA->getValueType(0), Offset);
20909     break;
20910   }
20911   }
20912
20913   if (Result.getNode()) {
20914     Ops.push_back(Result);
20915     return;
20916   }
20917   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20918 }
20919
20920 std::pair<unsigned, const TargetRegisterClass*>
20921 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20922                                                 MVT VT) const {
20923   // First, see if this is a constraint that directly corresponds to an LLVM
20924   // register class.
20925   if (Constraint.size() == 1) {
20926     // GCC Constraint Letters
20927     switch (Constraint[0]) {
20928     default: break;
20929       // TODO: Slight differences here in allocation order and leaving
20930       // RIP in the class. Do they matter any more here than they do
20931       // in the normal allocation?
20932     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20933       if (Subtarget->is64Bit()) {
20934         if (VT == MVT::i32 || VT == MVT::f32)
20935           return std::make_pair(0U, &X86::GR32RegClass);
20936         if (VT == MVT::i16)
20937           return std::make_pair(0U, &X86::GR16RegClass);
20938         if (VT == MVT::i8 || VT == MVT::i1)
20939           return std::make_pair(0U, &X86::GR8RegClass);
20940         if (VT == MVT::i64 || VT == MVT::f64)
20941           return std::make_pair(0U, &X86::GR64RegClass);
20942         break;
20943       }
20944       // 32-bit fallthrough
20945     case 'Q':   // Q_REGS
20946       if (VT == MVT::i32 || VT == MVT::f32)
20947         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20948       if (VT == MVT::i16)
20949         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20950       if (VT == MVT::i8 || VT == MVT::i1)
20951         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20952       if (VT == MVT::i64)
20953         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20954       break;
20955     case 'r':   // GENERAL_REGS
20956     case 'l':   // INDEX_REGS
20957       if (VT == MVT::i8 || VT == MVT::i1)
20958         return std::make_pair(0U, &X86::GR8RegClass);
20959       if (VT == MVT::i16)
20960         return std::make_pair(0U, &X86::GR16RegClass);
20961       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20962         return std::make_pair(0U, &X86::GR32RegClass);
20963       return std::make_pair(0U, &X86::GR64RegClass);
20964     case 'R':   // LEGACY_REGS
20965       if (VT == MVT::i8 || VT == MVT::i1)
20966         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20967       if (VT == MVT::i16)
20968         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20969       if (VT == MVT::i32 || !Subtarget->is64Bit())
20970         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20971       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20972     case 'f':  // FP Stack registers.
20973       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20974       // value to the correct fpstack register class.
20975       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20976         return std::make_pair(0U, &X86::RFP32RegClass);
20977       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20978         return std::make_pair(0U, &X86::RFP64RegClass);
20979       return std::make_pair(0U, &X86::RFP80RegClass);
20980     case 'y':   // MMX_REGS if MMX allowed.
20981       if (!Subtarget->hasMMX()) break;
20982       return std::make_pair(0U, &X86::VR64RegClass);
20983     case 'Y':   // SSE_REGS if SSE2 allowed
20984       if (!Subtarget->hasSSE2()) break;
20985       // FALL THROUGH.
20986     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20987       if (!Subtarget->hasSSE1()) break;
20988
20989       switch (VT.SimpleTy) {
20990       default: break;
20991       // Scalar SSE types.
20992       case MVT::f32:
20993       case MVT::i32:
20994         return std::make_pair(0U, &X86::FR32RegClass);
20995       case MVT::f64:
20996       case MVT::i64:
20997         return std::make_pair(0U, &X86::FR64RegClass);
20998       // Vector types.
20999       case MVT::v16i8:
21000       case MVT::v8i16:
21001       case MVT::v4i32:
21002       case MVT::v2i64:
21003       case MVT::v4f32:
21004       case MVT::v2f64:
21005         return std::make_pair(0U, &X86::VR128RegClass);
21006       // AVX types.
21007       case MVT::v32i8:
21008       case MVT::v16i16:
21009       case MVT::v8i32:
21010       case MVT::v4i64:
21011       case MVT::v8f32:
21012       case MVT::v4f64:
21013         return std::make_pair(0U, &X86::VR256RegClass);
21014       case MVT::v8f64:
21015       case MVT::v16f32:
21016       case MVT::v16i32:
21017       case MVT::v8i64:
21018         return std::make_pair(0U, &X86::VR512RegClass);
21019       }
21020       break;
21021     }
21022   }
21023
21024   // Use the default implementation in TargetLowering to convert the register
21025   // constraint into a member of a register class.
21026   std::pair<unsigned, const TargetRegisterClass*> Res;
21027   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21028
21029   // Not found as a standard register?
21030   if (!Res.second) {
21031     // Map st(0) -> st(7) -> ST0
21032     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21033         tolower(Constraint[1]) == 's' &&
21034         tolower(Constraint[2]) == 't' &&
21035         Constraint[3] == '(' &&
21036         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21037         Constraint[5] == ')' &&
21038         Constraint[6] == '}') {
21039
21040       Res.first = X86::ST0+Constraint[4]-'0';
21041       Res.second = &X86::RFP80RegClass;
21042       return Res;
21043     }
21044
21045     // GCC allows "st(0)" to be called just plain "st".
21046     if (StringRef("{st}").equals_lower(Constraint)) {
21047       Res.first = X86::ST0;
21048       Res.second = &X86::RFP80RegClass;
21049       return Res;
21050     }
21051
21052     // flags -> EFLAGS
21053     if (StringRef("{flags}").equals_lower(Constraint)) {
21054       Res.first = X86::EFLAGS;
21055       Res.second = &X86::CCRRegClass;
21056       return Res;
21057     }
21058
21059     // 'A' means EAX + EDX.
21060     if (Constraint == "A") {
21061       Res.first = X86::EAX;
21062       Res.second = &X86::GR32_ADRegClass;
21063       return Res;
21064     }
21065     return Res;
21066   }
21067
21068   // Otherwise, check to see if this is a register class of the wrong value
21069   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21070   // turn into {ax},{dx}.
21071   if (Res.second->hasType(VT))
21072     return Res;   // Correct type already, nothing to do.
21073
21074   // All of the single-register GCC register classes map their values onto
21075   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21076   // really want an 8-bit or 32-bit register, map to the appropriate register
21077   // class and return the appropriate register.
21078   if (Res.second == &X86::GR16RegClass) {
21079     if (VT == MVT::i8 || VT == MVT::i1) {
21080       unsigned DestReg = 0;
21081       switch (Res.first) {
21082       default: break;
21083       case X86::AX: DestReg = X86::AL; break;
21084       case X86::DX: DestReg = X86::DL; break;
21085       case X86::CX: DestReg = X86::CL; break;
21086       case X86::BX: DestReg = X86::BL; break;
21087       }
21088       if (DestReg) {
21089         Res.first = DestReg;
21090         Res.second = &X86::GR8RegClass;
21091       }
21092     } else if (VT == MVT::i32 || VT == MVT::f32) {
21093       unsigned DestReg = 0;
21094       switch (Res.first) {
21095       default: break;
21096       case X86::AX: DestReg = X86::EAX; break;
21097       case X86::DX: DestReg = X86::EDX; break;
21098       case X86::CX: DestReg = X86::ECX; break;
21099       case X86::BX: DestReg = X86::EBX; break;
21100       case X86::SI: DestReg = X86::ESI; break;
21101       case X86::DI: DestReg = X86::EDI; break;
21102       case X86::BP: DestReg = X86::EBP; break;
21103       case X86::SP: DestReg = X86::ESP; break;
21104       }
21105       if (DestReg) {
21106         Res.first = DestReg;
21107         Res.second = &X86::GR32RegClass;
21108       }
21109     } else if (VT == MVT::i64 || VT == MVT::f64) {
21110       unsigned DestReg = 0;
21111       switch (Res.first) {
21112       default: break;
21113       case X86::AX: DestReg = X86::RAX; break;
21114       case X86::DX: DestReg = X86::RDX; break;
21115       case X86::CX: DestReg = X86::RCX; break;
21116       case X86::BX: DestReg = X86::RBX; break;
21117       case X86::SI: DestReg = X86::RSI; break;
21118       case X86::DI: DestReg = X86::RDI; break;
21119       case X86::BP: DestReg = X86::RBP; break;
21120       case X86::SP: DestReg = X86::RSP; break;
21121       }
21122       if (DestReg) {
21123         Res.first = DestReg;
21124         Res.second = &X86::GR64RegClass;
21125       }
21126     }
21127   } else if (Res.second == &X86::FR32RegClass ||
21128              Res.second == &X86::FR64RegClass ||
21129              Res.second == &X86::VR128RegClass ||
21130              Res.second == &X86::VR256RegClass ||
21131              Res.second == &X86::FR32XRegClass ||
21132              Res.second == &X86::FR64XRegClass ||
21133              Res.second == &X86::VR128XRegClass ||
21134              Res.second == &X86::VR256XRegClass ||
21135              Res.second == &X86::VR512RegClass) {
21136     // Handle references to XMM physical registers that got mapped into the
21137     // wrong class.  This can happen with constraints like {xmm0} where the
21138     // target independent register mapper will just pick the first match it can
21139     // find, ignoring the required type.
21140
21141     if (VT == MVT::f32 || VT == MVT::i32)
21142       Res.second = &X86::FR32RegClass;
21143     else if (VT == MVT::f64 || VT == MVT::i64)
21144       Res.second = &X86::FR64RegClass;
21145     else if (X86::VR128RegClass.hasType(VT))
21146       Res.second = &X86::VR128RegClass;
21147     else if (X86::VR256RegClass.hasType(VT))
21148       Res.second = &X86::VR256RegClass;
21149     else if (X86::VR512RegClass.hasType(VT))
21150       Res.second = &X86::VR512RegClass;
21151   }
21152
21153   return Res;
21154 }
21155
21156 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21157                                             Type *Ty) const {
21158   // Scaling factors are not free at all.
21159   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21160   // will take 2 allocations in the out of order engine instead of 1
21161   // for plain addressing mode, i.e. inst (reg1).
21162   // E.g.,
21163   // vaddps (%rsi,%drx), %ymm0, %ymm1
21164   // Requires two allocations (one for the load, one for the computation)
21165   // whereas:
21166   // vaddps (%rsi), %ymm0, %ymm1
21167   // Requires just 1 allocation, i.e., freeing allocations for other operations
21168   // and having less micro operations to execute.
21169   //
21170   // For some X86 architectures, this is even worse because for instance for
21171   // stores, the complex addressing mode forces the instruction to use the
21172   // "load" ports instead of the dedicated "store" port.
21173   // E.g., on Haswell:
21174   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21175   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21176   if (isLegalAddressingMode(AM, Ty))
21177     // Scale represents reg2 * scale, thus account for 1
21178     // as soon as we use a second register.
21179     return AM.Scale != 0;
21180   return -1;
21181 }