X86: Split the relocation selection up
[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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86CallingConv.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.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 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetKnownWindowsMSVC())
193     return new X86WindowsTargetObjectFile();
194   if (Subtarget->isTargetCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetKnownWindowsMSVC()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetWindowsGNU()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
444   if (Subtarget->is64Bit())
445     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
449   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
453   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
454
455   // Promote the i8 variants and force them on up to i32 which has a shorter
456   // encoding.
457   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
459   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
461   if (Subtarget->hasBMI()) {
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466   } else {
467     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
468     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
469     if (Subtarget->is64Bit())
470       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasLZCNT()) {
474     // When promoting the i8 variants, force them to i32 for a shorter
475     // encoding.
476     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484   } else {
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
491     if (Subtarget->is64Bit()) {
492       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
493       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
494     }
495   }
496
497   if (Subtarget->hasPOPCNT()) {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
499   } else {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
505   }
506
507   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
508
509   if (!Subtarget->hasMOVBE())
510     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
511
512   // These should be promoted to a larger select which is supported.
513   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
514   // X86 wants to expand cmov itself.
515   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
516   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
529     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
530   }
531   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
532   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534   // support continuation, user-level threading, and etc.. As a result, no
535   // other SjLj exception interfaces are implemented and please don't build
536   // your own exception handling based on them.
537   // LLVM/Clang supports zero-cost DWARF exception handling.
538   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
540
541   // Darwin ABI issue.
542   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
543   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
544   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
546   if (Subtarget->is64Bit())
547     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
549   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
550   if (Subtarget->is64Bit()) {
551     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
552     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
553     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
554     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
555     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
556   }
557   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
559   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
561   if (Subtarget->is64Bit()) {
562     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
563     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
565   }
566
567   if (Subtarget->hasSSE1())
568     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
569
570   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
571
572   // Expand certain atomics
573   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
574     MVT VT = IntVTs[i];
575     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
578   }
579
580   if (!Subtarget->is64Bit()) {
581     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
593   }
594
595   if (Subtarget->hasCmpxchg16b()) {
596     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
597   }
598
599   // FIXME - use subtarget debug flags
600   if (!Subtarget->isTargetDarwin() &&
601       !Subtarget->isTargetELF() &&
602       !Subtarget->isTargetCygMing()) {
603     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
604   }
605
606   if (Subtarget->is64Bit()) {
607     setExceptionPointerRegister(X86::RAX);
608     setExceptionSelectorRegister(X86::RDX);
609   } else {
610     setExceptionPointerRegister(X86::EAX);
611     setExceptionSelectorRegister(X86::EDX);
612   }
613   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
615
616   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
618
619   setOperationAction(ISD::TRAP, MVT::Other, Legal);
620   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
621
622   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
624   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
625   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626     // TargetInfo::X86_64ABIBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
629   } else {
630     // TargetInfo::CharPtrBuiltinVaList
631     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
632     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
633   }
634
635   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
636   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
637
638   if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
639     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                        MVT::i64 : MVT::i32, Custom);
641   else if (TM.Options.EnableSegmentedStacks)
642     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643                        MVT::i64 : MVT::i32, Custom);
644   else
645     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646                        MVT::i64 : MVT::i32, Expand);
647
648   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649     // f32 and f64 use SSE.
650     // Set up the FP register classes.
651     addRegisterClass(MVT::f32, &X86::FR32RegClass);
652     addRegisterClass(MVT::f64, &X86::FR64RegClass);
653
654     // Use ANDPD to simulate FABS.
655     setOperationAction(ISD::FABS , MVT::f64, Custom);
656     setOperationAction(ISD::FABS , MVT::f32, Custom);
657
658     // Use XORP to simulate FNEG.
659     setOperationAction(ISD::FNEG , MVT::f64, Custom);
660     setOperationAction(ISD::FNEG , MVT::f32, Custom);
661
662     // Use ANDPD and ORPD to simulate FCOPYSIGN.
663     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
665
666     // Lower this to FGETSIGNx86 plus an AND.
667     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
669
670     // We don't support sin/cos/fmod
671     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
672     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
673     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
675     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
676     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
677
678     // Expand FP immediates into loads from the stack, except for the special
679     // cases we handle.
680     addLegalFPImmediate(APFloat(+0.0)); // xorpd
681     addLegalFPImmediate(APFloat(+0.0f)); // xorps
682   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683     // Use SSE for f32, x87 for f64.
684     // Set up the FP register classes.
685     addRegisterClass(MVT::f32, &X86::FR32RegClass);
686     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
687
688     // Use ANDPS to simulate FABS.
689     setOperationAction(ISD::FABS , MVT::f32, Custom);
690
691     // Use XORP to simulate FNEG.
692     setOperationAction(ISD::FNEG , MVT::f32, Custom);
693
694     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
695
696     // Use ANDPS and ORPS to simulate FCOPYSIGN.
697     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
699
700     // We don't support sin/cos/fmod
701     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
702     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
703     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704
705     // Special cases we handle for FP constants.
706     addLegalFPImmediate(APFloat(+0.0f)); // xorps
707     addLegalFPImmediate(APFloat(+0.0)); // FLD0
708     addLegalFPImmediate(APFloat(+1.0)); // FLD1
709     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
711
712     if (!TM.Options.UnsafeFPMath) {
713       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
714       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
715       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
716     }
717   } else if (!TM.Options.UseSoftFloat) {
718     // f32 and f64 in x87.
719     // Set up the FP register classes.
720     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
722
723     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
724     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
725     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
733       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
735     }
736     addLegalFPImmediate(APFloat(+0.0)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
744   }
745
746   // We don't support FMA.
747   setOperationAction(ISD::FMA, MVT::f64, Expand);
748   setOperationAction(ISD::FMA, MVT::f32, Expand);
749
750   // Long double always uses X87.
751   if (!TM.Options.UseSoftFloat) {
752     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
754     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
755     {
756       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757       addLegalFPImmediate(TmpFlt);  // FLD0
758       TmpFlt.changeSign();
759       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
760
761       bool ignored;
762       APFloat TmpFlt2(+1.0);
763       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
764                       &ignored);
765       addLegalFPImmediate(TmpFlt2);  // FLD1
766       TmpFlt2.changeSign();
767       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
768     }
769
770     if (!TM.Options.UnsafeFPMath) {
771       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
772       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
773       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
774     }
775
776     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
778     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
780     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781     setOperationAction(ISD::FMA, MVT::f80, Expand);
782   }
783
784   // Always use a library call for pow.
785   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
786   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
787   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
788
789   setOperationAction(ISD::FLOG, MVT::f80, Expand);
790   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792   setOperationAction(ISD::FEXP, MVT::f80, Expand);
793   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
794
795   // First set operation action for all vector types to either promote
796   // (for widening) or expand (for scalarization). Then we will selectively
797   // turn on ones that can be effectively codegen'd.
798   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800     MVT VT = (MVT::SimpleValueType)i;
801     setOperationAction(ISD::ADD , VT, Expand);
802     setOperationAction(ISD::SUB , VT, Expand);
803     setOperationAction(ISD::FADD, VT, Expand);
804     setOperationAction(ISD::FNEG, VT, Expand);
805     setOperationAction(ISD::FSUB, VT, Expand);
806     setOperationAction(ISD::MUL , VT, Expand);
807     setOperationAction(ISD::FMUL, VT, Expand);
808     setOperationAction(ISD::SDIV, VT, Expand);
809     setOperationAction(ISD::UDIV, VT, Expand);
810     setOperationAction(ISD::FDIV, VT, Expand);
811     setOperationAction(ISD::SREM, VT, Expand);
812     setOperationAction(ISD::UREM, VT, Expand);
813     setOperationAction(ISD::LOAD, VT, Expand);
814     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819     setOperationAction(ISD::FABS, VT, Expand);
820     setOperationAction(ISD::FSIN, VT, Expand);
821     setOperationAction(ISD::FSINCOS, VT, Expand);
822     setOperationAction(ISD::FCOS, VT, Expand);
823     setOperationAction(ISD::FSINCOS, VT, Expand);
824     setOperationAction(ISD::FREM, VT, Expand);
825     setOperationAction(ISD::FMA,  VT, Expand);
826     setOperationAction(ISD::FPOWI, VT, Expand);
827     setOperationAction(ISD::FSQRT, VT, Expand);
828     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829     setOperationAction(ISD::FFLOOR, VT, Expand);
830     setOperationAction(ISD::FCEIL, VT, Expand);
831     setOperationAction(ISD::FTRUNC, VT, Expand);
832     setOperationAction(ISD::FRINT, VT, Expand);
833     setOperationAction(ISD::FNEARBYINT, VT, Expand);
834     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836     setOperationAction(ISD::SDIVREM, VT, Expand);
837     setOperationAction(ISD::UDIVREM, VT, Expand);
838     setOperationAction(ISD::FPOW, VT, Expand);
839     setOperationAction(ISD::CTPOP, VT, Expand);
840     setOperationAction(ISD::CTTZ, VT, Expand);
841     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::CTLZ, VT, Expand);
843     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844     setOperationAction(ISD::SHL, VT, Expand);
845     setOperationAction(ISD::SRA, VT, Expand);
846     setOperationAction(ISD::SRL, VT, Expand);
847     setOperationAction(ISD::ROTL, VT, Expand);
848     setOperationAction(ISD::ROTR, VT, Expand);
849     setOperationAction(ISD::BSWAP, VT, Expand);
850     setOperationAction(ISD::SETCC, VT, Expand);
851     setOperationAction(ISD::FLOG, VT, Expand);
852     setOperationAction(ISD::FLOG2, VT, Expand);
853     setOperationAction(ISD::FLOG10, VT, Expand);
854     setOperationAction(ISD::FEXP, VT, Expand);
855     setOperationAction(ISD::FEXP2, VT, Expand);
856     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861     setOperationAction(ISD::TRUNCATE, VT, Expand);
862     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865     setOperationAction(ISD::VSELECT, VT, Expand);
866     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
867              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
868       setTruncStoreAction(VT,
869                           (MVT::SimpleValueType)InnerVT, Expand);
870     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
871     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
872     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
873   }
874
875   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
876   // with -msoft-float, disable use of MMX as well.
877   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
878     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
879     // No operations on x86mmx supported, everything uses intrinsics.
880   }
881
882   // MMX-sized vectors (other than x86mmx) are expected to be expanded
883   // into smaller operations.
884   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
885   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
886   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
887   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
888   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
889   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
890   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
891   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
892   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
893   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
894   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
895   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
896   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
897   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
898   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
899   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
902   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
903   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
904   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
906   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
907   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
908   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
911   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
912   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
913
914   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
915     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
916
917     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
920     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
921     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
922     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
923     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
924     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
925     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
926     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
927     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
929   }
930
931   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
932     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
933
934     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
935     // registers cannot be used even for integer operations.
936     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
937     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
938     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
939     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
940
941     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
942     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
943     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
944     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
945     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
946     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
947     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
948     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
950     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
951     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
952     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
957     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
958     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
959
960     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
964
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
966     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
970
971     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973       MVT VT = (MVT::SimpleValueType)i;
974       // Do not attempt to custom lower non-power-of-2 vectors
975       if (!isPowerOf2_32(VT.getVectorNumElements()))
976         continue;
977       // Do not attempt to custom lower non-128-bit vectors
978       if (!VT.is128BitVector())
979         continue;
980       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
981       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
982       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
983     }
984
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
986     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
988     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991
992     if (Subtarget->is64Bit()) {
993       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
994       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
995     }
996
997     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999       MVT VT = (MVT::SimpleValueType)i;
1000
1001       // Do not attempt to promote non-128-bit vectors
1002       if (!VT.is128BitVector())
1003         continue;
1004
1005       setOperationAction(ISD::AND,    VT, Promote);
1006       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1007       setOperationAction(ISD::OR,     VT, Promote);
1008       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1009       setOperationAction(ISD::XOR,    VT, Promote);
1010       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1011       setOperationAction(ISD::LOAD,   VT, Promote);
1012       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1013       setOperationAction(ISD::SELECT, VT, Promote);
1014       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1015     }
1016
1017     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018
1019     // Custom lower v2i64 and v2f64 selects.
1020     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1021     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1022     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1023     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1024
1025     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1026     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1027
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1029     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1030     // As there is no 64-bit GPR available, we need build a special custom
1031     // sequence to convert from v2i32 to v2f32.
1032     if (!Subtarget->is64Bit())
1033       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1034
1035     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1036     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1037
1038     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1039   }
1040
1041   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1043     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1044     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1045     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1046     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1047     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1050     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1052
1053     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1054     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1055     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1056     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1057     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1061     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1063
1064     // FIXME: Do we need to handle scalar-to-vector here?
1065     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1066
1067     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1070     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1071     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1072
1073     // i8 and i16 vectors are custom , because the source register and source
1074     // source memory operand types are not the same width.  f32 vectors are
1075     // custom since the immediate controlling the insert encodes additional
1076     // information.
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1079     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1080     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1081
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1086
1087     // FIXME: these should be Legal but thats only for the case where
1088     // the index is constant.  For now custom expand to deal with that.
1089     if (Subtarget->is64Bit()) {
1090       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1091       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1092     }
1093   }
1094
1095   if (Subtarget->hasSSE2()) {
1096     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1104
1105     // In the customized shift lowering, the legal cases in AVX2 will be
1106     // recognized.
1107     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1114
1115     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1116     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1117   }
1118
1119   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1120     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1122     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1123     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1125     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1126
1127     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1129     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1130
1131     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1134     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1137     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1138     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1139     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1140     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1141     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1142     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1143
1144     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1150     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1151     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1152     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1153     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1154     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1155     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1156
1157     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1158     // even though v8i16 is a legal type.
1159     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1160     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1161     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1162
1163     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1164     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1165     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1166
1167     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1168     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1169
1170     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1171
1172     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1179     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1180
1181     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1182
1183     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1184     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1185     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1186     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1187
1188     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1189     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1190     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1191
1192     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1193     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1194     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1195     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1196
1197     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1198     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1199     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1200     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1201     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1202     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1203     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1204     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1205     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1206     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1207     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1208     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1209
1210     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1211       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1212       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1213       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1214       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1215       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1216       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1217     }
1218
1219     if (Subtarget->hasInt256()) {
1220       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1221       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1222       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1223       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1224
1225       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1226       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1227       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1228       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1229
1230       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1232       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1233       // Don't lower v32i8 because there is no 128-bit byte mul
1234
1235       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1236
1237       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1238     } else {
1239       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1240       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1241       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1242       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1243
1244       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1245       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1246       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1247       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1248
1249       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1250       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1251       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1252       // Don't lower v32i8 because there is no 128-bit byte mul
1253     }
1254
1255     // In the customized shift lowering, the legal cases in AVX2 will be
1256     // recognized.
1257     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1258     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1259
1260     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1261     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1262
1263     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1264
1265     // Custom lower several nodes for 256-bit types.
1266     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1267              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1268       MVT VT = (MVT::SimpleValueType)i;
1269
1270       // Extract subvector is special because the value type
1271       // (result) is 128-bit but the source is 256-bit wide.
1272       if (VT.is128BitVector())
1273         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1274
1275       // Do not attempt to custom lower other non-256-bit vectors
1276       if (!VT.is256BitVector())
1277         continue;
1278
1279       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1280       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1281       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1282       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1283       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1284       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1285       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1286     }
1287
1288     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1289     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1290       MVT VT = (MVT::SimpleValueType)i;
1291
1292       // Do not attempt to promote non-256-bit vectors
1293       if (!VT.is256BitVector())
1294         continue;
1295
1296       setOperationAction(ISD::AND,    VT, Promote);
1297       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1298       setOperationAction(ISD::OR,     VT, Promote);
1299       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1300       setOperationAction(ISD::XOR,    VT, Promote);
1301       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1302       setOperationAction(ISD::LOAD,   VT, Promote);
1303       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1304       setOperationAction(ISD::SELECT, VT, Promote);
1305       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1306     }
1307   }
1308
1309   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1310     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1314
1315     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1316     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1317     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1318
1319     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1320     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1321     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1322     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1323     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1324     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1329     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1330
1331     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1333     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1336     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1337
1338     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1342     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1343     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1344     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1345     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1346     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1347
1348     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1349     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1351     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1352     if (Subtarget->is64Bit()) {
1353       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1354       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1355       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1356       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1357     }
1358     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1359     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1361     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1364     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1365     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1366
1367     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1369     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1373     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1374     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1376     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1377     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1379     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1380
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1389     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1390
1391     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1392
1393     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1394     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1396     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1397     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1398     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1399     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1400
1401     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1402     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1403
1404     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1405     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1406
1407     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1408
1409     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1410     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1411
1412     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1413     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1414
1415     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1416     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1417
1418     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1420     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1422     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1423     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1424
1425     // Custom lower several nodes.
1426     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1427              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1428       MVT VT = (MVT::SimpleValueType)i;
1429
1430       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1431       // Extract subvector is special because the value type
1432       // (result) is 256/128-bit but the source is 512-bit wide.
1433       if (VT.is128BitVector() || VT.is256BitVector())
1434         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1435
1436       if (VT.getVectorElementType() == MVT::i1)
1437         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1438
1439       // Do not attempt to custom lower other non-512-bit vectors
1440       if (!VT.is512BitVector())
1441         continue;
1442
1443       if ( EltSize >= 32) {
1444         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1445         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1446         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1447         setOperationAction(ISD::VSELECT,             VT, Legal);
1448         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1449         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1450         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1451       }
1452     }
1453     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1454       MVT VT = (MVT::SimpleValueType)i;
1455
1456       // Do not attempt to promote non-256-bit vectors
1457       if (!VT.is512BitVector())
1458         continue;
1459
1460       setOperationAction(ISD::SELECT, VT, Promote);
1461       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1462     }
1463   }// has  AVX-512
1464
1465   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1466   // of this type with custom code.
1467   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1468            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1469     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1470                        Custom);
1471   }
1472
1473   // We want to custom lower some of our intrinsics.
1474   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1475   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1476   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1477
1478   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479   // handle type legalization for these operations here.
1480   //
1481   // FIXME: We really should do custom legalization for addition and
1482   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1483   // than generic legalization for 64-bit multiplication-with-overflow, though.
1484   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485     // Add/Sub/Mul with overflow operations are custom lowered.
1486     MVT VT = IntVTs[i];
1487     setOperationAction(ISD::SADDO, VT, Custom);
1488     setOperationAction(ISD::UADDO, VT, Custom);
1489     setOperationAction(ISD::SSUBO, VT, Custom);
1490     setOperationAction(ISD::USUBO, VT, Custom);
1491     setOperationAction(ISD::SMULO, VT, Custom);
1492     setOperationAction(ISD::UMULO, VT, Custom);
1493   }
1494
1495   // There are no 8-bit 3-address imul/mul instructions
1496   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1498
1499   if (!Subtarget->is64Bit()) {
1500     // These libcalls are not available in 32-bit.
1501     setLibcallName(RTLIB::SHL_I128, 0);
1502     setLibcallName(RTLIB::SRL_I128, 0);
1503     setLibcallName(RTLIB::SRA_I128, 0);
1504   }
1505
1506   // Combine sin / cos into one node or libcall if possible.
1507   if (Subtarget->hasSinCos()) {
1508     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510     if (Subtarget->isTargetDarwin()) {
1511       // For MacOSX, we don't want to the normal expansion of a libcall to
1512       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1513       // traffic.
1514       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1516     }
1517   }
1518
1519   // We have target-specific dag combine patterns for the following nodes:
1520   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522   setTargetDAGCombine(ISD::VSELECT);
1523   setTargetDAGCombine(ISD::SELECT);
1524   setTargetDAGCombine(ISD::SHL);
1525   setTargetDAGCombine(ISD::SRA);
1526   setTargetDAGCombine(ISD::SRL);
1527   setTargetDAGCombine(ISD::OR);
1528   setTargetDAGCombine(ISD::AND);
1529   setTargetDAGCombine(ISD::ADD);
1530   setTargetDAGCombine(ISD::FADD);
1531   setTargetDAGCombine(ISD::FSUB);
1532   setTargetDAGCombine(ISD::FMA);
1533   setTargetDAGCombine(ISD::SUB);
1534   setTargetDAGCombine(ISD::LOAD);
1535   setTargetDAGCombine(ISD::STORE);
1536   setTargetDAGCombine(ISD::ZERO_EXTEND);
1537   setTargetDAGCombine(ISD::ANY_EXTEND);
1538   setTargetDAGCombine(ISD::SIGN_EXTEND);
1539   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540   setTargetDAGCombine(ISD::TRUNCATE);
1541   setTargetDAGCombine(ISD::SINT_TO_FP);
1542   setTargetDAGCombine(ISD::SETCC);
1543   if (Subtarget->is64Bit())
1544     setTargetDAGCombine(ISD::MUL);
1545   setTargetDAGCombine(ISD::XOR);
1546
1547   computeRegisterProperties();
1548
1549   // On Darwin, -Os means optimize for size without hurting performance,
1550   // do not reduce the limit.
1551   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557   setPrefLoopAlignment(4); // 2^4 bytes.
1558
1559   // Predictable cmov don't hurt on atom because it's in-order.
1560   PredictableSelectIsExpensive = !Subtarget->isAtom();
1561
1562   setPrefFunctionAlignment(4); // 2^4 bytes.
1563 }
1564
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1566   if (!VT.isVector())
1567     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1568
1569   if (Subtarget->hasAVX512())
1570     switch(VT.getVectorNumElements()) {
1571     case  8: return MVT::v8i1;
1572     case 16: return MVT::v16i1;
1573   }
1574
1575   return VT.changeVectorElementTypeToInteger();
1576 }
1577
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1581   if (MaxAlign == 16)
1582     return;
1583   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584     if (VTy->getBitWidth() == 128)
1585       MaxAlign = 16;
1586   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587     unsigned EltAlign = 0;
1588     getMaxByValAlign(ATy->getElementType(), EltAlign);
1589     if (EltAlign > MaxAlign)
1590       MaxAlign = EltAlign;
1591   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593       unsigned EltAlign = 0;
1594       getMaxByValAlign(STy->getElementType(i), EltAlign);
1595       if (EltAlign > MaxAlign)
1596         MaxAlign = EltAlign;
1597       if (MaxAlign == 16)
1598         break;
1599     }
1600   }
1601 }
1602
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608   if (Subtarget->is64Bit()) {
1609     // Max of 8 and alignment of type.
1610     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1611     if (TyAlign > 8)
1612       return TyAlign;
1613     return 8;
1614   }
1615
1616   unsigned Align = 4;
1617   if (Subtarget->hasSSE1())
1618     getMaxByValAlign(Ty, Align);
1619   return Align;
1620 }
1621
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1633 EVT
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635                                        unsigned DstAlign, unsigned SrcAlign,
1636                                        bool IsMemset, bool ZeroMemset,
1637                                        bool MemcpyStrSrc,
1638                                        MachineFunction &MF) const {
1639   const Function *F = MF.getFunction();
1640   if ((!IsMemset || ZeroMemset) &&
1641       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642                                        Attribute::NoImplicitFloat)) {
1643     if (Size >= 16 &&
1644         (Subtarget->isUnalignedMemAccessFast() ||
1645          ((DstAlign == 0 || DstAlign >= 16) &&
1646           (SrcAlign == 0 || SrcAlign >= 16)))) {
1647       if (Size >= 32) {
1648         if (Subtarget->hasInt256())
1649           return MVT::v8i32;
1650         if (Subtarget->hasFp256())
1651           return MVT::v8f32;
1652       }
1653       if (Subtarget->hasSSE2())
1654         return MVT::v4i32;
1655       if (Subtarget->hasSSE1())
1656         return MVT::v4f32;
1657     } else if (!MemcpyStrSrc && Size >= 8 &&
1658                !Subtarget->is64Bit() &&
1659                Subtarget->hasSSE2()) {
1660       // Do not use f64 to lower memcpy if source is string constant. It's
1661       // better to use i32 to avoid the loads.
1662       return MVT::f64;
1663     }
1664   }
1665   if (Subtarget->is64Bit() && Size >= 8)
1666     return MVT::i64;
1667   return MVT::i32;
1668 }
1669
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1671   if (VT == MVT::f32)
1672     return X86ScalarSSEf32;
1673   else if (VT == MVT::f64)
1674     return X86ScalarSSEf64;
1675   return true;
1676 }
1677
1678 bool
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1680                                                  unsigned,
1681                                                  bool *Fast) const {
1682   if (Fast)
1683     *Fast = Subtarget->isUnalignedMemAccessFast();
1684   return true;
1685 }
1686
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function.  The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1692   // symbol.
1693   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694       Subtarget->isPICStyleGOT())
1695     return MachineJumpTableInfo::EK_Custom32;
1696
1697   // Otherwise, use the normal jump table encoding heuristics.
1698   return TargetLowering::getJumpTableEncoding();
1699 }
1700
1701 const MCExpr *
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703                                              const MachineBasicBlock *MBB,
1704                                              unsigned uid,MCContext &Ctx) const{
1705   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706          Subtarget->isPICStyleGOT());
1707   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1708   // entries.
1709   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1711 }
1712
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1714 /// jumptable.
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716                                                     SelectionDAG &DAG) const {
1717   if (!Subtarget->is64Bit())
1718     // This doesn't have SDLoc associated with it, but is not really the
1719     // same as a Register.
1720     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1721   return Table;
1722 }
1723
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1726 /// MCExpr.
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729                              MCContext &Ctx) const {
1730   // X86-64 uses RIP relative addressing based on the jump table label.
1731   if (Subtarget->isPICStyleRIPRel())
1732     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1733
1734   // Otherwise, the reference is relative to the PIC base.
1735   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1736 }
1737
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741   const TargetRegisterClass *RRC = 0;
1742   uint8_t Cost = 1;
1743   switch (VT.SimpleTy) {
1744   default:
1745     return TargetLowering::findRepresentativeClass(VT);
1746   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747     RRC = Subtarget->is64Bit() ?
1748       (const TargetRegisterClass*)&X86::GR64RegClass :
1749       (const TargetRegisterClass*)&X86::GR32RegClass;
1750     break;
1751   case MVT::x86mmx:
1752     RRC = &X86::VR64RegClass;
1753     break;
1754   case MVT::f32: case MVT::f64:
1755   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756   case MVT::v4f32: case MVT::v2f64:
1757   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1758   case MVT::v4f64:
1759     RRC = &X86::VR128RegClass;
1760     break;
1761   }
1762   return std::make_pair(RRC, Cost);
1763 }
1764
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766                                                unsigned &Offset) const {
1767   if (!Subtarget->isTargetLinux())
1768     return false;
1769
1770   if (Subtarget->is64Bit()) {
1771     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1772     Offset = 0x28;
1773     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1774       AddressSpace = 256;
1775     else
1776       AddressSpace = 257;
1777   } else {
1778     // %gs:0x14 on i386
1779     Offset = 0x14;
1780     AddressSpace = 256;
1781   }
1782   return true;
1783 }
1784
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786                                             unsigned DestAS) const {
1787   assert(SrcAS != DestAS && "Expected different address spaces!");
1788
1789   return SrcAS < 256 && DestAS < 256;
1790 }
1791
1792 //===----------------------------------------------------------------------===//
1793 //               Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1795
1796 #include "X86GenCallingConv.inc"
1797
1798 bool
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800                                   MachineFunction &MF, bool isVarArg,
1801                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1802                         LLVMContext &Context) const {
1803   SmallVector<CCValAssign, 16> RVLocs;
1804   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1805                  RVLocs, Context);
1806   return CCInfo.CheckReturn(Outs, RetCC_X86);
1807 }
1808
1809 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1811   return ScratchRegs;
1812 }
1813
1814 SDValue
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816                                CallingConv::ID CallConv, bool isVarArg,
1817                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1818                                const SmallVectorImpl<SDValue> &OutVals,
1819                                SDLoc dl, SelectionDAG &DAG) const {
1820   MachineFunction &MF = DAG.getMachineFunction();
1821   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1822
1823   SmallVector<CCValAssign, 16> RVLocs;
1824   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825                  RVLocs, *DAG.getContext());
1826   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1827
1828   SDValue Flag;
1829   SmallVector<SDValue, 6> RetOps;
1830   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831   // Operand #1 = Bytes To Pop
1832   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1833                    MVT::i16));
1834
1835   // Copy the result values into the output registers.
1836   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837     CCValAssign &VA = RVLocs[i];
1838     assert(VA.isRegLoc() && "Can only return in registers!");
1839     SDValue ValToCopy = OutVals[i];
1840     EVT ValVT = ValToCopy.getValueType();
1841
1842     // Promote values to the appropriate types
1843     if (VA.getLocInfo() == CCValAssign::SExt)
1844       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845     else if (VA.getLocInfo() == CCValAssign::ZExt)
1846       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847     else if (VA.getLocInfo() == CCValAssign::AExt)
1848       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849     else if (VA.getLocInfo() == CCValAssign::BCvt)
1850       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1851
1852     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853            "Unexpected FP-extend for return value.");  
1854
1855     // If this is x86-64, and we disabled SSE, we can't return FP values,
1856     // or SSE or MMX vectors.
1857     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860       report_fatal_error("SSE register return with SSE disabled");
1861     }
1862     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1863     // llvm-gcc has never done it right and no one has noticed, so this
1864     // should be OK for now.
1865     if (ValVT == MVT::f64 &&
1866         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867       report_fatal_error("SSE2 register return with SSE2 disabled");
1868
1869     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870     // the RET instruction and handled by the FP Stackifier.
1871     if (VA.getLocReg() == X86::ST0 ||
1872         VA.getLocReg() == X86::ST1) {
1873       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874       // change the value to the FP stack register class.
1875       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877       RetOps.push_back(ValToCopy);
1878       // Don't emit a copytoreg.
1879       continue;
1880     }
1881
1882     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883     // which is returned in RAX / RDX.
1884     if (Subtarget->is64Bit()) {
1885       if (ValVT == MVT::x86mmx) {
1886         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1889                                   ValToCopy);
1890           // If we don't have SSE2 available, convert to v4f32 so the generated
1891           // register is legal.
1892           if (!Subtarget->hasSSE2())
1893             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1894         }
1895       }
1896     }
1897
1898     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899     Flag = Chain.getValue(1);
1900     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1901   }
1902
1903   // The x86-64 ABIs require that for returning structs by value we copy
1904   // the sret argument into %rax/%eax (depending on ABI) for the return.
1905   // Win32 requires us to put the sret argument to %eax as well.
1906   // We saved the argument into a virtual register in the entry block,
1907   // so now we copy the value out and into %rax/%eax.
1908   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1910     MachineFunction &MF = DAG.getMachineFunction();
1911     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912     unsigned Reg = FuncInfo->getSRetReturnReg();
1913     assert(Reg &&
1914            "SRetReturnReg should have been set in LowerFormalArguments().");
1915     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1916
1917     unsigned RetValReg
1918         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919           X86::RAX : X86::EAX;
1920     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921     Flag = Chain.getValue(1);
1922
1923     // RAX/EAX now acts like a return value.
1924     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1925   }
1926
1927   RetOps[0] = Chain;  // Update chain.
1928
1929   // Add the flag if we have it.
1930   if (Flag.getNode())
1931     RetOps.push_back(Flag);
1932
1933   return DAG.getNode(X86ISD::RET_FLAG, dl,
1934                      MVT::Other, &RetOps[0], RetOps.size());
1935 }
1936
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938   if (N->getNumValues() != 1)
1939     return false;
1940   if (!N->hasNUsesOfValue(1, 0))
1941     return false;
1942
1943   SDValue TCChain = Chain;
1944   SDNode *Copy = *N->use_begin();
1945   if (Copy->getOpcode() == ISD::CopyToReg) {
1946     // If the copy has a glue operand, we conservatively assume it isn't safe to
1947     // perform a tail call.
1948     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1949       return false;
1950     TCChain = Copy->getOperand(0);
1951   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1952     return false;
1953
1954   bool HasRet = false;
1955   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1956        UI != UE; ++UI) {
1957     if (UI->getOpcode() != X86ISD::RET_FLAG)
1958       return false;
1959     HasRet = true;
1960   }
1961
1962   if (!HasRet)
1963     return false;
1964
1965   Chain = TCChain;
1966   return true;
1967 }
1968
1969 MVT
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971                                             ISD::NodeType ExtendKind) const {
1972   MVT ReturnMVT;
1973   // TODO: Is this also valid on 32-bit?
1974   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975     ReturnMVT = MVT::i8;
1976   else
1977     ReturnMVT = MVT::i32;
1978
1979   MVT MinVT = getRegisterType(ReturnMVT);
1980   return VT.bitsLT(MinVT) ? MinVT : VT;
1981 }
1982
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1985 ///
1986 SDValue
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988                                    CallingConv::ID CallConv, bool isVarArg,
1989                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1990                                    SDLoc dl, SelectionDAG &DAG,
1991                                    SmallVectorImpl<SDValue> &InVals) const {
1992
1993   // Assign locations to each value returned by this call.
1994   SmallVector<CCValAssign, 16> RVLocs;
1995   bool Is64Bit = Subtarget->is64Bit();
1996   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997                  getTargetMachine(), RVLocs, *DAG.getContext());
1998   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1999
2000   // Copy all of the result registers out of their specified physreg.
2001   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002     CCValAssign &VA = RVLocs[i];
2003     EVT CopyVT = VA.getValVT();
2004
2005     // If this is x86-64, and we disabled SSE, we can't return FP values
2006     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008       report_fatal_error("SSE register return with SSE disabled");
2009     }
2010
2011     SDValue Val;
2012
2013     // If this is a call to a function that returns an fp value on the floating
2014     // point stack, we must guarantee the value is popped from the stack, so
2015     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016     // if the return value is not used. We use the FpPOP_RETVAL instruction
2017     // instead.
2018     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019       // If we prefer to use the value in xmm registers, copy it out as f80 and
2020       // use a truncate to move it from fp stack reg to xmm reg.
2021       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022       SDValue Ops[] = { Chain, InFlag };
2023       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024                                          MVT::Other, MVT::Glue, Ops), 1);
2025       Val = Chain.getValue(0);
2026
2027       // Round the f80 to the right size, which also moves it to the appropriate
2028       // xmm register.
2029       if (CopyVT != VA.getValVT())
2030         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031                           // This truncation won't change the value.
2032                           DAG.getIntPtrConstant(1));
2033     } else {
2034       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035                                  CopyVT, InFlag).getValue(1);
2036       Val = Chain.getValue(0);
2037     }
2038     InFlag = Chain.getValue(2);
2039     InVals.push_back(Val);
2040   }
2041
2042   return Chain;
2043 }
2044
2045 //===----------------------------------------------------------------------===//
2046 //                C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 //  StdCall calling convention seems to be standard for many Windows' API
2049 //  routines and around. It differs from C calling convention just a little:
2050 //  callee should clean up the stack, not caller. Symbols should be also
2051 //  decorated in some fancy way :) It doesn't support any vector arguments.
2052 //  For info on fast calling convention see Fast Calling Convention (tail call)
2053 //  implementation LowerX86_32FastCCCallTo.
2054
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2056 /// semantics.
2057 enum StructReturnType {
2058   NotStructReturn,
2059   RegStructReturn,
2060   StackStructReturn
2061 };
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2064   if (Outs.empty())
2065     return NotStructReturn;
2066
2067   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068   if (!Flags.isSRet())
2069     return NotStructReturn;
2070   if (Flags.isInReg())
2071     return RegStructReturn;
2072   return StackStructReturn;
2073 }
2074
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2079   if (Ins.empty())
2080     return NotStructReturn;
2081
2082   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083   if (!Flags.isSRet())
2084     return NotStructReturn;
2085   if (Flags.isInReg())
2086     return RegStructReturn;
2087   return StackStructReturn;
2088 }
2089
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2094 static SDValue
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2097                           SDLoc dl) {
2098   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2099
2100   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101                        /*isVolatile*/false, /*AlwaysInline=*/true,
2102                        MachinePointerInfo(), MachinePointerInfo());
2103 }
2104
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109           CC == CallingConv::HiPE);
2110 }
2111
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115           CC == CallingConv::X86_64_SysV);
2116 }
2117
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2120     return false;
2121
2122   CallSite CS(CI);
2123   CallingConv::ID CalleeCC = CS.getCallingConv();
2124   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2125     return false;
2126
2127   return true;
2128 }
2129
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133                                    bool GuaranteedTailCallOpt) {
2134   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2135 }
2136
2137 SDValue
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139                                     CallingConv::ID CallConv,
2140                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2141                                     SDLoc dl, SelectionDAG &DAG,
2142                                     const CCValAssign &VA,
2143                                     MachineFrameInfo *MFI,
2144                                     unsigned i) const {
2145   // Create the nodes corresponding to a load from this parameter slot.
2146   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148                               getTargetMachine().Options.GuaranteedTailCallOpt);
2149   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2150   EVT ValVT;
2151
2152   // If value is passed by pointer we have address passed instead of the value
2153   // itself.
2154   if (VA.getLocInfo() == CCValAssign::Indirect)
2155     ValVT = VA.getLocVT();
2156   else
2157     ValVT = VA.getValVT();
2158
2159   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160   // changed with more analysis.
2161   // In case of tail call optimization mark all arguments mutable. Since they
2162   // could be overwritten by lowering of arguments in case of a tail call.
2163   if (Flags.isByVal()) {
2164     unsigned Bytes = Flags.getByValSize();
2165     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167     return DAG.getFrameIndex(FI, getPointerTy());
2168   } else {
2169     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170                                     VA.getLocMemOffset(), isImmutable);
2171     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172     return DAG.getLoad(ValVT, dl, Chain, FIN,
2173                        MachinePointerInfo::getFixedStack(FI),
2174                        false, false, false, 0);
2175   }
2176 }
2177
2178 SDValue
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180                                         CallingConv::ID CallConv,
2181                                         bool isVarArg,
2182                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2183                                         SDLoc dl,
2184                                         SelectionDAG &DAG,
2185                                         SmallVectorImpl<SDValue> &InVals)
2186                                           const {
2187   MachineFunction &MF = DAG.getMachineFunction();
2188   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2189
2190   const Function* Fn = MF.getFunction();
2191   if (Fn->hasExternalLinkage() &&
2192       Subtarget->isTargetCygMing() &&
2193       Fn->getName() == "main")
2194     FuncInfo->setForceFramePointer(true);
2195
2196   MachineFrameInfo *MFI = MF.getFrameInfo();
2197   bool Is64Bit = Subtarget->is64Bit();
2198   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2199
2200   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201          "Var args not supported with calling convention fastcc, ghc or hipe");
2202
2203   // Assign locations to all of the incoming arguments.
2204   SmallVector<CCValAssign, 16> ArgLocs;
2205   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206                  ArgLocs, *DAG.getContext());
2207
2208   // Allocate shadow area for Win64
2209   if (IsWin64)
2210     CCInfo.AllocateStack(32, 8);
2211
2212   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2213
2214   unsigned LastVal = ~0U;
2215   SDValue ArgValue;
2216   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217     CCValAssign &VA = ArgLocs[i];
2218     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2219     // places.
2220     assert(VA.getValNo() != LastVal &&
2221            "Don't support value assigned to multiple locs yet");
2222     (void)LastVal;
2223     LastVal = VA.getValNo();
2224
2225     if (VA.isRegLoc()) {
2226       EVT RegVT = VA.getLocVT();
2227       const TargetRegisterClass *RC;
2228       if (RegVT == MVT::i32)
2229         RC = &X86::GR32RegClass;
2230       else if (Is64Bit && RegVT == MVT::i64)
2231         RC = &X86::GR64RegClass;
2232       else if (RegVT == MVT::f32)
2233         RC = &X86::FR32RegClass;
2234       else if (RegVT == MVT::f64)
2235         RC = &X86::FR64RegClass;
2236       else if (RegVT.is512BitVector())
2237         RC = &X86::VR512RegClass;
2238       else if (RegVT.is256BitVector())
2239         RC = &X86::VR256RegClass;
2240       else if (RegVT.is128BitVector())
2241         RC = &X86::VR128RegClass;
2242       else if (RegVT == MVT::x86mmx)
2243         RC = &X86::VR64RegClass;
2244       else if (RegVT == MVT::i1)
2245         RC = &X86::VK1RegClass;
2246       else if (RegVT == MVT::v8i1)
2247         RC = &X86::VK8RegClass;
2248       else if (RegVT == MVT::v16i1)
2249         RC = &X86::VK16RegClass;
2250       else
2251         llvm_unreachable("Unknown argument type!");
2252
2253       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2255
2256       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2258       // right size.
2259       if (VA.getLocInfo() == CCValAssign::SExt)
2260         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261                                DAG.getValueType(VA.getValVT()));
2262       else if (VA.getLocInfo() == CCValAssign::ZExt)
2263         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264                                DAG.getValueType(VA.getValVT()));
2265       else if (VA.getLocInfo() == CCValAssign::BCvt)
2266         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2267
2268       if (VA.isExtInLoc()) {
2269         // Handle MMX values passed in XMM regs.
2270         if (RegVT.isVector())
2271           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2272         else
2273           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2274       }
2275     } else {
2276       assert(VA.isMemLoc());
2277       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2278     }
2279
2280     // If value is passed via pointer - do a load.
2281     if (VA.getLocInfo() == CCValAssign::Indirect)
2282       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283                              MachinePointerInfo(), false, false, false, 0);
2284
2285     InVals.push_back(ArgValue);
2286   }
2287
2288   // The x86-64 ABIs require that for returning structs by value we copy
2289   // the sret argument into %rax/%eax (depending on ABI) for the return.
2290   // Win32 requires us to put the sret argument to %eax as well.
2291   // Save the argument into a virtual register so that we can access it
2292   // from the return points.
2293   if (MF.getFunction()->hasStructRetAttr() &&
2294       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2295     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296     unsigned Reg = FuncInfo->getSRetReturnReg();
2297     if (!Reg) {
2298       MVT PtrTy = getPointerTy();
2299       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300       FuncInfo->setSRetReturnReg(Reg);
2301     }
2302     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2304   }
2305
2306   unsigned StackSize = CCInfo.getNextStackOffset();
2307   // Align stack specially for tail calls.
2308   if (FuncIsMadeTailCallSafe(CallConv,
2309                              MF.getTarget().Options.GuaranteedTailCallOpt))
2310     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2311
2312   // If the function takes variable number of arguments, make a frame index for
2313   // the start of the first vararg value... for expansion of llvm.va_start.
2314   if (isVarArg) {
2315     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316                     CallConv != CallingConv::X86_ThisCall)) {
2317       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2318     }
2319     if (Is64Bit) {
2320       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2321
2322       // FIXME: We should really autogenerate these arrays
2323       static const MCPhysReg GPR64ArgRegsWin64[] = {
2324         X86::RCX, X86::RDX, X86::R8,  X86::R9
2325       };
2326       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2327         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2328       };
2329       static const MCPhysReg XMMArgRegs64Bit[] = {
2330         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2332       };
2333       const MCPhysReg *GPR64ArgRegs;
2334       unsigned NumXMMRegs = 0;
2335
2336       if (IsWin64) {
2337         // The XMM registers which might contain var arg parameters are shadowed
2338         // in their paired GPR.  So we only need to save the GPR to their home
2339         // slots.
2340         TotalNumIntRegs = 4;
2341         GPR64ArgRegs = GPR64ArgRegsWin64;
2342       } else {
2343         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344         GPR64ArgRegs = GPR64ArgRegs64Bit;
2345
2346         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2347                                                 TotalNumXMMRegs);
2348       }
2349       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2350                                                        TotalNumIntRegs);
2351
2352       bool NoImplicitFloatOps = Fn->getAttributes().
2353         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355              "SSE register cannot be used when SSE is disabled!");
2356       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357                NoImplicitFloatOps) &&
2358              "SSE register cannot be used when SSE is disabled!");
2359       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360           !Subtarget->hasSSE1())
2361         // Kernel mode asks for SSE to be disabled, so don't push them
2362         // on the stack.
2363         TotalNumXMMRegs = 0;
2364
2365       if (IsWin64) {
2366         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367         // Get to the caller-allocated home save location.  Add 8 to account
2368         // for the return address.
2369         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370         FuncInfo->setRegSaveFrameIndex(
2371           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372         // Fixup to set vararg frame on shadow area (4 x i64).
2373         if (NumIntRegs < 4)
2374           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2375       } else {
2376         // For X86-64, if there are vararg parameters that are passed via
2377         // registers, then we must store them to their spots on the stack so
2378         // they may be loaded by deferencing the result of va_next.
2379         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381         FuncInfo->setRegSaveFrameIndex(
2382           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2383                                false));
2384       }
2385
2386       // Store the integer parameter registers.
2387       SmallVector<SDValue, 8> MemOps;
2388       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2389                                         getPointerTy());
2390       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393                                   DAG.getIntPtrConstant(Offset));
2394         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395                                      &X86::GR64RegClass);
2396         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2397         SDValue Store =
2398           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399                        MachinePointerInfo::getFixedStack(
2400                          FuncInfo->getRegSaveFrameIndex(), Offset),
2401                        false, false, 0);
2402         MemOps.push_back(Store);
2403         Offset += 8;
2404       }
2405
2406       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407         // Now store the XMM (fp + vector) parameter registers.
2408         SmallVector<SDValue, 11> SaveXMMOps;
2409         SaveXMMOps.push_back(Chain);
2410
2411         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413         SaveXMMOps.push_back(ALVal);
2414
2415         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416                                FuncInfo->getRegSaveFrameIndex()));
2417         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418                                FuncInfo->getVarArgsFPOffset()));
2419
2420         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422                                        &X86::VR128RegClass);
2423           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424           SaveXMMOps.push_back(Val);
2425         }
2426         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2427                                      MVT::Other,
2428                                      &SaveXMMOps[0], SaveXMMOps.size()));
2429       }
2430
2431       if (!MemOps.empty())
2432         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433                             &MemOps[0], MemOps.size());
2434     }
2435   }
2436
2437   // Some CCs need callee pop.
2438   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2441   } else {
2442     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443     // If this is an sret function, the return should pop the hidden pointer.
2444     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446         argsAreStructReturn(Ins) == StackStructReturn)
2447       FuncInfo->setBytesToPopOnReturn(4);
2448   }
2449
2450   if (!Is64Bit) {
2451     // RegSaveFrameIndex is X86-64 only.
2452     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453     if (CallConv == CallingConv::X86_FastCall ||
2454         CallConv == CallingConv::X86_ThisCall)
2455       // fastcc functions can't have varargs.
2456       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2457   }
2458
2459   FuncInfo->setArgumentStackSize(StackSize);
2460
2461   return Chain;
2462 }
2463
2464 SDValue
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466                                     SDValue StackPtr, SDValue Arg,
2467                                     SDLoc dl, SelectionDAG &DAG,
2468                                     const CCValAssign &VA,
2469                                     ISD::ArgFlagsTy Flags) const {
2470   unsigned LocMemOffset = VA.getLocMemOffset();
2471   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473   if (Flags.isByVal())
2474     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2475
2476   return DAG.getStore(Chain, dl, Arg, PtrOff,
2477                       MachinePointerInfo::getStack(LocMemOffset),
2478                       false, false, 0);
2479 }
2480
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2483 SDValue
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485                                            SDValue &OutRetAddr, SDValue Chain,
2486                                            bool IsTailCall, bool Is64Bit,
2487                                            int FPDiff, SDLoc dl) const {
2488   // Adjust the Return address stack slot.
2489   EVT VT = getPointerTy();
2490   OutRetAddr = getReturnAddressFrameIndex(DAG);
2491
2492   // Load the "old" Return address.
2493   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494                            false, false, false, 0);
2495   return SDValue(OutRetAddr.getNode(), 1);
2496 }
2497
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2500 static SDValue
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2504   // Store the return address to the appropriate stack slot.
2505   if (!FPDiff) return Chain;
2506   // Calculate the new stack slot for the return address.
2507   int NewReturnAddrFI =
2508     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2509                                          false);
2510   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2513                        false, false, 0);
2514   return Chain;
2515 }
2516
2517 SDValue
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519                              SmallVectorImpl<SDValue> &InVals) const {
2520   SelectionDAG &DAG                     = CLI.DAG;
2521   SDLoc &dl                             = CLI.DL;
2522   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2524   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2525   SDValue Chain                         = CLI.Chain;
2526   SDValue Callee                        = CLI.Callee;
2527   CallingConv::ID CallConv              = CLI.CallConv;
2528   bool &isTailCall                      = CLI.IsTailCall;
2529   bool isVarArg                         = CLI.IsVarArg;
2530
2531   MachineFunction &MF = DAG.getMachineFunction();
2532   bool Is64Bit        = Subtarget->is64Bit();
2533   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2534   StructReturnType SR = callIsStructReturn(Outs);
2535   bool IsSibcall      = false;
2536
2537   if (MF.getTarget().Options.DisableTailCalls)
2538     isTailCall = false;
2539
2540   if (isTailCall) {
2541     // Check if it's really possible to do a tail call.
2542     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543                     isVarArg, SR != NotStructReturn,
2544                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545                     Outs, OutVals, Ins, DAG);
2546
2547     // Sibcalls are automatically detected tailcalls which do not require
2548     // ABI changes.
2549     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2550       IsSibcall = true;
2551
2552     if (isTailCall)
2553       ++NumTailCalls;
2554   }
2555
2556   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2557          "Var args not supported with calling convention fastcc, ghc or hipe");
2558
2559   // Analyze operands of the call, assigning locations to each operand.
2560   SmallVector<CCValAssign, 16> ArgLocs;
2561   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2562                  ArgLocs, *DAG.getContext());
2563
2564   // Allocate shadow area for Win64
2565   if (IsWin64)
2566     CCInfo.AllocateStack(32, 8);
2567
2568   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2569
2570   // Get a count of how many bytes are to be pushed on the stack.
2571   unsigned NumBytes = CCInfo.getNextStackOffset();
2572   if (IsSibcall)
2573     // This is a sibcall. The memory operands are available in caller's
2574     // own caller's stack.
2575     NumBytes = 0;
2576   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2577            IsTailCallConvention(CallConv))
2578     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2579
2580   int FPDiff = 0;
2581   if (isTailCall && !IsSibcall) {
2582     // Lower arguments at fp - stackoffset + fpdiff.
2583     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2584     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2585
2586     FPDiff = NumBytesCallerPushed - NumBytes;
2587
2588     // Set the delta of movement of the returnaddr stackslot.
2589     // But only set if delta is greater than previous delta.
2590     if (FPDiff < X86Info->getTCReturnAddrDelta())
2591       X86Info->setTCReturnAddrDelta(FPDiff);
2592   }
2593
2594   unsigned NumBytesToPush = NumBytes;
2595   unsigned NumBytesToPop = NumBytes;
2596
2597   // If we have an inalloca argument, all stack space has already been allocated
2598   // for us and be right at the top of the stack.  We don't support multiple
2599   // arguments passed in memory when using inalloca.
2600   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2601     NumBytesToPush = 0;
2602     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2603            "an inalloca argument must be the only memory argument");
2604   }
2605
2606   if (!IsSibcall)
2607     Chain = DAG.getCALLSEQ_START(
2608         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2609
2610   SDValue RetAddrFrIdx;
2611   // Load return address for tail calls.
2612   if (isTailCall && FPDiff)
2613     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2614                                     Is64Bit, FPDiff, dl);
2615
2616   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2617   SmallVector<SDValue, 8> MemOpChains;
2618   SDValue StackPtr;
2619
2620   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2621   // of tail call optimization arguments are handle later.
2622   const X86RegisterInfo *RegInfo =
2623     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2624   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2625     // Skip inalloca arguments, they have already been written.
2626     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2627     if (Flags.isInAlloca())
2628       continue;
2629
2630     CCValAssign &VA = ArgLocs[i];
2631     EVT RegVT = VA.getLocVT();
2632     SDValue Arg = OutVals[i];
2633     bool isByVal = Flags.isByVal();
2634
2635     // Promote the value if needed.
2636     switch (VA.getLocInfo()) {
2637     default: llvm_unreachable("Unknown loc info!");
2638     case CCValAssign::Full: break;
2639     case CCValAssign::SExt:
2640       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2641       break;
2642     case CCValAssign::ZExt:
2643       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2644       break;
2645     case CCValAssign::AExt:
2646       if (RegVT.is128BitVector()) {
2647         // Special case: passing MMX values in XMM registers.
2648         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2649         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2650         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2651       } else
2652         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2653       break;
2654     case CCValAssign::BCvt:
2655       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2656       break;
2657     case CCValAssign::Indirect: {
2658       // Store the argument.
2659       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2660       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2661       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2662                            MachinePointerInfo::getFixedStack(FI),
2663                            false, false, 0);
2664       Arg = SpillSlot;
2665       break;
2666     }
2667     }
2668
2669     if (VA.isRegLoc()) {
2670       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2671       if (isVarArg && IsWin64) {
2672         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2673         // shadow reg if callee is a varargs function.
2674         unsigned ShadowReg = 0;
2675         switch (VA.getLocReg()) {
2676         case X86::XMM0: ShadowReg = X86::RCX; break;
2677         case X86::XMM1: ShadowReg = X86::RDX; break;
2678         case X86::XMM2: ShadowReg = X86::R8; break;
2679         case X86::XMM3: ShadowReg = X86::R9; break;
2680         }
2681         if (ShadowReg)
2682           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2683       }
2684     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2685       assert(VA.isMemLoc());
2686       if (StackPtr.getNode() == 0)
2687         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2688                                       getPointerTy());
2689       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2690                                              dl, DAG, VA, Flags));
2691     }
2692   }
2693
2694   if (!MemOpChains.empty())
2695     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2696                         &MemOpChains[0], MemOpChains.size());
2697
2698   if (Subtarget->isPICStyleGOT()) {
2699     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2700     // GOT pointer.
2701     if (!isTailCall) {
2702       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2703                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2704     } else {
2705       // If we are tail calling and generating PIC/GOT style code load the
2706       // address of the callee into ECX. The value in ecx is used as target of
2707       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2708       // for tail calls on PIC/GOT architectures. Normally we would just put the
2709       // address of GOT into ebx and then call target@PLT. But for tail calls
2710       // ebx would be restored (since ebx is callee saved) before jumping to the
2711       // target@PLT.
2712
2713       // Note: The actual moving to ECX is done further down.
2714       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2715       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2716           !G->getGlobal()->hasProtectedVisibility())
2717         Callee = LowerGlobalAddress(Callee, DAG);
2718       else if (isa<ExternalSymbolSDNode>(Callee))
2719         Callee = LowerExternalSymbol(Callee, DAG);
2720     }
2721   }
2722
2723   if (Is64Bit && isVarArg && !IsWin64) {
2724     // From AMD64 ABI document:
2725     // For calls that may call functions that use varargs or stdargs
2726     // (prototype-less calls or calls to functions containing ellipsis (...) in
2727     // the declaration) %al is used as hidden argument to specify the number
2728     // of SSE registers used. The contents of %al do not need to match exactly
2729     // the number of registers, but must be an ubound on the number of SSE
2730     // registers used and is in the range 0 - 8 inclusive.
2731
2732     // Count the number of XMM registers allocated.
2733     static const MCPhysReg XMMArgRegs[] = {
2734       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2735       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2736     };
2737     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2738     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2739            && "SSE registers cannot be used when SSE is disabled");
2740
2741     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2742                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2743   }
2744
2745   // For tail calls lower the arguments to the 'real' stack slot.
2746   if (isTailCall) {
2747     // Force all the incoming stack arguments to be loaded from the stack
2748     // before any new outgoing arguments are stored to the stack, because the
2749     // outgoing stack slots may alias the incoming argument stack slots, and
2750     // the alias isn't otherwise explicit. This is slightly more conservative
2751     // than necessary, because it means that each store effectively depends
2752     // on every argument instead of just those arguments it would clobber.
2753     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2754
2755     SmallVector<SDValue, 8> MemOpChains2;
2756     SDValue FIN;
2757     int FI = 0;
2758     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2759       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2760         CCValAssign &VA = ArgLocs[i];
2761         if (VA.isRegLoc())
2762           continue;
2763         assert(VA.isMemLoc());
2764         SDValue Arg = OutVals[i];
2765         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2766         // Create frame index.
2767         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2768         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2769         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2770         FIN = DAG.getFrameIndex(FI, getPointerTy());
2771
2772         if (Flags.isByVal()) {
2773           // Copy relative to framepointer.
2774           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2775           if (StackPtr.getNode() == 0)
2776             StackPtr = DAG.getCopyFromReg(Chain, dl,
2777                                           RegInfo->getStackRegister(),
2778                                           getPointerTy());
2779           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2780
2781           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2782                                                            ArgChain,
2783                                                            Flags, DAG, dl));
2784         } else {
2785           // Store relative to framepointer.
2786           MemOpChains2.push_back(
2787             DAG.getStore(ArgChain, dl, Arg, FIN,
2788                          MachinePointerInfo::getFixedStack(FI),
2789                          false, false, 0));
2790         }
2791       }
2792     }
2793
2794     if (!MemOpChains2.empty())
2795       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2796                           &MemOpChains2[0], MemOpChains2.size());
2797
2798     // Store the return address to the appropriate stack slot.
2799     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2800                                      getPointerTy(), RegInfo->getSlotSize(),
2801                                      FPDiff, dl);
2802   }
2803
2804   // Build a sequence of copy-to-reg nodes chained together with token chain
2805   // and flag operands which copy the outgoing args into registers.
2806   SDValue InFlag;
2807   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2808     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2809                              RegsToPass[i].second, InFlag);
2810     InFlag = Chain.getValue(1);
2811   }
2812
2813   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2814     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2815     // In the 64-bit large code model, we have to make all calls
2816     // through a register, since the call instruction's 32-bit
2817     // pc-relative offset may not be large enough to hold the whole
2818     // address.
2819   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2820     // If the callee is a GlobalAddress node (quite common, every direct call
2821     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2822     // it.
2823
2824     // We should use extra load for direct calls to dllimported functions in
2825     // non-JIT mode.
2826     const GlobalValue *GV = G->getGlobal();
2827     if (!GV->hasDLLImportStorageClass()) {
2828       unsigned char OpFlags = 0;
2829       bool ExtraLoad = false;
2830       unsigned WrapperKind = ISD::DELETED_NODE;
2831
2832       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2833       // external symbols most go through the PLT in PIC mode.  If the symbol
2834       // has hidden or protected visibility, or if it is static or local, then
2835       // we don't need to use the PLT - we can directly call it.
2836       if (Subtarget->isTargetELF() &&
2837           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2838           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2839         OpFlags = X86II::MO_PLT;
2840       } else if (Subtarget->isPICStyleStubAny() &&
2841                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2842                  (!Subtarget->getTargetTriple().isMacOSX() ||
2843                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2844         // PC-relative references to external symbols should go through $stub,
2845         // unless we're building with the leopard linker or later, which
2846         // automatically synthesizes these stubs.
2847         OpFlags = X86II::MO_DARWIN_STUB;
2848       } else if (Subtarget->isPICStyleRIPRel() &&
2849                  isa<Function>(GV) &&
2850                  cast<Function>(GV)->getAttributes().
2851                    hasAttribute(AttributeSet::FunctionIndex,
2852                                 Attribute::NonLazyBind)) {
2853         // If the function is marked as non-lazy, generate an indirect call
2854         // which loads from the GOT directly. This avoids runtime overhead
2855         // at the cost of eager binding (and one extra byte of encoding).
2856         OpFlags = X86II::MO_GOTPCREL;
2857         WrapperKind = X86ISD::WrapperRIP;
2858         ExtraLoad = true;
2859       }
2860
2861       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2862                                           G->getOffset(), OpFlags);
2863
2864       // Add a wrapper if needed.
2865       if (WrapperKind != ISD::DELETED_NODE)
2866         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2867       // Add extra indirection if needed.
2868       if (ExtraLoad)
2869         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2870                              MachinePointerInfo::getGOT(),
2871                              false, false, false, 0);
2872     }
2873   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2874     unsigned char OpFlags = 0;
2875
2876     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2877     // external symbols should go through the PLT.
2878     if (Subtarget->isTargetELF() &&
2879         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2880       OpFlags = X86II::MO_PLT;
2881     } else if (Subtarget->isPICStyleStubAny() &&
2882                (!Subtarget->getTargetTriple().isMacOSX() ||
2883                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2884       // PC-relative references to external symbols should go through $stub,
2885       // unless we're building with the leopard linker or later, which
2886       // automatically synthesizes these stubs.
2887       OpFlags = X86II::MO_DARWIN_STUB;
2888     }
2889
2890     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2891                                          OpFlags);
2892   }
2893
2894   // Returns a chain & a flag for retval copy to use.
2895   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2896   SmallVector<SDValue, 8> Ops;
2897
2898   if (!IsSibcall && isTailCall) {
2899     Chain = DAG.getCALLSEQ_END(Chain,
2900                                DAG.getIntPtrConstant(NumBytesToPop, true),
2901                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2902     InFlag = Chain.getValue(1);
2903   }
2904
2905   Ops.push_back(Chain);
2906   Ops.push_back(Callee);
2907
2908   if (isTailCall)
2909     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2910
2911   // Add argument registers to the end of the list so that they are known live
2912   // into the call.
2913   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2914     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2915                                   RegsToPass[i].second.getValueType()));
2916
2917   // Add a register mask operand representing the call-preserved registers.
2918   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2919   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2920   assert(Mask && "Missing call preserved mask for calling convention");
2921   Ops.push_back(DAG.getRegisterMask(Mask));
2922
2923   if (InFlag.getNode())
2924     Ops.push_back(InFlag);
2925
2926   if (isTailCall) {
2927     // We used to do:
2928     //// If this is the first return lowered for this function, add the regs
2929     //// to the liveout set for the function.
2930     // This isn't right, although it's probably harmless on x86; liveouts
2931     // should be computed from returns not tail calls.  Consider a void
2932     // function making a tail call to a function returning int.
2933     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2934   }
2935
2936   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2937   InFlag = Chain.getValue(1);
2938
2939   // Create the CALLSEQ_END node.
2940   unsigned NumBytesForCalleeToPop;
2941   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2942                        getTargetMachine().Options.GuaranteedTailCallOpt))
2943     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2944   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2945            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2946            SR == StackStructReturn)
2947     // If this is a call to a struct-return function, the callee
2948     // pops the hidden struct pointer, so we have to push it back.
2949     // This is common for Darwin/X86, Linux & Mingw32 targets.
2950     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2951     NumBytesForCalleeToPop = 4;
2952   else
2953     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2954
2955   // Returns a flag for retval copy to use.
2956   if (!IsSibcall) {
2957     Chain = DAG.getCALLSEQ_END(Chain,
2958                                DAG.getIntPtrConstant(NumBytesToPop, true),
2959                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2960                                                      true),
2961                                InFlag, dl);
2962     InFlag = Chain.getValue(1);
2963   }
2964
2965   // Handle result values, copying them out of physregs into vregs that we
2966   // return.
2967   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2968                          Ins, dl, DAG, InVals);
2969 }
2970
2971 //===----------------------------------------------------------------------===//
2972 //                Fast Calling Convention (tail call) implementation
2973 //===----------------------------------------------------------------------===//
2974
2975 //  Like std call, callee cleans arguments, convention except that ECX is
2976 //  reserved for storing the tail called function address. Only 2 registers are
2977 //  free for argument passing (inreg). Tail call optimization is performed
2978 //  provided:
2979 //                * tailcallopt is enabled
2980 //                * caller/callee are fastcc
2981 //  On X86_64 architecture with GOT-style position independent code only local
2982 //  (within module) calls are supported at the moment.
2983 //  To keep the stack aligned according to platform abi the function
2984 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2985 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2986 //  If a tail called function callee has more arguments than the caller the
2987 //  caller needs to make sure that there is room to move the RETADDR to. This is
2988 //  achieved by reserving an area the size of the argument delta right after the
2989 //  original REtADDR, but before the saved framepointer or the spilled registers
2990 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2991 //  stack layout:
2992 //    arg1
2993 //    arg2
2994 //    RETADDR
2995 //    [ new RETADDR
2996 //      move area ]
2997 //    (possible EBP)
2998 //    ESI
2999 //    EDI
3000 //    local1 ..
3001
3002 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3003 /// for a 16 byte align requirement.
3004 unsigned
3005 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3006                                                SelectionDAG& DAG) const {
3007   MachineFunction &MF = DAG.getMachineFunction();
3008   const TargetMachine &TM = MF.getTarget();
3009   const X86RegisterInfo *RegInfo =
3010     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3011   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3012   unsigned StackAlignment = TFI.getStackAlignment();
3013   uint64_t AlignMask = StackAlignment - 1;
3014   int64_t Offset = StackSize;
3015   unsigned SlotSize = RegInfo->getSlotSize();
3016   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3017     // Number smaller than 12 so just add the difference.
3018     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3019   } else {
3020     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3021     Offset = ((~AlignMask) & Offset) + StackAlignment +
3022       (StackAlignment-SlotSize);
3023   }
3024   return Offset;
3025 }
3026
3027 /// MatchingStackOffset - Return true if the given stack call argument is
3028 /// already available in the same position (relatively) of the caller's
3029 /// incoming argument stack.
3030 static
3031 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3032                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3033                          const X86InstrInfo *TII) {
3034   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3035   int FI = INT_MAX;
3036   if (Arg.getOpcode() == ISD::CopyFromReg) {
3037     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3038     if (!TargetRegisterInfo::isVirtualRegister(VR))
3039       return false;
3040     MachineInstr *Def = MRI->getVRegDef(VR);
3041     if (!Def)
3042       return false;
3043     if (!Flags.isByVal()) {
3044       if (!TII->isLoadFromStackSlot(Def, FI))
3045         return false;
3046     } else {
3047       unsigned Opcode = Def->getOpcode();
3048       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3049           Def->getOperand(1).isFI()) {
3050         FI = Def->getOperand(1).getIndex();
3051         Bytes = Flags.getByValSize();
3052       } else
3053         return false;
3054     }
3055   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3056     if (Flags.isByVal())
3057       // ByVal argument is passed in as a pointer but it's now being
3058       // dereferenced. e.g.
3059       // define @foo(%struct.X* %A) {
3060       //   tail call @bar(%struct.X* byval %A)
3061       // }
3062       return false;
3063     SDValue Ptr = Ld->getBasePtr();
3064     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3065     if (!FINode)
3066       return false;
3067     FI = FINode->getIndex();
3068   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3069     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3070     FI = FINode->getIndex();
3071     Bytes = Flags.getByValSize();
3072   } else
3073     return false;
3074
3075   assert(FI != INT_MAX);
3076   if (!MFI->isFixedObjectIndex(FI))
3077     return false;
3078   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3079 }
3080
3081 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3082 /// for tail call optimization. Targets which want to do tail call
3083 /// optimization should implement this function.
3084 bool
3085 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3086                                                      CallingConv::ID CalleeCC,
3087                                                      bool isVarArg,
3088                                                      bool isCalleeStructRet,
3089                                                      bool isCallerStructRet,
3090                                                      Type *RetTy,
3091                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3092                                     const SmallVectorImpl<SDValue> &OutVals,
3093                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3094                                                      SelectionDAG &DAG) const {
3095   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3096     return false;
3097
3098   // If -tailcallopt is specified, make fastcc functions tail-callable.
3099   const MachineFunction &MF = DAG.getMachineFunction();
3100   const Function *CallerF = MF.getFunction();
3101
3102   // If the function return type is x86_fp80 and the callee return type is not,
3103   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3104   // perform a tailcall optimization here.
3105   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3106     return false;
3107
3108   CallingConv::ID CallerCC = CallerF->getCallingConv();
3109   bool CCMatch = CallerCC == CalleeCC;
3110   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3111   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3112
3113   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3114     if (IsTailCallConvention(CalleeCC) && CCMatch)
3115       return true;
3116     return false;
3117   }
3118
3119   // Look for obvious safe cases to perform tail call optimization that do not
3120   // require ABI changes. This is what gcc calls sibcall.
3121
3122   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3123   // emit a special epilogue.
3124   const X86RegisterInfo *RegInfo =
3125     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3126   if (RegInfo->needsStackRealignment(MF))
3127     return false;
3128
3129   // Also avoid sibcall optimization if either caller or callee uses struct
3130   // return semantics.
3131   if (isCalleeStructRet || isCallerStructRet)
3132     return false;
3133
3134   // An stdcall/thiscall caller is expected to clean up its arguments; the
3135   // callee isn't going to do that.
3136   // FIXME: this is more restrictive than needed. We could produce a tailcall
3137   // when the stack adjustment matches. For example, with a thiscall that takes
3138   // only one argument.
3139   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3140                    CallerCC == CallingConv::X86_ThisCall))
3141     return false;
3142
3143   // Do not sibcall optimize vararg calls unless all arguments are passed via
3144   // registers.
3145   if (isVarArg && !Outs.empty()) {
3146
3147     // Optimizing for varargs on Win64 is unlikely to be safe without
3148     // additional testing.
3149     if (IsCalleeWin64 || IsCallerWin64)
3150       return false;
3151
3152     SmallVector<CCValAssign, 16> ArgLocs;
3153     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3154                    getTargetMachine(), ArgLocs, *DAG.getContext());
3155
3156     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3157     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3158       if (!ArgLocs[i].isRegLoc())
3159         return false;
3160   }
3161
3162   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3163   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3164   // this into a sibcall.
3165   bool Unused = false;
3166   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3167     if (!Ins[i].Used) {
3168       Unused = true;
3169       break;
3170     }
3171   }
3172   if (Unused) {
3173     SmallVector<CCValAssign, 16> RVLocs;
3174     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3175                    getTargetMachine(), RVLocs, *DAG.getContext());
3176     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3177     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3178       CCValAssign &VA = RVLocs[i];
3179       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3180         return false;
3181     }
3182   }
3183
3184   // If the calling conventions do not match, then we'd better make sure the
3185   // results are returned in the same way as what the caller expects.
3186   if (!CCMatch) {
3187     SmallVector<CCValAssign, 16> RVLocs1;
3188     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3189                     getTargetMachine(), RVLocs1, *DAG.getContext());
3190     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3191
3192     SmallVector<CCValAssign, 16> RVLocs2;
3193     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3194                     getTargetMachine(), RVLocs2, *DAG.getContext());
3195     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3196
3197     if (RVLocs1.size() != RVLocs2.size())
3198       return false;
3199     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3200       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3201         return false;
3202       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3203         return false;
3204       if (RVLocs1[i].isRegLoc()) {
3205         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3206           return false;
3207       } else {
3208         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3209           return false;
3210       }
3211     }
3212   }
3213
3214   // If the callee takes no arguments then go on to check the results of the
3215   // call.
3216   if (!Outs.empty()) {
3217     // Check if stack adjustment is needed. For now, do not do this if any
3218     // argument is passed on the stack.
3219     SmallVector<CCValAssign, 16> ArgLocs;
3220     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3221                    getTargetMachine(), ArgLocs, *DAG.getContext());
3222
3223     // Allocate shadow area for Win64
3224     if (IsCalleeWin64)
3225       CCInfo.AllocateStack(32, 8);
3226
3227     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3228     if (CCInfo.getNextStackOffset()) {
3229       MachineFunction &MF = DAG.getMachineFunction();
3230       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3231         return false;
3232
3233       // Check if the arguments are already laid out in the right way as
3234       // the caller's fixed stack objects.
3235       MachineFrameInfo *MFI = MF.getFrameInfo();
3236       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3237       const X86InstrInfo *TII =
3238         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3239       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3240         CCValAssign &VA = ArgLocs[i];
3241         SDValue Arg = OutVals[i];
3242         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3243         if (VA.getLocInfo() == CCValAssign::Indirect)
3244           return false;
3245         if (!VA.isRegLoc()) {
3246           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3247                                    MFI, MRI, TII))
3248             return false;
3249         }
3250       }
3251     }
3252
3253     // If the tailcall address may be in a register, then make sure it's
3254     // possible to register allocate for it. In 32-bit, the call address can
3255     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3256     // callee-saved registers are restored. These happen to be the same
3257     // registers used to pass 'inreg' arguments so watch out for those.
3258     if (!Subtarget->is64Bit() &&
3259         ((!isa<GlobalAddressSDNode>(Callee) &&
3260           !isa<ExternalSymbolSDNode>(Callee)) ||
3261          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3262       unsigned NumInRegs = 0;
3263       // In PIC we need an extra register to formulate the address computation
3264       // for the callee.
3265       unsigned MaxInRegs =
3266           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3267
3268       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3269         CCValAssign &VA = ArgLocs[i];
3270         if (!VA.isRegLoc())
3271           continue;
3272         unsigned Reg = VA.getLocReg();
3273         switch (Reg) {
3274         default: break;
3275         case X86::EAX: case X86::EDX: case X86::ECX:
3276           if (++NumInRegs == MaxInRegs)
3277             return false;
3278           break;
3279         }
3280       }
3281     }
3282   }
3283
3284   return true;
3285 }
3286
3287 FastISel *
3288 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3289                                   const TargetLibraryInfo *libInfo) const {
3290   return X86::createFastISel(funcInfo, libInfo);
3291 }
3292
3293 //===----------------------------------------------------------------------===//
3294 //                           Other Lowering Hooks
3295 //===----------------------------------------------------------------------===//
3296
3297 static bool MayFoldLoad(SDValue Op) {
3298   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3299 }
3300
3301 static bool MayFoldIntoStore(SDValue Op) {
3302   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3303 }
3304
3305 static bool isTargetShuffle(unsigned Opcode) {
3306   switch(Opcode) {
3307   default: return false;
3308   case X86ISD::PSHUFD:
3309   case X86ISD::PSHUFHW:
3310   case X86ISD::PSHUFLW:
3311   case X86ISD::SHUFP:
3312   case X86ISD::PALIGNR:
3313   case X86ISD::MOVLHPS:
3314   case X86ISD::MOVLHPD:
3315   case X86ISD::MOVHLPS:
3316   case X86ISD::MOVLPS:
3317   case X86ISD::MOVLPD:
3318   case X86ISD::MOVSHDUP:
3319   case X86ISD::MOVSLDUP:
3320   case X86ISD::MOVDDUP:
3321   case X86ISD::MOVSS:
3322   case X86ISD::MOVSD:
3323   case X86ISD::UNPCKL:
3324   case X86ISD::UNPCKH:
3325   case X86ISD::VPERMILP:
3326   case X86ISD::VPERM2X128:
3327   case X86ISD::VPERMI:
3328     return true;
3329   }
3330 }
3331
3332 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3333                                     SDValue V1, SelectionDAG &DAG) {
3334   switch(Opc) {
3335   default: llvm_unreachable("Unknown x86 shuffle node");
3336   case X86ISD::MOVSHDUP:
3337   case X86ISD::MOVSLDUP:
3338   case X86ISD::MOVDDUP:
3339     return DAG.getNode(Opc, dl, VT, V1);
3340   }
3341 }
3342
3343 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3344                                     SDValue V1, unsigned TargetMask,
3345                                     SelectionDAG &DAG) {
3346   switch(Opc) {
3347   default: llvm_unreachable("Unknown x86 shuffle node");
3348   case X86ISD::PSHUFD:
3349   case X86ISD::PSHUFHW:
3350   case X86ISD::PSHUFLW:
3351   case X86ISD::VPERMILP:
3352   case X86ISD::VPERMI:
3353     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3354   }
3355 }
3356
3357 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3358                                     SDValue V1, SDValue V2, unsigned TargetMask,
3359                                     SelectionDAG &DAG) {
3360   switch(Opc) {
3361   default: llvm_unreachable("Unknown x86 shuffle node");
3362   case X86ISD::PALIGNR:
3363   case X86ISD::SHUFP:
3364   case X86ISD::VPERM2X128:
3365     return DAG.getNode(Opc, dl, VT, V1, V2,
3366                        DAG.getConstant(TargetMask, MVT::i8));
3367   }
3368 }
3369
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3372   switch(Opc) {
3373   default: llvm_unreachable("Unknown x86 shuffle node");
3374   case X86ISD::MOVLHPS:
3375   case X86ISD::MOVLHPD:
3376   case X86ISD::MOVHLPS:
3377   case X86ISD::MOVLPS:
3378   case X86ISD::MOVLPD:
3379   case X86ISD::MOVSS:
3380   case X86ISD::MOVSD:
3381   case X86ISD::UNPCKL:
3382   case X86ISD::UNPCKH:
3383     return DAG.getNode(Opc, dl, VT, V1, V2);
3384   }
3385 }
3386
3387 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3388   MachineFunction &MF = DAG.getMachineFunction();
3389   const X86RegisterInfo *RegInfo =
3390     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3391   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3392   int ReturnAddrIndex = FuncInfo->getRAIndex();
3393
3394   if (ReturnAddrIndex == 0) {
3395     // Set up a frame object for the return address.
3396     unsigned SlotSize = RegInfo->getSlotSize();
3397     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3398                                                            -(int64_t)SlotSize,
3399                                                            false);
3400     FuncInfo->setRAIndex(ReturnAddrIndex);
3401   }
3402
3403   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3404 }
3405
3406 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3407                                        bool hasSymbolicDisplacement) {
3408   // Offset should fit into 32 bit immediate field.
3409   if (!isInt<32>(Offset))
3410     return false;
3411
3412   // If we don't have a symbolic displacement - we don't have any extra
3413   // restrictions.
3414   if (!hasSymbolicDisplacement)
3415     return true;
3416
3417   // FIXME: Some tweaks might be needed for medium code model.
3418   if (M != CodeModel::Small && M != CodeModel::Kernel)
3419     return false;
3420
3421   // For small code model we assume that latest object is 16MB before end of 31
3422   // bits boundary. We may also accept pretty large negative constants knowing
3423   // that all objects are in the positive half of address space.
3424   if (M == CodeModel::Small && Offset < 16*1024*1024)
3425     return true;
3426
3427   // For kernel code model we know that all object resist in the negative half
3428   // of 32bits address space. We may not accept negative offsets, since they may
3429   // be just off and we may accept pretty large positive ones.
3430   if (M == CodeModel::Kernel && Offset > 0)
3431     return true;
3432
3433   return false;
3434 }
3435
3436 /// isCalleePop - Determines whether the callee is required to pop its
3437 /// own arguments. Callee pop is necessary to support tail calls.
3438 bool X86::isCalleePop(CallingConv::ID CallingConv,
3439                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3440   if (IsVarArg)
3441     return false;
3442
3443   switch (CallingConv) {
3444   default:
3445     return false;
3446   case CallingConv::X86_StdCall:
3447     return !is64Bit;
3448   case CallingConv::X86_FastCall:
3449     return !is64Bit;
3450   case CallingConv::X86_ThisCall:
3451     return !is64Bit;
3452   case CallingConv::Fast:
3453     return TailCallOpt;
3454   case CallingConv::GHC:
3455     return TailCallOpt;
3456   case CallingConv::HiPE:
3457     return TailCallOpt;
3458   }
3459 }
3460
3461 /// \brief Return true if the condition is an unsigned comparison operation.
3462 static bool isX86CCUnsigned(unsigned X86CC) {
3463   switch (X86CC) {
3464   default: llvm_unreachable("Invalid integer condition!");
3465   case X86::COND_E:     return true;
3466   case X86::COND_G:     return false;
3467   case X86::COND_GE:    return false;
3468   case X86::COND_L:     return false;
3469   case X86::COND_LE:    return false;
3470   case X86::COND_NE:    return true;
3471   case X86::COND_B:     return true;
3472   case X86::COND_A:     return true;
3473   case X86::COND_BE:    return true;
3474   case X86::COND_AE:    return true;
3475   }
3476   llvm_unreachable("covered switch fell through?!");
3477 }
3478
3479 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3480 /// specific condition code, returning the condition code and the LHS/RHS of the
3481 /// comparison to make.
3482 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3483                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3484   if (!isFP) {
3485     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3486       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3487         // X > -1   -> X == 0, jump !sign.
3488         RHS = DAG.getConstant(0, RHS.getValueType());
3489         return X86::COND_NS;
3490       }
3491       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3492         // X < 0   -> X == 0, jump on sign.
3493         return X86::COND_S;
3494       }
3495       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3496         // X < 1   -> X <= 0
3497         RHS = DAG.getConstant(0, RHS.getValueType());
3498         return X86::COND_LE;
3499       }
3500     }
3501
3502     switch (SetCCOpcode) {
3503     default: llvm_unreachable("Invalid integer condition!");
3504     case ISD::SETEQ:  return X86::COND_E;
3505     case ISD::SETGT:  return X86::COND_G;
3506     case ISD::SETGE:  return X86::COND_GE;
3507     case ISD::SETLT:  return X86::COND_L;
3508     case ISD::SETLE:  return X86::COND_LE;
3509     case ISD::SETNE:  return X86::COND_NE;
3510     case ISD::SETULT: return X86::COND_B;
3511     case ISD::SETUGT: return X86::COND_A;
3512     case ISD::SETULE: return X86::COND_BE;
3513     case ISD::SETUGE: return X86::COND_AE;
3514     }
3515   }
3516
3517   // First determine if it is required or is profitable to flip the operands.
3518
3519   // If LHS is a foldable load, but RHS is not, flip the condition.
3520   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3521       !ISD::isNON_EXTLoad(RHS.getNode())) {
3522     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3523     std::swap(LHS, RHS);
3524   }
3525
3526   switch (SetCCOpcode) {
3527   default: break;
3528   case ISD::SETOLT:
3529   case ISD::SETOLE:
3530   case ISD::SETUGT:
3531   case ISD::SETUGE:
3532     std::swap(LHS, RHS);
3533     break;
3534   }
3535
3536   // On a floating point condition, the flags are set as follows:
3537   // ZF  PF  CF   op
3538   //  0 | 0 | 0 | X > Y
3539   //  0 | 0 | 1 | X < Y
3540   //  1 | 0 | 0 | X == Y
3541   //  1 | 1 | 1 | unordered
3542   switch (SetCCOpcode) {
3543   default: llvm_unreachable("Condcode should be pre-legalized away");
3544   case ISD::SETUEQ:
3545   case ISD::SETEQ:   return X86::COND_E;
3546   case ISD::SETOLT:              // flipped
3547   case ISD::SETOGT:
3548   case ISD::SETGT:   return X86::COND_A;
3549   case ISD::SETOLE:              // flipped
3550   case ISD::SETOGE:
3551   case ISD::SETGE:   return X86::COND_AE;
3552   case ISD::SETUGT:              // flipped
3553   case ISD::SETULT:
3554   case ISD::SETLT:   return X86::COND_B;
3555   case ISD::SETUGE:              // flipped
3556   case ISD::SETULE:
3557   case ISD::SETLE:   return X86::COND_BE;
3558   case ISD::SETONE:
3559   case ISD::SETNE:   return X86::COND_NE;
3560   case ISD::SETUO:   return X86::COND_P;
3561   case ISD::SETO:    return X86::COND_NP;
3562   case ISD::SETOEQ:
3563   case ISD::SETUNE:  return X86::COND_INVALID;
3564   }
3565 }
3566
3567 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3568 /// code. Current x86 isa includes the following FP cmov instructions:
3569 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3570 static bool hasFPCMov(unsigned X86CC) {
3571   switch (X86CC) {
3572   default:
3573     return false;
3574   case X86::COND_B:
3575   case X86::COND_BE:
3576   case X86::COND_E:
3577   case X86::COND_P:
3578   case X86::COND_A:
3579   case X86::COND_AE:
3580   case X86::COND_NE:
3581   case X86::COND_NP:
3582     return true;
3583   }
3584 }
3585
3586 /// isFPImmLegal - Returns true if the target can instruction select the
3587 /// specified FP immediate natively. If false, the legalizer will
3588 /// materialize the FP immediate as a load from a constant pool.
3589 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3590   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3591     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3592       return true;
3593   }
3594   return false;
3595 }
3596
3597 /// \brief Returns true if it is beneficial to convert a load of a constant
3598 /// to just the constant itself.
3599 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3600                                                           Type *Ty) const {
3601   assert(Ty->isIntegerTy());
3602
3603   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3604   if (BitSize == 0 || BitSize > 64)
3605     return false;
3606   return true;
3607 }
3608
3609 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3610 /// the specified range (L, H].
3611 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3612   return (Val < 0) || (Val >= Low && Val < Hi);
3613 }
3614
3615 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3616 /// specified value.
3617 static bool isUndefOrEqual(int Val, int CmpVal) {
3618   return (Val < 0 || Val == CmpVal);
3619 }
3620
3621 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3622 /// from position Pos and ending in Pos+Size, falls within the specified
3623 /// sequential range (L, L+Pos]. or is undef.
3624 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3625                                        unsigned Pos, unsigned Size, int Low) {
3626   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3627     if (!isUndefOrEqual(Mask[i], Low))
3628       return false;
3629   return true;
3630 }
3631
3632 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3633 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3634 /// the second operand.
3635 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3636   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3637     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3638   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3639     return (Mask[0] < 2 && Mask[1] < 2);
3640   return false;
3641 }
3642
3643 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3644 /// is suitable for input to PSHUFHW.
3645 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3646   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3647     return false;
3648
3649   // Lower quadword copied in order or undef.
3650   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3651     return false;
3652
3653   // Upper quadword shuffled.
3654   for (unsigned i = 4; i != 8; ++i)
3655     if (!isUndefOrInRange(Mask[i], 4, 8))
3656       return false;
3657
3658   if (VT == MVT::v16i16) {
3659     // Lower quadword copied in order or undef.
3660     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3661       return false;
3662
3663     // Upper quadword shuffled.
3664     for (unsigned i = 12; i != 16; ++i)
3665       if (!isUndefOrInRange(Mask[i], 12, 16))
3666         return false;
3667   }
3668
3669   return true;
3670 }
3671
3672 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3673 /// is suitable for input to PSHUFLW.
3674 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3675   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3676     return false;
3677
3678   // Upper quadword copied in order.
3679   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3680     return false;
3681
3682   // Lower quadword shuffled.
3683   for (unsigned i = 0; i != 4; ++i)
3684     if (!isUndefOrInRange(Mask[i], 0, 4))
3685       return false;
3686
3687   if (VT == MVT::v16i16) {
3688     // Upper quadword copied in order.
3689     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3690       return false;
3691
3692     // Lower quadword shuffled.
3693     for (unsigned i = 8; i != 12; ++i)
3694       if (!isUndefOrInRange(Mask[i], 8, 12))
3695         return false;
3696   }
3697
3698   return true;
3699 }
3700
3701 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3702 /// is suitable for input to PALIGNR.
3703 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3704                           const X86Subtarget *Subtarget) {
3705   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3706       (VT.is256BitVector() && !Subtarget->hasInt256()))
3707     return false;
3708
3709   unsigned NumElts = VT.getVectorNumElements();
3710   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3711   unsigned NumLaneElts = NumElts/NumLanes;
3712
3713   // Do not handle 64-bit element shuffles with palignr.
3714   if (NumLaneElts == 2)
3715     return false;
3716
3717   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3718     unsigned i;
3719     for (i = 0; i != NumLaneElts; ++i) {
3720       if (Mask[i+l] >= 0)
3721         break;
3722     }
3723
3724     // Lane is all undef, go to next lane
3725     if (i == NumLaneElts)
3726       continue;
3727
3728     int Start = Mask[i+l];
3729
3730     // Make sure its in this lane in one of the sources
3731     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3732         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3733       return false;
3734
3735     // If not lane 0, then we must match lane 0
3736     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3737       return false;
3738
3739     // Correct second source to be contiguous with first source
3740     if (Start >= (int)NumElts)
3741       Start -= NumElts - NumLaneElts;
3742
3743     // Make sure we're shifting in the right direction.
3744     if (Start <= (int)(i+l))
3745       return false;
3746
3747     Start -= i;
3748
3749     // Check the rest of the elements to see if they are consecutive.
3750     for (++i; i != NumLaneElts; ++i) {
3751       int Idx = Mask[i+l];
3752
3753       // Make sure its in this lane
3754       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3755           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3756         return false;
3757
3758       // If not lane 0, then we must match lane 0
3759       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3760         return false;
3761
3762       if (Idx >= (int)NumElts)
3763         Idx -= NumElts - NumLaneElts;
3764
3765       if (!isUndefOrEqual(Idx, Start+i))
3766         return false;
3767
3768     }
3769   }
3770
3771   return true;
3772 }
3773
3774 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3775 /// the two vector operands have swapped position.
3776 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3777                                      unsigned NumElems) {
3778   for (unsigned i = 0; i != NumElems; ++i) {
3779     int idx = Mask[i];
3780     if (idx < 0)
3781       continue;
3782     else if (idx < (int)NumElems)
3783       Mask[i] = idx + NumElems;
3784     else
3785       Mask[i] = idx - NumElems;
3786   }
3787 }
3788
3789 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3791 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3792 /// reverse of what x86 shuffles want.
3793 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3794
3795   unsigned NumElems = VT.getVectorNumElements();
3796   unsigned NumLanes = VT.getSizeInBits()/128;
3797   unsigned NumLaneElems = NumElems/NumLanes;
3798
3799   if (NumLaneElems != 2 && NumLaneElems != 4)
3800     return false;
3801
3802   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3803   bool symetricMaskRequired =
3804     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3805
3806   // VSHUFPSY divides the resulting vector into 4 chunks.
3807   // The sources are also splitted into 4 chunks, and each destination
3808   // chunk must come from a different source chunk.
3809   //
3810   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3811   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3812   //
3813   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3814   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3815   //
3816   // VSHUFPDY divides the resulting vector into 4 chunks.
3817   // The sources are also splitted into 4 chunks, and each destination
3818   // chunk must come from a different source chunk.
3819   //
3820   //  SRC1 =>      X3       X2       X1       X0
3821   //  SRC2 =>      Y3       Y2       Y1       Y0
3822   //
3823   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3824   //
3825   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3826   unsigned HalfLaneElems = NumLaneElems/2;
3827   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3828     for (unsigned i = 0; i != NumLaneElems; ++i) {
3829       int Idx = Mask[i+l];
3830       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3831       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3832         return false;
3833       // For VSHUFPSY, the mask of the second half must be the same as the
3834       // first but with the appropriate offsets. This works in the same way as
3835       // VPERMILPS works with masks.
3836       if (!symetricMaskRequired || Idx < 0)
3837         continue;
3838       if (MaskVal[i] < 0) {
3839         MaskVal[i] = Idx - l;
3840         continue;
3841       }
3842       if ((signed)(Idx - l) != MaskVal[i])
3843         return false;
3844     }
3845   }
3846
3847   return true;
3848 }
3849
3850 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3852 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3853   if (!VT.is128BitVector())
3854     return false;
3855
3856   unsigned NumElems = VT.getVectorNumElements();
3857
3858   if (NumElems != 4)
3859     return false;
3860
3861   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3862   return isUndefOrEqual(Mask[0], 6) &&
3863          isUndefOrEqual(Mask[1], 7) &&
3864          isUndefOrEqual(Mask[2], 2) &&
3865          isUndefOrEqual(Mask[3], 3);
3866 }
3867
3868 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3869 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3870 /// <2, 3, 2, 3>
3871 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3872   if (!VT.is128BitVector())
3873     return false;
3874
3875   unsigned NumElems = VT.getVectorNumElements();
3876
3877   if (NumElems != 4)
3878     return false;
3879
3880   return isUndefOrEqual(Mask[0], 2) &&
3881          isUndefOrEqual(Mask[1], 3) &&
3882          isUndefOrEqual(Mask[2], 2) &&
3883          isUndefOrEqual(Mask[3], 3);
3884 }
3885
3886 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3888 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3889   if (!VT.is128BitVector())
3890     return false;
3891
3892   unsigned NumElems = VT.getVectorNumElements();
3893
3894   if (NumElems != 2 && NumElems != 4)
3895     return false;
3896
3897   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3898     if (!isUndefOrEqual(Mask[i], i + NumElems))
3899       return false;
3900
3901   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3902     if (!isUndefOrEqual(Mask[i], i))
3903       return false;
3904
3905   return true;
3906 }
3907
3908 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3910 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3911   if (!VT.is128BitVector())
3912     return false;
3913
3914   unsigned NumElems = VT.getVectorNumElements();
3915
3916   if (NumElems != 2 && NumElems != 4)
3917     return false;
3918
3919   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3920     if (!isUndefOrEqual(Mask[i], i))
3921       return false;
3922
3923   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3925       return false;
3926
3927   return true;
3928 }
3929
3930 //
3931 // Some special combinations that can be optimized.
3932 //
3933 static
3934 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3935                                SelectionDAG &DAG) {
3936   MVT VT = SVOp->getSimpleValueType(0);
3937   SDLoc dl(SVOp);
3938
3939   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3940     return SDValue();
3941
3942   ArrayRef<int> Mask = SVOp->getMask();
3943
3944   // These are the special masks that may be optimized.
3945   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3946   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3947   bool MatchEvenMask = true;
3948   bool MatchOddMask  = true;
3949   for (int i=0; i<8; ++i) {
3950     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3951       MatchEvenMask = false;
3952     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3953       MatchOddMask = false;
3954   }
3955
3956   if (!MatchEvenMask && !MatchOddMask)
3957     return SDValue();
3958
3959   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3960
3961   SDValue Op0 = SVOp->getOperand(0);
3962   SDValue Op1 = SVOp->getOperand(1);
3963
3964   if (MatchEvenMask) {
3965     // Shift the second operand right to 32 bits.
3966     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3967     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3968   } else {
3969     // Shift the first operand left to 32 bits.
3970     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3971     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3972   }
3973   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3974   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3975 }
3976
3977 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3978 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3979 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3980                          bool HasInt256, bool V2IsSplat = false) {
3981
3982   assert(VT.getSizeInBits() >= 128 &&
3983          "Unsupported vector type for unpckl");
3984
3985   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3986   unsigned NumLanes;
3987   unsigned NumOf256BitLanes;
3988   unsigned NumElts = VT.getVectorNumElements();
3989   if (VT.is256BitVector()) {
3990     if (NumElts != 4 && NumElts != 8 &&
3991         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3992     return false;
3993     NumLanes = 2;
3994     NumOf256BitLanes = 1;
3995   } else if (VT.is512BitVector()) {
3996     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3997            "Unsupported vector type for unpckh");
3998     NumLanes = 2;
3999     NumOf256BitLanes = 2;
4000   } else {
4001     NumLanes = 1;
4002     NumOf256BitLanes = 1;
4003   }
4004
4005   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4006   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4007
4008   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4009     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4010       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4011         int BitI  = Mask[l256*NumEltsInStride+l+i];
4012         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4013         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4014           return false;
4015         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4016           return false;
4017         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4018           return false;
4019       }
4020     }
4021   }
4022   return true;
4023 }
4024
4025 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4027 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4028                          bool HasInt256, bool V2IsSplat = false) {
4029   assert(VT.getSizeInBits() >= 128 &&
4030          "Unsupported vector type for unpckh");
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+NumLaneElts/2; 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 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4073 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4074 /// <0, 0, 1, 1>
4075 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4076   unsigned NumElts = VT.getVectorNumElements();
4077   bool Is256BitVec = VT.is256BitVector();
4078
4079   if (VT.is512BitVector())
4080     return false;
4081   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4082          "Unsupported vector type for unpckh");
4083
4084   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4085       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4086     return false;
4087
4088   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4089   // FIXME: Need a better way to get rid of this, there's no latency difference
4090   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4091   // the former later. We should also remove the "_undef" special mask.
4092   if (NumElts == 4 && Is256BitVec)
4093     return false;
4094
4095   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4096   // independently on 128-bit lanes.
4097   unsigned NumLanes = VT.getSizeInBits()/128;
4098   unsigned NumLaneElts = NumElts/NumLanes;
4099
4100   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4101     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4102       int BitI  = Mask[l+i];
4103       int BitI1 = Mask[l+i+1];
4104
4105       if (!isUndefOrEqual(BitI, j))
4106         return false;
4107       if (!isUndefOrEqual(BitI1, j))
4108         return false;
4109     }
4110   }
4111
4112   return true;
4113 }
4114
4115 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4116 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4117 /// <2, 2, 3, 3>
4118 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4119   unsigned NumElts = VT.getVectorNumElements();
4120
4121   if (VT.is512BitVector())
4122     return false;
4123
4124   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4125          "Unsupported vector type for unpckh");
4126
4127   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4128       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4129     return false;
4130
4131   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4132   // independently on 128-bit lanes.
4133   unsigned NumLanes = VT.getSizeInBits()/128;
4134   unsigned NumLaneElts = NumElts/NumLanes;
4135
4136   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4137     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4138       int BitI  = Mask[l+i];
4139       int BitI1 = Mask[l+i+1];
4140       if (!isUndefOrEqual(BitI, j))
4141         return false;
4142       if (!isUndefOrEqual(BitI1, j))
4143         return false;
4144     }
4145   }
4146   return true;
4147 }
4148
4149 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4150 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4151 /// MOVSD, and MOVD, i.e. setting the lowest element.
4152 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4153   if (VT.getVectorElementType().getSizeInBits() < 32)
4154     return false;
4155   if (!VT.is128BitVector())
4156     return false;
4157
4158   unsigned NumElts = VT.getVectorNumElements();
4159
4160   if (!isUndefOrEqual(Mask[0], NumElts))
4161     return false;
4162
4163   for (unsigned i = 1; i != NumElts; ++i)
4164     if (!isUndefOrEqual(Mask[i], i))
4165       return false;
4166
4167   return true;
4168 }
4169
4170 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4171 /// as permutations between 128-bit chunks or halves. As an example: this
4172 /// shuffle bellow:
4173 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4174 /// The first half comes from the second half of V1 and the second half from the
4175 /// the second half of V2.
4176 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4177   if (!HasFp256 || !VT.is256BitVector())
4178     return false;
4179
4180   // The shuffle result is divided into half A and half B. In total the two
4181   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4182   // B must come from C, D, E or F.
4183   unsigned HalfSize = VT.getVectorNumElements()/2;
4184   bool MatchA = false, MatchB = false;
4185
4186   // Check if A comes from one of C, D, E, F.
4187   for (unsigned Half = 0; Half != 4; ++Half) {
4188     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4189       MatchA = true;
4190       break;
4191     }
4192   }
4193
4194   // Check if B comes from one of C, D, E, F.
4195   for (unsigned Half = 0; Half != 4; ++Half) {
4196     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4197       MatchB = true;
4198       break;
4199     }
4200   }
4201
4202   return MatchA && MatchB;
4203 }
4204
4205 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4206 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4207 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4208   MVT VT = SVOp->getSimpleValueType(0);
4209
4210   unsigned HalfSize = VT.getVectorNumElements()/2;
4211
4212   unsigned FstHalf = 0, SndHalf = 0;
4213   for (unsigned i = 0; i < HalfSize; ++i) {
4214     if (SVOp->getMaskElt(i) > 0) {
4215       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4216       break;
4217     }
4218   }
4219   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4220     if (SVOp->getMaskElt(i) > 0) {
4221       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4222       break;
4223     }
4224   }
4225
4226   return (FstHalf | (SndHalf << 4));
4227 }
4228
4229 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4230 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4231   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4232   if (EltSize < 32)
4233     return false;
4234
4235   unsigned NumElts = VT.getVectorNumElements();
4236   Imm8 = 0;
4237   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4238     for (unsigned i = 0; i != NumElts; ++i) {
4239       if (Mask[i] < 0)
4240         continue;
4241       Imm8 |= Mask[i] << (i*2);
4242     }
4243     return true;
4244   }
4245
4246   unsigned LaneSize = 4;
4247   SmallVector<int, 4> MaskVal(LaneSize, -1);
4248
4249   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4250     for (unsigned i = 0; i != LaneSize; ++i) {
4251       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4252         return false;
4253       if (Mask[i+l] < 0)
4254         continue;
4255       if (MaskVal[i] < 0) {
4256         MaskVal[i] = Mask[i+l] - l;
4257         Imm8 |= MaskVal[i] << (i*2);
4258         continue;
4259       }
4260       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4261         return false;
4262     }
4263   }
4264   return true;
4265 }
4266
4267 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4268 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4269 /// Note that VPERMIL mask matching is different depending whether theunderlying
4270 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4271 /// to the same elements of the low, but to the higher half of the source.
4272 /// In VPERMILPD the two lanes could be shuffled independently of each other
4273 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4274 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4275   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4276   if (VT.getSizeInBits() < 256 || EltSize < 32)
4277     return false;
4278   bool symetricMaskRequired = (EltSize == 32);
4279   unsigned NumElts = VT.getVectorNumElements();
4280
4281   unsigned NumLanes = VT.getSizeInBits()/128;
4282   unsigned LaneSize = NumElts/NumLanes;
4283   // 2 or 4 elements in one lane
4284
4285   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4286   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4287     for (unsigned i = 0; i != LaneSize; ++i) {
4288       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4289         return false;
4290       if (symetricMaskRequired) {
4291         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4292           ExpectedMaskVal[i] = Mask[i+l] - l;
4293           continue;
4294         }
4295         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4296           return false;
4297       }
4298     }
4299   }
4300   return true;
4301 }
4302
4303 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4304 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4305 /// element of vector 2 and the other elements to come from vector 1 in order.
4306 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4307                                bool V2IsSplat = false, bool V2IsUndef = false) {
4308   if (!VT.is128BitVector())
4309     return false;
4310
4311   unsigned NumOps = VT.getVectorNumElements();
4312   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4313     return false;
4314
4315   if (!isUndefOrEqual(Mask[0], 0))
4316     return false;
4317
4318   for (unsigned i = 1; i != NumOps; ++i)
4319     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4320           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4321           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4322       return false;
4323
4324   return true;
4325 }
4326
4327 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4328 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4329 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4330 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4331                            const X86Subtarget *Subtarget) {
4332   if (!Subtarget->hasSSE3())
4333     return false;
4334
4335   unsigned NumElems = VT.getVectorNumElements();
4336
4337   if ((VT.is128BitVector() && NumElems != 4) ||
4338       (VT.is256BitVector() && NumElems != 8) ||
4339       (VT.is512BitVector() && NumElems != 16))
4340     return false;
4341
4342   // "i+1" is the value the indexed mask element must have
4343   for (unsigned i = 0; i != NumElems; i += 2)
4344     if (!isUndefOrEqual(Mask[i], i+1) ||
4345         !isUndefOrEqual(Mask[i+1], i+1))
4346       return false;
4347
4348   return true;
4349 }
4350
4351 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4352 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4353 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4354 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4355                            const X86Subtarget *Subtarget) {
4356   if (!Subtarget->hasSSE3())
4357     return false;
4358
4359   unsigned NumElems = VT.getVectorNumElements();
4360
4361   if ((VT.is128BitVector() && NumElems != 4) ||
4362       (VT.is256BitVector() && NumElems != 8) ||
4363       (VT.is512BitVector() && NumElems != 16))
4364     return false;
4365
4366   // "i" is the value the indexed mask element must have
4367   for (unsigned i = 0; i != NumElems; i += 2)
4368     if (!isUndefOrEqual(Mask[i], i) ||
4369         !isUndefOrEqual(Mask[i+1], i))
4370       return false;
4371
4372   return true;
4373 }
4374
4375 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4376 /// specifies a shuffle of elements that is suitable for input to 256-bit
4377 /// version of MOVDDUP.
4378 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4379   if (!HasFp256 || !VT.is256BitVector())
4380     return false;
4381
4382   unsigned NumElts = VT.getVectorNumElements();
4383   if (NumElts != 4)
4384     return false;
4385
4386   for (unsigned i = 0; i != NumElts/2; ++i)
4387     if (!isUndefOrEqual(Mask[i], 0))
4388       return false;
4389   for (unsigned i = NumElts/2; i != NumElts; ++i)
4390     if (!isUndefOrEqual(Mask[i], NumElts/2))
4391       return false;
4392   return true;
4393 }
4394
4395 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4396 /// specifies a shuffle of elements that is suitable for input to 128-bit
4397 /// version of MOVDDUP.
4398 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4399   if (!VT.is128BitVector())
4400     return false;
4401
4402   unsigned e = VT.getVectorNumElements() / 2;
4403   for (unsigned i = 0; i != e; ++i)
4404     if (!isUndefOrEqual(Mask[i], i))
4405       return false;
4406   for (unsigned i = 0; i != e; ++i)
4407     if (!isUndefOrEqual(Mask[e+i], i))
4408       return false;
4409   return true;
4410 }
4411
4412 /// isVEXTRACTIndex - Return true if the specified
4413 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4414 /// suitable for instruction that extract 128 or 256 bit vectors
4415 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4416   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4417   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4418     return false;
4419
4420   // The index should be aligned on a vecWidth-bit boundary.
4421   uint64_t Index =
4422     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4423
4424   MVT VT = N->getSimpleValueType(0);
4425   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4426   bool Result = (Index * ElSize) % vecWidth == 0;
4427
4428   return Result;
4429 }
4430
4431 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4432 /// operand specifies a subvector insert that is suitable for input to
4433 /// insertion of 128 or 256-bit subvectors
4434 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4435   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4436   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4437     return false;
4438   // The index should be aligned on a vecWidth-bit boundary.
4439   uint64_t Index =
4440     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4441
4442   MVT VT = N->getSimpleValueType(0);
4443   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4444   bool Result = (Index * ElSize) % vecWidth == 0;
4445
4446   return Result;
4447 }
4448
4449 bool X86::isVINSERT128Index(SDNode *N) {
4450   return isVINSERTIndex(N, 128);
4451 }
4452
4453 bool X86::isVINSERT256Index(SDNode *N) {
4454   return isVINSERTIndex(N, 256);
4455 }
4456
4457 bool X86::isVEXTRACT128Index(SDNode *N) {
4458   return isVEXTRACTIndex(N, 128);
4459 }
4460
4461 bool X86::isVEXTRACT256Index(SDNode *N) {
4462   return isVEXTRACTIndex(N, 256);
4463 }
4464
4465 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4466 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4467 /// Handles 128-bit and 256-bit.
4468 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4469   MVT VT = N->getSimpleValueType(0);
4470
4471   assert((VT.getSizeInBits() >= 128) &&
4472          "Unsupported vector type for PSHUF/SHUFP");
4473
4474   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4475   // independently on 128-bit lanes.
4476   unsigned NumElts = VT.getVectorNumElements();
4477   unsigned NumLanes = VT.getSizeInBits()/128;
4478   unsigned NumLaneElts = NumElts/NumLanes;
4479
4480   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4481          "Only supports 2, 4 or 8 elements per lane");
4482
4483   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4484   unsigned Mask = 0;
4485   for (unsigned i = 0; i != NumElts; ++i) {
4486     int Elt = N->getMaskElt(i);
4487     if (Elt < 0) continue;
4488     Elt &= NumLaneElts - 1;
4489     unsigned ShAmt = (i << Shift) % 8;
4490     Mask |= Elt << ShAmt;
4491   }
4492
4493   return Mask;
4494 }
4495
4496 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4497 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4498 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4499   MVT VT = N->getSimpleValueType(0);
4500
4501   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4502          "Unsupported vector type for PSHUFHW");
4503
4504   unsigned NumElts = VT.getVectorNumElements();
4505
4506   unsigned Mask = 0;
4507   for (unsigned l = 0; l != NumElts; l += 8) {
4508     // 8 nodes per lane, but we only care about the last 4.
4509     for (unsigned i = 0; i < 4; ++i) {
4510       int Elt = N->getMaskElt(l+i+4);
4511       if (Elt < 0) continue;
4512       Elt &= 0x3; // only 2-bits.
4513       Mask |= Elt << (i * 2);
4514     }
4515   }
4516
4517   return Mask;
4518 }
4519
4520 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4521 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4522 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4523   MVT VT = N->getSimpleValueType(0);
4524
4525   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4526          "Unsupported vector type for PSHUFHW");
4527
4528   unsigned NumElts = VT.getVectorNumElements();
4529
4530   unsigned Mask = 0;
4531   for (unsigned l = 0; l != NumElts; l += 8) {
4532     // 8 nodes per lane, but we only care about the first 4.
4533     for (unsigned i = 0; i < 4; ++i) {
4534       int Elt = N->getMaskElt(l+i);
4535       if (Elt < 0) continue;
4536       Elt &= 0x3; // only 2-bits
4537       Mask |= Elt << (i * 2);
4538     }
4539   }
4540
4541   return Mask;
4542 }
4543
4544 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4545 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4546 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4547   MVT VT = SVOp->getSimpleValueType(0);
4548   unsigned EltSize = VT.is512BitVector() ? 1 :
4549     VT.getVectorElementType().getSizeInBits() >> 3;
4550
4551   unsigned NumElts = VT.getVectorNumElements();
4552   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4553   unsigned NumLaneElts = NumElts/NumLanes;
4554
4555   int Val = 0;
4556   unsigned i;
4557   for (i = 0; i != NumElts; ++i) {
4558     Val = SVOp->getMaskElt(i);
4559     if (Val >= 0)
4560       break;
4561   }
4562   if (Val >= (int)NumElts)
4563     Val -= NumElts - NumLaneElts;
4564
4565   assert(Val - i > 0 && "PALIGNR imm should be positive");
4566   return (Val - i) * EltSize;
4567 }
4568
4569 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4570   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4571   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4572     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4573
4574   uint64_t Index =
4575     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4576
4577   MVT VecVT = N->getOperand(0).getSimpleValueType();
4578   MVT ElVT = VecVT.getVectorElementType();
4579
4580   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4581   return Index / NumElemsPerChunk;
4582 }
4583
4584 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4585   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4586   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4587     llvm_unreachable("Illegal insert subvector for VINSERT");
4588
4589   uint64_t Index =
4590     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4591
4592   MVT VecVT = N->getSimpleValueType(0);
4593   MVT ElVT = VecVT.getVectorElementType();
4594
4595   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4596   return Index / NumElemsPerChunk;
4597 }
4598
4599 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4600 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4601 /// and VINSERTI128 instructions.
4602 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4603   return getExtractVEXTRACTImmediate(N, 128);
4604 }
4605
4606 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4607 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4608 /// and VINSERTI64x4 instructions.
4609 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4610   return getExtractVEXTRACTImmediate(N, 256);
4611 }
4612
4613 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4614 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4615 /// and VINSERTI128 instructions.
4616 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4617   return getInsertVINSERTImmediate(N, 128);
4618 }
4619
4620 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4621 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4622 /// and VINSERTI64x4 instructions.
4623 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4624   return getInsertVINSERTImmediate(N, 256);
4625 }
4626
4627 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4628 /// constant +0.0.
4629 bool X86::isZeroNode(SDValue Elt) {
4630   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4631     return CN->isNullValue();
4632   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4633     return CFP->getValueAPF().isPosZero();
4634   return false;
4635 }
4636
4637 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4638 /// their permute mask.
4639 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4640                                     SelectionDAG &DAG) {
4641   MVT VT = SVOp->getSimpleValueType(0);
4642   unsigned NumElems = VT.getVectorNumElements();
4643   SmallVector<int, 8> MaskVec;
4644
4645   for (unsigned i = 0; i != NumElems; ++i) {
4646     int Idx = SVOp->getMaskElt(i);
4647     if (Idx >= 0) {
4648       if (Idx < (int)NumElems)
4649         Idx += NumElems;
4650       else
4651         Idx -= NumElems;
4652     }
4653     MaskVec.push_back(Idx);
4654   }
4655   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4656                               SVOp->getOperand(0), &MaskVec[0]);
4657 }
4658
4659 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4660 /// match movhlps. The lower half elements should come from upper half of
4661 /// V1 (and in order), and the upper half elements should come from the upper
4662 /// half of V2 (and in order).
4663 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4664   if (!VT.is128BitVector())
4665     return false;
4666   if (VT.getVectorNumElements() != 4)
4667     return false;
4668   for (unsigned i = 0, e = 2; i != e; ++i)
4669     if (!isUndefOrEqual(Mask[i], i+2))
4670       return false;
4671   for (unsigned i = 2; i != 4; ++i)
4672     if (!isUndefOrEqual(Mask[i], i+4))
4673       return false;
4674   return true;
4675 }
4676
4677 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4678 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4679 /// required.
4680 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4681   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4682     return false;
4683   N = N->getOperand(0).getNode();
4684   if (!ISD::isNON_EXTLoad(N))
4685     return false;
4686   if (LD)
4687     *LD = cast<LoadSDNode>(N);
4688   return true;
4689 }
4690
4691 // Test whether the given value is a vector value which will be legalized
4692 // into a load.
4693 static bool WillBeConstantPoolLoad(SDNode *N) {
4694   if (N->getOpcode() != ISD::BUILD_VECTOR)
4695     return false;
4696
4697   // Check for any non-constant elements.
4698   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4699     switch (N->getOperand(i).getNode()->getOpcode()) {
4700     case ISD::UNDEF:
4701     case ISD::ConstantFP:
4702     case ISD::Constant:
4703       break;
4704     default:
4705       return false;
4706     }
4707
4708   // Vectors of all-zeros and all-ones are materialized with special
4709   // instructions rather than being loaded.
4710   return !ISD::isBuildVectorAllZeros(N) &&
4711          !ISD::isBuildVectorAllOnes(N);
4712 }
4713
4714 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4715 /// match movlp{s|d}. The lower half elements should come from lower half of
4716 /// V1 (and in order), and the upper half elements should come from the upper
4717 /// half of V2 (and in order). And since V1 will become the source of the
4718 /// MOVLP, it must be either a vector load or a scalar load to vector.
4719 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4720                                ArrayRef<int> Mask, MVT VT) {
4721   if (!VT.is128BitVector())
4722     return false;
4723
4724   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4725     return false;
4726   // Is V2 is a vector load, don't do this transformation. We will try to use
4727   // load folding shufps op.
4728   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4729     return false;
4730
4731   unsigned NumElems = VT.getVectorNumElements();
4732
4733   if (NumElems != 2 && NumElems != 4)
4734     return false;
4735   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4736     if (!isUndefOrEqual(Mask[i], i))
4737       return false;
4738   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4739     if (!isUndefOrEqual(Mask[i], i+NumElems))
4740       return false;
4741   return true;
4742 }
4743
4744 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4745 /// all the same.
4746 static bool isSplatVector(SDNode *N) {
4747   if (N->getOpcode() != ISD::BUILD_VECTOR)
4748     return false;
4749
4750   SDValue SplatValue = N->getOperand(0);
4751   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4752     if (N->getOperand(i) != SplatValue)
4753       return false;
4754   return true;
4755 }
4756
4757 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4758 /// to an zero vector.
4759 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4760 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4761   SDValue V1 = N->getOperand(0);
4762   SDValue V2 = N->getOperand(1);
4763   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4764   for (unsigned i = 0; i != NumElems; ++i) {
4765     int Idx = N->getMaskElt(i);
4766     if (Idx >= (int)NumElems) {
4767       unsigned Opc = V2.getOpcode();
4768       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4769         continue;
4770       if (Opc != ISD::BUILD_VECTOR ||
4771           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4772         return false;
4773     } else if (Idx >= 0) {
4774       unsigned Opc = V1.getOpcode();
4775       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4776         continue;
4777       if (Opc != ISD::BUILD_VECTOR ||
4778           !X86::isZeroNode(V1.getOperand(Idx)))
4779         return false;
4780     }
4781   }
4782   return true;
4783 }
4784
4785 /// getZeroVector - Returns a vector of specified type with all zero elements.
4786 ///
4787 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4788                              SelectionDAG &DAG, SDLoc dl) {
4789   assert(VT.isVector() && "Expected a vector type");
4790
4791   // Always build SSE zero vectors as <4 x i32> bitcasted
4792   // to their dest type. This ensures they get CSE'd.
4793   SDValue Vec;
4794   if (VT.is128BitVector()) {  // SSE
4795     if (Subtarget->hasSSE2()) {  // SSE2
4796       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4797       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4798     } else { // SSE1
4799       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4800       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4801     }
4802   } else if (VT.is256BitVector()) { // AVX
4803     if (Subtarget->hasInt256()) { // AVX2
4804       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4805       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4806       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4807                         array_lengthof(Ops));
4808     } else {
4809       // 256-bit logic and arithmetic instructions in AVX are all
4810       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4811       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4812       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4813       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4814                         array_lengthof(Ops));
4815     }
4816   } else if (VT.is512BitVector()) { // AVX-512
4817       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4818       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4819                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4820       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4821   } else if (VT.getScalarType() == MVT::i1) {
4822     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4823     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4824     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4825                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4826     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4827                        Ops, VT.getVectorNumElements());
4828   } else
4829     llvm_unreachable("Unexpected vector type");
4830
4831   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4832 }
4833
4834 /// getOnesVector - Returns a vector of specified type with all bits set.
4835 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4836 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4837 /// Then bitcast to their original type, ensuring they get CSE'd.
4838 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4839                              SDLoc dl) {
4840   assert(VT.isVector() && "Expected a vector type");
4841
4842   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4843   SDValue Vec;
4844   if (VT.is256BitVector()) {
4845     if (HasInt256) { // AVX2
4846       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4847       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4848                         array_lengthof(Ops));
4849     } else { // AVX
4850       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4851       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4852     }
4853   } else if (VT.is128BitVector()) {
4854     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4855   } else
4856     llvm_unreachable("Unexpected vector type");
4857
4858   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4859 }
4860
4861 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4862 /// that point to V2 points to its first element.
4863 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4864   for (unsigned i = 0; i != NumElems; ++i) {
4865     if (Mask[i] > (int)NumElems) {
4866       Mask[i] = NumElems;
4867     }
4868   }
4869 }
4870
4871 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4872 /// operation of specified width.
4873 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4874                        SDValue V2) {
4875   unsigned NumElems = VT.getVectorNumElements();
4876   SmallVector<int, 8> Mask;
4877   Mask.push_back(NumElems);
4878   for (unsigned i = 1; i != NumElems; ++i)
4879     Mask.push_back(i);
4880   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4881 }
4882
4883 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4884 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4885                           SDValue V2) {
4886   unsigned NumElems = VT.getVectorNumElements();
4887   SmallVector<int, 8> Mask;
4888   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4889     Mask.push_back(i);
4890     Mask.push_back(i + NumElems);
4891   }
4892   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4893 }
4894
4895 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4896 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4897                           SDValue V2) {
4898   unsigned NumElems = VT.getVectorNumElements();
4899   SmallVector<int, 8> Mask;
4900   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4901     Mask.push_back(i + Half);
4902     Mask.push_back(i + NumElems + Half);
4903   }
4904   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4905 }
4906
4907 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4908 // a generic shuffle instruction because the target has no such instructions.
4909 // Generate shuffles which repeat i16 and i8 several times until they can be
4910 // represented by v4f32 and then be manipulated by target suported shuffles.
4911 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4912   MVT VT = V.getSimpleValueType();
4913   int NumElems = VT.getVectorNumElements();
4914   SDLoc dl(V);
4915
4916   while (NumElems > 4) {
4917     if (EltNo < NumElems/2) {
4918       V = getUnpackl(DAG, dl, VT, V, V);
4919     } else {
4920       V = getUnpackh(DAG, dl, VT, V, V);
4921       EltNo -= NumElems/2;
4922     }
4923     NumElems >>= 1;
4924   }
4925   return V;
4926 }
4927
4928 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4929 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4930   MVT VT = V.getSimpleValueType();
4931   SDLoc dl(V);
4932
4933   if (VT.is128BitVector()) {
4934     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4935     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4936     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4937                              &SplatMask[0]);
4938   } else if (VT.is256BitVector()) {
4939     // To use VPERMILPS to splat scalars, the second half of indicies must
4940     // refer to the higher part, which is a duplication of the lower one,
4941     // because VPERMILPS can only handle in-lane permutations.
4942     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4943                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4944
4945     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4946     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4947                              &SplatMask[0]);
4948   } else
4949     llvm_unreachable("Vector size not supported");
4950
4951   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4952 }
4953
4954 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4955 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4956   MVT SrcVT = SV->getSimpleValueType(0);
4957   SDValue V1 = SV->getOperand(0);
4958   SDLoc dl(SV);
4959
4960   int EltNo = SV->getSplatIndex();
4961   int NumElems = SrcVT.getVectorNumElements();
4962   bool Is256BitVec = SrcVT.is256BitVector();
4963
4964   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4965          "Unknown how to promote splat for type");
4966
4967   // Extract the 128-bit part containing the splat element and update
4968   // the splat element index when it refers to the higher register.
4969   if (Is256BitVec) {
4970     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4971     if (EltNo >= NumElems/2)
4972       EltNo -= NumElems/2;
4973   }
4974
4975   // All i16 and i8 vector types can't be used directly by a generic shuffle
4976   // instruction because the target has no such instruction. Generate shuffles
4977   // which repeat i16 and i8 several times until they fit in i32, and then can
4978   // be manipulated by target suported shuffles.
4979   MVT EltVT = SrcVT.getVectorElementType();
4980   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4981     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4982
4983   // Recreate the 256-bit vector and place the same 128-bit vector
4984   // into the low and high part. This is necessary because we want
4985   // to use VPERM* to shuffle the vectors
4986   if (Is256BitVec) {
4987     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4988   }
4989
4990   return getLegalSplat(DAG, V1, EltNo);
4991 }
4992
4993 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4994 /// vector of zero or undef vector.  This produces a shuffle where the low
4995 /// element of V2 is swizzled into the zero/undef vector, landing at element
4996 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4997 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4998                                            bool IsZero,
4999                                            const X86Subtarget *Subtarget,
5000                                            SelectionDAG &DAG) {
5001   MVT VT = V2.getSimpleValueType();
5002   SDValue V1 = IsZero
5003     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5004   unsigned NumElems = VT.getVectorNumElements();
5005   SmallVector<int, 16> MaskVec;
5006   for (unsigned i = 0; i != NumElems; ++i)
5007     // If this is the insertion idx, put the low elt of V2 here.
5008     MaskVec.push_back(i == Idx ? NumElems : i);
5009   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5010 }
5011
5012 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5013 /// target specific opcode. Returns true if the Mask could be calculated.
5014 /// Sets IsUnary to true if only uses one source.
5015 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5016                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5017   unsigned NumElems = VT.getVectorNumElements();
5018   SDValue ImmN;
5019
5020   IsUnary = false;
5021   switch(N->getOpcode()) {
5022   case X86ISD::SHUFP:
5023     ImmN = N->getOperand(N->getNumOperands()-1);
5024     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5025     break;
5026   case X86ISD::UNPCKH:
5027     DecodeUNPCKHMask(VT, Mask);
5028     break;
5029   case X86ISD::UNPCKL:
5030     DecodeUNPCKLMask(VT, Mask);
5031     break;
5032   case X86ISD::MOVHLPS:
5033     DecodeMOVHLPSMask(NumElems, Mask);
5034     break;
5035   case X86ISD::MOVLHPS:
5036     DecodeMOVLHPSMask(NumElems, Mask);
5037     break;
5038   case X86ISD::PALIGNR:
5039     ImmN = N->getOperand(N->getNumOperands()-1);
5040     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5041     break;
5042   case X86ISD::PSHUFD:
5043   case X86ISD::VPERMILP:
5044     ImmN = N->getOperand(N->getNumOperands()-1);
5045     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5046     IsUnary = true;
5047     break;
5048   case X86ISD::PSHUFHW:
5049     ImmN = N->getOperand(N->getNumOperands()-1);
5050     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5051     IsUnary = true;
5052     break;
5053   case X86ISD::PSHUFLW:
5054     ImmN = N->getOperand(N->getNumOperands()-1);
5055     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5056     IsUnary = true;
5057     break;
5058   case X86ISD::VPERMI:
5059     ImmN = N->getOperand(N->getNumOperands()-1);
5060     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5061     IsUnary = true;
5062     break;
5063   case X86ISD::MOVSS:
5064   case X86ISD::MOVSD: {
5065     // The index 0 always comes from the first element of the second source,
5066     // this is why MOVSS and MOVSD are used in the first place. The other
5067     // elements come from the other positions of the first source vector
5068     Mask.push_back(NumElems);
5069     for (unsigned i = 1; i != NumElems; ++i) {
5070       Mask.push_back(i);
5071     }
5072     break;
5073   }
5074   case X86ISD::VPERM2X128:
5075     ImmN = N->getOperand(N->getNumOperands()-1);
5076     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5077     if (Mask.empty()) return false;
5078     break;
5079   case X86ISD::MOVDDUP:
5080   case X86ISD::MOVLHPD:
5081   case X86ISD::MOVLPD:
5082   case X86ISD::MOVLPS:
5083   case X86ISD::MOVSHDUP:
5084   case X86ISD::MOVSLDUP:
5085     // Not yet implemented
5086     return false;
5087   default: llvm_unreachable("unknown target shuffle node");
5088   }
5089
5090   return true;
5091 }
5092
5093 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5094 /// element of the result of the vector shuffle.
5095 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5096                                    unsigned Depth) {
5097   if (Depth == 6)
5098     return SDValue();  // Limit search depth.
5099
5100   SDValue V = SDValue(N, 0);
5101   EVT VT = V.getValueType();
5102   unsigned Opcode = V.getOpcode();
5103
5104   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5105   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5106     int Elt = SV->getMaskElt(Index);
5107
5108     if (Elt < 0)
5109       return DAG.getUNDEF(VT.getVectorElementType());
5110
5111     unsigned NumElems = VT.getVectorNumElements();
5112     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5113                                          : SV->getOperand(1);
5114     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5115   }
5116
5117   // Recurse into target specific vector shuffles to find scalars.
5118   if (isTargetShuffle(Opcode)) {
5119     MVT ShufVT = V.getSimpleValueType();
5120     unsigned NumElems = ShufVT.getVectorNumElements();
5121     SmallVector<int, 16> ShuffleMask;
5122     bool IsUnary;
5123
5124     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5125       return SDValue();
5126
5127     int Elt = ShuffleMask[Index];
5128     if (Elt < 0)
5129       return DAG.getUNDEF(ShufVT.getVectorElementType());
5130
5131     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5132                                          : N->getOperand(1);
5133     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5134                                Depth+1);
5135   }
5136
5137   // Actual nodes that may contain scalar elements
5138   if (Opcode == ISD::BITCAST) {
5139     V = V.getOperand(0);
5140     EVT SrcVT = V.getValueType();
5141     unsigned NumElems = VT.getVectorNumElements();
5142
5143     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5144       return SDValue();
5145   }
5146
5147   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5148     return (Index == 0) ? V.getOperand(0)
5149                         : DAG.getUNDEF(VT.getVectorElementType());
5150
5151   if (V.getOpcode() == ISD::BUILD_VECTOR)
5152     return V.getOperand(Index);
5153
5154   return SDValue();
5155 }
5156
5157 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5158 /// shuffle operation which come from a consecutively from a zero. The
5159 /// search can start in two different directions, from left or right.
5160 /// We count undefs as zeros until PreferredNum is reached.
5161 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5162                                          unsigned NumElems, bool ZerosFromLeft,
5163                                          SelectionDAG &DAG,
5164                                          unsigned PreferredNum = -1U) {
5165   unsigned NumZeros = 0;
5166   for (unsigned i = 0; i != NumElems; ++i) {
5167     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5168     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5169     if (!Elt.getNode())
5170       break;
5171
5172     if (X86::isZeroNode(Elt))
5173       ++NumZeros;
5174     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5175       NumZeros = std::min(NumZeros + 1, PreferredNum);
5176     else
5177       break;
5178   }
5179
5180   return NumZeros;
5181 }
5182
5183 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5184 /// correspond consecutively to elements from one of the vector operands,
5185 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5186 static
5187 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5188                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5189                               unsigned NumElems, unsigned &OpNum) {
5190   bool SeenV1 = false;
5191   bool SeenV2 = false;
5192
5193   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5194     int Idx = SVOp->getMaskElt(i);
5195     // Ignore undef indicies
5196     if (Idx < 0)
5197       continue;
5198
5199     if (Idx < (int)NumElems)
5200       SeenV1 = true;
5201     else
5202       SeenV2 = true;
5203
5204     // Only accept consecutive elements from the same vector
5205     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5206       return false;
5207   }
5208
5209   OpNum = SeenV1 ? 0 : 1;
5210   return true;
5211 }
5212
5213 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5214 /// logical left shift of a vector.
5215 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5216                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5217   unsigned NumElems =
5218     SVOp->getSimpleValueType(0).getVectorNumElements();
5219   unsigned NumZeros = getNumOfConsecutiveZeros(
5220       SVOp, NumElems, false /* check zeros from right */, DAG,
5221       SVOp->getMaskElt(0));
5222   unsigned OpSrc;
5223
5224   if (!NumZeros)
5225     return false;
5226
5227   // Considering the elements in the mask that are not consecutive zeros,
5228   // check if they consecutively come from only one of the source vectors.
5229   //
5230   //               V1 = {X, A, B, C}     0
5231   //                         \  \  \    /
5232   //   vector_shuffle V1, V2 <1, 2, 3, X>
5233   //
5234   if (!isShuffleMaskConsecutive(SVOp,
5235             0,                   // Mask Start Index
5236             NumElems-NumZeros,   // Mask End Index(exclusive)
5237             NumZeros,            // Where to start looking in the src vector
5238             NumElems,            // Number of elements in vector
5239             OpSrc))              // Which source operand ?
5240     return false;
5241
5242   isLeft = false;
5243   ShAmt = NumZeros;
5244   ShVal = SVOp->getOperand(OpSrc);
5245   return true;
5246 }
5247
5248 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5249 /// logical left shift of a vector.
5250 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5251                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5252   unsigned NumElems =
5253     SVOp->getSimpleValueType(0).getVectorNumElements();
5254   unsigned NumZeros = getNumOfConsecutiveZeros(
5255       SVOp, NumElems, true /* check zeros from left */, DAG,
5256       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5257   unsigned OpSrc;
5258
5259   if (!NumZeros)
5260     return false;
5261
5262   // Considering the elements in the mask that are not consecutive zeros,
5263   // check if they consecutively come from only one of the source vectors.
5264   //
5265   //                           0    { A, B, X, X } = V2
5266   //                          / \    /  /
5267   //   vector_shuffle V1, V2 <X, X, 4, 5>
5268   //
5269   if (!isShuffleMaskConsecutive(SVOp,
5270             NumZeros,     // Mask Start Index
5271             NumElems,     // Mask End Index(exclusive)
5272             0,            // Where to start looking in the src vector
5273             NumElems,     // Number of elements in vector
5274             OpSrc))       // Which source operand ?
5275     return false;
5276
5277   isLeft = true;
5278   ShAmt = NumZeros;
5279   ShVal = SVOp->getOperand(OpSrc);
5280   return true;
5281 }
5282
5283 /// isVectorShift - Returns true if the shuffle can be implemented as a
5284 /// logical left or right shift of a vector.
5285 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5286                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5287   // Although the logic below support any bitwidth size, there are no
5288   // shift instructions which handle more than 128-bit vectors.
5289   if (!SVOp->getSimpleValueType(0).is128BitVector())
5290     return false;
5291
5292   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5293       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5294     return true;
5295
5296   return false;
5297 }
5298
5299 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5300 ///
5301 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5302                                        unsigned NumNonZero, unsigned NumZero,
5303                                        SelectionDAG &DAG,
5304                                        const X86Subtarget* Subtarget,
5305                                        const TargetLowering &TLI) {
5306   if (NumNonZero > 8)
5307     return SDValue();
5308
5309   SDLoc dl(Op);
5310   SDValue V(0, 0);
5311   bool First = true;
5312   for (unsigned i = 0; i < 16; ++i) {
5313     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5314     if (ThisIsNonZero && First) {
5315       if (NumZero)
5316         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5317       else
5318         V = DAG.getUNDEF(MVT::v8i16);
5319       First = false;
5320     }
5321
5322     if ((i & 1) != 0) {
5323       SDValue ThisElt(0, 0), LastElt(0, 0);
5324       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5325       if (LastIsNonZero) {
5326         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5327                               MVT::i16, Op.getOperand(i-1));
5328       }
5329       if (ThisIsNonZero) {
5330         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5331         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5332                               ThisElt, DAG.getConstant(8, MVT::i8));
5333         if (LastIsNonZero)
5334           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5335       } else
5336         ThisElt = LastElt;
5337
5338       if (ThisElt.getNode())
5339         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5340                         DAG.getIntPtrConstant(i/2));
5341     }
5342   }
5343
5344   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5345 }
5346
5347 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5348 ///
5349 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5350                                      unsigned NumNonZero, unsigned NumZero,
5351                                      SelectionDAG &DAG,
5352                                      const X86Subtarget* Subtarget,
5353                                      const TargetLowering &TLI) {
5354   if (NumNonZero > 4)
5355     return SDValue();
5356
5357   SDLoc dl(Op);
5358   SDValue V(0, 0);
5359   bool First = true;
5360   for (unsigned i = 0; i < 8; ++i) {
5361     bool isNonZero = (NonZeros & (1 << i)) != 0;
5362     if (isNonZero) {
5363       if (First) {
5364         if (NumZero)
5365           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5366         else
5367           V = DAG.getUNDEF(MVT::v8i16);
5368         First = false;
5369       }
5370       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5371                       MVT::v8i16, V, Op.getOperand(i),
5372                       DAG.getIntPtrConstant(i));
5373     }
5374   }
5375
5376   return V;
5377 }
5378
5379 /// getVShift - Return a vector logical shift node.
5380 ///
5381 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5382                          unsigned NumBits, SelectionDAG &DAG,
5383                          const TargetLowering &TLI, SDLoc dl) {
5384   assert(VT.is128BitVector() && "Unknown type for VShift");
5385   EVT ShVT = MVT::v2i64;
5386   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5387   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5388   return DAG.getNode(ISD::BITCAST, dl, VT,
5389                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5390                              DAG.getConstant(NumBits,
5391                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5392 }
5393
5394 static SDValue
5395 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5396
5397   // Check if the scalar load can be widened into a vector load. And if
5398   // the address is "base + cst" see if the cst can be "absorbed" into
5399   // the shuffle mask.
5400   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5401     SDValue Ptr = LD->getBasePtr();
5402     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5403       return SDValue();
5404     EVT PVT = LD->getValueType(0);
5405     if (PVT != MVT::i32 && PVT != MVT::f32)
5406       return SDValue();
5407
5408     int FI = -1;
5409     int64_t Offset = 0;
5410     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5411       FI = FINode->getIndex();
5412       Offset = 0;
5413     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5414                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5415       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5416       Offset = Ptr.getConstantOperandVal(1);
5417       Ptr = Ptr.getOperand(0);
5418     } else {
5419       return SDValue();
5420     }
5421
5422     // FIXME: 256-bit vector instructions don't require a strict alignment,
5423     // improve this code to support it better.
5424     unsigned RequiredAlign = VT.getSizeInBits()/8;
5425     SDValue Chain = LD->getChain();
5426     // Make sure the stack object alignment is at least 16 or 32.
5427     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5428     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5429       if (MFI->isFixedObjectIndex(FI)) {
5430         // Can't change the alignment. FIXME: It's possible to compute
5431         // the exact stack offset and reference FI + adjust offset instead.
5432         // If someone *really* cares about this. That's the way to implement it.
5433         return SDValue();
5434       } else {
5435         MFI->setObjectAlignment(FI, RequiredAlign);
5436       }
5437     }
5438
5439     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5440     // Ptr + (Offset & ~15).
5441     if (Offset < 0)
5442       return SDValue();
5443     if ((Offset % RequiredAlign) & 3)
5444       return SDValue();
5445     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5446     if (StartOffset)
5447       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5448                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5449
5450     int EltNo = (Offset - StartOffset) >> 2;
5451     unsigned NumElems = VT.getVectorNumElements();
5452
5453     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5454     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5455                              LD->getPointerInfo().getWithOffset(StartOffset),
5456                              false, false, false, 0);
5457
5458     SmallVector<int, 8> Mask;
5459     for (unsigned i = 0; i != NumElems; ++i)
5460       Mask.push_back(EltNo);
5461
5462     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5463   }
5464
5465   return SDValue();
5466 }
5467
5468 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5469 /// vector of type 'VT', see if the elements can be replaced by a single large
5470 /// load which has the same value as a build_vector whose operands are 'elts'.
5471 ///
5472 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5473 ///
5474 /// FIXME: we'd also like to handle the case where the last elements are zero
5475 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5476 /// There's even a handy isZeroNode for that purpose.
5477 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5478                                         SDLoc &DL, SelectionDAG &DAG,
5479                                         bool isAfterLegalize) {
5480   EVT EltVT = VT.getVectorElementType();
5481   unsigned NumElems = Elts.size();
5482
5483   LoadSDNode *LDBase = NULL;
5484   unsigned LastLoadedElt = -1U;
5485
5486   // For each element in the initializer, see if we've found a load or an undef.
5487   // If we don't find an initial load element, or later load elements are
5488   // non-consecutive, bail out.
5489   for (unsigned i = 0; i < NumElems; ++i) {
5490     SDValue Elt = Elts[i];
5491
5492     if (!Elt.getNode() ||
5493         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5494       return SDValue();
5495     if (!LDBase) {
5496       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5497         return SDValue();
5498       LDBase = cast<LoadSDNode>(Elt.getNode());
5499       LastLoadedElt = i;
5500       continue;
5501     }
5502     if (Elt.getOpcode() == ISD::UNDEF)
5503       continue;
5504
5505     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5506     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5507       return SDValue();
5508     LastLoadedElt = i;
5509   }
5510
5511   // If we have found an entire vector of loads and undefs, then return a large
5512   // load of the entire vector width starting at the base pointer.  If we found
5513   // consecutive loads for the low half, generate a vzext_load node.
5514   if (LastLoadedElt == NumElems - 1) {
5515
5516     if (isAfterLegalize &&
5517         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5518       return SDValue();
5519
5520     SDValue NewLd = SDValue();
5521
5522     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5523       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5524                           LDBase->getPointerInfo(),
5525                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5526                           LDBase->isInvariant(), 0);
5527     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528                         LDBase->getPointerInfo(),
5529                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5530                         LDBase->isInvariant(), LDBase->getAlignment());
5531
5532     if (LDBase->hasAnyUseOfValue(1)) {
5533       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5534                                      SDValue(LDBase, 1),
5535                                      SDValue(NewLd.getNode(), 1));
5536       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5537       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5538                              SDValue(NewLd.getNode(), 1));
5539     }
5540
5541     return NewLd;
5542   }
5543   if (NumElems == 4 && LastLoadedElt == 1 &&
5544       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5545     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5546     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5547     SDValue ResNode =
5548         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5549                                 array_lengthof(Ops), MVT::i64,
5550                                 LDBase->getPointerInfo(),
5551                                 LDBase->getAlignment(),
5552                                 false/*isVolatile*/, true/*ReadMem*/,
5553                                 false/*WriteMem*/);
5554
5555     // Make sure the newly-created LOAD is in the same position as LDBase in
5556     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5557     // update uses of LDBase's output chain to use the TokenFactor.
5558     if (LDBase->hasAnyUseOfValue(1)) {
5559       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5560                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5561       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5562       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5563                              SDValue(ResNode.getNode(), 1));
5564     }
5565
5566     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5567   }
5568   return SDValue();
5569 }
5570
5571 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5572 /// to generate a splat value for the following cases:
5573 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5574 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5575 /// a scalar load, or a constant.
5576 /// The VBROADCAST node is returned when a pattern is found,
5577 /// or SDValue() otherwise.
5578 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5579                                     SelectionDAG &DAG) {
5580   if (!Subtarget->hasFp256())
5581     return SDValue();
5582
5583   MVT VT = Op.getSimpleValueType();
5584   SDLoc dl(Op);
5585
5586   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5587          "Unsupported vector type for broadcast.");
5588
5589   SDValue Ld;
5590   bool ConstSplatVal;
5591
5592   switch (Op.getOpcode()) {
5593     default:
5594       // Unknown pattern found.
5595       return SDValue();
5596
5597     case ISD::BUILD_VECTOR: {
5598       // The BUILD_VECTOR node must be a splat.
5599       if (!isSplatVector(Op.getNode()))
5600         return SDValue();
5601
5602       Ld = Op.getOperand(0);
5603       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5604                      Ld.getOpcode() == ISD::ConstantFP);
5605
5606       // The suspected load node has several users. Make sure that all
5607       // of its users are from the BUILD_VECTOR node.
5608       // Constants may have multiple users.
5609       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5610         return SDValue();
5611       break;
5612     }
5613
5614     case ISD::VECTOR_SHUFFLE: {
5615       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5616
5617       // Shuffles must have a splat mask where the first element is
5618       // broadcasted.
5619       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5620         return SDValue();
5621
5622       SDValue Sc = Op.getOperand(0);
5623       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5624           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5625
5626         if (!Subtarget->hasInt256())
5627           return SDValue();
5628
5629         // Use the register form of the broadcast instruction available on AVX2.
5630         if (VT.getSizeInBits() >= 256)
5631           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5632         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5633       }
5634
5635       Ld = Sc.getOperand(0);
5636       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5637                        Ld.getOpcode() == ISD::ConstantFP);
5638
5639       // The scalar_to_vector node and the suspected
5640       // load node must have exactly one user.
5641       // Constants may have multiple users.
5642
5643       // AVX-512 has register version of the broadcast
5644       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5645         Ld.getValueType().getSizeInBits() >= 32;
5646       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5647           !hasRegVer))
5648         return SDValue();
5649       break;
5650     }
5651   }
5652
5653   bool IsGE256 = (VT.getSizeInBits() >= 256);
5654
5655   // Handle the broadcasting a single constant scalar from the constant pool
5656   // into a vector. On Sandybridge it is still better to load a constant vector
5657   // from the constant pool and not to broadcast it from a scalar.
5658   if (ConstSplatVal && Subtarget->hasInt256()) {
5659     EVT CVT = Ld.getValueType();
5660     assert(!CVT.isVector() && "Must not broadcast a vector type");
5661     unsigned ScalarSize = CVT.getSizeInBits();
5662
5663     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5664       const Constant *C = 0;
5665       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5666         C = CI->getConstantIntValue();
5667       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5668         C = CF->getConstantFPValue();
5669
5670       assert(C && "Invalid constant type");
5671
5672       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5673       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5674       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5675       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5676                        MachinePointerInfo::getConstantPool(),
5677                        false, false, false, Alignment);
5678
5679       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5680     }
5681   }
5682
5683   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5684   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5685
5686   // Handle AVX2 in-register broadcasts.
5687   if (!IsLoad && Subtarget->hasInt256() &&
5688       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5689     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5690
5691   // The scalar source must be a normal load.
5692   if (!IsLoad)
5693     return SDValue();
5694
5695   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5696     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5697
5698   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5699   // double since there is no vbroadcastsd xmm
5700   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5701     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5702       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5703   }
5704
5705   // Unsupported broadcast.
5706   return SDValue();
5707 }
5708
5709 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5710   MVT VT = Op.getSimpleValueType();
5711
5712   // Skip if insert_vec_elt is not supported.
5713   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5714   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5715     return SDValue();
5716
5717   SDLoc DL(Op);
5718   unsigned NumElems = Op.getNumOperands();
5719
5720   SDValue VecIn1;
5721   SDValue VecIn2;
5722   SmallVector<unsigned, 4> InsertIndices;
5723   SmallVector<int, 8> Mask(NumElems, -1);
5724
5725   for (unsigned i = 0; i != NumElems; ++i) {
5726     unsigned Opc = Op.getOperand(i).getOpcode();
5727
5728     if (Opc == ISD::UNDEF)
5729       continue;
5730
5731     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5732       // Quit if more than 1 elements need inserting.
5733       if (InsertIndices.size() > 1)
5734         return SDValue();
5735
5736       InsertIndices.push_back(i);
5737       continue;
5738     }
5739
5740     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5741     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5742
5743     // Quit if extracted from vector of different type.
5744     if (ExtractedFromVec.getValueType() != VT)
5745       return SDValue();
5746
5747     // Quit if non-constant index.
5748     if (!isa<ConstantSDNode>(ExtIdx))
5749       return SDValue();
5750
5751     if (VecIn1.getNode() == 0)
5752       VecIn1 = ExtractedFromVec;
5753     else if (VecIn1 != ExtractedFromVec) {
5754       if (VecIn2.getNode() == 0)
5755         VecIn2 = ExtractedFromVec;
5756       else if (VecIn2 != ExtractedFromVec)
5757         // Quit if more than 2 vectors to shuffle
5758         return SDValue();
5759     }
5760
5761     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5762
5763     if (ExtractedFromVec == VecIn1)
5764       Mask[i] = Idx;
5765     else if (ExtractedFromVec == VecIn2)
5766       Mask[i] = Idx + NumElems;
5767   }
5768
5769   if (VecIn1.getNode() == 0)
5770     return SDValue();
5771
5772   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5773   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5774   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5775     unsigned Idx = InsertIndices[i];
5776     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5777                      DAG.getIntPtrConstant(Idx));
5778   }
5779
5780   return NV;
5781 }
5782
5783 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5784 SDValue
5785 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5786
5787   MVT VT = Op.getSimpleValueType();
5788   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5789          "Unexpected type in LowerBUILD_VECTORvXi1!");
5790
5791   SDLoc dl(Op);
5792   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5793     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5794     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5795                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5796     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5797                        Ops, VT.getVectorNumElements());
5798   }
5799
5800   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5801     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5802     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5803                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5804     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5805                        Ops, VT.getVectorNumElements());
5806   }
5807
5808   bool AllContants = true;
5809   uint64_t Immediate = 0;
5810   int NonConstIdx = -1;
5811   bool IsSplat = true;
5812   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5813     SDValue In = Op.getOperand(idx);
5814     if (In.getOpcode() == ISD::UNDEF)
5815       continue;
5816     if (!isa<ConstantSDNode>(In)) {
5817       AllContants = false;
5818       NonConstIdx = idx;
5819     }
5820     else if (cast<ConstantSDNode>(In)->getZExtValue())
5821       Immediate |= (1ULL << idx);
5822     if (In != Op.getOperand(0))
5823       IsSplat = false;
5824   }
5825
5826   if (AllContants) {
5827     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5828       DAG.getConstant(Immediate, MVT::i16));
5829     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5830                        DAG.getIntPtrConstant(0));
5831   }
5832
5833   if (!IsSplat && (NonConstIdx != 0))
5834     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5835   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5836   SDValue Select;
5837   if (IsSplat)
5838     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5839                           DAG.getConstant(-1, SelectVT),
5840                           DAG.getConstant(0, SelectVT));
5841   else
5842     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5843                          DAG.getConstant((Immediate | 1), SelectVT),
5844                          DAG.getConstant(Immediate, SelectVT));
5845   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5846 }
5847
5848 SDValue
5849 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5850   SDLoc dl(Op);
5851
5852   MVT VT = Op.getSimpleValueType();
5853   MVT ExtVT = VT.getVectorElementType();
5854   unsigned NumElems = Op.getNumOperands();
5855
5856   // Generate vectors for predicate vectors.
5857   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5858     return LowerBUILD_VECTORvXi1(Op, DAG);
5859
5860   // Vectors containing all zeros can be matched by pxor and xorps later
5861   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5862     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5863     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5864     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5865       return Op;
5866
5867     return getZeroVector(VT, Subtarget, DAG, dl);
5868   }
5869
5870   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5871   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5872   // vpcmpeqd on 256-bit vectors.
5873   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5874     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5875       return Op;
5876
5877     if (!VT.is512BitVector())
5878       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5879   }
5880
5881   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5882   if (Broadcast.getNode())
5883     return Broadcast;
5884
5885   unsigned EVTBits = ExtVT.getSizeInBits();
5886
5887   unsigned NumZero  = 0;
5888   unsigned NumNonZero = 0;
5889   unsigned NonZeros = 0;
5890   bool IsAllConstants = true;
5891   SmallSet<SDValue, 8> Values;
5892   for (unsigned i = 0; i < NumElems; ++i) {
5893     SDValue Elt = Op.getOperand(i);
5894     if (Elt.getOpcode() == ISD::UNDEF)
5895       continue;
5896     Values.insert(Elt);
5897     if (Elt.getOpcode() != ISD::Constant &&
5898         Elt.getOpcode() != ISD::ConstantFP)
5899       IsAllConstants = false;
5900     if (X86::isZeroNode(Elt))
5901       NumZero++;
5902     else {
5903       NonZeros |= (1 << i);
5904       NumNonZero++;
5905     }
5906   }
5907
5908   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5909   if (NumNonZero == 0)
5910     return DAG.getUNDEF(VT);
5911
5912   // Special case for single non-zero, non-undef, element.
5913   if (NumNonZero == 1) {
5914     unsigned Idx = countTrailingZeros(NonZeros);
5915     SDValue Item = Op.getOperand(Idx);
5916
5917     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5918     // the value are obviously zero, truncate the value to i32 and do the
5919     // insertion that way.  Only do this if the value is non-constant or if the
5920     // value is a constant being inserted into element 0.  It is cheaper to do
5921     // a constant pool load than it is to do a movd + shuffle.
5922     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5923         (!IsAllConstants || Idx == 0)) {
5924       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5925         // Handle SSE only.
5926         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5927         EVT VecVT = MVT::v4i32;
5928         unsigned VecElts = 4;
5929
5930         // Truncate the value (which may itself be a constant) to i32, and
5931         // convert it to a vector with movd (S2V+shuffle to zero extend).
5932         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5933         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5934         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5935
5936         // Now we have our 32-bit value zero extended in the low element of
5937         // a vector.  If Idx != 0, swizzle it into place.
5938         if (Idx != 0) {
5939           SmallVector<int, 4> Mask;
5940           Mask.push_back(Idx);
5941           for (unsigned i = 1; i != VecElts; ++i)
5942             Mask.push_back(i);
5943           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5944                                       &Mask[0]);
5945         }
5946         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5947       }
5948     }
5949
5950     // If we have a constant or non-constant insertion into the low element of
5951     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5952     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5953     // depending on what the source datatype is.
5954     if (Idx == 0) {
5955       if (NumZero == 0)
5956         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5957
5958       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5959           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5960         if (VT.is256BitVector() || VT.is512BitVector()) {
5961           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5962           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5963                              Item, DAG.getIntPtrConstant(0));
5964         }
5965         assert(VT.is128BitVector() && "Expected an SSE value type!");
5966         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5967         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5968         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5969       }
5970
5971       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5972         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5973         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5974         if (VT.is256BitVector()) {
5975           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5976           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5977         } else {
5978           assert(VT.is128BitVector() && "Expected an SSE value type!");
5979           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5980         }
5981         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5982       }
5983     }
5984
5985     // Is it a vector logical left shift?
5986     if (NumElems == 2 && Idx == 1 &&
5987         X86::isZeroNode(Op.getOperand(0)) &&
5988         !X86::isZeroNode(Op.getOperand(1))) {
5989       unsigned NumBits = VT.getSizeInBits();
5990       return getVShift(true, VT,
5991                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5992                                    VT, Op.getOperand(1)),
5993                        NumBits/2, DAG, *this, dl);
5994     }
5995
5996     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5997       return SDValue();
5998
5999     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6000     // is a non-constant being inserted into an element other than the low one,
6001     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6002     // movd/movss) to move this into the low element, then shuffle it into
6003     // place.
6004     if (EVTBits == 32) {
6005       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6006
6007       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6008       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6009       SmallVector<int, 8> MaskVec;
6010       for (unsigned i = 0; i != NumElems; ++i)
6011         MaskVec.push_back(i == Idx ? 0 : 1);
6012       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6013     }
6014   }
6015
6016   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6017   if (Values.size() == 1) {
6018     if (EVTBits == 32) {
6019       // Instead of a shuffle like this:
6020       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6021       // Check if it's possible to issue this instead.
6022       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6023       unsigned Idx = countTrailingZeros(NonZeros);
6024       SDValue Item = Op.getOperand(Idx);
6025       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6026         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6027     }
6028     return SDValue();
6029   }
6030
6031   // A vector full of immediates; various special cases are already
6032   // handled, so this is best done with a single constant-pool load.
6033   if (IsAllConstants)
6034     return SDValue();
6035
6036   // For AVX-length vectors, build the individual 128-bit pieces and use
6037   // shuffles to put them in place.
6038   if (VT.is256BitVector() || VT.is512BitVector()) {
6039     SmallVector<SDValue, 64> V;
6040     for (unsigned i = 0; i != NumElems; ++i)
6041       V.push_back(Op.getOperand(i));
6042
6043     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6044
6045     // Build both the lower and upper subvector.
6046     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6047     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6048                                 NumElems/2);
6049
6050     // Recreate the wider vector with the lower and upper part.
6051     if (VT.is256BitVector())
6052       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6053     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6054   }
6055
6056   // Let legalizer expand 2-wide build_vectors.
6057   if (EVTBits == 64) {
6058     if (NumNonZero == 1) {
6059       // One half is zero or undef.
6060       unsigned Idx = countTrailingZeros(NonZeros);
6061       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6062                                  Op.getOperand(Idx));
6063       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6064     }
6065     return SDValue();
6066   }
6067
6068   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6069   if (EVTBits == 8 && NumElems == 16) {
6070     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6071                                         Subtarget, *this);
6072     if (V.getNode()) return V;
6073   }
6074
6075   if (EVTBits == 16 && NumElems == 8) {
6076     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6077                                       Subtarget, *this);
6078     if (V.getNode()) return V;
6079   }
6080
6081   // If element VT is == 32 bits, turn it into a number of shuffles.
6082   SmallVector<SDValue, 8> V(NumElems);
6083   if (NumElems == 4 && NumZero > 0) {
6084     for (unsigned i = 0; i < 4; ++i) {
6085       bool isZero = !(NonZeros & (1 << i));
6086       if (isZero)
6087         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6088       else
6089         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6090     }
6091
6092     for (unsigned i = 0; i < 2; ++i) {
6093       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6094         default: break;
6095         case 0:
6096           V[i] = V[i*2];  // Must be a zero vector.
6097           break;
6098         case 1:
6099           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6100           break;
6101         case 2:
6102           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6103           break;
6104         case 3:
6105           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6106           break;
6107       }
6108     }
6109
6110     bool Reverse1 = (NonZeros & 0x3) == 2;
6111     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6112     int MaskVec[] = {
6113       Reverse1 ? 1 : 0,
6114       Reverse1 ? 0 : 1,
6115       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6116       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6117     };
6118     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6119   }
6120
6121   if (Values.size() > 1 && VT.is128BitVector()) {
6122     // Check for a build vector of consecutive loads.
6123     for (unsigned i = 0; i < NumElems; ++i)
6124       V[i] = Op.getOperand(i);
6125
6126     // Check for elements which are consecutive loads.
6127     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6128     if (LD.getNode())
6129       return LD;
6130
6131     // Check for a build vector from mostly shuffle plus few inserting.
6132     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6133     if (Sh.getNode())
6134       return Sh;
6135
6136     // For SSE 4.1, use insertps to put the high elements into the low element.
6137     if (getSubtarget()->hasSSE41()) {
6138       SDValue Result;
6139       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6140         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6141       else
6142         Result = DAG.getUNDEF(VT);
6143
6144       for (unsigned i = 1; i < NumElems; ++i) {
6145         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6146         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6147                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6148       }
6149       return Result;
6150     }
6151
6152     // Otherwise, expand into a number of unpckl*, start by extending each of
6153     // our (non-undef) elements to the full vector width with the element in the
6154     // bottom slot of the vector (which generates no code for SSE).
6155     for (unsigned i = 0; i < NumElems; ++i) {
6156       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6157         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6158       else
6159         V[i] = DAG.getUNDEF(VT);
6160     }
6161
6162     // Next, we iteratively mix elements, e.g. for v4f32:
6163     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6164     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6165     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6166     unsigned EltStride = NumElems >> 1;
6167     while (EltStride != 0) {
6168       for (unsigned i = 0; i < EltStride; ++i) {
6169         // If V[i+EltStride] is undef and this is the first round of mixing,
6170         // then it is safe to just drop this shuffle: V[i] is already in the
6171         // right place, the one element (since it's the first round) being
6172         // inserted as undef can be dropped.  This isn't safe for successive
6173         // rounds because they will permute elements within both vectors.
6174         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6175             EltStride == NumElems/2)
6176           continue;
6177
6178         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6179       }
6180       EltStride >>= 1;
6181     }
6182     return V[0];
6183   }
6184   return SDValue();
6185 }
6186
6187 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6188 // to create 256-bit vectors from two other 128-bit ones.
6189 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6190   SDLoc dl(Op);
6191   MVT ResVT = Op.getSimpleValueType();
6192
6193   assert((ResVT.is256BitVector() ||
6194           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6195
6196   SDValue V1 = Op.getOperand(0);
6197   SDValue V2 = Op.getOperand(1);
6198   unsigned NumElems = ResVT.getVectorNumElements();
6199   if(ResVT.is256BitVector())
6200     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6201
6202   if (Op.getNumOperands() == 4) {
6203     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6204                                 ResVT.getVectorNumElements()/2);
6205     SDValue V3 = Op.getOperand(2);
6206     SDValue V4 = Op.getOperand(3);
6207     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6208       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6209   }
6210   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6211 }
6212
6213 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6214   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6215   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6216          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6217           Op.getNumOperands() == 4)));
6218
6219   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6220   // from two other 128-bit ones.
6221
6222   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6223   return LowerAVXCONCAT_VECTORS(Op, DAG);
6224 }
6225
6226 // Try to lower a shuffle node into a simple blend instruction.
6227 static SDValue
6228 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6229                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6230   SDValue V1 = SVOp->getOperand(0);
6231   SDValue V2 = SVOp->getOperand(1);
6232   SDLoc dl(SVOp);
6233   MVT VT = SVOp->getSimpleValueType(0);
6234   MVT EltVT = VT.getVectorElementType();
6235   unsigned NumElems = VT.getVectorNumElements();
6236
6237   // There is no blend with immediate in AVX-512.
6238   if (VT.is512BitVector())
6239     return SDValue();
6240
6241   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6242     return SDValue();
6243   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6244     return SDValue();
6245
6246   // Check the mask for BLEND and build the value.
6247   unsigned MaskValue = 0;
6248   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6249   unsigned NumLanes = (NumElems-1)/8 + 1;
6250   unsigned NumElemsInLane = NumElems / NumLanes;
6251
6252   // Blend for v16i16 should be symetric for the both lanes.
6253   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6254
6255     int SndLaneEltIdx = (NumLanes == 2) ?
6256       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6257     int EltIdx = SVOp->getMaskElt(i);
6258
6259     if ((EltIdx < 0 || EltIdx == (int)i) &&
6260         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6261       continue;
6262
6263     if (((unsigned)EltIdx == (i + NumElems)) &&
6264         (SndLaneEltIdx < 0 ||
6265          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6266       MaskValue |= (1<<i);
6267     else
6268       return SDValue();
6269   }
6270
6271   // Convert i32 vectors to floating point if it is not AVX2.
6272   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6273   MVT BlendVT = VT;
6274   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6275     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6276                                NumElems);
6277     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6278     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6279   }
6280
6281   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6282                             DAG.getConstant(MaskValue, MVT::i32));
6283   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6284 }
6285
6286 /// In vector type \p VT, return true if the element at index \p InputIdx
6287 /// falls on a different 128-bit lane than \p OutputIdx.
6288 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6289                                      unsigned OutputIdx) {
6290   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6291   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6292 }
6293
6294 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6295 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6296 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6297 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6298 /// zero.
6299 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6300                          SelectionDAG &DAG) {
6301   MVT VT = V1.getSimpleValueType();
6302   assert(VT.is128BitVector() || VT.is256BitVector());
6303
6304   MVT EltVT = VT.getVectorElementType();
6305   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6306   unsigned NumElts = VT.getVectorNumElements();
6307
6308   SmallVector<SDValue, 32> PshufbMask;
6309   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6310     int InputIdx = MaskVals[OutputIdx];
6311     unsigned InputByteIdx;
6312
6313     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6314       InputByteIdx = 0x80;
6315     else {
6316       // Cross lane is not allowed.
6317       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6318         return SDValue();
6319       InputByteIdx = InputIdx * EltSizeInBytes;
6320       // Index is an byte offset within the 128-bit lane.
6321       InputByteIdx &= 0xf;
6322     }
6323
6324     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6325       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6326       if (InputByteIdx != 0x80)
6327         ++InputByteIdx;
6328     }
6329   }
6330
6331   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6332   if (ShufVT != VT)
6333     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6334   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6335                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6336                                  PshufbMask.data(), PshufbMask.size()));
6337 }
6338
6339 // v8i16 shuffles - Prefer shuffles in the following order:
6340 // 1. [all]   pshuflw, pshufhw, optional move
6341 // 2. [ssse3] 1 x pshufb
6342 // 3. [ssse3] 2 x pshufb + 1 x por
6343 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6344 static SDValue
6345 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6346                          SelectionDAG &DAG) {
6347   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6348   SDValue V1 = SVOp->getOperand(0);
6349   SDValue V2 = SVOp->getOperand(1);
6350   SDLoc dl(SVOp);
6351   SmallVector<int, 8> MaskVals;
6352
6353   // Determine if more than 1 of the words in each of the low and high quadwords
6354   // of the result come from the same quadword of one of the two inputs.  Undef
6355   // mask values count as coming from any quadword, for better codegen.
6356   //
6357   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6358   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6359   unsigned LoQuad[] = { 0, 0, 0, 0 };
6360   unsigned HiQuad[] = { 0, 0, 0, 0 };
6361   // Indices of quads used.
6362   std::bitset<4> InputQuads;
6363   for (unsigned i = 0; i < 8; ++i) {
6364     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6365     int EltIdx = SVOp->getMaskElt(i);
6366     MaskVals.push_back(EltIdx);
6367     if (EltIdx < 0) {
6368       ++Quad[0];
6369       ++Quad[1];
6370       ++Quad[2];
6371       ++Quad[3];
6372       continue;
6373     }
6374     ++Quad[EltIdx / 4];
6375     InputQuads.set(EltIdx / 4);
6376   }
6377
6378   int BestLoQuad = -1;
6379   unsigned MaxQuad = 1;
6380   for (unsigned i = 0; i < 4; ++i) {
6381     if (LoQuad[i] > MaxQuad) {
6382       BestLoQuad = i;
6383       MaxQuad = LoQuad[i];
6384     }
6385   }
6386
6387   int BestHiQuad = -1;
6388   MaxQuad = 1;
6389   for (unsigned i = 0; i < 4; ++i) {
6390     if (HiQuad[i] > MaxQuad) {
6391       BestHiQuad = i;
6392       MaxQuad = HiQuad[i];
6393     }
6394   }
6395
6396   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6397   // of the two input vectors, shuffle them into one input vector so only a
6398   // single pshufb instruction is necessary. If there are more than 2 input
6399   // quads, disable the next transformation since it does not help SSSE3.
6400   bool V1Used = InputQuads[0] || InputQuads[1];
6401   bool V2Used = InputQuads[2] || InputQuads[3];
6402   if (Subtarget->hasSSSE3()) {
6403     if (InputQuads.count() == 2 && V1Used && V2Used) {
6404       BestLoQuad = InputQuads[0] ? 0 : 1;
6405       BestHiQuad = InputQuads[2] ? 2 : 3;
6406     }
6407     if (InputQuads.count() > 2) {
6408       BestLoQuad = -1;
6409       BestHiQuad = -1;
6410     }
6411   }
6412
6413   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6414   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6415   // words from all 4 input quadwords.
6416   SDValue NewV;
6417   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6418     int MaskV[] = {
6419       BestLoQuad < 0 ? 0 : BestLoQuad,
6420       BestHiQuad < 0 ? 1 : BestHiQuad
6421     };
6422     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6423                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6424                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6425     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6426
6427     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6428     // source words for the shuffle, to aid later transformations.
6429     bool AllWordsInNewV = true;
6430     bool InOrder[2] = { true, true };
6431     for (unsigned i = 0; i != 8; ++i) {
6432       int idx = MaskVals[i];
6433       if (idx != (int)i)
6434         InOrder[i/4] = false;
6435       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6436         continue;
6437       AllWordsInNewV = false;
6438       break;
6439     }
6440
6441     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6442     if (AllWordsInNewV) {
6443       for (int i = 0; i != 8; ++i) {
6444         int idx = MaskVals[i];
6445         if (idx < 0)
6446           continue;
6447         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6448         if ((idx != i) && idx < 4)
6449           pshufhw = false;
6450         if ((idx != i) && idx > 3)
6451           pshuflw = false;
6452       }
6453       V1 = NewV;
6454       V2Used = false;
6455       BestLoQuad = 0;
6456       BestHiQuad = 1;
6457     }
6458
6459     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6460     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6461     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6462       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6463       unsigned TargetMask = 0;
6464       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6465                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6466       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6467       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6468                              getShufflePSHUFLWImmediate(SVOp);
6469       V1 = NewV.getOperand(0);
6470       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6471     }
6472   }
6473
6474   // Promote splats to a larger type which usually leads to more efficient code.
6475   // FIXME: Is this true if pshufb is available?
6476   if (SVOp->isSplat())
6477     return PromoteSplat(SVOp, DAG);
6478
6479   // If we have SSSE3, and all words of the result are from 1 input vector,
6480   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6481   // is present, fall back to case 4.
6482   if (Subtarget->hasSSSE3()) {
6483     SmallVector<SDValue,16> pshufbMask;
6484
6485     // If we have elements from both input vectors, set the high bit of the
6486     // shuffle mask element to zero out elements that come from V2 in the V1
6487     // mask, and elements that come from V1 in the V2 mask, so that the two
6488     // results can be OR'd together.
6489     bool TwoInputs = V1Used && V2Used;
6490     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6491     if (!TwoInputs)
6492       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6493
6494     // Calculate the shuffle mask for the second input, shuffle it, and
6495     // OR it with the first shuffled input.
6496     CommuteVectorShuffleMask(MaskVals, 8);
6497     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6498     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6499     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6500   }
6501
6502   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6503   // and update MaskVals with new element order.
6504   std::bitset<8> InOrder;
6505   if (BestLoQuad >= 0) {
6506     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6507     for (int i = 0; i != 4; ++i) {
6508       int idx = MaskVals[i];
6509       if (idx < 0) {
6510         InOrder.set(i);
6511       } else if ((idx / 4) == BestLoQuad) {
6512         MaskV[i] = idx & 3;
6513         InOrder.set(i);
6514       }
6515     }
6516     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6517                                 &MaskV[0]);
6518
6519     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6520       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6521       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6522                                   NewV.getOperand(0),
6523                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6524     }
6525   }
6526
6527   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6528   // and update MaskVals with the new element order.
6529   if (BestHiQuad >= 0) {
6530     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6531     for (unsigned i = 4; i != 8; ++i) {
6532       int idx = MaskVals[i];
6533       if (idx < 0) {
6534         InOrder.set(i);
6535       } else if ((idx / 4) == BestHiQuad) {
6536         MaskV[i] = (idx & 3) + 4;
6537         InOrder.set(i);
6538       }
6539     }
6540     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6541                                 &MaskV[0]);
6542
6543     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6544       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6545       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6546                                   NewV.getOperand(0),
6547                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6548     }
6549   }
6550
6551   // In case BestHi & BestLo were both -1, which means each quadword has a word
6552   // from each of the four input quadwords, calculate the InOrder bitvector now
6553   // before falling through to the insert/extract cleanup.
6554   if (BestLoQuad == -1 && BestHiQuad == -1) {
6555     NewV = V1;
6556     for (int i = 0; i != 8; ++i)
6557       if (MaskVals[i] < 0 || MaskVals[i] == i)
6558         InOrder.set(i);
6559   }
6560
6561   // The other elements are put in the right place using pextrw and pinsrw.
6562   for (unsigned i = 0; i != 8; ++i) {
6563     if (InOrder[i])
6564       continue;
6565     int EltIdx = MaskVals[i];
6566     if (EltIdx < 0)
6567       continue;
6568     SDValue ExtOp = (EltIdx < 8) ?
6569       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6570                   DAG.getIntPtrConstant(EltIdx)) :
6571       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6572                   DAG.getIntPtrConstant(EltIdx - 8));
6573     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6574                        DAG.getIntPtrConstant(i));
6575   }
6576   return NewV;
6577 }
6578
6579 /// \brief v16i16 shuffles
6580 ///
6581 /// FIXME: We only support generation of a single pshufb currently.  We can
6582 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6583 /// well (e.g 2 x pshufb + 1 x por).
6584 static SDValue
6585 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6586   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6587   SDValue V1 = SVOp->getOperand(0);
6588   SDValue V2 = SVOp->getOperand(1);
6589   SDLoc dl(SVOp);
6590
6591   if (V2.getOpcode() != ISD::UNDEF)
6592     return SDValue();
6593
6594   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6595   return getPSHUFB(MaskVals, V1, dl, DAG);
6596 }
6597
6598 // v16i8 shuffles - Prefer shuffles in the following order:
6599 // 1. [ssse3] 1 x pshufb
6600 // 2. [ssse3] 2 x pshufb + 1 x por
6601 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6602 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6603                                         const X86Subtarget* Subtarget,
6604                                         SelectionDAG &DAG) {
6605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6606   SDValue V1 = SVOp->getOperand(0);
6607   SDValue V2 = SVOp->getOperand(1);
6608   SDLoc dl(SVOp);
6609   ArrayRef<int> MaskVals = SVOp->getMask();
6610
6611   // Promote splats to a larger type which usually leads to more efficient code.
6612   // FIXME: Is this true if pshufb is available?
6613   if (SVOp->isSplat())
6614     return PromoteSplat(SVOp, DAG);
6615
6616   // If we have SSSE3, case 1 is generated when all result bytes come from
6617   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6618   // present, fall back to case 3.
6619
6620   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6621   if (Subtarget->hasSSSE3()) {
6622     SmallVector<SDValue,16> pshufbMask;
6623
6624     // If all result elements are from one input vector, then only translate
6625     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6626     //
6627     // Otherwise, we have elements from both input vectors, and must zero out
6628     // elements that come from V2 in the first mask, and V1 in the second mask
6629     // so that we can OR them together.
6630     for (unsigned i = 0; i != 16; ++i) {
6631       int EltIdx = MaskVals[i];
6632       if (EltIdx < 0 || EltIdx >= 16)
6633         EltIdx = 0x80;
6634       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6635     }
6636     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6637                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6638                                  MVT::v16i8, &pshufbMask[0], 16));
6639
6640     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6641     // the 2nd operand if it's undefined or zero.
6642     if (V2.getOpcode() == ISD::UNDEF ||
6643         ISD::isBuildVectorAllZeros(V2.getNode()))
6644       return V1;
6645
6646     // Calculate the shuffle mask for the second input, shuffle it, and
6647     // OR it with the first shuffled input.
6648     pshufbMask.clear();
6649     for (unsigned i = 0; i != 16; ++i) {
6650       int EltIdx = MaskVals[i];
6651       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6652       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6653     }
6654     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6655                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6656                                  MVT::v16i8, &pshufbMask[0], 16));
6657     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6658   }
6659
6660   // No SSSE3 - Calculate in place words and then fix all out of place words
6661   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6662   // the 16 different words that comprise the two doublequadword input vectors.
6663   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6664   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6665   SDValue NewV = V1;
6666   for (int i = 0; i != 8; ++i) {
6667     int Elt0 = MaskVals[i*2];
6668     int Elt1 = MaskVals[i*2+1];
6669
6670     // This word of the result is all undef, skip it.
6671     if (Elt0 < 0 && Elt1 < 0)
6672       continue;
6673
6674     // This word of the result is already in the correct place, skip it.
6675     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6676       continue;
6677
6678     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6679     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6680     SDValue InsElt;
6681
6682     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6683     // using a single extract together, load it and store it.
6684     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6685       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6686                            DAG.getIntPtrConstant(Elt1 / 2));
6687       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6688                         DAG.getIntPtrConstant(i));
6689       continue;
6690     }
6691
6692     // If Elt1 is defined, extract it from the appropriate source.  If the
6693     // source byte is not also odd, shift the extracted word left 8 bits
6694     // otherwise clear the bottom 8 bits if we need to do an or.
6695     if (Elt1 >= 0) {
6696       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6697                            DAG.getIntPtrConstant(Elt1 / 2));
6698       if ((Elt1 & 1) == 0)
6699         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6700                              DAG.getConstant(8,
6701                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6702       else if (Elt0 >= 0)
6703         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6704                              DAG.getConstant(0xFF00, MVT::i16));
6705     }
6706     // If Elt0 is defined, extract it from the appropriate source.  If the
6707     // source byte is not also even, shift the extracted word right 8 bits. If
6708     // Elt1 was also defined, OR the extracted values together before
6709     // inserting them in the result.
6710     if (Elt0 >= 0) {
6711       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6712                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6713       if ((Elt0 & 1) != 0)
6714         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6715                               DAG.getConstant(8,
6716                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6717       else if (Elt1 >= 0)
6718         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6719                              DAG.getConstant(0x00FF, MVT::i16));
6720       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6721                          : InsElt0;
6722     }
6723     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6724                        DAG.getIntPtrConstant(i));
6725   }
6726   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6727 }
6728
6729 // v32i8 shuffles - Translate to VPSHUFB if possible.
6730 static
6731 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6732                                  const X86Subtarget *Subtarget,
6733                                  SelectionDAG &DAG) {
6734   MVT VT = SVOp->getSimpleValueType(0);
6735   SDValue V1 = SVOp->getOperand(0);
6736   SDValue V2 = SVOp->getOperand(1);
6737   SDLoc dl(SVOp);
6738   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6739
6740   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6741   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6742   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6743
6744   // VPSHUFB may be generated if
6745   // (1) one of input vector is undefined or zeroinitializer.
6746   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6747   // And (2) the mask indexes don't cross the 128-bit lane.
6748   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6749       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6750     return SDValue();
6751
6752   if (V1IsAllZero && !V2IsAllZero) {
6753     CommuteVectorShuffleMask(MaskVals, 32);
6754     V1 = V2;
6755   }
6756   return getPSHUFB(MaskVals, V1, dl, DAG);
6757 }
6758
6759 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6760 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6761 /// done when every pair / quad of shuffle mask elements point to elements in
6762 /// the right sequence. e.g.
6763 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6764 static
6765 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6766                                  SelectionDAG &DAG) {
6767   MVT VT = SVOp->getSimpleValueType(0);
6768   SDLoc dl(SVOp);
6769   unsigned NumElems = VT.getVectorNumElements();
6770   MVT NewVT;
6771   unsigned Scale;
6772   switch (VT.SimpleTy) {
6773   default: llvm_unreachable("Unexpected!");
6774   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6775   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6776   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6777   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6778   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6779   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6780   }
6781
6782   SmallVector<int, 8> MaskVec;
6783   for (unsigned i = 0; i != NumElems; i += Scale) {
6784     int StartIdx = -1;
6785     for (unsigned j = 0; j != Scale; ++j) {
6786       int EltIdx = SVOp->getMaskElt(i+j);
6787       if (EltIdx < 0)
6788         continue;
6789       if (StartIdx < 0)
6790         StartIdx = (EltIdx / Scale);
6791       if (EltIdx != (int)(StartIdx*Scale + j))
6792         return SDValue();
6793     }
6794     MaskVec.push_back(StartIdx);
6795   }
6796
6797   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6798   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6799   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6800 }
6801
6802 /// getVZextMovL - Return a zero-extending vector move low node.
6803 ///
6804 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6805                             SDValue SrcOp, SelectionDAG &DAG,
6806                             const X86Subtarget *Subtarget, SDLoc dl) {
6807   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6808     LoadSDNode *LD = NULL;
6809     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6810       LD = dyn_cast<LoadSDNode>(SrcOp);
6811     if (!LD) {
6812       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6813       // instead.
6814       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6815       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6816           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6817           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6818           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6819         // PR2108
6820         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6821         return DAG.getNode(ISD::BITCAST, dl, VT,
6822                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6823                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6824                                                    OpVT,
6825                                                    SrcOp.getOperand(0)
6826                                                           .getOperand(0))));
6827       }
6828     }
6829   }
6830
6831   return DAG.getNode(ISD::BITCAST, dl, VT,
6832                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6833                                  DAG.getNode(ISD::BITCAST, dl,
6834                                              OpVT, SrcOp)));
6835 }
6836
6837 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6838 /// which could not be matched by any known target speficic shuffle
6839 static SDValue
6840 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6841
6842   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6843   if (NewOp.getNode())
6844     return NewOp;
6845
6846   MVT VT = SVOp->getSimpleValueType(0);
6847
6848   unsigned NumElems = VT.getVectorNumElements();
6849   unsigned NumLaneElems = NumElems / 2;
6850
6851   SDLoc dl(SVOp);
6852   MVT EltVT = VT.getVectorElementType();
6853   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6854   SDValue Output[2];
6855
6856   SmallVector<int, 16> Mask;
6857   for (unsigned l = 0; l < 2; ++l) {
6858     // Build a shuffle mask for the output, discovering on the fly which
6859     // input vectors to use as shuffle operands (recorded in InputUsed).
6860     // If building a suitable shuffle vector proves too hard, then bail
6861     // out with UseBuildVector set.
6862     bool UseBuildVector = false;
6863     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6864     unsigned LaneStart = l * NumLaneElems;
6865     for (unsigned i = 0; i != NumLaneElems; ++i) {
6866       // The mask element.  This indexes into the input.
6867       int Idx = SVOp->getMaskElt(i+LaneStart);
6868       if (Idx < 0) {
6869         // the mask element does not index into any input vector.
6870         Mask.push_back(-1);
6871         continue;
6872       }
6873
6874       // The input vector this mask element indexes into.
6875       int Input = Idx / NumLaneElems;
6876
6877       // Turn the index into an offset from the start of the input vector.
6878       Idx -= Input * NumLaneElems;
6879
6880       // Find or create a shuffle vector operand to hold this input.
6881       unsigned OpNo;
6882       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6883         if (InputUsed[OpNo] == Input)
6884           // This input vector is already an operand.
6885           break;
6886         if (InputUsed[OpNo] < 0) {
6887           // Create a new operand for this input vector.
6888           InputUsed[OpNo] = Input;
6889           break;
6890         }
6891       }
6892
6893       if (OpNo >= array_lengthof(InputUsed)) {
6894         // More than two input vectors used!  Give up on trying to create a
6895         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6896         UseBuildVector = true;
6897         break;
6898       }
6899
6900       // Add the mask index for the new shuffle vector.
6901       Mask.push_back(Idx + OpNo * NumLaneElems);
6902     }
6903
6904     if (UseBuildVector) {
6905       SmallVector<SDValue, 16> SVOps;
6906       for (unsigned i = 0; i != NumLaneElems; ++i) {
6907         // The mask element.  This indexes into the input.
6908         int Idx = SVOp->getMaskElt(i+LaneStart);
6909         if (Idx < 0) {
6910           SVOps.push_back(DAG.getUNDEF(EltVT));
6911           continue;
6912         }
6913
6914         // The input vector this mask element indexes into.
6915         int Input = Idx / NumElems;
6916
6917         // Turn the index into an offset from the start of the input vector.
6918         Idx -= Input * NumElems;
6919
6920         // Extract the vector element by hand.
6921         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6922                                     SVOp->getOperand(Input),
6923                                     DAG.getIntPtrConstant(Idx)));
6924       }
6925
6926       // Construct the output using a BUILD_VECTOR.
6927       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6928                               SVOps.size());
6929     } else if (InputUsed[0] < 0) {
6930       // No input vectors were used! The result is undefined.
6931       Output[l] = DAG.getUNDEF(NVT);
6932     } else {
6933       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6934                                         (InputUsed[0] % 2) * NumLaneElems,
6935                                         DAG, dl);
6936       // If only one input was used, use an undefined vector for the other.
6937       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6938         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6939                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6940       // At least one input vector was used. Create a new shuffle vector.
6941       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6942     }
6943
6944     Mask.clear();
6945   }
6946
6947   // Concatenate the result back
6948   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6949 }
6950
6951 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6952 /// 4 elements, and match them with several different shuffle types.
6953 static SDValue
6954 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6955   SDValue V1 = SVOp->getOperand(0);
6956   SDValue V2 = SVOp->getOperand(1);
6957   SDLoc dl(SVOp);
6958   MVT VT = SVOp->getSimpleValueType(0);
6959
6960   assert(VT.is128BitVector() && "Unsupported vector size");
6961
6962   std::pair<int, int> Locs[4];
6963   int Mask1[] = { -1, -1, -1, -1 };
6964   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6965
6966   unsigned NumHi = 0;
6967   unsigned NumLo = 0;
6968   for (unsigned i = 0; i != 4; ++i) {
6969     int Idx = PermMask[i];
6970     if (Idx < 0) {
6971       Locs[i] = std::make_pair(-1, -1);
6972     } else {
6973       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6974       if (Idx < 4) {
6975         Locs[i] = std::make_pair(0, NumLo);
6976         Mask1[NumLo] = Idx;
6977         NumLo++;
6978       } else {
6979         Locs[i] = std::make_pair(1, NumHi);
6980         if (2+NumHi < 4)
6981           Mask1[2+NumHi] = Idx;
6982         NumHi++;
6983       }
6984     }
6985   }
6986
6987   if (NumLo <= 2 && NumHi <= 2) {
6988     // If no more than two elements come from either vector. This can be
6989     // implemented with two shuffles. First shuffle gather the elements.
6990     // The second shuffle, which takes the first shuffle as both of its
6991     // vector operands, put the elements into the right order.
6992     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6993
6994     int Mask2[] = { -1, -1, -1, -1 };
6995
6996     for (unsigned i = 0; i != 4; ++i)
6997       if (Locs[i].first != -1) {
6998         unsigned Idx = (i < 2) ? 0 : 4;
6999         Idx += Locs[i].first * 2 + Locs[i].second;
7000         Mask2[i] = Idx;
7001       }
7002
7003     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7004   }
7005
7006   if (NumLo == 3 || NumHi == 3) {
7007     // Otherwise, we must have three elements from one vector, call it X, and
7008     // one element from the other, call it Y.  First, use a shufps to build an
7009     // intermediate vector with the one element from Y and the element from X
7010     // that will be in the same half in the final destination (the indexes don't
7011     // matter). Then, use a shufps to build the final vector, taking the half
7012     // containing the element from Y from the intermediate, and the other half
7013     // from X.
7014     if (NumHi == 3) {
7015       // Normalize it so the 3 elements come from V1.
7016       CommuteVectorShuffleMask(PermMask, 4);
7017       std::swap(V1, V2);
7018     }
7019
7020     // Find the element from V2.
7021     unsigned HiIndex;
7022     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7023       int Val = PermMask[HiIndex];
7024       if (Val < 0)
7025         continue;
7026       if (Val >= 4)
7027         break;
7028     }
7029
7030     Mask1[0] = PermMask[HiIndex];
7031     Mask1[1] = -1;
7032     Mask1[2] = PermMask[HiIndex^1];
7033     Mask1[3] = -1;
7034     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7035
7036     if (HiIndex >= 2) {
7037       Mask1[0] = PermMask[0];
7038       Mask1[1] = PermMask[1];
7039       Mask1[2] = HiIndex & 1 ? 6 : 4;
7040       Mask1[3] = HiIndex & 1 ? 4 : 6;
7041       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7042     }
7043
7044     Mask1[0] = HiIndex & 1 ? 2 : 0;
7045     Mask1[1] = HiIndex & 1 ? 0 : 2;
7046     Mask1[2] = PermMask[2];
7047     Mask1[3] = PermMask[3];
7048     if (Mask1[2] >= 0)
7049       Mask1[2] += 4;
7050     if (Mask1[3] >= 0)
7051       Mask1[3] += 4;
7052     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7053   }
7054
7055   // Break it into (shuffle shuffle_hi, shuffle_lo).
7056   int LoMask[] = { -1, -1, -1, -1 };
7057   int HiMask[] = { -1, -1, -1, -1 };
7058
7059   int *MaskPtr = LoMask;
7060   unsigned MaskIdx = 0;
7061   unsigned LoIdx = 0;
7062   unsigned HiIdx = 2;
7063   for (unsigned i = 0; i != 4; ++i) {
7064     if (i == 2) {
7065       MaskPtr = HiMask;
7066       MaskIdx = 1;
7067       LoIdx = 0;
7068       HiIdx = 2;
7069     }
7070     int Idx = PermMask[i];
7071     if (Idx < 0) {
7072       Locs[i] = std::make_pair(-1, -1);
7073     } else if (Idx < 4) {
7074       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7075       MaskPtr[LoIdx] = Idx;
7076       LoIdx++;
7077     } else {
7078       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7079       MaskPtr[HiIdx] = Idx;
7080       HiIdx++;
7081     }
7082   }
7083
7084   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7085   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7086   int MaskOps[] = { -1, -1, -1, -1 };
7087   for (unsigned i = 0; i != 4; ++i)
7088     if (Locs[i].first != -1)
7089       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7090   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7091 }
7092
7093 static bool MayFoldVectorLoad(SDValue V) {
7094   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7095     V = V.getOperand(0);
7096
7097   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7098     V = V.getOperand(0);
7099   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7100       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7101     // BUILD_VECTOR (load), undef
7102     V = V.getOperand(0);
7103
7104   return MayFoldLoad(V);
7105 }
7106
7107 static
7108 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7109   MVT VT = Op.getSimpleValueType();
7110
7111   // Canonizalize to v2f64.
7112   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7113   return DAG.getNode(ISD::BITCAST, dl, VT,
7114                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7115                                           V1, DAG));
7116 }
7117
7118 static
7119 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7120                         bool HasSSE2) {
7121   SDValue V1 = Op.getOperand(0);
7122   SDValue V2 = Op.getOperand(1);
7123   MVT VT = Op.getSimpleValueType();
7124
7125   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7126
7127   if (HasSSE2 && VT == MVT::v2f64)
7128     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7129
7130   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7131   return DAG.getNode(ISD::BITCAST, dl, VT,
7132                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7133                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7134                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7135 }
7136
7137 static
7138 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7139   SDValue V1 = Op.getOperand(0);
7140   SDValue V2 = Op.getOperand(1);
7141   MVT VT = Op.getSimpleValueType();
7142
7143   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7144          "unsupported shuffle type");
7145
7146   if (V2.getOpcode() == ISD::UNDEF)
7147     V2 = V1;
7148
7149   // v4i32 or v4f32
7150   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7151 }
7152
7153 static
7154 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7155   SDValue V1 = Op.getOperand(0);
7156   SDValue V2 = Op.getOperand(1);
7157   MVT VT = Op.getSimpleValueType();
7158   unsigned NumElems = VT.getVectorNumElements();
7159
7160   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7161   // operand of these instructions is only memory, so check if there's a
7162   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7163   // same masks.
7164   bool CanFoldLoad = false;
7165
7166   // Trivial case, when V2 comes from a load.
7167   if (MayFoldVectorLoad(V2))
7168     CanFoldLoad = true;
7169
7170   // When V1 is a load, it can be folded later into a store in isel, example:
7171   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7172   //    turns into:
7173   //  (MOVLPSmr addr:$src1, VR128:$src2)
7174   // So, recognize this potential and also use MOVLPS or MOVLPD
7175   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7176     CanFoldLoad = true;
7177
7178   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7179   if (CanFoldLoad) {
7180     if (HasSSE2 && NumElems == 2)
7181       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7182
7183     if (NumElems == 4)
7184       // If we don't care about the second element, proceed to use movss.
7185       if (SVOp->getMaskElt(1) != -1)
7186         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7187   }
7188
7189   // movl and movlp will both match v2i64, but v2i64 is never matched by
7190   // movl earlier because we make it strict to avoid messing with the movlp load
7191   // folding logic (see the code above getMOVLP call). Match it here then,
7192   // this is horrible, but will stay like this until we move all shuffle
7193   // matching to x86 specific nodes. Note that for the 1st condition all
7194   // types are matched with movsd.
7195   if (HasSSE2) {
7196     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7197     // as to remove this logic from here, as much as possible
7198     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7199       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7200     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7201   }
7202
7203   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7204
7205   // Invert the operand order and use SHUFPS to match it.
7206   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7207                               getShuffleSHUFImmediate(SVOp), DAG);
7208 }
7209
7210 // Reduce a vector shuffle to zext.
7211 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7212                                     SelectionDAG &DAG) {
7213   // PMOVZX is only available from SSE41.
7214   if (!Subtarget->hasSSE41())
7215     return SDValue();
7216
7217   MVT VT = Op.getSimpleValueType();
7218
7219   // Only AVX2 support 256-bit vector integer extending.
7220   if (!Subtarget->hasInt256() && VT.is256BitVector())
7221     return SDValue();
7222
7223   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7224   SDLoc DL(Op);
7225   SDValue V1 = Op.getOperand(0);
7226   SDValue V2 = Op.getOperand(1);
7227   unsigned NumElems = VT.getVectorNumElements();
7228
7229   // Extending is an unary operation and the element type of the source vector
7230   // won't be equal to or larger than i64.
7231   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7232       VT.getVectorElementType() == MVT::i64)
7233     return SDValue();
7234
7235   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7236   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7237   while ((1U << Shift) < NumElems) {
7238     if (SVOp->getMaskElt(1U << Shift) == 1)
7239       break;
7240     Shift += 1;
7241     // The maximal ratio is 8, i.e. from i8 to i64.
7242     if (Shift > 3)
7243       return SDValue();
7244   }
7245
7246   // Check the shuffle mask.
7247   unsigned Mask = (1U << Shift) - 1;
7248   for (unsigned i = 0; i != NumElems; ++i) {
7249     int EltIdx = SVOp->getMaskElt(i);
7250     if ((i & Mask) != 0 && EltIdx != -1)
7251       return SDValue();
7252     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7253       return SDValue();
7254   }
7255
7256   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7257   MVT NeVT = MVT::getIntegerVT(NBits);
7258   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7259
7260   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7261     return SDValue();
7262
7263   // Simplify the operand as it's prepared to be fed into shuffle.
7264   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7265   if (V1.getOpcode() == ISD::BITCAST &&
7266       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7267       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7268       V1.getOperand(0).getOperand(0)
7269         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7270     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7271     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7272     ConstantSDNode *CIdx =
7273       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7274     // If it's foldable, i.e. normal load with single use, we will let code
7275     // selection to fold it. Otherwise, we will short the conversion sequence.
7276     if (CIdx && CIdx->getZExtValue() == 0 &&
7277         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7278       MVT FullVT = V.getSimpleValueType();
7279       MVT V1VT = V1.getSimpleValueType();
7280       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7281         // The "ext_vec_elt" node is wider than the result node.
7282         // In this case we should extract subvector from V.
7283         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7284         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7285         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7286                                         FullVT.getVectorNumElements()/Ratio);
7287         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7288                         DAG.getIntPtrConstant(0));
7289       }
7290       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7291     }
7292   }
7293
7294   return DAG.getNode(ISD::BITCAST, DL, VT,
7295                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7296 }
7297
7298 static SDValue
7299 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7300                        SelectionDAG &DAG) {
7301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7302   MVT VT = Op.getSimpleValueType();
7303   SDLoc dl(Op);
7304   SDValue V1 = Op.getOperand(0);
7305   SDValue V2 = Op.getOperand(1);
7306
7307   if (isZeroShuffle(SVOp))
7308     return getZeroVector(VT, Subtarget, DAG, dl);
7309
7310   // Handle splat operations
7311   if (SVOp->isSplat()) {
7312     // Use vbroadcast whenever the splat comes from a foldable load
7313     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7314     if (Broadcast.getNode())
7315       return Broadcast;
7316   }
7317
7318   // Check integer expanding shuffles.
7319   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7320   if (NewOp.getNode())
7321     return NewOp;
7322
7323   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7324   // do it!
7325   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7326       VT == MVT::v16i16 || VT == MVT::v32i8) {
7327     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7328     if (NewOp.getNode())
7329       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7330   } else if ((VT == MVT::v4i32 ||
7331              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7332     // FIXME: Figure out a cleaner way to do this.
7333     // Try to make use of movq to zero out the top part.
7334     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7335       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7336       if (NewOp.getNode()) {
7337         MVT NewVT = NewOp.getSimpleValueType();
7338         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7339                                NewVT, true, false))
7340           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7341                               DAG, Subtarget, dl);
7342       }
7343     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7344       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7345       if (NewOp.getNode()) {
7346         MVT NewVT = NewOp.getSimpleValueType();
7347         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7348           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7349                               DAG, Subtarget, dl);
7350       }
7351     }
7352   }
7353   return SDValue();
7354 }
7355
7356 SDValue
7357 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7358   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7359   SDValue V1 = Op.getOperand(0);
7360   SDValue V2 = Op.getOperand(1);
7361   MVT VT = Op.getSimpleValueType();
7362   SDLoc dl(Op);
7363   unsigned NumElems = VT.getVectorNumElements();
7364   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7365   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7366   bool V1IsSplat = false;
7367   bool V2IsSplat = false;
7368   bool HasSSE2 = Subtarget->hasSSE2();
7369   bool HasFp256    = Subtarget->hasFp256();
7370   bool HasInt256   = Subtarget->hasInt256();
7371   MachineFunction &MF = DAG.getMachineFunction();
7372   bool OptForSize = MF.getFunction()->getAttributes().
7373     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7374
7375   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7376
7377   if (V1IsUndef && V2IsUndef)
7378     return DAG.getUNDEF(VT);
7379
7380   // When we create a shuffle node we put the UNDEF node to second operand,
7381   // but in some cases the first operand may be transformed to UNDEF.
7382   // In this case we should just commute the node.
7383   if (V1IsUndef)
7384     return CommuteVectorShuffle(SVOp, DAG);
7385
7386   // Vector shuffle lowering takes 3 steps:
7387   //
7388   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7389   //    narrowing and commutation of operands should be handled.
7390   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7391   //    shuffle nodes.
7392   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7393   //    so the shuffle can be broken into other shuffles and the legalizer can
7394   //    try the lowering again.
7395   //
7396   // The general idea is that no vector_shuffle operation should be left to
7397   // be matched during isel, all of them must be converted to a target specific
7398   // node here.
7399
7400   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7401   // narrowing and commutation of operands should be handled. The actual code
7402   // doesn't include all of those, work in progress...
7403   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7404   if (NewOp.getNode())
7405     return NewOp;
7406
7407   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7408
7409   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7410   // unpckh_undef). Only use pshufd if speed is more important than size.
7411   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7412     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7413   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7414     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7415
7416   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7417       V2IsUndef && MayFoldVectorLoad(V1))
7418     return getMOVDDup(Op, dl, V1, DAG);
7419
7420   if (isMOVHLPS_v_undef_Mask(M, VT))
7421     return getMOVHighToLow(Op, dl, DAG);
7422
7423   // Use to match splats
7424   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7425       (VT == MVT::v2f64 || VT == MVT::v2i64))
7426     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7427
7428   if (isPSHUFDMask(M, VT)) {
7429     // The actual implementation will match the mask in the if above and then
7430     // during isel it can match several different instructions, not only pshufd
7431     // as its name says, sad but true, emulate the behavior for now...
7432     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7433       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7434
7435     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7436
7437     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7438       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7439
7440     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7441       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7442                                   DAG);
7443
7444     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7445                                 TargetMask, DAG);
7446   }
7447
7448   if (isPALIGNRMask(M, VT, Subtarget))
7449     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7450                                 getShufflePALIGNRImmediate(SVOp),
7451                                 DAG);
7452
7453   // Check if this can be converted into a logical shift.
7454   bool isLeft = false;
7455   unsigned ShAmt = 0;
7456   SDValue ShVal;
7457   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7458   if (isShift && ShVal.hasOneUse()) {
7459     // If the shifted value has multiple uses, it may be cheaper to use
7460     // v_set0 + movlhps or movhlps, etc.
7461     MVT EltVT = VT.getVectorElementType();
7462     ShAmt *= EltVT.getSizeInBits();
7463     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7464   }
7465
7466   if (isMOVLMask(M, VT)) {
7467     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7468       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7469     if (!isMOVLPMask(M, VT)) {
7470       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7471         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7472
7473       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7474         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7475     }
7476   }
7477
7478   // FIXME: fold these into legal mask.
7479   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7480     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7481
7482   if (isMOVHLPSMask(M, VT))
7483     return getMOVHighToLow(Op, dl, DAG);
7484
7485   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7486     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7487
7488   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7489     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7490
7491   if (isMOVLPMask(M, VT))
7492     return getMOVLP(Op, dl, DAG, HasSSE2);
7493
7494   if (ShouldXformToMOVHLPS(M, VT) ||
7495       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7496     return CommuteVectorShuffle(SVOp, DAG);
7497
7498   if (isShift) {
7499     // No better options. Use a vshldq / vsrldq.
7500     MVT EltVT = VT.getVectorElementType();
7501     ShAmt *= EltVT.getSizeInBits();
7502     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7503   }
7504
7505   bool Commuted = false;
7506   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7507   // 1,1,1,1 -> v8i16 though.
7508   V1IsSplat = isSplatVector(V1.getNode());
7509   V2IsSplat = isSplatVector(V2.getNode());
7510
7511   // Canonicalize the splat or undef, if present, to be on the RHS.
7512   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7513     CommuteVectorShuffleMask(M, NumElems);
7514     std::swap(V1, V2);
7515     std::swap(V1IsSplat, V2IsSplat);
7516     Commuted = true;
7517   }
7518
7519   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7520     // Shuffling low element of v1 into undef, just return v1.
7521     if (V2IsUndef)
7522       return V1;
7523     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7524     // the instruction selector will not match, so get a canonical MOVL with
7525     // swapped operands to undo the commute.
7526     return getMOVL(DAG, dl, VT, V2, V1);
7527   }
7528
7529   if (isUNPCKLMask(M, VT, HasInt256))
7530     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7531
7532   if (isUNPCKHMask(M, VT, HasInt256))
7533     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7534
7535   if (V2IsSplat) {
7536     // Normalize mask so all entries that point to V2 points to its first
7537     // element then try to match unpck{h|l} again. If match, return a
7538     // new vector_shuffle with the corrected mask.p
7539     SmallVector<int, 8> NewMask(M.begin(), M.end());
7540     NormalizeMask(NewMask, NumElems);
7541     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7542       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7543     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7544       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7545   }
7546
7547   if (Commuted) {
7548     // Commute is back and try unpck* again.
7549     // FIXME: this seems wrong.
7550     CommuteVectorShuffleMask(M, NumElems);
7551     std::swap(V1, V2);
7552     std::swap(V1IsSplat, V2IsSplat);
7553
7554     if (isUNPCKLMask(M, VT, HasInt256))
7555       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7556
7557     if (isUNPCKHMask(M, VT, HasInt256))
7558       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7559   }
7560
7561   // Normalize the node to match x86 shuffle ops if needed
7562   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7563     return CommuteVectorShuffle(SVOp, DAG);
7564
7565   // The checks below are all present in isShuffleMaskLegal, but they are
7566   // inlined here right now to enable us to directly emit target specific
7567   // nodes, and remove one by one until they don't return Op anymore.
7568
7569   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7570       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7571     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7572       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7573   }
7574
7575   if (isPSHUFHWMask(M, VT, HasInt256))
7576     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7577                                 getShufflePSHUFHWImmediate(SVOp),
7578                                 DAG);
7579
7580   if (isPSHUFLWMask(M, VT, HasInt256))
7581     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7582                                 getShufflePSHUFLWImmediate(SVOp),
7583                                 DAG);
7584
7585   if (isSHUFPMask(M, VT))
7586     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7587                                 getShuffleSHUFImmediate(SVOp), DAG);
7588
7589   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7590     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7591   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7592     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7593
7594   //===--------------------------------------------------------------------===//
7595   // Generate target specific nodes for 128 or 256-bit shuffles only
7596   // supported in the AVX instruction set.
7597   //
7598
7599   // Handle VMOVDDUPY permutations
7600   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7601     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7602
7603   // Handle VPERMILPS/D* permutations
7604   if (isVPERMILPMask(M, VT)) {
7605     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7606       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7607                                   getShuffleSHUFImmediate(SVOp), DAG);
7608     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7609                                 getShuffleSHUFImmediate(SVOp), DAG);
7610   }
7611
7612   // Handle VPERM2F128/VPERM2I128 permutations
7613   if (isVPERM2X128Mask(M, VT, HasFp256))
7614     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7615                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7616
7617   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7618   if (BlendOp.getNode())
7619     return BlendOp;
7620
7621   unsigned Imm8;
7622   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7623     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7624
7625   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7626       VT.is512BitVector()) {
7627     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7628     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7629     SmallVector<SDValue, 16> permclMask;
7630     for (unsigned i = 0; i != NumElems; ++i) {
7631       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7632     }
7633
7634     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7635                                 &permclMask[0], NumElems);
7636     if (V2IsUndef)
7637       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7638       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7639                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7640     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7641                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7642   }
7643
7644   //===--------------------------------------------------------------------===//
7645   // Since no target specific shuffle was selected for this generic one,
7646   // lower it into other known shuffles. FIXME: this isn't true yet, but
7647   // this is the plan.
7648   //
7649
7650   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7651   if (VT == MVT::v8i16) {
7652     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7653     if (NewOp.getNode())
7654       return NewOp;
7655   }
7656
7657   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7658     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7659     if (NewOp.getNode())
7660       return NewOp;
7661   }
7662
7663   if (VT == MVT::v16i8) {
7664     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7665     if (NewOp.getNode())
7666       return NewOp;
7667   }
7668
7669   if (VT == MVT::v32i8) {
7670     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7671     if (NewOp.getNode())
7672       return NewOp;
7673   }
7674
7675   // Handle all 128-bit wide vectors with 4 elements, and match them with
7676   // several different shuffle types.
7677   if (NumElems == 4 && VT.is128BitVector())
7678     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7679
7680   // Handle general 256-bit shuffles
7681   if (VT.is256BitVector())
7682     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7683
7684   return SDValue();
7685 }
7686
7687 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7688   MVT VT = Op.getSimpleValueType();
7689   SDLoc dl(Op);
7690
7691   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7692     return SDValue();
7693
7694   if (VT.getSizeInBits() == 8) {
7695     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7696                                   Op.getOperand(0), Op.getOperand(1));
7697     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7698                                   DAG.getValueType(VT));
7699     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7700   }
7701
7702   if (VT.getSizeInBits() == 16) {
7703     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7704     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7705     if (Idx == 0)
7706       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7707                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7708                                      DAG.getNode(ISD::BITCAST, dl,
7709                                                  MVT::v4i32,
7710                                                  Op.getOperand(0)),
7711                                      Op.getOperand(1)));
7712     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7713                                   Op.getOperand(0), Op.getOperand(1));
7714     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7715                                   DAG.getValueType(VT));
7716     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7717   }
7718
7719   if (VT == MVT::f32) {
7720     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7721     // the result back to FR32 register. It's only worth matching if the
7722     // result has a single use which is a store or a bitcast to i32.  And in
7723     // the case of a store, it's not worth it if the index is a constant 0,
7724     // because a MOVSSmr can be used instead, which is smaller and faster.
7725     if (!Op.hasOneUse())
7726       return SDValue();
7727     SDNode *User = *Op.getNode()->use_begin();
7728     if ((User->getOpcode() != ISD::STORE ||
7729          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7730           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7731         (User->getOpcode() != ISD::BITCAST ||
7732          User->getValueType(0) != MVT::i32))
7733       return SDValue();
7734     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7735                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7736                                               Op.getOperand(0)),
7737                                               Op.getOperand(1));
7738     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7739   }
7740
7741   if (VT == MVT::i32 || VT == MVT::i64) {
7742     // ExtractPS/pextrq works with constant index.
7743     if (isa<ConstantSDNode>(Op.getOperand(1)))
7744       return Op;
7745   }
7746   return SDValue();
7747 }
7748
7749 /// Extract one bit from mask vector, like v16i1 or v8i1.
7750 /// AVX-512 feature.
7751 SDValue
7752 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7753   SDValue Vec = Op.getOperand(0);
7754   SDLoc dl(Vec);
7755   MVT VecVT = Vec.getSimpleValueType();
7756   SDValue Idx = Op.getOperand(1);
7757   MVT EltVT = Op.getSimpleValueType();
7758
7759   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7760
7761   // variable index can't be handled in mask registers,
7762   // extend vector to VR512
7763   if (!isa<ConstantSDNode>(Idx)) {
7764     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7765     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7766     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7767                               ExtVT.getVectorElementType(), Ext, Idx);
7768     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7769   }
7770
7771   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7772   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7773   unsigned MaxSift = rc->getSize()*8 - 1;
7774   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7775                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7776   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7777                     DAG.getConstant(MaxSift, MVT::i8));
7778   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7779                        DAG.getIntPtrConstant(0));
7780 }
7781
7782 SDValue
7783 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7784                                            SelectionDAG &DAG) const {
7785   SDLoc dl(Op);
7786   SDValue Vec = Op.getOperand(0);
7787   MVT VecVT = Vec.getSimpleValueType();
7788   SDValue Idx = Op.getOperand(1);
7789
7790   if (Op.getSimpleValueType() == MVT::i1)
7791     return ExtractBitFromMaskVector(Op, DAG);
7792
7793   if (!isa<ConstantSDNode>(Idx)) {
7794     if (VecVT.is512BitVector() ||
7795         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7796          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7797
7798       MVT MaskEltVT =
7799         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7800       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7801                                     MaskEltVT.getSizeInBits());
7802
7803       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7804       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7805                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7806                                 Idx, DAG.getConstant(0, getPointerTy()));
7807       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7808       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7809                         Perm, DAG.getConstant(0, getPointerTy()));
7810     }
7811     return SDValue();
7812   }
7813
7814   // If this is a 256-bit vector result, first extract the 128-bit vector and
7815   // then extract the element from the 128-bit vector.
7816   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7817
7818     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7819     // Get the 128-bit vector.
7820     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7821     MVT EltVT = VecVT.getVectorElementType();
7822
7823     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7824
7825     //if (IdxVal >= NumElems/2)
7826     //  IdxVal -= NumElems/2;
7827     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7829                        DAG.getConstant(IdxVal, MVT::i32));
7830   }
7831
7832   assert(VecVT.is128BitVector() && "Unexpected vector length");
7833
7834   if (Subtarget->hasSSE41()) {
7835     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7836     if (Res.getNode())
7837       return Res;
7838   }
7839
7840   MVT VT = Op.getSimpleValueType();
7841   // TODO: handle v16i8.
7842   if (VT.getSizeInBits() == 16) {
7843     SDValue Vec = Op.getOperand(0);
7844     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7845     if (Idx == 0)
7846       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7847                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7848                                      DAG.getNode(ISD::BITCAST, dl,
7849                                                  MVT::v4i32, Vec),
7850                                      Op.getOperand(1)));
7851     // Transform it so it match pextrw which produces a 32-bit result.
7852     MVT EltVT = MVT::i32;
7853     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7854                                   Op.getOperand(0), Op.getOperand(1));
7855     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7856                                   DAG.getValueType(VT));
7857     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7858   }
7859
7860   if (VT.getSizeInBits() == 32) {
7861     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7862     if (Idx == 0)
7863       return Op;
7864
7865     // SHUFPS the element to the lowest double word, then movss.
7866     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7867     MVT VVT = Op.getOperand(0).getSimpleValueType();
7868     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7869                                        DAG.getUNDEF(VVT), Mask);
7870     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7871                        DAG.getIntPtrConstant(0));
7872   }
7873
7874   if (VT.getSizeInBits() == 64) {
7875     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7876     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7877     //        to match extract_elt for f64.
7878     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7879     if (Idx == 0)
7880       return Op;
7881
7882     // UNPCKHPD the element to the lowest double word, then movsd.
7883     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7884     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7885     int Mask[2] = { 1, -1 };
7886     MVT VVT = Op.getOperand(0).getSimpleValueType();
7887     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7888                                        DAG.getUNDEF(VVT), Mask);
7889     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7890                        DAG.getIntPtrConstant(0));
7891   }
7892
7893   return SDValue();
7894 }
7895
7896 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7897   MVT VT = Op.getSimpleValueType();
7898   MVT EltVT = VT.getVectorElementType();
7899   SDLoc dl(Op);
7900
7901   SDValue N0 = Op.getOperand(0);
7902   SDValue N1 = Op.getOperand(1);
7903   SDValue N2 = Op.getOperand(2);
7904
7905   if (!VT.is128BitVector())
7906     return SDValue();
7907
7908   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7909       isa<ConstantSDNode>(N2)) {
7910     unsigned Opc;
7911     if (VT == MVT::v8i16)
7912       Opc = X86ISD::PINSRW;
7913     else if (VT == MVT::v16i8)
7914       Opc = X86ISD::PINSRB;
7915     else
7916       Opc = X86ISD::PINSRB;
7917
7918     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7919     // argument.
7920     if (N1.getValueType() != MVT::i32)
7921       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7922     if (N2.getValueType() != MVT::i32)
7923       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7924     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7925   }
7926
7927   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7928     // Bits [7:6] of the constant are the source select.  This will always be
7929     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7930     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7931     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7932     // Bits [5:4] of the constant are the destination select.  This is the
7933     //  value of the incoming immediate.
7934     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7935     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7936     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7937     // Create this as a scalar to vector..
7938     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7939     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7940   }
7941
7942   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7943     // PINSR* works with constant index.
7944     return Op;
7945   }
7946   return SDValue();
7947 }
7948
7949 SDValue
7950 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7951   MVT VT = Op.getSimpleValueType();
7952   MVT EltVT = VT.getVectorElementType();
7953
7954   SDLoc dl(Op);
7955   SDValue N0 = Op.getOperand(0);
7956   SDValue N1 = Op.getOperand(1);
7957   SDValue N2 = Op.getOperand(2);
7958
7959   // If this is a 256-bit vector result, first extract the 128-bit vector,
7960   // insert the element into the extracted half and then place it back.
7961   if (VT.is256BitVector() || VT.is512BitVector()) {
7962     if (!isa<ConstantSDNode>(N2))
7963       return SDValue();
7964
7965     // Get the desired 128-bit vector half.
7966     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7967     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7968
7969     // Insert the element into the desired half.
7970     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7971     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7972
7973     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7974                     DAG.getConstant(IdxIn128, MVT::i32));
7975
7976     // Insert the changed part back to the 256-bit vector
7977     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7978   }
7979
7980   if (Subtarget->hasSSE41())
7981     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7982
7983   if (EltVT == MVT::i8)
7984     return SDValue();
7985
7986   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7987     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7988     // as its second argument.
7989     if (N1.getValueType() != MVT::i32)
7990       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7991     if (N2.getValueType() != MVT::i32)
7992       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7993     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7994   }
7995   return SDValue();
7996 }
7997
7998 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7999   SDLoc dl(Op);
8000   MVT OpVT = Op.getSimpleValueType();
8001
8002   // If this is a 256-bit vector result, first insert into a 128-bit
8003   // vector and then insert into the 256-bit vector.
8004   if (!OpVT.is128BitVector()) {
8005     // Insert into a 128-bit vector.
8006     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8007     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8008                                  OpVT.getVectorNumElements() / SizeFactor);
8009
8010     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8011
8012     // Insert the 128-bit vector.
8013     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8014   }
8015
8016   if (OpVT == MVT::v1i64 &&
8017       Op.getOperand(0).getValueType() == MVT::i64)
8018     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8019
8020   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8021   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8022   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8023                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8024 }
8025
8026 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8027 // a simple subregister reference or explicit instructions to grab
8028 // upper bits of a vector.
8029 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8030                                       SelectionDAG &DAG) {
8031   SDLoc dl(Op);
8032   SDValue In =  Op.getOperand(0);
8033   SDValue Idx = Op.getOperand(1);
8034   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8035   MVT ResVT   = Op.getSimpleValueType();
8036   MVT InVT    = In.getSimpleValueType();
8037
8038   if (Subtarget->hasFp256()) {
8039     if (ResVT.is128BitVector() &&
8040         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8041         isa<ConstantSDNode>(Idx)) {
8042       return Extract128BitVector(In, IdxVal, DAG, dl);
8043     }
8044     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8045         isa<ConstantSDNode>(Idx)) {
8046       return Extract256BitVector(In, IdxVal, DAG, dl);
8047     }
8048   }
8049   return SDValue();
8050 }
8051
8052 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8053 // simple superregister reference or explicit instructions to insert
8054 // the upper bits of a vector.
8055 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8056                                      SelectionDAG &DAG) {
8057   if (Subtarget->hasFp256()) {
8058     SDLoc dl(Op.getNode());
8059     SDValue Vec = Op.getNode()->getOperand(0);
8060     SDValue SubVec = Op.getNode()->getOperand(1);
8061     SDValue Idx = Op.getNode()->getOperand(2);
8062
8063     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8064          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8065         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8066         isa<ConstantSDNode>(Idx)) {
8067       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8068       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8069     }
8070
8071     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8072         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8073         isa<ConstantSDNode>(Idx)) {
8074       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8075       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8076     }
8077   }
8078   return SDValue();
8079 }
8080
8081 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8082 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8083 // one of the above mentioned nodes. It has to be wrapped because otherwise
8084 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8085 // be used to form addressing mode. These wrapped nodes will be selected
8086 // into MOV32ri.
8087 SDValue
8088 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8089   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8090
8091   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8092   // global base reg.
8093   unsigned char OpFlag = 0;
8094   unsigned WrapperKind = X86ISD::Wrapper;
8095   CodeModel::Model M = getTargetMachine().getCodeModel();
8096
8097   if (Subtarget->isPICStyleRIPRel() &&
8098       (M == CodeModel::Small || M == CodeModel::Kernel))
8099     WrapperKind = X86ISD::WrapperRIP;
8100   else if (Subtarget->isPICStyleGOT())
8101     OpFlag = X86II::MO_GOTOFF;
8102   else if (Subtarget->isPICStyleStubPIC())
8103     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8104
8105   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8106                                              CP->getAlignment(),
8107                                              CP->getOffset(), OpFlag);
8108   SDLoc DL(CP);
8109   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8110   // With PIC, the address is actually $g + Offset.
8111   if (OpFlag) {
8112     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8113                          DAG.getNode(X86ISD::GlobalBaseReg,
8114                                      SDLoc(), getPointerTy()),
8115                          Result);
8116   }
8117
8118   return Result;
8119 }
8120
8121 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8122   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8123
8124   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8125   // global base reg.
8126   unsigned char OpFlag = 0;
8127   unsigned WrapperKind = X86ISD::Wrapper;
8128   CodeModel::Model M = getTargetMachine().getCodeModel();
8129
8130   if (Subtarget->isPICStyleRIPRel() &&
8131       (M == CodeModel::Small || M == CodeModel::Kernel))
8132     WrapperKind = X86ISD::WrapperRIP;
8133   else if (Subtarget->isPICStyleGOT())
8134     OpFlag = X86II::MO_GOTOFF;
8135   else if (Subtarget->isPICStyleStubPIC())
8136     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8137
8138   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8139                                           OpFlag);
8140   SDLoc DL(JT);
8141   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8142
8143   // With PIC, the address is actually $g + Offset.
8144   if (OpFlag)
8145     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8146                          DAG.getNode(X86ISD::GlobalBaseReg,
8147                                      SDLoc(), getPointerTy()),
8148                          Result);
8149
8150   return Result;
8151 }
8152
8153 SDValue
8154 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8155   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8156
8157   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8158   // global base reg.
8159   unsigned char OpFlag = 0;
8160   unsigned WrapperKind = X86ISD::Wrapper;
8161   CodeModel::Model M = getTargetMachine().getCodeModel();
8162
8163   if (Subtarget->isPICStyleRIPRel() &&
8164       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8165     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8166       OpFlag = X86II::MO_GOTPCREL;
8167     WrapperKind = X86ISD::WrapperRIP;
8168   } else if (Subtarget->isPICStyleGOT()) {
8169     OpFlag = X86II::MO_GOT;
8170   } else if (Subtarget->isPICStyleStubPIC()) {
8171     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8172   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8173     OpFlag = X86II::MO_DARWIN_NONLAZY;
8174   }
8175
8176   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8177
8178   SDLoc DL(Op);
8179   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8180
8181   // With PIC, the address is actually $g + Offset.
8182   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8183       !Subtarget->is64Bit()) {
8184     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8185                          DAG.getNode(X86ISD::GlobalBaseReg,
8186                                      SDLoc(), getPointerTy()),
8187                          Result);
8188   }
8189
8190   // For symbols that require a load from a stub to get the address, emit the
8191   // load.
8192   if (isGlobalStubReference(OpFlag))
8193     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8194                          MachinePointerInfo::getGOT(), false, false, false, 0);
8195
8196   return Result;
8197 }
8198
8199 SDValue
8200 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8201   // Create the TargetBlockAddressAddress node.
8202   unsigned char OpFlags =
8203     Subtarget->ClassifyBlockAddressReference();
8204   CodeModel::Model M = getTargetMachine().getCodeModel();
8205   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8206   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8207   SDLoc dl(Op);
8208   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8209                                              OpFlags);
8210
8211   if (Subtarget->isPICStyleRIPRel() &&
8212       (M == CodeModel::Small || M == CodeModel::Kernel))
8213     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8214   else
8215     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8216
8217   // With PIC, the address is actually $g + Offset.
8218   if (isGlobalRelativeToPICBase(OpFlags)) {
8219     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8220                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8221                          Result);
8222   }
8223
8224   return Result;
8225 }
8226
8227 SDValue
8228 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8229                                       int64_t Offset, SelectionDAG &DAG) const {
8230   // Create the TargetGlobalAddress node, folding in the constant
8231   // offset if it is legal.
8232   unsigned char OpFlags =
8233     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8234   CodeModel::Model M = getTargetMachine().getCodeModel();
8235   SDValue Result;
8236   if (OpFlags == X86II::MO_NO_FLAG &&
8237       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8238     // A direct static reference to a global.
8239     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8240     Offset = 0;
8241   } else {
8242     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8243   }
8244
8245   if (Subtarget->isPICStyleRIPRel() &&
8246       (M == CodeModel::Small || M == CodeModel::Kernel))
8247     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8248   else
8249     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8250
8251   // With PIC, the address is actually $g + Offset.
8252   if (isGlobalRelativeToPICBase(OpFlags)) {
8253     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8254                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8255                          Result);
8256   }
8257
8258   // For globals that require a load from a stub to get the address, emit the
8259   // load.
8260   if (isGlobalStubReference(OpFlags))
8261     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8262                          MachinePointerInfo::getGOT(), false, false, false, 0);
8263
8264   // If there was a non-zero offset that we didn't fold, create an explicit
8265   // addition for it.
8266   if (Offset != 0)
8267     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8268                          DAG.getConstant(Offset, getPointerTy()));
8269
8270   return Result;
8271 }
8272
8273 SDValue
8274 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8275   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8276   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8277   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8278 }
8279
8280 static SDValue
8281 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8282            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8283            unsigned char OperandFlags, bool LocalDynamic = false) {
8284   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8285   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8286   SDLoc dl(GA);
8287   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8288                                            GA->getValueType(0),
8289                                            GA->getOffset(),
8290                                            OperandFlags);
8291
8292   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8293                                            : X86ISD::TLSADDR;
8294
8295   if (InFlag) {
8296     SDValue Ops[] = { Chain,  TGA, *InFlag };
8297     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8298   } else {
8299     SDValue Ops[]  = { Chain, TGA };
8300     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8301   }
8302
8303   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8304   MFI->setAdjustsStack(true);
8305
8306   SDValue Flag = Chain.getValue(1);
8307   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8308 }
8309
8310 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8311 static SDValue
8312 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8313                                 const EVT PtrVT) {
8314   SDValue InFlag;
8315   SDLoc dl(GA);  // ? function entry point might be better
8316   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8317                                    DAG.getNode(X86ISD::GlobalBaseReg,
8318                                                SDLoc(), PtrVT), InFlag);
8319   InFlag = Chain.getValue(1);
8320
8321   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8322 }
8323
8324 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8325 static SDValue
8326 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8327                                 const EVT PtrVT) {
8328   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8329                     X86::RAX, X86II::MO_TLSGD);
8330 }
8331
8332 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8333                                            SelectionDAG &DAG,
8334                                            const EVT PtrVT,
8335                                            bool is64Bit) {
8336   SDLoc dl(GA);
8337
8338   // Get the start address of the TLS block for this module.
8339   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8340       .getInfo<X86MachineFunctionInfo>();
8341   MFI->incNumLocalDynamicTLSAccesses();
8342
8343   SDValue Base;
8344   if (is64Bit) {
8345     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8346                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8347   } else {
8348     SDValue InFlag;
8349     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8350         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8351     InFlag = Chain.getValue(1);
8352     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8353                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8354   }
8355
8356   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8357   // of Base.
8358
8359   // Build x@dtpoff.
8360   unsigned char OperandFlags = X86II::MO_DTPOFF;
8361   unsigned WrapperKind = X86ISD::Wrapper;
8362   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8363                                            GA->getValueType(0),
8364                                            GA->getOffset(), OperandFlags);
8365   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8366
8367   // Add x@dtpoff with the base.
8368   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8369 }
8370
8371 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8372 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8373                                    const EVT PtrVT, TLSModel::Model model,
8374                                    bool is64Bit, bool isPIC) {
8375   SDLoc dl(GA);
8376
8377   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8378   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8379                                                          is64Bit ? 257 : 256));
8380
8381   SDValue ThreadPointer =
8382       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8383                   MachinePointerInfo(Ptr), false, false, false, 0);
8384
8385   unsigned char OperandFlags = 0;
8386   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8387   // initialexec.
8388   unsigned WrapperKind = X86ISD::Wrapper;
8389   if (model == TLSModel::LocalExec) {
8390     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8391   } else if (model == TLSModel::InitialExec) {
8392     if (is64Bit) {
8393       OperandFlags = X86II::MO_GOTTPOFF;
8394       WrapperKind = X86ISD::WrapperRIP;
8395     } else {
8396       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8397     }
8398   } else {
8399     llvm_unreachable("Unexpected model");
8400   }
8401
8402   // emit "addl x@ntpoff,%eax" (local exec)
8403   // or "addl x@indntpoff,%eax" (initial exec)
8404   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8405   SDValue TGA =
8406       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8407                                  GA->getOffset(), OperandFlags);
8408   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8409
8410   if (model == TLSModel::InitialExec) {
8411     if (isPIC && !is64Bit) {
8412       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8413                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8414                            Offset);
8415     }
8416
8417     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8418                          MachinePointerInfo::getGOT(), false, false, false, 0);
8419   }
8420
8421   // The address of the thread local variable is the add of the thread
8422   // pointer with the offset of the variable.
8423   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8424 }
8425
8426 SDValue
8427 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8428
8429   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8430   const GlobalValue *GV = GA->getGlobal();
8431
8432   if (Subtarget->isTargetELF()) {
8433     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8434
8435     switch (model) {
8436       case TLSModel::GeneralDynamic:
8437         if (Subtarget->is64Bit())
8438           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8439         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8440       case TLSModel::LocalDynamic:
8441         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8442                                            Subtarget->is64Bit());
8443       case TLSModel::InitialExec:
8444       case TLSModel::LocalExec:
8445         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8446                                    Subtarget->is64Bit(),
8447                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8448     }
8449     llvm_unreachable("Unknown TLS model.");
8450   }
8451
8452   if (Subtarget->isTargetDarwin()) {
8453     // Darwin only has one model of TLS.  Lower to that.
8454     unsigned char OpFlag = 0;
8455     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8456                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8457
8458     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8459     // global base reg.
8460     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8461                   !Subtarget->is64Bit();
8462     if (PIC32)
8463       OpFlag = X86II::MO_TLVP_PIC_BASE;
8464     else
8465       OpFlag = X86II::MO_TLVP;
8466     SDLoc DL(Op);
8467     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8468                                                 GA->getValueType(0),
8469                                                 GA->getOffset(), OpFlag);
8470     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8471
8472     // With PIC32, the address is actually $g + Offset.
8473     if (PIC32)
8474       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8475                            DAG.getNode(X86ISD::GlobalBaseReg,
8476                                        SDLoc(), getPointerTy()),
8477                            Offset);
8478
8479     // Lowering the machine isd will make sure everything is in the right
8480     // location.
8481     SDValue Chain = DAG.getEntryNode();
8482     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8483     SDValue Args[] = { Chain, Offset };
8484     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8485
8486     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8487     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8488     MFI->setAdjustsStack(true);
8489
8490     // And our return value (tls address) is in the standard call return value
8491     // location.
8492     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8493     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8494                               Chain.getValue(1));
8495   }
8496
8497   if (Subtarget->isTargetKnownWindowsMSVC() ||
8498       Subtarget->isTargetWindowsGNU()) {
8499     // Just use the implicit TLS architecture
8500     // Need to generate someting similar to:
8501     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8502     //                                  ; from TEB
8503     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8504     //   mov     rcx, qword [rdx+rcx*8]
8505     //   mov     eax, .tls$:tlsvar
8506     //   [rax+rcx] contains the address
8507     // Windows 64bit: gs:0x58
8508     // Windows 32bit: fs:__tls_array
8509
8510     // If GV is an alias then use the aliasee for determining
8511     // thread-localness.
8512     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8513       GV = GA->getAliasedGlobal();
8514     SDLoc dl(GA);
8515     SDValue Chain = DAG.getEntryNode();
8516
8517     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8518     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8519     // use its literal value of 0x2C.
8520     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8521                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8522                                                              256)
8523                                         : Type::getInt32PtrTy(*DAG.getContext(),
8524                                                               257));
8525
8526     SDValue TlsArray =
8527         Subtarget->is64Bit()
8528             ? DAG.getIntPtrConstant(0x58)
8529             : (Subtarget->isTargetWindowsGNU()
8530                    ? DAG.getIntPtrConstant(0x2C)
8531                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8532
8533     SDValue ThreadPointer =
8534         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8535                     MachinePointerInfo(Ptr), false, false, false, 0);
8536
8537     // Load the _tls_index variable
8538     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8539     if (Subtarget->is64Bit())
8540       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8541                            IDX, MachinePointerInfo(), MVT::i32,
8542                            false, false, 0);
8543     else
8544       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8545                         false, false, false, 0);
8546
8547     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8548                                     getPointerTy());
8549     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8550
8551     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8552     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8553                       false, false, false, 0);
8554
8555     // Get the offset of start of .tls section
8556     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8557                                              GA->getValueType(0),
8558                                              GA->getOffset(), X86II::MO_SECREL);
8559     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8560
8561     // The address of the thread local variable is the add of the thread
8562     // pointer with the offset of the variable.
8563     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8564   }
8565
8566   llvm_unreachable("TLS not implemented for this target.");
8567 }
8568
8569 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8570 /// and take a 2 x i32 value to shift plus a shift amount.
8571 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8572   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8573   MVT VT = Op.getSimpleValueType();
8574   unsigned VTBits = VT.getSizeInBits();
8575   SDLoc dl(Op);
8576   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8577   SDValue ShOpLo = Op.getOperand(0);
8578   SDValue ShOpHi = Op.getOperand(1);
8579   SDValue ShAmt  = Op.getOperand(2);
8580   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8581   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8582   // during isel.
8583   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8584                                   DAG.getConstant(VTBits - 1, MVT::i8));
8585   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8586                                      DAG.getConstant(VTBits - 1, MVT::i8))
8587                        : DAG.getConstant(0, VT);
8588
8589   SDValue Tmp2, Tmp3;
8590   if (Op.getOpcode() == ISD::SHL_PARTS) {
8591     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8592     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8593   } else {
8594     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8595     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8596   }
8597
8598   // If the shift amount is larger or equal than the width of a part we can't
8599   // rely on the results of shld/shrd. Insert a test and select the appropriate
8600   // values for large shift amounts.
8601   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8602                                 DAG.getConstant(VTBits, MVT::i8));
8603   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8604                              AndNode, DAG.getConstant(0, MVT::i8));
8605
8606   SDValue Hi, Lo;
8607   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8608   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8609   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8610
8611   if (Op.getOpcode() == ISD::SHL_PARTS) {
8612     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8613     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8614   } else {
8615     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8616     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8617   }
8618
8619   SDValue Ops[2] = { Lo, Hi };
8620   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8621 }
8622
8623 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8624                                            SelectionDAG &DAG) const {
8625   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8626
8627   if (SrcVT.isVector())
8628     return SDValue();
8629
8630   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8631          "Unknown SINT_TO_FP to lower!");
8632
8633   // These are really Legal; return the operand so the caller accepts it as
8634   // Legal.
8635   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8636     return Op;
8637   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8638       Subtarget->is64Bit()) {
8639     return Op;
8640   }
8641
8642   SDLoc dl(Op);
8643   unsigned Size = SrcVT.getSizeInBits()/8;
8644   MachineFunction &MF = DAG.getMachineFunction();
8645   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8646   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8647   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8648                                StackSlot,
8649                                MachinePointerInfo::getFixedStack(SSFI),
8650                                false, false, 0);
8651   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8652 }
8653
8654 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8655                                      SDValue StackSlot,
8656                                      SelectionDAG &DAG) const {
8657   // Build the FILD
8658   SDLoc DL(Op);
8659   SDVTList Tys;
8660   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8661   if (useSSE)
8662     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8663   else
8664     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8665
8666   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8667
8668   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8669   MachineMemOperand *MMO;
8670   if (FI) {
8671     int SSFI = FI->getIndex();
8672     MMO =
8673       DAG.getMachineFunction()
8674       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8675                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8676   } else {
8677     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8678     StackSlot = StackSlot.getOperand(1);
8679   }
8680   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8681   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8682                                            X86ISD::FILD, DL,
8683                                            Tys, Ops, array_lengthof(Ops),
8684                                            SrcVT, MMO);
8685
8686   if (useSSE) {
8687     Chain = Result.getValue(1);
8688     SDValue InFlag = Result.getValue(2);
8689
8690     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8691     // shouldn't be necessary except that RFP cannot be live across
8692     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8693     MachineFunction &MF = DAG.getMachineFunction();
8694     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8695     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8696     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8697     Tys = DAG.getVTList(MVT::Other);
8698     SDValue Ops[] = {
8699       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8700     };
8701     MachineMemOperand *MMO =
8702       DAG.getMachineFunction()
8703       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8704                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8705
8706     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8707                                     Ops, array_lengthof(Ops),
8708                                     Op.getValueType(), MMO);
8709     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8710                          MachinePointerInfo::getFixedStack(SSFI),
8711                          false, false, false, 0);
8712   }
8713
8714   return Result;
8715 }
8716
8717 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8718 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8719                                                SelectionDAG &DAG) const {
8720   // This algorithm is not obvious. Here it is what we're trying to output:
8721   /*
8722      movq       %rax,  %xmm0
8723      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8724      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8725      #ifdef __SSE3__
8726        haddpd   %xmm0, %xmm0
8727      #else
8728        pshufd   $0x4e, %xmm0, %xmm1
8729        addpd    %xmm1, %xmm0
8730      #endif
8731   */
8732
8733   SDLoc dl(Op);
8734   LLVMContext *Context = DAG.getContext();
8735
8736   // Build some magic constants.
8737   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8738   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8739   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8740
8741   SmallVector<Constant*,2> CV1;
8742   CV1.push_back(
8743     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8744                                       APInt(64, 0x4330000000000000ULL))));
8745   CV1.push_back(
8746     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8747                                       APInt(64, 0x4530000000000000ULL))));
8748   Constant *C1 = ConstantVector::get(CV1);
8749   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8750
8751   // Load the 64-bit value into an XMM register.
8752   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8753                             Op.getOperand(0));
8754   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8755                               MachinePointerInfo::getConstantPool(),
8756                               false, false, false, 16);
8757   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8758                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8759                               CLod0);
8760
8761   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8762                               MachinePointerInfo::getConstantPool(),
8763                               false, false, false, 16);
8764   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8765   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8766   SDValue Result;
8767
8768   if (Subtarget->hasSSE3()) {
8769     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8770     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8771   } else {
8772     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8773     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8774                                            S2F, 0x4E, DAG);
8775     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8776                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8777                          Sub);
8778   }
8779
8780   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8781                      DAG.getIntPtrConstant(0));
8782 }
8783
8784 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8785 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8786                                                SelectionDAG &DAG) const {
8787   SDLoc dl(Op);
8788   // FP constant to bias correct the final result.
8789   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8790                                    MVT::f64);
8791
8792   // Load the 32-bit value into an XMM register.
8793   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8794                              Op.getOperand(0));
8795
8796   // Zero out the upper parts of the register.
8797   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8798
8799   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8800                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8801                      DAG.getIntPtrConstant(0));
8802
8803   // Or the load with the bias.
8804   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8805                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8806                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8807                                                    MVT::v2f64, Load)),
8808                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8809                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8810                                                    MVT::v2f64, Bias)));
8811   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8812                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8813                    DAG.getIntPtrConstant(0));
8814
8815   // Subtract the bias.
8816   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8817
8818   // Handle final rounding.
8819   EVT DestVT = Op.getValueType();
8820
8821   if (DestVT.bitsLT(MVT::f64))
8822     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8823                        DAG.getIntPtrConstant(0));
8824   if (DestVT.bitsGT(MVT::f64))
8825     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8826
8827   // Handle final rounding.
8828   return Sub;
8829 }
8830
8831 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8832                                                SelectionDAG &DAG) const {
8833   SDValue N0 = Op.getOperand(0);
8834   MVT SVT = N0.getSimpleValueType();
8835   SDLoc dl(Op);
8836
8837   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8838           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8839          "Custom UINT_TO_FP is not supported!");
8840
8841   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8842   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8843                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8844 }
8845
8846 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8847                                            SelectionDAG &DAG) const {
8848   SDValue N0 = Op.getOperand(0);
8849   SDLoc dl(Op);
8850
8851   if (Op.getValueType().isVector())
8852     return lowerUINT_TO_FP_vec(Op, DAG);
8853
8854   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8855   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8856   // the optimization here.
8857   if (DAG.SignBitIsZero(N0))
8858     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8859
8860   MVT SrcVT = N0.getSimpleValueType();
8861   MVT DstVT = Op.getSimpleValueType();
8862   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8863     return LowerUINT_TO_FP_i64(Op, DAG);
8864   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8865     return LowerUINT_TO_FP_i32(Op, DAG);
8866   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8867     return SDValue();
8868
8869   // Make a 64-bit buffer, and use it to build an FILD.
8870   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8871   if (SrcVT == MVT::i32) {
8872     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8873     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8874                                      getPointerTy(), StackSlot, WordOff);
8875     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8876                                   StackSlot, MachinePointerInfo(),
8877                                   false, false, 0);
8878     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8879                                   OffsetSlot, MachinePointerInfo(),
8880                                   false, false, 0);
8881     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8882     return Fild;
8883   }
8884
8885   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8886   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8887                                StackSlot, MachinePointerInfo(),
8888                                false, false, 0);
8889   // For i64 source, we need to add the appropriate power of 2 if the input
8890   // was negative.  This is the same as the optimization in
8891   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8892   // we must be careful to do the computation in x87 extended precision, not
8893   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8894   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8895   MachineMemOperand *MMO =
8896     DAG.getMachineFunction()
8897     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8898                           MachineMemOperand::MOLoad, 8, 8);
8899
8900   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8901   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8902   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8903                                          array_lengthof(Ops), MVT::i64, MMO);
8904
8905   APInt FF(32, 0x5F800000ULL);
8906
8907   // Check whether the sign bit is set.
8908   SDValue SignSet = DAG.getSetCC(dl,
8909                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8910                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8911                                  ISD::SETLT);
8912
8913   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8914   SDValue FudgePtr = DAG.getConstantPool(
8915                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8916                                          getPointerTy());
8917
8918   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8919   SDValue Zero = DAG.getIntPtrConstant(0);
8920   SDValue Four = DAG.getIntPtrConstant(4);
8921   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8922                                Zero, Four);
8923   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8924
8925   // Load the value out, extending it from f32 to f80.
8926   // FIXME: Avoid the extend by constructing the right constant pool?
8927   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8928                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8929                                  MVT::f32, false, false, 4);
8930   // Extend everything to 80 bits to force it to be done on x87.
8931   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8932   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8933 }
8934
8935 std::pair<SDValue,SDValue>
8936 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8937                                     bool IsSigned, bool IsReplace) const {
8938   SDLoc DL(Op);
8939
8940   EVT DstTy = Op.getValueType();
8941
8942   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8943     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8944     DstTy = MVT::i64;
8945   }
8946
8947   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8948          DstTy.getSimpleVT() >= MVT::i16 &&
8949          "Unknown FP_TO_INT to lower!");
8950
8951   // These are really Legal.
8952   if (DstTy == MVT::i32 &&
8953       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8954     return std::make_pair(SDValue(), SDValue());
8955   if (Subtarget->is64Bit() &&
8956       DstTy == MVT::i64 &&
8957       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8958     return std::make_pair(SDValue(), SDValue());
8959
8960   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8961   // stack slot, or into the FTOL runtime function.
8962   MachineFunction &MF = DAG.getMachineFunction();
8963   unsigned MemSize = DstTy.getSizeInBits()/8;
8964   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8965   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8966
8967   unsigned Opc;
8968   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8969     Opc = X86ISD::WIN_FTOL;
8970   else
8971     switch (DstTy.getSimpleVT().SimpleTy) {
8972     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8973     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8974     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8975     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8976     }
8977
8978   SDValue Chain = DAG.getEntryNode();
8979   SDValue Value = Op.getOperand(0);
8980   EVT TheVT = Op.getOperand(0).getValueType();
8981   // FIXME This causes a redundant load/store if the SSE-class value is already
8982   // in memory, such as if it is on the callstack.
8983   if (isScalarFPTypeInSSEReg(TheVT)) {
8984     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8985     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8986                          MachinePointerInfo::getFixedStack(SSFI),
8987                          false, false, 0);
8988     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8989     SDValue Ops[] = {
8990       Chain, StackSlot, DAG.getValueType(TheVT)
8991     };
8992
8993     MachineMemOperand *MMO =
8994       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8995                               MachineMemOperand::MOLoad, MemSize, MemSize);
8996     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8997                                     array_lengthof(Ops), DstTy, MMO);
8998     Chain = Value.getValue(1);
8999     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9000     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9001   }
9002
9003   MachineMemOperand *MMO =
9004     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9005                             MachineMemOperand::MOStore, MemSize, MemSize);
9006
9007   if (Opc != X86ISD::WIN_FTOL) {
9008     // Build the FP_TO_INT*_IN_MEM
9009     SDValue Ops[] = { Chain, Value, StackSlot };
9010     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9011                                            Ops, array_lengthof(Ops), DstTy,
9012                                            MMO);
9013     return std::make_pair(FIST, StackSlot);
9014   } else {
9015     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9016       DAG.getVTList(MVT::Other, MVT::Glue),
9017       Chain, Value);
9018     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9019       MVT::i32, ftol.getValue(1));
9020     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9021       MVT::i32, eax.getValue(2));
9022     SDValue Ops[] = { eax, edx };
9023     SDValue pair = IsReplace
9024       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9025       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9026     return std::make_pair(pair, SDValue());
9027   }
9028 }
9029
9030 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9031                               const X86Subtarget *Subtarget) {
9032   MVT VT = Op->getSimpleValueType(0);
9033   SDValue In = Op->getOperand(0);
9034   MVT InVT = In.getSimpleValueType();
9035   SDLoc dl(Op);
9036
9037   // Optimize vectors in AVX mode:
9038   //
9039   //   v8i16 -> v8i32
9040   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9041   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9042   //   Concat upper and lower parts.
9043   //
9044   //   v4i32 -> v4i64
9045   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9046   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9047   //   Concat upper and lower parts.
9048   //
9049
9050   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9051       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9052       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9053     return SDValue();
9054
9055   if (Subtarget->hasInt256())
9056     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9057
9058   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9059   SDValue Undef = DAG.getUNDEF(InVT);
9060   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9061   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9062   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9063
9064   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9065                              VT.getVectorNumElements()/2);
9066
9067   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9068   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9069
9070   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9071 }
9072
9073 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9074                                         SelectionDAG &DAG) {
9075   MVT VT = Op->getSimpleValueType(0);
9076   SDValue In = Op->getOperand(0);
9077   MVT InVT = In.getSimpleValueType();
9078   SDLoc DL(Op);
9079   unsigned int NumElts = VT.getVectorNumElements();
9080   if (NumElts != 8 && NumElts != 16)
9081     return SDValue();
9082
9083   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9084     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9085
9086   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9088   // Now we have only mask extension
9089   assert(InVT.getVectorElementType() == MVT::i1);
9090   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9091   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9092   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9093   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9094   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9095                            MachinePointerInfo::getConstantPool(),
9096                            false, false, false, Alignment);
9097
9098   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9099   if (VT.is512BitVector())
9100     return Brcst;
9101   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9102 }
9103
9104 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9105                                SelectionDAG &DAG) {
9106   if (Subtarget->hasFp256()) {
9107     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9108     if (Res.getNode())
9109       return Res;
9110   }
9111
9112   return SDValue();
9113 }
9114
9115 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9116                                 SelectionDAG &DAG) {
9117   SDLoc DL(Op);
9118   MVT VT = Op.getSimpleValueType();
9119   SDValue In = Op.getOperand(0);
9120   MVT SVT = In.getSimpleValueType();
9121
9122   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9123     return LowerZERO_EXTEND_AVX512(Op, DAG);
9124
9125   if (Subtarget->hasFp256()) {
9126     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9127     if (Res.getNode())
9128       return Res;
9129   }
9130
9131   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9132          VT.getVectorNumElements() != SVT.getVectorNumElements());
9133   return SDValue();
9134 }
9135
9136 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9137   SDLoc DL(Op);
9138   MVT VT = Op.getSimpleValueType();
9139   SDValue In = Op.getOperand(0);
9140   MVT InVT = In.getSimpleValueType();
9141
9142   if (VT == MVT::i1) {
9143     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9144            "Invalid scalar TRUNCATE operation");
9145     if (InVT == MVT::i32)
9146       return SDValue();
9147     if (InVT.getSizeInBits() == 64)
9148       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9149     else if (InVT.getSizeInBits() < 32)
9150       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9151     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9152   }
9153   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9154          "Invalid TRUNCATE operation");
9155
9156   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9157     if (VT.getVectorElementType().getSizeInBits() >=8)
9158       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9159
9160     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9161     unsigned NumElts = InVT.getVectorNumElements();
9162     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9163     if (InVT.getSizeInBits() < 512) {
9164       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9165       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9166       InVT = ExtVT;
9167     }
9168     
9169     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9170     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9171     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9172     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9173     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9174                            MachinePointerInfo::getConstantPool(),
9175                            false, false, false, Alignment);
9176     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9177     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9178     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9179   }
9180
9181   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9182     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9183     if (Subtarget->hasInt256()) {
9184       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9185       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9186       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9187                                 ShufMask);
9188       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9189                          DAG.getIntPtrConstant(0));
9190     }
9191
9192     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9193                                DAG.getIntPtrConstant(0));
9194     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9195                                DAG.getIntPtrConstant(2));
9196     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9197     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9198     static const int ShufMask[] = {0, 2, 4, 6};
9199     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9200   }
9201
9202   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9203     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9204     if (Subtarget->hasInt256()) {
9205       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9206
9207       SmallVector<SDValue,32> pshufbMask;
9208       for (unsigned i = 0; i < 2; ++i) {
9209         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9210         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9211         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9212         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9213         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9214         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9215         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9216         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9217         for (unsigned j = 0; j < 8; ++j)
9218           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9219       }
9220       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9221                                &pshufbMask[0], 32);
9222       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9223       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9224
9225       static const int ShufMask[] = {0,  2,  -1,  -1};
9226       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9227                                 &ShufMask[0]);
9228       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9229                        DAG.getIntPtrConstant(0));
9230       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9231     }
9232
9233     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9234                                DAG.getIntPtrConstant(0));
9235
9236     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9237                                DAG.getIntPtrConstant(4));
9238
9239     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9240     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9241
9242     // The PSHUFB mask:
9243     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9244                                    -1, -1, -1, -1, -1, -1, -1, -1};
9245
9246     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9247     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9248     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9249
9250     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9251     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9252
9253     // The MOVLHPS Mask:
9254     static const int ShufMask2[] = {0, 1, 4, 5};
9255     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9256     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9257   }
9258
9259   // Handle truncation of V256 to V128 using shuffles.
9260   if (!VT.is128BitVector() || !InVT.is256BitVector())
9261     return SDValue();
9262
9263   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9264
9265   unsigned NumElems = VT.getVectorNumElements();
9266   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9267
9268   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9269   // Prepare truncation shuffle mask
9270   for (unsigned i = 0; i != NumElems; ++i)
9271     MaskVec[i] = i * 2;
9272   SDValue V = DAG.getVectorShuffle(NVT, DL,
9273                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9274                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9275   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9276                      DAG.getIntPtrConstant(0));
9277 }
9278
9279 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9280                                            SelectionDAG &DAG) const {
9281   assert(!Op.getSimpleValueType().isVector());
9282
9283   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9284     /*IsSigned=*/ true, /*IsReplace=*/ false);
9285   SDValue FIST = Vals.first, StackSlot = Vals.second;
9286   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9287   if (FIST.getNode() == 0) return Op;
9288
9289   if (StackSlot.getNode())
9290     // Load the result.
9291     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9292                        FIST, StackSlot, MachinePointerInfo(),
9293                        false, false, false, 0);
9294
9295   // The node is the result.
9296   return FIST;
9297 }
9298
9299 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9300                                            SelectionDAG &DAG) const {
9301   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9302     /*IsSigned=*/ false, /*IsReplace=*/ false);
9303   SDValue FIST = Vals.first, StackSlot = Vals.second;
9304   assert(FIST.getNode() && "Unexpected failure");
9305
9306   if (StackSlot.getNode())
9307     // Load the result.
9308     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9309                        FIST, StackSlot, MachinePointerInfo(),
9310                        false, false, false, 0);
9311
9312   // The node is the result.
9313   return FIST;
9314 }
9315
9316 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9317   SDLoc DL(Op);
9318   MVT VT = Op.getSimpleValueType();
9319   SDValue In = Op.getOperand(0);
9320   MVT SVT = In.getSimpleValueType();
9321
9322   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9323
9324   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9325                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9326                                  In, DAG.getUNDEF(SVT)));
9327 }
9328
9329 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9330   LLVMContext *Context = DAG.getContext();
9331   SDLoc dl(Op);
9332   MVT VT = Op.getSimpleValueType();
9333   MVT EltVT = VT;
9334   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9335   if (VT.isVector()) {
9336     EltVT = VT.getVectorElementType();
9337     NumElts = VT.getVectorNumElements();
9338   }
9339   Constant *C;
9340   if (EltVT == MVT::f64)
9341     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9342                                           APInt(64, ~(1ULL << 63))));
9343   else
9344     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9345                                           APInt(32, ~(1U << 31))));
9346   C = ConstantVector::getSplat(NumElts, C);
9347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9348   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9349   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9350   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9351                              MachinePointerInfo::getConstantPool(),
9352                              false, false, false, Alignment);
9353   if (VT.isVector()) {
9354     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9355     return DAG.getNode(ISD::BITCAST, dl, VT,
9356                        DAG.getNode(ISD::AND, dl, ANDVT,
9357                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9358                                                Op.getOperand(0)),
9359                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9360   }
9361   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9362 }
9363
9364 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9365   LLVMContext *Context = DAG.getContext();
9366   SDLoc dl(Op);
9367   MVT VT = Op.getSimpleValueType();
9368   MVT EltVT = VT;
9369   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9370   if (VT.isVector()) {
9371     EltVT = VT.getVectorElementType();
9372     NumElts = VT.getVectorNumElements();
9373   }
9374   Constant *C;
9375   if (EltVT == MVT::f64)
9376     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9377                                           APInt(64, 1ULL << 63)));
9378   else
9379     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9380                                           APInt(32, 1U << 31)));
9381   C = ConstantVector::getSplat(NumElts, C);
9382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9383   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9384   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9385   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9386                              MachinePointerInfo::getConstantPool(),
9387                              false, false, false, Alignment);
9388   if (VT.isVector()) {
9389     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9390     return DAG.getNode(ISD::BITCAST, dl, VT,
9391                        DAG.getNode(ISD::XOR, dl, XORVT,
9392                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9393                                                Op.getOperand(0)),
9394                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9395   }
9396
9397   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9398 }
9399
9400 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9402   LLVMContext *Context = DAG.getContext();
9403   SDValue Op0 = Op.getOperand(0);
9404   SDValue Op1 = Op.getOperand(1);
9405   SDLoc dl(Op);
9406   MVT VT = Op.getSimpleValueType();
9407   MVT SrcVT = Op1.getSimpleValueType();
9408
9409   // If second operand is smaller, extend it first.
9410   if (SrcVT.bitsLT(VT)) {
9411     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9412     SrcVT = VT;
9413   }
9414   // And if it is bigger, shrink it first.
9415   if (SrcVT.bitsGT(VT)) {
9416     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9417     SrcVT = VT;
9418   }
9419
9420   // At this point the operands and the result should have the same
9421   // type, and that won't be f80 since that is not custom lowered.
9422
9423   // First get the sign bit of second operand.
9424   SmallVector<Constant*,4> CV;
9425   if (SrcVT == MVT::f64) {
9426     const fltSemantics &Sem = APFloat::IEEEdouble;
9427     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9428     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9429   } else {
9430     const fltSemantics &Sem = APFloat::IEEEsingle;
9431     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9432     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9433     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9434     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9435   }
9436   Constant *C = ConstantVector::get(CV);
9437   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9438   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9439                               MachinePointerInfo::getConstantPool(),
9440                               false, false, false, 16);
9441   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9442
9443   // Shift sign bit right or left if the two operands have different types.
9444   if (SrcVT.bitsGT(VT)) {
9445     // Op0 is MVT::f32, Op1 is MVT::f64.
9446     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9447     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9448                           DAG.getConstant(32, MVT::i32));
9449     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9450     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9451                           DAG.getIntPtrConstant(0));
9452   }
9453
9454   // Clear first operand sign bit.
9455   CV.clear();
9456   if (VT == MVT::f64) {
9457     const fltSemantics &Sem = APFloat::IEEEdouble;
9458     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9459                                                    APInt(64, ~(1ULL << 63)))));
9460     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9461   } else {
9462     const fltSemantics &Sem = APFloat::IEEEsingle;
9463     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9464                                                    APInt(32, ~(1U << 31)))));
9465     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9466     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9467     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9468   }
9469   C = ConstantVector::get(CV);
9470   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9471   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9472                               MachinePointerInfo::getConstantPool(),
9473                               false, false, false, 16);
9474   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9475
9476   // Or the value with the sign bit.
9477   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9478 }
9479
9480 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9481   SDValue N0 = Op.getOperand(0);
9482   SDLoc dl(Op);
9483   MVT VT = Op.getSimpleValueType();
9484
9485   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9486   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9487                                   DAG.getConstant(1, VT));
9488   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9489 }
9490
9491 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9492 //
9493 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9494                                       SelectionDAG &DAG) {
9495   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9496
9497   if (!Subtarget->hasSSE41())
9498     return SDValue();
9499
9500   if (!Op->hasOneUse())
9501     return SDValue();
9502
9503   SDNode *N = Op.getNode();
9504   SDLoc DL(N);
9505
9506   SmallVector<SDValue, 8> Opnds;
9507   DenseMap<SDValue, unsigned> VecInMap;
9508   SmallVector<SDValue, 8> VecIns;
9509   EVT VT = MVT::Other;
9510
9511   // Recognize a special case where a vector is casted into wide integer to
9512   // test all 0s.
9513   Opnds.push_back(N->getOperand(0));
9514   Opnds.push_back(N->getOperand(1));
9515
9516   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9517     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9518     // BFS traverse all OR'd operands.
9519     if (I->getOpcode() == ISD::OR) {
9520       Opnds.push_back(I->getOperand(0));
9521       Opnds.push_back(I->getOperand(1));
9522       // Re-evaluate the number of nodes to be traversed.
9523       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9524       continue;
9525     }
9526
9527     // Quit if a non-EXTRACT_VECTOR_ELT
9528     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9529       return SDValue();
9530
9531     // Quit if without a constant index.
9532     SDValue Idx = I->getOperand(1);
9533     if (!isa<ConstantSDNode>(Idx))
9534       return SDValue();
9535
9536     SDValue ExtractedFromVec = I->getOperand(0);
9537     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9538     if (M == VecInMap.end()) {
9539       VT = ExtractedFromVec.getValueType();
9540       // Quit if not 128/256-bit vector.
9541       if (!VT.is128BitVector() && !VT.is256BitVector())
9542         return SDValue();
9543       // Quit if not the same type.
9544       if (VecInMap.begin() != VecInMap.end() &&
9545           VT != VecInMap.begin()->first.getValueType())
9546         return SDValue();
9547       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9548       VecIns.push_back(ExtractedFromVec);
9549     }
9550     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9551   }
9552
9553   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9554          "Not extracted from 128-/256-bit vector.");
9555
9556   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9557
9558   for (DenseMap<SDValue, unsigned>::const_iterator
9559         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9560     // Quit if not all elements are used.
9561     if (I->second != FullMask)
9562       return SDValue();
9563   }
9564
9565   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9566
9567   // Cast all vectors into TestVT for PTEST.
9568   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9569     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9570
9571   // If more than one full vectors are evaluated, OR them first before PTEST.
9572   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9573     // Each iteration will OR 2 nodes and append the result until there is only
9574     // 1 node left, i.e. the final OR'd value of all vectors.
9575     SDValue LHS = VecIns[Slot];
9576     SDValue RHS = VecIns[Slot + 1];
9577     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9578   }
9579
9580   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9581                      VecIns.back(), VecIns.back());
9582 }
9583
9584 /// Emit nodes that will be selected as "test Op0,Op0", or something
9585 /// equivalent.
9586 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9587                                     SelectionDAG &DAG) const {
9588   SDLoc dl(Op);
9589
9590   if (Op.getValueType() == MVT::i1)
9591     // KORTEST instruction should be selected
9592     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9593                        DAG.getConstant(0, Op.getValueType()));
9594
9595   // CF and OF aren't always set the way we want. Determine which
9596   // of these we need.
9597   bool NeedCF = false;
9598   bool NeedOF = false;
9599   switch (X86CC) {
9600   default: break;
9601   case X86::COND_A: case X86::COND_AE:
9602   case X86::COND_B: case X86::COND_BE:
9603     NeedCF = true;
9604     break;
9605   case X86::COND_G: case X86::COND_GE:
9606   case X86::COND_L: case X86::COND_LE:
9607   case X86::COND_O: case X86::COND_NO:
9608     NeedOF = true;
9609     break;
9610   }
9611   // See if we can use the EFLAGS value from the operand instead of
9612   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9613   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9614   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9615     // Emit a CMP with 0, which is the TEST pattern.
9616     //if (Op.getValueType() == MVT::i1)
9617     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9618     //                     DAG.getConstant(0, MVT::i1));
9619     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9620                        DAG.getConstant(0, Op.getValueType()));
9621   }
9622   unsigned Opcode = 0;
9623   unsigned NumOperands = 0;
9624
9625   // Truncate operations may prevent the merge of the SETCC instruction
9626   // and the arithmetic instruction before it. Attempt to truncate the operands
9627   // of the arithmetic instruction and use a reduced bit-width instruction.
9628   bool NeedTruncation = false;
9629   SDValue ArithOp = Op;
9630   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9631     SDValue Arith = Op->getOperand(0);
9632     // Both the trunc and the arithmetic op need to have one user each.
9633     if (Arith->hasOneUse())
9634       switch (Arith.getOpcode()) {
9635         default: break;
9636         case ISD::ADD:
9637         case ISD::SUB:
9638         case ISD::AND:
9639         case ISD::OR:
9640         case ISD::XOR: {
9641           NeedTruncation = true;
9642           ArithOp = Arith;
9643         }
9644       }
9645   }
9646
9647   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9648   // which may be the result of a CAST.  We use the variable 'Op', which is the
9649   // non-casted variable when we check for possible users.
9650   switch (ArithOp.getOpcode()) {
9651   case ISD::ADD:
9652     // Due to an isel shortcoming, be conservative if this add is likely to be
9653     // selected as part of a load-modify-store instruction. When the root node
9654     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9655     // uses of other nodes in the match, such as the ADD in this case. This
9656     // leads to the ADD being left around and reselected, with the result being
9657     // two adds in the output.  Alas, even if none our users are stores, that
9658     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9659     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9660     // climbing the DAG back to the root, and it doesn't seem to be worth the
9661     // effort.
9662     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9663          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9664       if (UI->getOpcode() != ISD::CopyToReg &&
9665           UI->getOpcode() != ISD::SETCC &&
9666           UI->getOpcode() != ISD::STORE)
9667         goto default_case;
9668
9669     if (ConstantSDNode *C =
9670         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9671       // An add of one will be selected as an INC.
9672       if (C->getAPIntValue() == 1) {
9673         Opcode = X86ISD::INC;
9674         NumOperands = 1;
9675         break;
9676       }
9677
9678       // An add of negative one (subtract of one) will be selected as a DEC.
9679       if (C->getAPIntValue().isAllOnesValue()) {
9680         Opcode = X86ISD::DEC;
9681         NumOperands = 1;
9682         break;
9683       }
9684     }
9685
9686     // Otherwise use a regular EFLAGS-setting add.
9687     Opcode = X86ISD::ADD;
9688     NumOperands = 2;
9689     break;
9690   case ISD::AND: {
9691     // If the primary and result isn't used, don't bother using X86ISD::AND,
9692     // because a TEST instruction will be better.
9693     bool NonFlagUse = false;
9694     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9695            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9696       SDNode *User = *UI;
9697       unsigned UOpNo = UI.getOperandNo();
9698       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9699         // Look pass truncate.
9700         UOpNo = User->use_begin().getOperandNo();
9701         User = *User->use_begin();
9702       }
9703
9704       if (User->getOpcode() != ISD::BRCOND &&
9705           User->getOpcode() != ISD::SETCC &&
9706           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9707         NonFlagUse = true;
9708         break;
9709       }
9710     }
9711
9712     if (!NonFlagUse)
9713       break;
9714   }
9715     // FALL THROUGH
9716   case ISD::SUB:
9717   case ISD::OR:
9718   case ISD::XOR:
9719     // Due to the ISEL shortcoming noted above, be conservative if this op is
9720     // likely to be selected as part of a load-modify-store instruction.
9721     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9722            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9723       if (UI->getOpcode() == ISD::STORE)
9724         goto default_case;
9725
9726     // Otherwise use a regular EFLAGS-setting instruction.
9727     switch (ArithOp.getOpcode()) {
9728     default: llvm_unreachable("unexpected operator!");
9729     case ISD::SUB: Opcode = X86ISD::SUB; break;
9730     case ISD::XOR: Opcode = X86ISD::XOR; break;
9731     case ISD::AND: Opcode = X86ISD::AND; break;
9732     case ISD::OR: {
9733       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9734         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9735         if (EFLAGS.getNode())
9736           return EFLAGS;
9737       }
9738       Opcode = X86ISD::OR;
9739       break;
9740     }
9741     }
9742
9743     NumOperands = 2;
9744     break;
9745   case X86ISD::ADD:
9746   case X86ISD::SUB:
9747   case X86ISD::INC:
9748   case X86ISD::DEC:
9749   case X86ISD::OR:
9750   case X86ISD::XOR:
9751   case X86ISD::AND:
9752     return SDValue(Op.getNode(), 1);
9753   default:
9754   default_case:
9755     break;
9756   }
9757
9758   // If we found that truncation is beneficial, perform the truncation and
9759   // update 'Op'.
9760   if (NeedTruncation) {
9761     EVT VT = Op.getValueType();
9762     SDValue WideVal = Op->getOperand(0);
9763     EVT WideVT = WideVal.getValueType();
9764     unsigned ConvertedOp = 0;
9765     // Use a target machine opcode to prevent further DAGCombine
9766     // optimizations that may separate the arithmetic operations
9767     // from the setcc node.
9768     switch (WideVal.getOpcode()) {
9769       default: break;
9770       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9771       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9772       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9773       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9774       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9775     }
9776
9777     if (ConvertedOp) {
9778       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9779       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9780         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9781         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9782         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9783       }
9784     }
9785   }
9786
9787   if (Opcode == 0)
9788     // Emit a CMP with 0, which is the TEST pattern.
9789     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9790                        DAG.getConstant(0, Op.getValueType()));
9791
9792   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9793   SmallVector<SDValue, 4> Ops;
9794   for (unsigned i = 0; i != NumOperands; ++i)
9795     Ops.push_back(Op.getOperand(i));
9796
9797   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9798   DAG.ReplaceAllUsesWith(Op, New);
9799   return SDValue(New.getNode(), 1);
9800 }
9801
9802 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9803 /// equivalent.
9804 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9805                                    SelectionDAG &DAG) const {
9806   SDLoc dl(Op0);
9807   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9808     if (C->getAPIntValue() == 0)
9809       return EmitTest(Op0, X86CC, DAG);
9810
9811      if (Op0.getValueType() == MVT::i1)
9812        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9813   }
9814  
9815   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9816        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9817     // Do the comparison at i32 if it's smaller, besides the Atom case. 
9818     // This avoids subregister aliasing issues. Keep the smaller reference 
9819     // if we're optimizing for size, however, as that'll allow better folding 
9820     // of memory operations.
9821     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9822         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9823              AttributeSet::FunctionIndex, Attribute::MinSize) &&
9824         !Subtarget->isAtom()) {
9825       unsigned ExtendOp =
9826           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9827       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9828       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9829     }
9830     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9831     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9832     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9833                               Op0, Op1);
9834     return SDValue(Sub.getNode(), 1);
9835   }
9836   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9837 }
9838
9839 /// Convert a comparison if required by the subtarget.
9840 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9841                                                  SelectionDAG &DAG) const {
9842   // If the subtarget does not support the FUCOMI instruction, floating-point
9843   // comparisons have to be converted.
9844   if (Subtarget->hasCMov() ||
9845       Cmp.getOpcode() != X86ISD::CMP ||
9846       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9847       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9848     return Cmp;
9849
9850   // The instruction selector will select an FUCOM instruction instead of
9851   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9852   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9853   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9854   SDLoc dl(Cmp);
9855   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9856   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9857   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9858                             DAG.getConstant(8, MVT::i8));
9859   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9860   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9861 }
9862
9863 static bool isAllOnes(SDValue V) {
9864   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9865   return C && C->isAllOnesValue();
9866 }
9867
9868 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9869 /// if it's possible.
9870 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9871                                      SDLoc dl, SelectionDAG &DAG) const {
9872   SDValue Op0 = And.getOperand(0);
9873   SDValue Op1 = And.getOperand(1);
9874   if (Op0.getOpcode() == ISD::TRUNCATE)
9875     Op0 = Op0.getOperand(0);
9876   if (Op1.getOpcode() == ISD::TRUNCATE)
9877     Op1 = Op1.getOperand(0);
9878
9879   SDValue LHS, RHS;
9880   if (Op1.getOpcode() == ISD::SHL)
9881     std::swap(Op0, Op1);
9882   if (Op0.getOpcode() == ISD::SHL) {
9883     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9884       if (And00C->getZExtValue() == 1) {
9885         // If we looked past a truncate, check that it's only truncating away
9886         // known zeros.
9887         unsigned BitWidth = Op0.getValueSizeInBits();
9888         unsigned AndBitWidth = And.getValueSizeInBits();
9889         if (BitWidth > AndBitWidth) {
9890           APInt Zeros, Ones;
9891           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9892           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9893             return SDValue();
9894         }
9895         LHS = Op1;
9896         RHS = Op0.getOperand(1);
9897       }
9898   } else if (Op1.getOpcode() == ISD::Constant) {
9899     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9900     uint64_t AndRHSVal = AndRHS->getZExtValue();
9901     SDValue AndLHS = Op0;
9902
9903     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9904       LHS = AndLHS.getOperand(0);
9905       RHS = AndLHS.getOperand(1);
9906     }
9907
9908     // Use BT if the immediate can't be encoded in a TEST instruction.
9909     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9910       LHS = AndLHS;
9911       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9912     }
9913   }
9914
9915   if (LHS.getNode()) {
9916     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9917     // instruction.  Since the shift amount is in-range-or-undefined, we know
9918     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9919     // the encoding for the i16 version is larger than the i32 version.
9920     // Also promote i16 to i32 for performance / code size reason.
9921     if (LHS.getValueType() == MVT::i8 ||
9922         LHS.getValueType() == MVT::i16)
9923       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9924
9925     // If the operand types disagree, extend the shift amount to match.  Since
9926     // BT ignores high bits (like shifts) we can use anyextend.
9927     if (LHS.getValueType() != RHS.getValueType())
9928       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9929
9930     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9931     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9932     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9933                        DAG.getConstant(Cond, MVT::i8), BT);
9934   }
9935
9936   return SDValue();
9937 }
9938
9939 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9940 /// mask CMPs.
9941 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9942                               SDValue &Op1) {
9943   unsigned SSECC;
9944   bool Swap = false;
9945
9946   // SSE Condition code mapping:
9947   //  0 - EQ
9948   //  1 - LT
9949   //  2 - LE
9950   //  3 - UNORD
9951   //  4 - NEQ
9952   //  5 - NLT
9953   //  6 - NLE
9954   //  7 - ORD
9955   switch (SetCCOpcode) {
9956   default: llvm_unreachable("Unexpected SETCC condition");
9957   case ISD::SETOEQ:
9958   case ISD::SETEQ:  SSECC = 0; break;
9959   case ISD::SETOGT:
9960   case ISD::SETGT:  Swap = true; // Fallthrough
9961   case ISD::SETLT:
9962   case ISD::SETOLT: SSECC = 1; break;
9963   case ISD::SETOGE:
9964   case ISD::SETGE:  Swap = true; // Fallthrough
9965   case ISD::SETLE:
9966   case ISD::SETOLE: SSECC = 2; break;
9967   case ISD::SETUO:  SSECC = 3; break;
9968   case ISD::SETUNE:
9969   case ISD::SETNE:  SSECC = 4; break;
9970   case ISD::SETULE: Swap = true; // Fallthrough
9971   case ISD::SETUGE: SSECC = 5; break;
9972   case ISD::SETULT: Swap = true; // Fallthrough
9973   case ISD::SETUGT: SSECC = 6; break;
9974   case ISD::SETO:   SSECC = 7; break;
9975   case ISD::SETUEQ:
9976   case ISD::SETONE: SSECC = 8; break;
9977   }
9978   if (Swap)
9979     std::swap(Op0, Op1);
9980
9981   return SSECC;
9982 }
9983
9984 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9985 // ones, and then concatenate the result back.
9986 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9987   MVT VT = Op.getSimpleValueType();
9988
9989   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9990          "Unsupported value type for operation");
9991
9992   unsigned NumElems = VT.getVectorNumElements();
9993   SDLoc dl(Op);
9994   SDValue CC = Op.getOperand(2);
9995
9996   // Extract the LHS vectors
9997   SDValue LHS = Op.getOperand(0);
9998   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9999   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10000
10001   // Extract the RHS vectors
10002   SDValue RHS = Op.getOperand(1);
10003   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10004   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10005
10006   // Issue the operation on the smaller types and concatenate the result back
10007   MVT EltVT = VT.getVectorElementType();
10008   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10009   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10010                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10011                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10012 }
10013
10014 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10015                                      const X86Subtarget *Subtarget) {
10016   SDValue Op0 = Op.getOperand(0);
10017   SDValue Op1 = Op.getOperand(1);
10018   SDValue CC = Op.getOperand(2);
10019   MVT VT = Op.getSimpleValueType();
10020   SDLoc dl(Op);
10021
10022   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10023          Op.getValueType().getScalarType() == MVT::i1 &&
10024          "Cannot set masked compare for this operation");
10025
10026   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10027   unsigned  Opc = 0;
10028   bool Unsigned = false;
10029   bool Swap = false;
10030   unsigned SSECC;
10031   switch (SetCCOpcode) {
10032   default: llvm_unreachable("Unexpected SETCC condition");
10033   case ISD::SETNE:  SSECC = 4; break;
10034   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10035   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10036   case ISD::SETLT:  Swap = true; //fall-through
10037   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10038   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10039   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10040   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10041   case ISD::SETULE: Unsigned = true; //fall-through
10042   case ISD::SETLE:  SSECC = 2; break;
10043   }
10044
10045   if (Swap)
10046     std::swap(Op0, Op1);
10047   if (Opc)
10048     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10049   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10050   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10051                      DAG.getConstant(SSECC, MVT::i8));
10052 }
10053
10054 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10055 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10056 /// return an empty value.
10057 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10058 {
10059   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10060   if (!BV)
10061     return SDValue();
10062
10063   MVT VT = Op1.getSimpleValueType();
10064   MVT EVT = VT.getVectorElementType();
10065   unsigned n = VT.getVectorNumElements();
10066   SmallVector<SDValue, 8> ULTOp1;
10067
10068   for (unsigned i = 0; i < n; ++i) {
10069     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10070     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10071       return SDValue();
10072
10073     // Avoid underflow.
10074     APInt Val = Elt->getAPIntValue();
10075     if (Val == 0)
10076       return SDValue();
10077
10078     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10079   }
10080
10081   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10082                      ULTOp1.size());
10083 }
10084
10085 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10086                            SelectionDAG &DAG) {
10087   SDValue Op0 = Op.getOperand(0);
10088   SDValue Op1 = Op.getOperand(1);
10089   SDValue CC = Op.getOperand(2);
10090   MVT VT = Op.getSimpleValueType();
10091   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10092   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10093   SDLoc dl(Op);
10094
10095   if (isFP) {
10096 #ifndef NDEBUG
10097     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10098     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10099 #endif
10100
10101     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10102     unsigned Opc = X86ISD::CMPP;
10103     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10104       assert(VT.getVectorNumElements() <= 16);
10105       Opc = X86ISD::CMPM;
10106     }
10107     // In the two special cases we can't handle, emit two comparisons.
10108     if (SSECC == 8) {
10109       unsigned CC0, CC1;
10110       unsigned CombineOpc;
10111       if (SetCCOpcode == ISD::SETUEQ) {
10112         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10113       } else {
10114         assert(SetCCOpcode == ISD::SETONE);
10115         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10116       }
10117
10118       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10119                                  DAG.getConstant(CC0, MVT::i8));
10120       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10121                                  DAG.getConstant(CC1, MVT::i8));
10122       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10123     }
10124     // Handle all other FP comparisons here.
10125     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10126                        DAG.getConstant(SSECC, MVT::i8));
10127   }
10128
10129   // Break 256-bit integer vector compare into smaller ones.
10130   if (VT.is256BitVector() && !Subtarget->hasInt256())
10131     return Lower256IntVSETCC(Op, DAG);
10132
10133   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10134   EVT OpVT = Op1.getValueType();
10135   if (Subtarget->hasAVX512()) {
10136     if (Op1.getValueType().is512BitVector() ||
10137         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10138       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10139
10140     // In AVX-512 architecture setcc returns mask with i1 elements,
10141     // But there is no compare instruction for i8 and i16 elements.
10142     // We are not talking about 512-bit operands in this case, these
10143     // types are illegal.
10144     if (MaskResult &&
10145         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10146          OpVT.getVectorElementType().getSizeInBits() >= 8))
10147       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10148                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10149   }
10150
10151   // We are handling one of the integer comparisons here.  Since SSE only has
10152   // GT and EQ comparisons for integer, swapping operands and multiple
10153   // operations may be required for some comparisons.
10154   unsigned Opc;
10155   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10156   bool Subus = false;
10157
10158   switch (SetCCOpcode) {
10159   default: llvm_unreachable("Unexpected SETCC condition");
10160   case ISD::SETNE:  Invert = true;
10161   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10162   case ISD::SETLT:  Swap = true;
10163   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10164   case ISD::SETGE:  Swap = true;
10165   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10166                     Invert = true; break;
10167   case ISD::SETULT: Swap = true;
10168   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10169                     FlipSigns = true; break;
10170   case ISD::SETUGE: Swap = true;
10171   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10172                     FlipSigns = true; Invert = true; break;
10173   }
10174
10175   // Special case: Use min/max operations for SETULE/SETUGE
10176   MVT VET = VT.getVectorElementType();
10177   bool hasMinMax =
10178        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10179     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10180
10181   if (hasMinMax) {
10182     switch (SetCCOpcode) {
10183     default: break;
10184     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10185     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10186     }
10187
10188     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10189   }
10190
10191   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10192   if (!MinMax && hasSubus) {
10193     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10194     // Op0 u<= Op1:
10195     //   t = psubus Op0, Op1
10196     //   pcmpeq t, <0..0>
10197     switch (SetCCOpcode) {
10198     default: break;
10199     case ISD::SETULT: {
10200       // If the comparison is against a constant we can turn this into a
10201       // setule.  With psubus, setule does not require a swap.  This is
10202       // beneficial because the constant in the register is no longer
10203       // destructed as the destination so it can be hoisted out of a loop.
10204       // Only do this pre-AVX since vpcmp* is no longer destructive.
10205       if (Subtarget->hasAVX())
10206         break;
10207       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10208       if (ULEOp1.getNode()) {
10209         Op1 = ULEOp1;
10210         Subus = true; Invert = false; Swap = false;
10211       }
10212       break;
10213     }
10214     // Psubus is better than flip-sign because it requires no inversion.
10215     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10216     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10217     }
10218
10219     if (Subus) {
10220       Opc = X86ISD::SUBUS;
10221       FlipSigns = false;
10222     }
10223   }
10224
10225   if (Swap)
10226     std::swap(Op0, Op1);
10227
10228   // Check that the operation in question is available (most are plain SSE2,
10229   // but PCMPGTQ and PCMPEQQ have different requirements).
10230   if (VT == MVT::v2i64) {
10231     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10232       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10233
10234       // First cast everything to the right type.
10235       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10236       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10237
10238       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10239       // bits of the inputs before performing those operations. The lower
10240       // compare is always unsigned.
10241       SDValue SB;
10242       if (FlipSigns) {
10243         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10244       } else {
10245         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10246         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10247         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10248                          Sign, Zero, Sign, Zero);
10249       }
10250       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10251       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10252
10253       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10254       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10255       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10256
10257       // Create masks for only the low parts/high parts of the 64 bit integers.
10258       static const int MaskHi[] = { 1, 1, 3, 3 };
10259       static const int MaskLo[] = { 0, 0, 2, 2 };
10260       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10261       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10262       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10263
10264       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10265       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10266
10267       if (Invert)
10268         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10269
10270       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10271     }
10272
10273     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10274       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10275       // pcmpeqd + pshufd + pand.
10276       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10277
10278       // First cast everything to the right type.
10279       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10280       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10281
10282       // Do the compare.
10283       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10284
10285       // Make sure the lower and upper halves are both all-ones.
10286       static const int Mask[] = { 1, 0, 3, 2 };
10287       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10288       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10289
10290       if (Invert)
10291         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10292
10293       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10294     }
10295   }
10296
10297   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10298   // bits of the inputs before performing those operations.
10299   if (FlipSigns) {
10300     EVT EltVT = VT.getVectorElementType();
10301     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10302     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10303     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10304   }
10305
10306   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10307
10308   // If the logical-not of the result is required, perform that now.
10309   if (Invert)
10310     Result = DAG.getNOT(dl, Result, VT);
10311
10312   if (MinMax)
10313     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10314
10315   if (Subus)
10316     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10317                          getZeroVector(VT, Subtarget, DAG, dl));
10318
10319   return Result;
10320 }
10321
10322 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10323
10324   MVT VT = Op.getSimpleValueType();
10325
10326   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10327
10328   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10329          && "SetCC type must be 8-bit or 1-bit integer");
10330   SDValue Op0 = Op.getOperand(0);
10331   SDValue Op1 = Op.getOperand(1);
10332   SDLoc dl(Op);
10333   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10334
10335   // Optimize to BT if possible.
10336   // Lower (X & (1 << N)) == 0 to BT(X, N).
10337   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10338   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10339   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10340       Op1.getOpcode() == ISD::Constant &&
10341       cast<ConstantSDNode>(Op1)->isNullValue() &&
10342       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10343     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10344     if (NewSetCC.getNode())
10345       return NewSetCC;
10346   }
10347
10348   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10349   // these.
10350   if (Op1.getOpcode() == ISD::Constant &&
10351       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10352        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10353       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10354
10355     // If the input is a setcc, then reuse the input setcc or use a new one with
10356     // the inverted condition.
10357     if (Op0.getOpcode() == X86ISD::SETCC) {
10358       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10359       bool Invert = (CC == ISD::SETNE) ^
10360         cast<ConstantSDNode>(Op1)->isNullValue();
10361       if (!Invert)
10362         return Op0;
10363
10364       CCode = X86::GetOppositeBranchCondition(CCode);
10365       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10366                                   DAG.getConstant(CCode, MVT::i8),
10367                                   Op0.getOperand(1));
10368       if (VT == MVT::i1)
10369         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10370       return SetCC;
10371     }
10372   }
10373   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10374       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10375       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10376
10377     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10378     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10379   }
10380
10381   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10382   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10383   if (X86CC == X86::COND_INVALID)
10384     return SDValue();
10385
10386   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10387   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10388   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10389                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10390   if (VT == MVT::i1)
10391     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10392   return SetCC;
10393 }
10394
10395 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10396 static bool isX86LogicalCmp(SDValue Op) {
10397   unsigned Opc = Op.getNode()->getOpcode();
10398   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10399       Opc == X86ISD::SAHF)
10400     return true;
10401   if (Op.getResNo() == 1 &&
10402       (Opc == X86ISD::ADD ||
10403        Opc == X86ISD::SUB ||
10404        Opc == X86ISD::ADC ||
10405        Opc == X86ISD::SBB ||
10406        Opc == X86ISD::SMUL ||
10407        Opc == X86ISD::UMUL ||
10408        Opc == X86ISD::INC ||
10409        Opc == X86ISD::DEC ||
10410        Opc == X86ISD::OR ||
10411        Opc == X86ISD::XOR ||
10412        Opc == X86ISD::AND))
10413     return true;
10414
10415   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10416     return true;
10417
10418   return false;
10419 }
10420
10421 static bool isZero(SDValue V) {
10422   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10423   return C && C->isNullValue();
10424 }
10425
10426 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10427   if (V.getOpcode() != ISD::TRUNCATE)
10428     return false;
10429
10430   SDValue VOp0 = V.getOperand(0);
10431   unsigned InBits = VOp0.getValueSizeInBits();
10432   unsigned Bits = V.getValueSizeInBits();
10433   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10434 }
10435
10436 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10437   bool addTest = true;
10438   SDValue Cond  = Op.getOperand(0);
10439   SDValue Op1 = Op.getOperand(1);
10440   SDValue Op2 = Op.getOperand(2);
10441   SDLoc DL(Op);
10442   EVT VT = Op1.getValueType();
10443   SDValue CC;
10444
10445   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10446   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10447   // sequence later on.
10448   if (Cond.getOpcode() == ISD::SETCC &&
10449       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10450        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10451       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10452     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10453     int SSECC = translateX86FSETCC(
10454         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10455
10456     if (SSECC != 8) {
10457       if (Subtarget->hasAVX512()) {
10458         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10459                                   DAG.getConstant(SSECC, MVT::i8));
10460         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10461       }
10462       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10463                                 DAG.getConstant(SSECC, MVT::i8));
10464       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10465       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10466       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10467     }
10468   }
10469
10470   if (Cond.getOpcode() == ISD::SETCC) {
10471     SDValue NewCond = LowerSETCC(Cond, DAG);
10472     if (NewCond.getNode())
10473       Cond = NewCond;
10474   }
10475
10476   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10477   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10478   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10479   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10480   if (Cond.getOpcode() == X86ISD::SETCC &&
10481       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10482       isZero(Cond.getOperand(1).getOperand(1))) {
10483     SDValue Cmp = Cond.getOperand(1);
10484
10485     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10486
10487     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10488         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10489       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10490
10491       SDValue CmpOp0 = Cmp.getOperand(0);
10492       // Apply further optimizations for special cases
10493       // (select (x != 0), -1, 0) -> neg & sbb
10494       // (select (x == 0), 0, -1) -> neg & sbb
10495       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10496         if (YC->isNullValue() &&
10497             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10498           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10499           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10500                                     DAG.getConstant(0, CmpOp0.getValueType()),
10501                                     CmpOp0);
10502           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10503                                     DAG.getConstant(X86::COND_B, MVT::i8),
10504                                     SDValue(Neg.getNode(), 1));
10505           return Res;
10506         }
10507
10508       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10509                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10510       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10511
10512       SDValue Res =   // Res = 0 or -1.
10513         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10514                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10515
10516       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10517         Res = DAG.getNOT(DL, Res, Res.getValueType());
10518
10519       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10520       if (N2C == 0 || !N2C->isNullValue())
10521         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10522       return Res;
10523     }
10524   }
10525
10526   // Look past (and (setcc_carry (cmp ...)), 1).
10527   if (Cond.getOpcode() == ISD::AND &&
10528       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10529     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10530     if (C && C->getAPIntValue() == 1)
10531       Cond = Cond.getOperand(0);
10532   }
10533
10534   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10535   // setting operand in place of the X86ISD::SETCC.
10536   unsigned CondOpcode = Cond.getOpcode();
10537   if (CondOpcode == X86ISD::SETCC ||
10538       CondOpcode == X86ISD::SETCC_CARRY) {
10539     CC = Cond.getOperand(0);
10540
10541     SDValue Cmp = Cond.getOperand(1);
10542     unsigned Opc = Cmp.getOpcode();
10543     MVT VT = Op.getSimpleValueType();
10544
10545     bool IllegalFPCMov = false;
10546     if (VT.isFloatingPoint() && !VT.isVector() &&
10547         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10548       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10549
10550     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10551         Opc == X86ISD::BT) { // FIXME
10552       Cond = Cmp;
10553       addTest = false;
10554     }
10555   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10556              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10557              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10558               Cond.getOperand(0).getValueType() != MVT::i8)) {
10559     SDValue LHS = Cond.getOperand(0);
10560     SDValue RHS = Cond.getOperand(1);
10561     unsigned X86Opcode;
10562     unsigned X86Cond;
10563     SDVTList VTs;
10564     switch (CondOpcode) {
10565     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10566     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10567     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10568     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10569     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10570     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10571     default: llvm_unreachable("unexpected overflowing operator");
10572     }
10573     if (CondOpcode == ISD::UMULO)
10574       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10575                           MVT::i32);
10576     else
10577       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10578
10579     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10580
10581     if (CondOpcode == ISD::UMULO)
10582       Cond = X86Op.getValue(2);
10583     else
10584       Cond = X86Op.getValue(1);
10585
10586     CC = DAG.getConstant(X86Cond, MVT::i8);
10587     addTest = false;
10588   }
10589
10590   if (addTest) {
10591     // Look pass the truncate if the high bits are known zero.
10592     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10593         Cond = Cond.getOperand(0);
10594
10595     // We know the result of AND is compared against zero. Try to match
10596     // it to BT.
10597     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10598       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10599       if (NewSetCC.getNode()) {
10600         CC = NewSetCC.getOperand(0);
10601         Cond = NewSetCC.getOperand(1);
10602         addTest = false;
10603       }
10604     }
10605   }
10606
10607   if (addTest) {
10608     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10609     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10610   }
10611
10612   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10613   // a <  b ?  0 : -1 -> RES = setcc_carry
10614   // a >= b ? -1 :  0 -> RES = setcc_carry
10615   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10616   if (Cond.getOpcode() == X86ISD::SUB) {
10617     Cond = ConvertCmpIfNecessary(Cond, DAG);
10618     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10619
10620     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10621         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10622       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10623                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10624       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10625         return DAG.getNOT(DL, Res, Res.getValueType());
10626       return Res;
10627     }
10628   }
10629
10630   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10631   // widen the cmov and push the truncate through. This avoids introducing a new
10632   // branch during isel and doesn't add any extensions.
10633   if (Op.getValueType() == MVT::i8 &&
10634       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10635     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10636     if (T1.getValueType() == T2.getValueType() &&
10637         // Blacklist CopyFromReg to avoid partial register stalls.
10638         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10639       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10640       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10641       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10642     }
10643   }
10644
10645   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10646   // condition is true.
10647   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10648   SDValue Ops[] = { Op2, Op1, CC, Cond };
10649   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10650 }
10651
10652 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10653   MVT VT = Op->getSimpleValueType(0);
10654   SDValue In = Op->getOperand(0);
10655   MVT InVT = In.getSimpleValueType();
10656   SDLoc dl(Op);
10657
10658   unsigned int NumElts = VT.getVectorNumElements();
10659   if (NumElts != 8 && NumElts != 16)
10660     return SDValue();
10661
10662   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10663     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10664
10665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10666   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10667
10668   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10669   Constant *C = ConstantInt::get(*DAG.getContext(),
10670     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10671
10672   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10673   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10674   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10675                           MachinePointerInfo::getConstantPool(),
10676                           false, false, false, Alignment);
10677   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10678   if (VT.is512BitVector())
10679     return Brcst;
10680   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10681 }
10682
10683 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10684                                 SelectionDAG &DAG) {
10685   MVT VT = Op->getSimpleValueType(0);
10686   SDValue In = Op->getOperand(0);
10687   MVT InVT = In.getSimpleValueType();
10688   SDLoc dl(Op);
10689
10690   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10691     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10692
10693   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10694       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10695       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10696     return SDValue();
10697
10698   if (Subtarget->hasInt256())
10699     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10700
10701   // Optimize vectors in AVX mode
10702   // Sign extend  v8i16 to v8i32 and
10703   //              v4i32 to v4i64
10704   //
10705   // Divide input vector into two parts
10706   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10707   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10708   // concat the vectors to original VT
10709
10710   unsigned NumElems = InVT.getVectorNumElements();
10711   SDValue Undef = DAG.getUNDEF(InVT);
10712
10713   SmallVector<int,8> ShufMask1(NumElems, -1);
10714   for (unsigned i = 0; i != NumElems/2; ++i)
10715     ShufMask1[i] = i;
10716
10717   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10718
10719   SmallVector<int,8> ShufMask2(NumElems, -1);
10720   for (unsigned i = 0; i != NumElems/2; ++i)
10721     ShufMask2[i] = i + NumElems/2;
10722
10723   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10724
10725   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10726                                 VT.getVectorNumElements()/2);
10727
10728   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10729   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10730
10731   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10732 }
10733
10734 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10735 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10736 // from the AND / OR.
10737 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10738   Opc = Op.getOpcode();
10739   if (Opc != ISD::OR && Opc != ISD::AND)
10740     return false;
10741   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10742           Op.getOperand(0).hasOneUse() &&
10743           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10744           Op.getOperand(1).hasOneUse());
10745 }
10746
10747 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10748 // 1 and that the SETCC node has a single use.
10749 static bool isXor1OfSetCC(SDValue Op) {
10750   if (Op.getOpcode() != ISD::XOR)
10751     return false;
10752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10753   if (N1C && N1C->getAPIntValue() == 1) {
10754     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10755       Op.getOperand(0).hasOneUse();
10756   }
10757   return false;
10758 }
10759
10760 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10761   bool addTest = true;
10762   SDValue Chain = Op.getOperand(0);
10763   SDValue Cond  = Op.getOperand(1);
10764   SDValue Dest  = Op.getOperand(2);
10765   SDLoc dl(Op);
10766   SDValue CC;
10767   bool Inverted = false;
10768
10769   if (Cond.getOpcode() == ISD::SETCC) {
10770     // Check for setcc([su]{add,sub,mul}o == 0).
10771     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10772         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10773         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10774         Cond.getOperand(0).getResNo() == 1 &&
10775         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10776          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10777          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10778          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10779          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10780          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10781       Inverted = true;
10782       Cond = Cond.getOperand(0);
10783     } else {
10784       SDValue NewCond = LowerSETCC(Cond, DAG);
10785       if (NewCond.getNode())
10786         Cond = NewCond;
10787     }
10788   }
10789 #if 0
10790   // FIXME: LowerXALUO doesn't handle these!!
10791   else if (Cond.getOpcode() == X86ISD::ADD  ||
10792            Cond.getOpcode() == X86ISD::SUB  ||
10793            Cond.getOpcode() == X86ISD::SMUL ||
10794            Cond.getOpcode() == X86ISD::UMUL)
10795     Cond = LowerXALUO(Cond, DAG);
10796 #endif
10797
10798   // Look pass (and (setcc_carry (cmp ...)), 1).
10799   if (Cond.getOpcode() == ISD::AND &&
10800       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10801     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10802     if (C && C->getAPIntValue() == 1)
10803       Cond = Cond.getOperand(0);
10804   }
10805
10806   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10807   // setting operand in place of the X86ISD::SETCC.
10808   unsigned CondOpcode = Cond.getOpcode();
10809   if (CondOpcode == X86ISD::SETCC ||
10810       CondOpcode == X86ISD::SETCC_CARRY) {
10811     CC = Cond.getOperand(0);
10812
10813     SDValue Cmp = Cond.getOperand(1);
10814     unsigned Opc = Cmp.getOpcode();
10815     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10816     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10817       Cond = Cmp;
10818       addTest = false;
10819     } else {
10820       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10821       default: break;
10822       case X86::COND_O:
10823       case X86::COND_B:
10824         // These can only come from an arithmetic instruction with overflow,
10825         // e.g. SADDO, UADDO.
10826         Cond = Cond.getNode()->getOperand(1);
10827         addTest = false;
10828         break;
10829       }
10830     }
10831   }
10832   CondOpcode = Cond.getOpcode();
10833   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10834       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10835       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10836        Cond.getOperand(0).getValueType() != MVT::i8)) {
10837     SDValue LHS = Cond.getOperand(0);
10838     SDValue RHS = Cond.getOperand(1);
10839     unsigned X86Opcode;
10840     unsigned X86Cond;
10841     SDVTList VTs;
10842     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10843     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10844     // X86ISD::INC).
10845     switch (CondOpcode) {
10846     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10847     case ISD::SADDO:
10848       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10849         if (C->isOne()) {
10850           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10851           break;
10852         }
10853       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10854     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10855     case ISD::SSUBO:
10856       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10857         if (C->isOne()) {
10858           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10859           break;
10860         }
10861       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10862     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10863     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10864     default: llvm_unreachable("unexpected overflowing operator");
10865     }
10866     if (Inverted)
10867       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10868     if (CondOpcode == ISD::UMULO)
10869       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10870                           MVT::i32);
10871     else
10872       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10873
10874     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10875
10876     if (CondOpcode == ISD::UMULO)
10877       Cond = X86Op.getValue(2);
10878     else
10879       Cond = X86Op.getValue(1);
10880
10881     CC = DAG.getConstant(X86Cond, MVT::i8);
10882     addTest = false;
10883   } else {
10884     unsigned CondOpc;
10885     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10886       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10887       if (CondOpc == ISD::OR) {
10888         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10889         // two branches instead of an explicit OR instruction with a
10890         // separate test.
10891         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10892             isX86LogicalCmp(Cmp)) {
10893           CC = Cond.getOperand(0).getOperand(0);
10894           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10895                               Chain, Dest, CC, Cmp);
10896           CC = Cond.getOperand(1).getOperand(0);
10897           Cond = Cmp;
10898           addTest = false;
10899         }
10900       } else { // ISD::AND
10901         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10902         // two branches instead of an explicit AND instruction with a
10903         // separate test. However, we only do this if this block doesn't
10904         // have a fall-through edge, because this requires an explicit
10905         // jmp when the condition is false.
10906         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10907             isX86LogicalCmp(Cmp) &&
10908             Op.getNode()->hasOneUse()) {
10909           X86::CondCode CCode =
10910             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10911           CCode = X86::GetOppositeBranchCondition(CCode);
10912           CC = DAG.getConstant(CCode, MVT::i8);
10913           SDNode *User = *Op.getNode()->use_begin();
10914           // Look for an unconditional branch following this conditional branch.
10915           // We need this because we need to reverse the successors in order
10916           // to implement FCMP_OEQ.
10917           if (User->getOpcode() == ISD::BR) {
10918             SDValue FalseBB = User->getOperand(1);
10919             SDNode *NewBR =
10920               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10921             assert(NewBR == User);
10922             (void)NewBR;
10923             Dest = FalseBB;
10924
10925             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10926                                 Chain, Dest, CC, Cmp);
10927             X86::CondCode CCode =
10928               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10929             CCode = X86::GetOppositeBranchCondition(CCode);
10930             CC = DAG.getConstant(CCode, MVT::i8);
10931             Cond = Cmp;
10932             addTest = false;
10933           }
10934         }
10935       }
10936     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10937       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10938       // It should be transformed during dag combiner except when the condition
10939       // is set by a arithmetics with overflow node.
10940       X86::CondCode CCode =
10941         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10942       CCode = X86::GetOppositeBranchCondition(CCode);
10943       CC = DAG.getConstant(CCode, MVT::i8);
10944       Cond = Cond.getOperand(0).getOperand(1);
10945       addTest = false;
10946     } else if (Cond.getOpcode() == ISD::SETCC &&
10947                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10948       // For FCMP_OEQ, we can emit
10949       // two branches instead of an explicit AND instruction with a
10950       // separate test. However, we only do this if this block doesn't
10951       // have a fall-through edge, because this requires an explicit
10952       // jmp when the condition is false.
10953       if (Op.getNode()->hasOneUse()) {
10954         SDNode *User = *Op.getNode()->use_begin();
10955         // Look for an unconditional branch following this conditional branch.
10956         // We need this because we need to reverse the successors in order
10957         // to implement FCMP_OEQ.
10958         if (User->getOpcode() == ISD::BR) {
10959           SDValue FalseBB = User->getOperand(1);
10960           SDNode *NewBR =
10961             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10962           assert(NewBR == User);
10963           (void)NewBR;
10964           Dest = FalseBB;
10965
10966           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10967                                     Cond.getOperand(0), Cond.getOperand(1));
10968           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10969           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10970           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10971                               Chain, Dest, CC, Cmp);
10972           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10973           Cond = Cmp;
10974           addTest = false;
10975         }
10976       }
10977     } else if (Cond.getOpcode() == ISD::SETCC &&
10978                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10979       // For FCMP_UNE, we can emit
10980       // two branches instead of an explicit AND instruction with a
10981       // separate test. However, we only do this if this block doesn't
10982       // have a fall-through edge, because this requires an explicit
10983       // jmp when the condition is false.
10984       if (Op.getNode()->hasOneUse()) {
10985         SDNode *User = *Op.getNode()->use_begin();
10986         // Look for an unconditional branch following this conditional branch.
10987         // We need this because we need to reverse the successors in order
10988         // to implement FCMP_UNE.
10989         if (User->getOpcode() == ISD::BR) {
10990           SDValue FalseBB = User->getOperand(1);
10991           SDNode *NewBR =
10992             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10993           assert(NewBR == User);
10994           (void)NewBR;
10995
10996           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10997                                     Cond.getOperand(0), Cond.getOperand(1));
10998           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10999           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11000           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11001                               Chain, Dest, CC, Cmp);
11002           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11003           Cond = Cmp;
11004           addTest = false;
11005           Dest = FalseBB;
11006         }
11007       }
11008     }
11009   }
11010
11011   if (addTest) {
11012     // Look pass the truncate if the high bits are known zero.
11013     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11014         Cond = Cond.getOperand(0);
11015
11016     // We know the result of AND is compared against zero. Try to match
11017     // it to BT.
11018     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11019       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11020       if (NewSetCC.getNode()) {
11021         CC = NewSetCC.getOperand(0);
11022         Cond = NewSetCC.getOperand(1);
11023         addTest = false;
11024       }
11025     }
11026   }
11027
11028   if (addTest) {
11029     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11030     Cond = EmitTest(Cond, X86::COND_NE, DAG);
11031   }
11032   Cond = ConvertCmpIfNecessary(Cond, DAG);
11033   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11034                      Chain, Dest, CC, Cond);
11035 }
11036
11037 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11038 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11039 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11040 // that the guard pages used by the OS virtual memory manager are allocated in
11041 // correct sequence.
11042 SDValue
11043 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11044                                            SelectionDAG &DAG) const {
11045   assert((Subtarget->isOSWindows() ||
11046           getTargetMachine().Options.EnableSegmentedStacks) &&
11047          "This should be used only on Windows targets or when segmented stacks "
11048          "are being used");
11049   assert(!Subtarget->isTargetMacho() && "Not implemented");
11050   SDLoc dl(Op);
11051
11052   // Get the inputs.
11053   SDValue Chain = Op.getOperand(0);
11054   SDValue Size  = Op.getOperand(1);
11055   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11056   EVT VT = Op.getNode()->getValueType(0);
11057
11058   bool Is64Bit = Subtarget->is64Bit();
11059   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11060
11061   if (getTargetMachine().Options.EnableSegmentedStacks) {
11062     MachineFunction &MF = DAG.getMachineFunction();
11063     MachineRegisterInfo &MRI = MF.getRegInfo();
11064
11065     if (Is64Bit) {
11066       // The 64 bit implementation of segmented stacks needs to clobber both r10
11067       // r11. This makes it impossible to use it along with nested parameters.
11068       const Function *F = MF.getFunction();
11069
11070       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11071            I != E; ++I)
11072         if (I->hasNestAttr())
11073           report_fatal_error("Cannot use segmented stacks with functions that "
11074                              "have nested arguments.");
11075     }
11076
11077     const TargetRegisterClass *AddrRegClass =
11078       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11079     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11080     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11081     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11082                                 DAG.getRegister(Vreg, SPTy));
11083     SDValue Ops1[2] = { Value, Chain };
11084     return DAG.getMergeValues(Ops1, 2, dl);
11085   } else {
11086     SDValue Flag;
11087     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11088
11089     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11090     Flag = Chain.getValue(1);
11091     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11092
11093     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11094
11095     const X86RegisterInfo *RegInfo =
11096       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11097     unsigned SPReg = RegInfo->getStackRegister();
11098     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11099     Chain = SP.getValue(1);
11100
11101     if (Align) {
11102       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11103                        DAG.getConstant(-(uint64_t)Align, VT));
11104       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11105     }
11106
11107     SDValue Ops1[2] = { SP, Chain };
11108     return DAG.getMergeValues(Ops1, 2, dl);
11109   }
11110 }
11111
11112 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11113   MachineFunction &MF = DAG.getMachineFunction();
11114   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11115
11116   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11117   SDLoc DL(Op);
11118
11119   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11120     // vastart just stores the address of the VarArgsFrameIndex slot into the
11121     // memory location argument.
11122     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11123                                    getPointerTy());
11124     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11125                         MachinePointerInfo(SV), false, false, 0);
11126   }
11127
11128   // __va_list_tag:
11129   //   gp_offset         (0 - 6 * 8)
11130   //   fp_offset         (48 - 48 + 8 * 16)
11131   //   overflow_arg_area (point to parameters coming in memory).
11132   //   reg_save_area
11133   SmallVector<SDValue, 8> MemOps;
11134   SDValue FIN = Op.getOperand(1);
11135   // Store gp_offset
11136   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11137                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11138                                                MVT::i32),
11139                                FIN, MachinePointerInfo(SV), false, false, 0);
11140   MemOps.push_back(Store);
11141
11142   // Store fp_offset
11143   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11144                     FIN, DAG.getIntPtrConstant(4));
11145   Store = DAG.getStore(Op.getOperand(0), DL,
11146                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11147                                        MVT::i32),
11148                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11149   MemOps.push_back(Store);
11150
11151   // Store ptr to overflow_arg_area
11152   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11153                     FIN, DAG.getIntPtrConstant(4));
11154   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11155                                     getPointerTy());
11156   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11157                        MachinePointerInfo(SV, 8),
11158                        false, false, 0);
11159   MemOps.push_back(Store);
11160
11161   // Store ptr to reg_save_area.
11162   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11163                     FIN, DAG.getIntPtrConstant(8));
11164   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11165                                     getPointerTy());
11166   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11167                        MachinePointerInfo(SV, 16), false, false, 0);
11168   MemOps.push_back(Store);
11169   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11170                      &MemOps[0], MemOps.size());
11171 }
11172
11173 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11174   assert(Subtarget->is64Bit() &&
11175          "LowerVAARG only handles 64-bit va_arg!");
11176   assert((Subtarget->isTargetLinux() ||
11177           Subtarget->isTargetDarwin()) &&
11178           "Unhandled target in LowerVAARG");
11179   assert(Op.getNode()->getNumOperands() == 4);
11180   SDValue Chain = Op.getOperand(0);
11181   SDValue SrcPtr = Op.getOperand(1);
11182   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11183   unsigned Align = Op.getConstantOperandVal(3);
11184   SDLoc dl(Op);
11185
11186   EVT ArgVT = Op.getNode()->getValueType(0);
11187   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11188   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11189   uint8_t ArgMode;
11190
11191   // Decide which area this value should be read from.
11192   // TODO: Implement the AMD64 ABI in its entirety. This simple
11193   // selection mechanism works only for the basic types.
11194   if (ArgVT == MVT::f80) {
11195     llvm_unreachable("va_arg for f80 not yet implemented");
11196   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11197     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11198   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11199     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11200   } else {
11201     llvm_unreachable("Unhandled argument type in LowerVAARG");
11202   }
11203
11204   if (ArgMode == 2) {
11205     // Sanity Check: Make sure using fp_offset makes sense.
11206     assert(!getTargetMachine().Options.UseSoftFloat &&
11207            !(DAG.getMachineFunction()
11208                 .getFunction()->getAttributes()
11209                 .hasAttribute(AttributeSet::FunctionIndex,
11210                               Attribute::NoImplicitFloat)) &&
11211            Subtarget->hasSSE1());
11212   }
11213
11214   // Insert VAARG_64 node into the DAG
11215   // VAARG_64 returns two values: Variable Argument Address, Chain
11216   SmallVector<SDValue, 11> InstOps;
11217   InstOps.push_back(Chain);
11218   InstOps.push_back(SrcPtr);
11219   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11220   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11221   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11222   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11223   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11224                                           VTs, &InstOps[0], InstOps.size(),
11225                                           MVT::i64,
11226                                           MachinePointerInfo(SV),
11227                                           /*Align=*/0,
11228                                           /*Volatile=*/false,
11229                                           /*ReadMem=*/true,
11230                                           /*WriteMem=*/true);
11231   Chain = VAARG.getValue(1);
11232
11233   // Load the next argument and return it
11234   return DAG.getLoad(ArgVT, dl,
11235                      Chain,
11236                      VAARG,
11237                      MachinePointerInfo(),
11238                      false, false, false, 0);
11239 }
11240
11241 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11242                            SelectionDAG &DAG) {
11243   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11244   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11245   SDValue Chain = Op.getOperand(0);
11246   SDValue DstPtr = Op.getOperand(1);
11247   SDValue SrcPtr = Op.getOperand(2);
11248   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11249   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11250   SDLoc DL(Op);
11251
11252   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11253                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11254                        false,
11255                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11256 }
11257
11258 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11259 // amount is a constant. Takes immediate version of shift as input.
11260 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11261                                           SDValue SrcOp, uint64_t ShiftAmt,
11262                                           SelectionDAG &DAG) {
11263   MVT ElementType = VT.getVectorElementType();
11264
11265   // Check for ShiftAmt >= element width
11266   if (ShiftAmt >= ElementType.getSizeInBits()) {
11267     if (Opc == X86ISD::VSRAI)
11268       ShiftAmt = ElementType.getSizeInBits() - 1;
11269     else
11270       return DAG.getConstant(0, VT);
11271   }
11272
11273   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11274          && "Unknown target vector shift-by-constant node");
11275
11276   // Fold this packed vector shift into a build vector if SrcOp is a
11277   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11278   if (VT == SrcOp.getSimpleValueType() &&
11279       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11280     SmallVector<SDValue, 8> Elts;
11281     unsigned NumElts = SrcOp->getNumOperands();
11282     ConstantSDNode *ND;
11283
11284     switch(Opc) {
11285     default: llvm_unreachable(0);
11286     case X86ISD::VSHLI:
11287       for (unsigned i=0; i!=NumElts; ++i) {
11288         SDValue CurrentOp = SrcOp->getOperand(i);
11289         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11290           Elts.push_back(CurrentOp);
11291           continue;
11292         }
11293         ND = cast<ConstantSDNode>(CurrentOp);
11294         const APInt &C = ND->getAPIntValue();
11295         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11296       }
11297       break;
11298     case X86ISD::VSRLI:
11299       for (unsigned i=0; i!=NumElts; ++i) {
11300         SDValue CurrentOp = SrcOp->getOperand(i);
11301         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11302           Elts.push_back(CurrentOp);
11303           continue;
11304         }
11305         ND = cast<ConstantSDNode>(CurrentOp);
11306         const APInt &C = ND->getAPIntValue();
11307         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11308       }
11309       break;
11310     case X86ISD::VSRAI:
11311       for (unsigned i=0; i!=NumElts; ++i) {
11312         SDValue CurrentOp = SrcOp->getOperand(i);
11313         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11314           Elts.push_back(CurrentOp);
11315           continue;
11316         }
11317         ND = cast<ConstantSDNode>(CurrentOp);
11318         const APInt &C = ND->getAPIntValue();
11319         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11320       }
11321       break;
11322     }
11323
11324     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11325   }
11326
11327   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11328 }
11329
11330 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11331 // may or may not be a constant. Takes immediate version of shift as input.
11332 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11333                                    SDValue SrcOp, SDValue ShAmt,
11334                                    SelectionDAG &DAG) {
11335   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11336
11337   // Catch shift-by-constant.
11338   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11339     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11340                                       CShAmt->getZExtValue(), DAG);
11341
11342   // Change opcode to non-immediate version
11343   switch (Opc) {
11344     default: llvm_unreachable("Unknown target vector shift node");
11345     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11346     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11347     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11348   }
11349
11350   // Need to build a vector containing shift amount
11351   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11352   SDValue ShOps[4];
11353   ShOps[0] = ShAmt;
11354   ShOps[1] = DAG.getConstant(0, MVT::i32);
11355   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11356   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11357
11358   // The return type has to be a 128-bit type with the same element
11359   // type as the input type.
11360   MVT EltVT = VT.getVectorElementType();
11361   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11362
11363   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11364   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11365 }
11366
11367 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11368   SDLoc dl(Op);
11369   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11370   switch (IntNo) {
11371   default: return SDValue();    // Don't custom lower most intrinsics.
11372   // Comparison intrinsics.
11373   case Intrinsic::x86_sse_comieq_ss:
11374   case Intrinsic::x86_sse_comilt_ss:
11375   case Intrinsic::x86_sse_comile_ss:
11376   case Intrinsic::x86_sse_comigt_ss:
11377   case Intrinsic::x86_sse_comige_ss:
11378   case Intrinsic::x86_sse_comineq_ss:
11379   case Intrinsic::x86_sse_ucomieq_ss:
11380   case Intrinsic::x86_sse_ucomilt_ss:
11381   case Intrinsic::x86_sse_ucomile_ss:
11382   case Intrinsic::x86_sse_ucomigt_ss:
11383   case Intrinsic::x86_sse_ucomige_ss:
11384   case Intrinsic::x86_sse_ucomineq_ss:
11385   case Intrinsic::x86_sse2_comieq_sd:
11386   case Intrinsic::x86_sse2_comilt_sd:
11387   case Intrinsic::x86_sse2_comile_sd:
11388   case Intrinsic::x86_sse2_comigt_sd:
11389   case Intrinsic::x86_sse2_comige_sd:
11390   case Intrinsic::x86_sse2_comineq_sd:
11391   case Intrinsic::x86_sse2_ucomieq_sd:
11392   case Intrinsic::x86_sse2_ucomilt_sd:
11393   case Intrinsic::x86_sse2_ucomile_sd:
11394   case Intrinsic::x86_sse2_ucomigt_sd:
11395   case Intrinsic::x86_sse2_ucomige_sd:
11396   case Intrinsic::x86_sse2_ucomineq_sd: {
11397     unsigned Opc;
11398     ISD::CondCode CC;
11399     switch (IntNo) {
11400     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11401     case Intrinsic::x86_sse_comieq_ss:
11402     case Intrinsic::x86_sse2_comieq_sd:
11403       Opc = X86ISD::COMI;
11404       CC = ISD::SETEQ;
11405       break;
11406     case Intrinsic::x86_sse_comilt_ss:
11407     case Intrinsic::x86_sse2_comilt_sd:
11408       Opc = X86ISD::COMI;
11409       CC = ISD::SETLT;
11410       break;
11411     case Intrinsic::x86_sse_comile_ss:
11412     case Intrinsic::x86_sse2_comile_sd:
11413       Opc = X86ISD::COMI;
11414       CC = ISD::SETLE;
11415       break;
11416     case Intrinsic::x86_sse_comigt_ss:
11417     case Intrinsic::x86_sse2_comigt_sd:
11418       Opc = X86ISD::COMI;
11419       CC = ISD::SETGT;
11420       break;
11421     case Intrinsic::x86_sse_comige_ss:
11422     case Intrinsic::x86_sse2_comige_sd:
11423       Opc = X86ISD::COMI;
11424       CC = ISD::SETGE;
11425       break;
11426     case Intrinsic::x86_sse_comineq_ss:
11427     case Intrinsic::x86_sse2_comineq_sd:
11428       Opc = X86ISD::COMI;
11429       CC = ISD::SETNE;
11430       break;
11431     case Intrinsic::x86_sse_ucomieq_ss:
11432     case Intrinsic::x86_sse2_ucomieq_sd:
11433       Opc = X86ISD::UCOMI;
11434       CC = ISD::SETEQ;
11435       break;
11436     case Intrinsic::x86_sse_ucomilt_ss:
11437     case Intrinsic::x86_sse2_ucomilt_sd:
11438       Opc = X86ISD::UCOMI;
11439       CC = ISD::SETLT;
11440       break;
11441     case Intrinsic::x86_sse_ucomile_ss:
11442     case Intrinsic::x86_sse2_ucomile_sd:
11443       Opc = X86ISD::UCOMI;
11444       CC = ISD::SETLE;
11445       break;
11446     case Intrinsic::x86_sse_ucomigt_ss:
11447     case Intrinsic::x86_sse2_ucomigt_sd:
11448       Opc = X86ISD::UCOMI;
11449       CC = ISD::SETGT;
11450       break;
11451     case Intrinsic::x86_sse_ucomige_ss:
11452     case Intrinsic::x86_sse2_ucomige_sd:
11453       Opc = X86ISD::UCOMI;
11454       CC = ISD::SETGE;
11455       break;
11456     case Intrinsic::x86_sse_ucomineq_ss:
11457     case Intrinsic::x86_sse2_ucomineq_sd:
11458       Opc = X86ISD::UCOMI;
11459       CC = ISD::SETNE;
11460       break;
11461     }
11462
11463     SDValue LHS = Op.getOperand(1);
11464     SDValue RHS = Op.getOperand(2);
11465     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11466     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11467     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11468     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11469                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11470     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11471   }
11472
11473   // Arithmetic intrinsics.
11474   case Intrinsic::x86_sse2_pmulu_dq:
11475   case Intrinsic::x86_avx2_pmulu_dq:
11476     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11477                        Op.getOperand(1), Op.getOperand(2));
11478
11479   // SSE2/AVX2 sub with unsigned saturation intrinsics
11480   case Intrinsic::x86_sse2_psubus_b:
11481   case Intrinsic::x86_sse2_psubus_w:
11482   case Intrinsic::x86_avx2_psubus_b:
11483   case Intrinsic::x86_avx2_psubus_w:
11484     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11485                        Op.getOperand(1), Op.getOperand(2));
11486
11487   // SSE3/AVX horizontal add/sub intrinsics
11488   case Intrinsic::x86_sse3_hadd_ps:
11489   case Intrinsic::x86_sse3_hadd_pd:
11490   case Intrinsic::x86_avx_hadd_ps_256:
11491   case Intrinsic::x86_avx_hadd_pd_256:
11492   case Intrinsic::x86_sse3_hsub_ps:
11493   case Intrinsic::x86_sse3_hsub_pd:
11494   case Intrinsic::x86_avx_hsub_ps_256:
11495   case Intrinsic::x86_avx_hsub_pd_256:
11496   case Intrinsic::x86_ssse3_phadd_w_128:
11497   case Intrinsic::x86_ssse3_phadd_d_128:
11498   case Intrinsic::x86_avx2_phadd_w:
11499   case Intrinsic::x86_avx2_phadd_d:
11500   case Intrinsic::x86_ssse3_phsub_w_128:
11501   case Intrinsic::x86_ssse3_phsub_d_128:
11502   case Intrinsic::x86_avx2_phsub_w:
11503   case Intrinsic::x86_avx2_phsub_d: {
11504     unsigned Opcode;
11505     switch (IntNo) {
11506     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11507     case Intrinsic::x86_sse3_hadd_ps:
11508     case Intrinsic::x86_sse3_hadd_pd:
11509     case Intrinsic::x86_avx_hadd_ps_256:
11510     case Intrinsic::x86_avx_hadd_pd_256:
11511       Opcode = X86ISD::FHADD;
11512       break;
11513     case Intrinsic::x86_sse3_hsub_ps:
11514     case Intrinsic::x86_sse3_hsub_pd:
11515     case Intrinsic::x86_avx_hsub_ps_256:
11516     case Intrinsic::x86_avx_hsub_pd_256:
11517       Opcode = X86ISD::FHSUB;
11518       break;
11519     case Intrinsic::x86_ssse3_phadd_w_128:
11520     case Intrinsic::x86_ssse3_phadd_d_128:
11521     case Intrinsic::x86_avx2_phadd_w:
11522     case Intrinsic::x86_avx2_phadd_d:
11523       Opcode = X86ISD::HADD;
11524       break;
11525     case Intrinsic::x86_ssse3_phsub_w_128:
11526     case Intrinsic::x86_ssse3_phsub_d_128:
11527     case Intrinsic::x86_avx2_phsub_w:
11528     case Intrinsic::x86_avx2_phsub_d:
11529       Opcode = X86ISD::HSUB;
11530       break;
11531     }
11532     return DAG.getNode(Opcode, dl, Op.getValueType(),
11533                        Op.getOperand(1), Op.getOperand(2));
11534   }
11535
11536   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11537   case Intrinsic::x86_sse2_pmaxu_b:
11538   case Intrinsic::x86_sse41_pmaxuw:
11539   case Intrinsic::x86_sse41_pmaxud:
11540   case Intrinsic::x86_avx2_pmaxu_b:
11541   case Intrinsic::x86_avx2_pmaxu_w:
11542   case Intrinsic::x86_avx2_pmaxu_d:
11543   case Intrinsic::x86_sse2_pminu_b:
11544   case Intrinsic::x86_sse41_pminuw:
11545   case Intrinsic::x86_sse41_pminud:
11546   case Intrinsic::x86_avx2_pminu_b:
11547   case Intrinsic::x86_avx2_pminu_w:
11548   case Intrinsic::x86_avx2_pminu_d:
11549   case Intrinsic::x86_sse41_pmaxsb:
11550   case Intrinsic::x86_sse2_pmaxs_w:
11551   case Intrinsic::x86_sse41_pmaxsd:
11552   case Intrinsic::x86_avx2_pmaxs_b:
11553   case Intrinsic::x86_avx2_pmaxs_w:
11554   case Intrinsic::x86_avx2_pmaxs_d:
11555   case Intrinsic::x86_sse41_pminsb:
11556   case Intrinsic::x86_sse2_pmins_w:
11557   case Intrinsic::x86_sse41_pminsd:
11558   case Intrinsic::x86_avx2_pmins_b:
11559   case Intrinsic::x86_avx2_pmins_w:
11560   case Intrinsic::x86_avx2_pmins_d: {
11561     unsigned Opcode;
11562     switch (IntNo) {
11563     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11564     case Intrinsic::x86_sse2_pmaxu_b:
11565     case Intrinsic::x86_sse41_pmaxuw:
11566     case Intrinsic::x86_sse41_pmaxud:
11567     case Intrinsic::x86_avx2_pmaxu_b:
11568     case Intrinsic::x86_avx2_pmaxu_w:
11569     case Intrinsic::x86_avx2_pmaxu_d:
11570       Opcode = X86ISD::UMAX;
11571       break;
11572     case Intrinsic::x86_sse2_pminu_b:
11573     case Intrinsic::x86_sse41_pminuw:
11574     case Intrinsic::x86_sse41_pminud:
11575     case Intrinsic::x86_avx2_pminu_b:
11576     case Intrinsic::x86_avx2_pminu_w:
11577     case Intrinsic::x86_avx2_pminu_d:
11578       Opcode = X86ISD::UMIN;
11579       break;
11580     case Intrinsic::x86_sse41_pmaxsb:
11581     case Intrinsic::x86_sse2_pmaxs_w:
11582     case Intrinsic::x86_sse41_pmaxsd:
11583     case Intrinsic::x86_avx2_pmaxs_b:
11584     case Intrinsic::x86_avx2_pmaxs_w:
11585     case Intrinsic::x86_avx2_pmaxs_d:
11586       Opcode = X86ISD::SMAX;
11587       break;
11588     case Intrinsic::x86_sse41_pminsb:
11589     case Intrinsic::x86_sse2_pmins_w:
11590     case Intrinsic::x86_sse41_pminsd:
11591     case Intrinsic::x86_avx2_pmins_b:
11592     case Intrinsic::x86_avx2_pmins_w:
11593     case Intrinsic::x86_avx2_pmins_d:
11594       Opcode = X86ISD::SMIN;
11595       break;
11596     }
11597     return DAG.getNode(Opcode, dl, Op.getValueType(),
11598                        Op.getOperand(1), Op.getOperand(2));
11599   }
11600
11601   // SSE/SSE2/AVX floating point max/min intrinsics.
11602   case Intrinsic::x86_sse_max_ps:
11603   case Intrinsic::x86_sse2_max_pd:
11604   case Intrinsic::x86_avx_max_ps_256:
11605   case Intrinsic::x86_avx_max_pd_256:
11606   case Intrinsic::x86_sse_min_ps:
11607   case Intrinsic::x86_sse2_min_pd:
11608   case Intrinsic::x86_avx_min_ps_256:
11609   case Intrinsic::x86_avx_min_pd_256: {
11610     unsigned Opcode;
11611     switch (IntNo) {
11612     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11613     case Intrinsic::x86_sse_max_ps:
11614     case Intrinsic::x86_sse2_max_pd:
11615     case Intrinsic::x86_avx_max_ps_256:
11616     case Intrinsic::x86_avx_max_pd_256:
11617       Opcode = X86ISD::FMAX;
11618       break;
11619     case Intrinsic::x86_sse_min_ps:
11620     case Intrinsic::x86_sse2_min_pd:
11621     case Intrinsic::x86_avx_min_ps_256:
11622     case Intrinsic::x86_avx_min_pd_256:
11623       Opcode = X86ISD::FMIN;
11624       break;
11625     }
11626     return DAG.getNode(Opcode, dl, Op.getValueType(),
11627                        Op.getOperand(1), Op.getOperand(2));
11628   }
11629
11630   // AVX2 variable shift intrinsics
11631   case Intrinsic::x86_avx2_psllv_d:
11632   case Intrinsic::x86_avx2_psllv_q:
11633   case Intrinsic::x86_avx2_psllv_d_256:
11634   case Intrinsic::x86_avx2_psllv_q_256:
11635   case Intrinsic::x86_avx2_psrlv_d:
11636   case Intrinsic::x86_avx2_psrlv_q:
11637   case Intrinsic::x86_avx2_psrlv_d_256:
11638   case Intrinsic::x86_avx2_psrlv_q_256:
11639   case Intrinsic::x86_avx2_psrav_d:
11640   case Intrinsic::x86_avx2_psrav_d_256: {
11641     unsigned Opcode;
11642     switch (IntNo) {
11643     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11644     case Intrinsic::x86_avx2_psllv_d:
11645     case Intrinsic::x86_avx2_psllv_q:
11646     case Intrinsic::x86_avx2_psllv_d_256:
11647     case Intrinsic::x86_avx2_psllv_q_256:
11648       Opcode = ISD::SHL;
11649       break;
11650     case Intrinsic::x86_avx2_psrlv_d:
11651     case Intrinsic::x86_avx2_psrlv_q:
11652     case Intrinsic::x86_avx2_psrlv_d_256:
11653     case Intrinsic::x86_avx2_psrlv_q_256:
11654       Opcode = ISD::SRL;
11655       break;
11656     case Intrinsic::x86_avx2_psrav_d:
11657     case Intrinsic::x86_avx2_psrav_d_256:
11658       Opcode = ISD::SRA;
11659       break;
11660     }
11661     return DAG.getNode(Opcode, dl, Op.getValueType(),
11662                        Op.getOperand(1), Op.getOperand(2));
11663   }
11664
11665   case Intrinsic::x86_ssse3_pshuf_b_128:
11666   case Intrinsic::x86_avx2_pshuf_b:
11667     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11668                        Op.getOperand(1), Op.getOperand(2));
11669
11670   case Intrinsic::x86_ssse3_psign_b_128:
11671   case Intrinsic::x86_ssse3_psign_w_128:
11672   case Intrinsic::x86_ssse3_psign_d_128:
11673   case Intrinsic::x86_avx2_psign_b:
11674   case Intrinsic::x86_avx2_psign_w:
11675   case Intrinsic::x86_avx2_psign_d:
11676     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11677                        Op.getOperand(1), Op.getOperand(2));
11678
11679   case Intrinsic::x86_sse41_insertps:
11680     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11681                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11682
11683   case Intrinsic::x86_avx_vperm2f128_ps_256:
11684   case Intrinsic::x86_avx_vperm2f128_pd_256:
11685   case Intrinsic::x86_avx_vperm2f128_si_256:
11686   case Intrinsic::x86_avx2_vperm2i128:
11687     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11688                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11689
11690   case Intrinsic::x86_avx2_permd:
11691   case Intrinsic::x86_avx2_permps:
11692     // Operands intentionally swapped. Mask is last operand to intrinsic,
11693     // but second operand for node/instruction.
11694     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11695                        Op.getOperand(2), Op.getOperand(1));
11696
11697   case Intrinsic::x86_sse_sqrt_ps:
11698   case Intrinsic::x86_sse2_sqrt_pd:
11699   case Intrinsic::x86_avx_sqrt_ps_256:
11700   case Intrinsic::x86_avx_sqrt_pd_256:
11701     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11702
11703   // ptest and testp intrinsics. The intrinsic these come from are designed to
11704   // return an integer value, not just an instruction so lower it to the ptest
11705   // or testp pattern and a setcc for the result.
11706   case Intrinsic::x86_sse41_ptestz:
11707   case Intrinsic::x86_sse41_ptestc:
11708   case Intrinsic::x86_sse41_ptestnzc:
11709   case Intrinsic::x86_avx_ptestz_256:
11710   case Intrinsic::x86_avx_ptestc_256:
11711   case Intrinsic::x86_avx_ptestnzc_256:
11712   case Intrinsic::x86_avx_vtestz_ps:
11713   case Intrinsic::x86_avx_vtestc_ps:
11714   case Intrinsic::x86_avx_vtestnzc_ps:
11715   case Intrinsic::x86_avx_vtestz_pd:
11716   case Intrinsic::x86_avx_vtestc_pd:
11717   case Intrinsic::x86_avx_vtestnzc_pd:
11718   case Intrinsic::x86_avx_vtestz_ps_256:
11719   case Intrinsic::x86_avx_vtestc_ps_256:
11720   case Intrinsic::x86_avx_vtestnzc_ps_256:
11721   case Intrinsic::x86_avx_vtestz_pd_256:
11722   case Intrinsic::x86_avx_vtestc_pd_256:
11723   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11724     bool IsTestPacked = false;
11725     unsigned X86CC;
11726     switch (IntNo) {
11727     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11728     case Intrinsic::x86_avx_vtestz_ps:
11729     case Intrinsic::x86_avx_vtestz_pd:
11730     case Intrinsic::x86_avx_vtestz_ps_256:
11731     case Intrinsic::x86_avx_vtestz_pd_256:
11732       IsTestPacked = true; // Fallthrough
11733     case Intrinsic::x86_sse41_ptestz:
11734     case Intrinsic::x86_avx_ptestz_256:
11735       // ZF = 1
11736       X86CC = X86::COND_E;
11737       break;
11738     case Intrinsic::x86_avx_vtestc_ps:
11739     case Intrinsic::x86_avx_vtestc_pd:
11740     case Intrinsic::x86_avx_vtestc_ps_256:
11741     case Intrinsic::x86_avx_vtestc_pd_256:
11742       IsTestPacked = true; // Fallthrough
11743     case Intrinsic::x86_sse41_ptestc:
11744     case Intrinsic::x86_avx_ptestc_256:
11745       // CF = 1
11746       X86CC = X86::COND_B;
11747       break;
11748     case Intrinsic::x86_avx_vtestnzc_ps:
11749     case Intrinsic::x86_avx_vtestnzc_pd:
11750     case Intrinsic::x86_avx_vtestnzc_ps_256:
11751     case Intrinsic::x86_avx_vtestnzc_pd_256:
11752       IsTestPacked = true; // Fallthrough
11753     case Intrinsic::x86_sse41_ptestnzc:
11754     case Intrinsic::x86_avx_ptestnzc_256:
11755       // ZF and CF = 0
11756       X86CC = X86::COND_A;
11757       break;
11758     }
11759
11760     SDValue LHS = Op.getOperand(1);
11761     SDValue RHS = Op.getOperand(2);
11762     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11763     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11764     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11765     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11766     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11767   }
11768   case Intrinsic::x86_avx512_kortestz_w:
11769   case Intrinsic::x86_avx512_kortestc_w: {
11770     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11771     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11772     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11773     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11774     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11775     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11776     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11777   }
11778
11779   // SSE/AVX shift intrinsics
11780   case Intrinsic::x86_sse2_psll_w:
11781   case Intrinsic::x86_sse2_psll_d:
11782   case Intrinsic::x86_sse2_psll_q:
11783   case Intrinsic::x86_avx2_psll_w:
11784   case Intrinsic::x86_avx2_psll_d:
11785   case Intrinsic::x86_avx2_psll_q:
11786   case Intrinsic::x86_sse2_psrl_w:
11787   case Intrinsic::x86_sse2_psrl_d:
11788   case Intrinsic::x86_sse2_psrl_q:
11789   case Intrinsic::x86_avx2_psrl_w:
11790   case Intrinsic::x86_avx2_psrl_d:
11791   case Intrinsic::x86_avx2_psrl_q:
11792   case Intrinsic::x86_sse2_psra_w:
11793   case Intrinsic::x86_sse2_psra_d:
11794   case Intrinsic::x86_avx2_psra_w:
11795   case Intrinsic::x86_avx2_psra_d: {
11796     unsigned Opcode;
11797     switch (IntNo) {
11798     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11799     case Intrinsic::x86_sse2_psll_w:
11800     case Intrinsic::x86_sse2_psll_d:
11801     case Intrinsic::x86_sse2_psll_q:
11802     case Intrinsic::x86_avx2_psll_w:
11803     case Intrinsic::x86_avx2_psll_d:
11804     case Intrinsic::x86_avx2_psll_q:
11805       Opcode = X86ISD::VSHL;
11806       break;
11807     case Intrinsic::x86_sse2_psrl_w:
11808     case Intrinsic::x86_sse2_psrl_d:
11809     case Intrinsic::x86_sse2_psrl_q:
11810     case Intrinsic::x86_avx2_psrl_w:
11811     case Intrinsic::x86_avx2_psrl_d:
11812     case Intrinsic::x86_avx2_psrl_q:
11813       Opcode = X86ISD::VSRL;
11814       break;
11815     case Intrinsic::x86_sse2_psra_w:
11816     case Intrinsic::x86_sse2_psra_d:
11817     case Intrinsic::x86_avx2_psra_w:
11818     case Intrinsic::x86_avx2_psra_d:
11819       Opcode = X86ISD::VSRA;
11820       break;
11821     }
11822     return DAG.getNode(Opcode, dl, Op.getValueType(),
11823                        Op.getOperand(1), Op.getOperand(2));
11824   }
11825
11826   // SSE/AVX immediate shift intrinsics
11827   case Intrinsic::x86_sse2_pslli_w:
11828   case Intrinsic::x86_sse2_pslli_d:
11829   case Intrinsic::x86_sse2_pslli_q:
11830   case Intrinsic::x86_avx2_pslli_w:
11831   case Intrinsic::x86_avx2_pslli_d:
11832   case Intrinsic::x86_avx2_pslli_q:
11833   case Intrinsic::x86_sse2_psrli_w:
11834   case Intrinsic::x86_sse2_psrli_d:
11835   case Intrinsic::x86_sse2_psrli_q:
11836   case Intrinsic::x86_avx2_psrli_w:
11837   case Intrinsic::x86_avx2_psrli_d:
11838   case Intrinsic::x86_avx2_psrli_q:
11839   case Intrinsic::x86_sse2_psrai_w:
11840   case Intrinsic::x86_sse2_psrai_d:
11841   case Intrinsic::x86_avx2_psrai_w:
11842   case Intrinsic::x86_avx2_psrai_d: {
11843     unsigned Opcode;
11844     switch (IntNo) {
11845     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11846     case Intrinsic::x86_sse2_pslli_w:
11847     case Intrinsic::x86_sse2_pslli_d:
11848     case Intrinsic::x86_sse2_pslli_q:
11849     case Intrinsic::x86_avx2_pslli_w:
11850     case Intrinsic::x86_avx2_pslli_d:
11851     case Intrinsic::x86_avx2_pslli_q:
11852       Opcode = X86ISD::VSHLI;
11853       break;
11854     case Intrinsic::x86_sse2_psrli_w:
11855     case Intrinsic::x86_sse2_psrli_d:
11856     case Intrinsic::x86_sse2_psrli_q:
11857     case Intrinsic::x86_avx2_psrli_w:
11858     case Intrinsic::x86_avx2_psrli_d:
11859     case Intrinsic::x86_avx2_psrli_q:
11860       Opcode = X86ISD::VSRLI;
11861       break;
11862     case Intrinsic::x86_sse2_psrai_w:
11863     case Intrinsic::x86_sse2_psrai_d:
11864     case Intrinsic::x86_avx2_psrai_w:
11865     case Intrinsic::x86_avx2_psrai_d:
11866       Opcode = X86ISD::VSRAI;
11867       break;
11868     }
11869     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11870                                Op.getOperand(1), Op.getOperand(2), DAG);
11871   }
11872
11873   case Intrinsic::x86_sse42_pcmpistria128:
11874   case Intrinsic::x86_sse42_pcmpestria128:
11875   case Intrinsic::x86_sse42_pcmpistric128:
11876   case Intrinsic::x86_sse42_pcmpestric128:
11877   case Intrinsic::x86_sse42_pcmpistrio128:
11878   case Intrinsic::x86_sse42_pcmpestrio128:
11879   case Intrinsic::x86_sse42_pcmpistris128:
11880   case Intrinsic::x86_sse42_pcmpestris128:
11881   case Intrinsic::x86_sse42_pcmpistriz128:
11882   case Intrinsic::x86_sse42_pcmpestriz128: {
11883     unsigned Opcode;
11884     unsigned X86CC;
11885     switch (IntNo) {
11886     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11887     case Intrinsic::x86_sse42_pcmpistria128:
11888       Opcode = X86ISD::PCMPISTRI;
11889       X86CC = X86::COND_A;
11890       break;
11891     case Intrinsic::x86_sse42_pcmpestria128:
11892       Opcode = X86ISD::PCMPESTRI;
11893       X86CC = X86::COND_A;
11894       break;
11895     case Intrinsic::x86_sse42_pcmpistric128:
11896       Opcode = X86ISD::PCMPISTRI;
11897       X86CC = X86::COND_B;
11898       break;
11899     case Intrinsic::x86_sse42_pcmpestric128:
11900       Opcode = X86ISD::PCMPESTRI;
11901       X86CC = X86::COND_B;
11902       break;
11903     case Intrinsic::x86_sse42_pcmpistrio128:
11904       Opcode = X86ISD::PCMPISTRI;
11905       X86CC = X86::COND_O;
11906       break;
11907     case Intrinsic::x86_sse42_pcmpestrio128:
11908       Opcode = X86ISD::PCMPESTRI;
11909       X86CC = X86::COND_O;
11910       break;
11911     case Intrinsic::x86_sse42_pcmpistris128:
11912       Opcode = X86ISD::PCMPISTRI;
11913       X86CC = X86::COND_S;
11914       break;
11915     case Intrinsic::x86_sse42_pcmpestris128:
11916       Opcode = X86ISD::PCMPESTRI;
11917       X86CC = X86::COND_S;
11918       break;
11919     case Intrinsic::x86_sse42_pcmpistriz128:
11920       Opcode = X86ISD::PCMPISTRI;
11921       X86CC = X86::COND_E;
11922       break;
11923     case Intrinsic::x86_sse42_pcmpestriz128:
11924       Opcode = X86ISD::PCMPESTRI;
11925       X86CC = X86::COND_E;
11926       break;
11927     }
11928     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11929     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11930     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11931     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11932                                 DAG.getConstant(X86CC, MVT::i8),
11933                                 SDValue(PCMP.getNode(), 1));
11934     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11935   }
11936
11937   case Intrinsic::x86_sse42_pcmpistri128:
11938   case Intrinsic::x86_sse42_pcmpestri128: {
11939     unsigned Opcode;
11940     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11941       Opcode = X86ISD::PCMPISTRI;
11942     else
11943       Opcode = X86ISD::PCMPESTRI;
11944
11945     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11946     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11947     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11948   }
11949   case Intrinsic::x86_fma_vfmadd_ps:
11950   case Intrinsic::x86_fma_vfmadd_pd:
11951   case Intrinsic::x86_fma_vfmsub_ps:
11952   case Intrinsic::x86_fma_vfmsub_pd:
11953   case Intrinsic::x86_fma_vfnmadd_ps:
11954   case Intrinsic::x86_fma_vfnmadd_pd:
11955   case Intrinsic::x86_fma_vfnmsub_ps:
11956   case Intrinsic::x86_fma_vfnmsub_pd:
11957   case Intrinsic::x86_fma_vfmaddsub_ps:
11958   case Intrinsic::x86_fma_vfmaddsub_pd:
11959   case Intrinsic::x86_fma_vfmsubadd_ps:
11960   case Intrinsic::x86_fma_vfmsubadd_pd:
11961   case Intrinsic::x86_fma_vfmadd_ps_256:
11962   case Intrinsic::x86_fma_vfmadd_pd_256:
11963   case Intrinsic::x86_fma_vfmsub_ps_256:
11964   case Intrinsic::x86_fma_vfmsub_pd_256:
11965   case Intrinsic::x86_fma_vfnmadd_ps_256:
11966   case Intrinsic::x86_fma_vfnmadd_pd_256:
11967   case Intrinsic::x86_fma_vfnmsub_ps_256:
11968   case Intrinsic::x86_fma_vfnmsub_pd_256:
11969   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11970   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11971   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11972   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11973   case Intrinsic::x86_fma_vfmadd_ps_512:
11974   case Intrinsic::x86_fma_vfmadd_pd_512:
11975   case Intrinsic::x86_fma_vfmsub_ps_512:
11976   case Intrinsic::x86_fma_vfmsub_pd_512:
11977   case Intrinsic::x86_fma_vfnmadd_ps_512:
11978   case Intrinsic::x86_fma_vfnmadd_pd_512:
11979   case Intrinsic::x86_fma_vfnmsub_ps_512:
11980   case Intrinsic::x86_fma_vfnmsub_pd_512:
11981   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11982   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11983   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11984   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11985     unsigned Opc;
11986     switch (IntNo) {
11987     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11988     case Intrinsic::x86_fma_vfmadd_ps:
11989     case Intrinsic::x86_fma_vfmadd_pd:
11990     case Intrinsic::x86_fma_vfmadd_ps_256:
11991     case Intrinsic::x86_fma_vfmadd_pd_256:
11992     case Intrinsic::x86_fma_vfmadd_ps_512:
11993     case Intrinsic::x86_fma_vfmadd_pd_512:
11994       Opc = X86ISD::FMADD;
11995       break;
11996     case Intrinsic::x86_fma_vfmsub_ps:
11997     case Intrinsic::x86_fma_vfmsub_pd:
11998     case Intrinsic::x86_fma_vfmsub_ps_256:
11999     case Intrinsic::x86_fma_vfmsub_pd_256:
12000     case Intrinsic::x86_fma_vfmsub_ps_512:
12001     case Intrinsic::x86_fma_vfmsub_pd_512:
12002       Opc = X86ISD::FMSUB;
12003       break;
12004     case Intrinsic::x86_fma_vfnmadd_ps:
12005     case Intrinsic::x86_fma_vfnmadd_pd:
12006     case Intrinsic::x86_fma_vfnmadd_ps_256:
12007     case Intrinsic::x86_fma_vfnmadd_pd_256:
12008     case Intrinsic::x86_fma_vfnmadd_ps_512:
12009     case Intrinsic::x86_fma_vfnmadd_pd_512:
12010       Opc = X86ISD::FNMADD;
12011       break;
12012     case Intrinsic::x86_fma_vfnmsub_ps:
12013     case Intrinsic::x86_fma_vfnmsub_pd:
12014     case Intrinsic::x86_fma_vfnmsub_ps_256:
12015     case Intrinsic::x86_fma_vfnmsub_pd_256:
12016     case Intrinsic::x86_fma_vfnmsub_ps_512:
12017     case Intrinsic::x86_fma_vfnmsub_pd_512:
12018       Opc = X86ISD::FNMSUB;
12019       break;
12020     case Intrinsic::x86_fma_vfmaddsub_ps:
12021     case Intrinsic::x86_fma_vfmaddsub_pd:
12022     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12023     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12024     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12025     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12026       Opc = X86ISD::FMADDSUB;
12027       break;
12028     case Intrinsic::x86_fma_vfmsubadd_ps:
12029     case Intrinsic::x86_fma_vfmsubadd_pd:
12030     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12031     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12032     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12033     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12034       Opc = X86ISD::FMSUBADD;
12035       break;
12036     }
12037
12038     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12039                        Op.getOperand(2), Op.getOperand(3));
12040   }
12041   }
12042 }
12043
12044 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12045                              SDValue Base, SDValue Index,
12046                              SDValue ScaleOp, SDValue Chain,
12047                              const X86Subtarget * Subtarget) {
12048   SDLoc dl(Op);
12049   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12050   assert(C && "Invalid scale type");
12051   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12052   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12053   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12054                              Index.getSimpleValueType().getVectorNumElements());
12055   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12056   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12057   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12058   SDValue Segment = DAG.getRegister(0, MVT::i32);
12059   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12060   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12061   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12062   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12063 }
12064
12065 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12066                               SDValue Src, SDValue Mask, SDValue Base,
12067                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12068                               const X86Subtarget * Subtarget) {
12069   SDLoc dl(Op);
12070   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12071   assert(C && "Invalid scale type");
12072   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12073   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12074                              Index.getSimpleValueType().getVectorNumElements());
12075   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12076   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12077   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12078   SDValue Segment = DAG.getRegister(0, MVT::i32);
12079   if (Src.getOpcode() == ISD::UNDEF)
12080     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12081   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12082   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12083   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12084   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12085 }
12086
12087 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12088                               SDValue Src, SDValue Base, SDValue Index,
12089                               SDValue ScaleOp, SDValue Chain) {
12090   SDLoc dl(Op);
12091   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12092   assert(C && "Invalid scale type");
12093   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12094   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12095   SDValue Segment = DAG.getRegister(0, MVT::i32);
12096   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12097                              Index.getSimpleValueType().getVectorNumElements());
12098   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12099   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12100   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12101   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12102   return SDValue(Res, 1);
12103 }
12104
12105 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12106                                SDValue Src, SDValue Mask, SDValue Base,
12107                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12108   SDLoc dl(Op);
12109   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12110   assert(C && "Invalid scale type");
12111   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12112   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12113   SDValue Segment = DAG.getRegister(0, MVT::i32);
12114   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12115                              Index.getSimpleValueType().getVectorNumElements());
12116   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12117   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12118   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12119   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12120   return SDValue(Res, 1);
12121 }
12122
12123 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12124                                       SelectionDAG &DAG) {
12125   SDLoc dl(Op);
12126   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12127   switch (IntNo) {
12128   default: return SDValue();    // Don't custom lower most intrinsics.
12129
12130   // RDRAND/RDSEED intrinsics.
12131   case Intrinsic::x86_rdrand_16:
12132   case Intrinsic::x86_rdrand_32:
12133   case Intrinsic::x86_rdrand_64:
12134   case Intrinsic::x86_rdseed_16:
12135   case Intrinsic::x86_rdseed_32:
12136   case Intrinsic::x86_rdseed_64: {
12137     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12138                        IntNo == Intrinsic::x86_rdseed_32 ||
12139                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12140                                                             X86ISD::RDRAND;
12141     // Emit the node with the right value type.
12142     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12143     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12144
12145     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12146     // Otherwise return the value from Rand, which is always 0, casted to i32.
12147     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12148                       DAG.getConstant(1, Op->getValueType(1)),
12149                       DAG.getConstant(X86::COND_B, MVT::i32),
12150                       SDValue(Result.getNode(), 1) };
12151     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12152                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12153                                   Ops, array_lengthof(Ops));
12154
12155     // Return { result, isValid, chain }.
12156     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12157                        SDValue(Result.getNode(), 2));
12158   }
12159   //int_gather(index, base, scale);
12160   case Intrinsic::x86_avx512_gather_qpd_512:
12161   case Intrinsic::x86_avx512_gather_qps_512:
12162   case Intrinsic::x86_avx512_gather_dpd_512:
12163   case Intrinsic::x86_avx512_gather_qpi_512:
12164   case Intrinsic::x86_avx512_gather_qpq_512:
12165   case Intrinsic::x86_avx512_gather_dpq_512:
12166   case Intrinsic::x86_avx512_gather_dps_512:
12167   case Intrinsic::x86_avx512_gather_dpi_512: {
12168     unsigned Opc;
12169     switch (IntNo) {
12170     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12171     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12172     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12173     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12174     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12175     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12176     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12177     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12178     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12179     }
12180     SDValue Chain = Op.getOperand(0);
12181     SDValue Index = Op.getOperand(2);
12182     SDValue Base  = Op.getOperand(3);
12183     SDValue Scale = Op.getOperand(4);
12184     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12185   }
12186   //int_gather_mask(v1, mask, index, base, scale);
12187   case Intrinsic::x86_avx512_gather_qps_mask_512:
12188   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12189   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12190   case Intrinsic::x86_avx512_gather_dps_mask_512:
12191   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12192   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12193   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12194   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12195     unsigned Opc;
12196     switch (IntNo) {
12197     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12198     case Intrinsic::x86_avx512_gather_qps_mask_512:
12199       Opc = X86::VGATHERQPSZrm; break;
12200     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12201       Opc = X86::VGATHERQPDZrm; break;
12202     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12203       Opc = X86::VGATHERDPDZrm; break;
12204     case Intrinsic::x86_avx512_gather_dps_mask_512:
12205       Opc = X86::VGATHERDPSZrm; break;
12206     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12207       Opc = X86::VPGATHERQDZrm; break;
12208     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12209       Opc = X86::VPGATHERQQZrm; break;
12210     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12211       Opc = X86::VPGATHERDDZrm; break;
12212     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12213       Opc = X86::VPGATHERDQZrm; break;
12214     }
12215     SDValue Chain = Op.getOperand(0);
12216     SDValue Src   = Op.getOperand(2);
12217     SDValue Mask  = Op.getOperand(3);
12218     SDValue Index = Op.getOperand(4);
12219     SDValue Base  = Op.getOperand(5);
12220     SDValue Scale = Op.getOperand(6);
12221     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12222                           Subtarget);
12223   }
12224   //int_scatter(base, index, v1, scale);
12225   case Intrinsic::x86_avx512_scatter_qpd_512:
12226   case Intrinsic::x86_avx512_scatter_qps_512:
12227   case Intrinsic::x86_avx512_scatter_dpd_512:
12228   case Intrinsic::x86_avx512_scatter_qpi_512:
12229   case Intrinsic::x86_avx512_scatter_qpq_512:
12230   case Intrinsic::x86_avx512_scatter_dpq_512:
12231   case Intrinsic::x86_avx512_scatter_dps_512:
12232   case Intrinsic::x86_avx512_scatter_dpi_512: {
12233     unsigned Opc;
12234     switch (IntNo) {
12235     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12236     case Intrinsic::x86_avx512_scatter_qpd_512:
12237       Opc = X86::VSCATTERQPDZmr; break;
12238     case Intrinsic::x86_avx512_scatter_qps_512:
12239       Opc = X86::VSCATTERQPSZmr; break;
12240     case Intrinsic::x86_avx512_scatter_dpd_512:
12241       Opc = X86::VSCATTERDPDZmr; break;
12242     case Intrinsic::x86_avx512_scatter_dps_512:
12243       Opc = X86::VSCATTERDPSZmr; break;
12244     case Intrinsic::x86_avx512_scatter_qpi_512:
12245       Opc = X86::VPSCATTERQDZmr; break;
12246     case Intrinsic::x86_avx512_scatter_qpq_512:
12247       Opc = X86::VPSCATTERQQZmr; break;
12248     case Intrinsic::x86_avx512_scatter_dpq_512:
12249       Opc = X86::VPSCATTERDQZmr; break;
12250     case Intrinsic::x86_avx512_scatter_dpi_512:
12251       Opc = X86::VPSCATTERDDZmr; break;
12252     }
12253     SDValue Chain = Op.getOperand(0);
12254     SDValue Base  = Op.getOperand(2);
12255     SDValue Index = Op.getOperand(3);
12256     SDValue Src   = Op.getOperand(4);
12257     SDValue Scale = Op.getOperand(5);
12258     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12259   }
12260   //int_scatter_mask(base, mask, index, v1, scale);
12261   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12262   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12263   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12264   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12265   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12266   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12267   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12268   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12269     unsigned Opc;
12270     switch (IntNo) {
12271     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12272     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12273       Opc = X86::VSCATTERQPDZmr; break;
12274     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12275       Opc = X86::VSCATTERQPSZmr; break;
12276     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12277       Opc = X86::VSCATTERDPDZmr; break;
12278     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12279       Opc = X86::VSCATTERDPSZmr; break;
12280     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12281       Opc = X86::VPSCATTERQDZmr; break;
12282     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12283       Opc = X86::VPSCATTERQQZmr; break;
12284     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12285       Opc = X86::VPSCATTERDQZmr; break;
12286     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12287       Opc = X86::VPSCATTERDDZmr; break;
12288     }
12289     SDValue Chain = Op.getOperand(0);
12290     SDValue Base  = Op.getOperand(2);
12291     SDValue Mask  = Op.getOperand(3);
12292     SDValue Index = Op.getOperand(4);
12293     SDValue Src   = Op.getOperand(5);
12294     SDValue Scale = Op.getOperand(6);
12295     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12296   }
12297   // XTEST intrinsics.
12298   case Intrinsic::x86_xtest: {
12299     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12300     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12301     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12302                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12303                                 InTrans);
12304     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12305     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12306                        Ret, SDValue(InTrans.getNode(), 1));
12307   }
12308   }
12309 }
12310
12311 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12312                                            SelectionDAG &DAG) const {
12313   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12314   MFI->setReturnAddressIsTaken(true);
12315
12316   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12317     return SDValue();
12318
12319   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12320   SDLoc dl(Op);
12321   EVT PtrVT = getPointerTy();
12322
12323   if (Depth > 0) {
12324     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12325     const X86RegisterInfo *RegInfo =
12326       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12327     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12328     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12329                        DAG.getNode(ISD::ADD, dl, PtrVT,
12330                                    FrameAddr, Offset),
12331                        MachinePointerInfo(), false, false, false, 0);
12332   }
12333
12334   // Just load the return address.
12335   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12336   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12337                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12338 }
12339
12340 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12341   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12342   MFI->setFrameAddressIsTaken(true);
12343
12344   EVT VT = Op.getValueType();
12345   SDLoc dl(Op);  // FIXME probably not meaningful
12346   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12347   const X86RegisterInfo *RegInfo =
12348     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12349   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12350   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12351           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12352          "Invalid Frame Register!");
12353   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12354   while (Depth--)
12355     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12356                             MachinePointerInfo(),
12357                             false, false, false, 0);
12358   return FrameAddr;
12359 }
12360
12361 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12362                                                      SelectionDAG &DAG) const {
12363   const X86RegisterInfo *RegInfo =
12364     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12365   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12366 }
12367
12368 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12369   SDValue Chain     = Op.getOperand(0);
12370   SDValue Offset    = Op.getOperand(1);
12371   SDValue Handler   = Op.getOperand(2);
12372   SDLoc dl      (Op);
12373
12374   EVT PtrVT = getPointerTy();
12375   const X86RegisterInfo *RegInfo =
12376     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12377   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12378   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12379           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12380          "Invalid Frame Register!");
12381   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12382   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12383
12384   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12385                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12386   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12387   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12388                        false, false, 0);
12389   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12390
12391   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12392                      DAG.getRegister(StoreAddrReg, PtrVT));
12393 }
12394
12395 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12396                                                SelectionDAG &DAG) const {
12397   SDLoc DL(Op);
12398   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12399                      DAG.getVTList(MVT::i32, MVT::Other),
12400                      Op.getOperand(0), Op.getOperand(1));
12401 }
12402
12403 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12404                                                 SelectionDAG &DAG) const {
12405   SDLoc DL(Op);
12406   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12407                      Op.getOperand(0), Op.getOperand(1));
12408 }
12409
12410 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12411   return Op.getOperand(0);
12412 }
12413
12414 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12415                                                 SelectionDAG &DAG) const {
12416   SDValue Root = Op.getOperand(0);
12417   SDValue Trmp = Op.getOperand(1); // trampoline
12418   SDValue FPtr = Op.getOperand(2); // nested function
12419   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12420   SDLoc dl (Op);
12421
12422   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12423   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12424
12425   if (Subtarget->is64Bit()) {
12426     SDValue OutChains[6];
12427
12428     // Large code-model.
12429     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12430     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12431
12432     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12433     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12434
12435     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12436
12437     // Load the pointer to the nested function into R11.
12438     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12439     SDValue Addr = Trmp;
12440     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12441                                 Addr, MachinePointerInfo(TrmpAddr),
12442                                 false, false, 0);
12443
12444     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12445                        DAG.getConstant(2, MVT::i64));
12446     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12447                                 MachinePointerInfo(TrmpAddr, 2),
12448                                 false, false, 2);
12449
12450     // Load the 'nest' parameter value into R10.
12451     // R10 is specified in X86CallingConv.td
12452     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12454                        DAG.getConstant(10, MVT::i64));
12455     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12456                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12457                                 false, false, 0);
12458
12459     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12460                        DAG.getConstant(12, MVT::i64));
12461     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12462                                 MachinePointerInfo(TrmpAddr, 12),
12463                                 false, false, 2);
12464
12465     // Jump to the nested function.
12466     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12467     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12468                        DAG.getConstant(20, MVT::i64));
12469     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12470                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12471                                 false, false, 0);
12472
12473     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12474     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12475                        DAG.getConstant(22, MVT::i64));
12476     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12477                                 MachinePointerInfo(TrmpAddr, 22),
12478                                 false, false, 0);
12479
12480     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12481   } else {
12482     const Function *Func =
12483       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12484     CallingConv::ID CC = Func->getCallingConv();
12485     unsigned NestReg;
12486
12487     switch (CC) {
12488     default:
12489       llvm_unreachable("Unsupported calling convention");
12490     case CallingConv::C:
12491     case CallingConv::X86_StdCall: {
12492       // Pass 'nest' parameter in ECX.
12493       // Must be kept in sync with X86CallingConv.td
12494       NestReg = X86::ECX;
12495
12496       // Check that ECX wasn't needed by an 'inreg' parameter.
12497       FunctionType *FTy = Func->getFunctionType();
12498       const AttributeSet &Attrs = Func->getAttributes();
12499
12500       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12501         unsigned InRegCount = 0;
12502         unsigned Idx = 1;
12503
12504         for (FunctionType::param_iterator I = FTy->param_begin(),
12505              E = FTy->param_end(); I != E; ++I, ++Idx)
12506           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12507             // FIXME: should only count parameters that are lowered to integers.
12508             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12509
12510         if (InRegCount > 2) {
12511           report_fatal_error("Nest register in use - reduce number of inreg"
12512                              " parameters!");
12513         }
12514       }
12515       break;
12516     }
12517     case CallingConv::X86_FastCall:
12518     case CallingConv::X86_ThisCall:
12519     case CallingConv::Fast:
12520       // Pass 'nest' parameter in EAX.
12521       // Must be kept in sync with X86CallingConv.td
12522       NestReg = X86::EAX;
12523       break;
12524     }
12525
12526     SDValue OutChains[4];
12527     SDValue Addr, Disp;
12528
12529     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12530                        DAG.getConstant(10, MVT::i32));
12531     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12532
12533     // This is storing the opcode for MOV32ri.
12534     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12535     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12536     OutChains[0] = DAG.getStore(Root, dl,
12537                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12538                                 Trmp, MachinePointerInfo(TrmpAddr),
12539                                 false, false, 0);
12540
12541     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12542                        DAG.getConstant(1, MVT::i32));
12543     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12544                                 MachinePointerInfo(TrmpAddr, 1),
12545                                 false, false, 1);
12546
12547     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12549                        DAG.getConstant(5, MVT::i32));
12550     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12551                                 MachinePointerInfo(TrmpAddr, 5),
12552                                 false, false, 1);
12553
12554     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12555                        DAG.getConstant(6, MVT::i32));
12556     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12557                                 MachinePointerInfo(TrmpAddr, 6),
12558                                 false, false, 1);
12559
12560     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12561   }
12562 }
12563
12564 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12565                                             SelectionDAG &DAG) const {
12566   /*
12567    The rounding mode is in bits 11:10 of FPSR, and has the following
12568    settings:
12569      00 Round to nearest
12570      01 Round to -inf
12571      10 Round to +inf
12572      11 Round to 0
12573
12574   FLT_ROUNDS, on the other hand, expects the following:
12575     -1 Undefined
12576      0 Round to 0
12577      1 Round to nearest
12578      2 Round to +inf
12579      3 Round to -inf
12580
12581   To perform the conversion, we do:
12582     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12583   */
12584
12585   MachineFunction &MF = DAG.getMachineFunction();
12586   const TargetMachine &TM = MF.getTarget();
12587   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12588   unsigned StackAlignment = TFI.getStackAlignment();
12589   MVT VT = Op.getSimpleValueType();
12590   SDLoc DL(Op);
12591
12592   // Save FP Control Word to stack slot
12593   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12594   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12595
12596   MachineMemOperand *MMO =
12597    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12598                            MachineMemOperand::MOStore, 2, 2);
12599
12600   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12601   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12602                                           DAG.getVTList(MVT::Other),
12603                                           Ops, array_lengthof(Ops), MVT::i16,
12604                                           MMO);
12605
12606   // Load FP Control Word from stack slot
12607   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12608                             MachinePointerInfo(), false, false, false, 0);
12609
12610   // Transform as necessary
12611   SDValue CWD1 =
12612     DAG.getNode(ISD::SRL, DL, MVT::i16,
12613                 DAG.getNode(ISD::AND, DL, MVT::i16,
12614                             CWD, DAG.getConstant(0x800, MVT::i16)),
12615                 DAG.getConstant(11, MVT::i8));
12616   SDValue CWD2 =
12617     DAG.getNode(ISD::SRL, DL, MVT::i16,
12618                 DAG.getNode(ISD::AND, DL, MVT::i16,
12619                             CWD, DAG.getConstant(0x400, MVT::i16)),
12620                 DAG.getConstant(9, MVT::i8));
12621
12622   SDValue RetVal =
12623     DAG.getNode(ISD::AND, DL, MVT::i16,
12624                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12625                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12626                             DAG.getConstant(1, MVT::i16)),
12627                 DAG.getConstant(3, MVT::i16));
12628
12629   return DAG.getNode((VT.getSizeInBits() < 16 ?
12630                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12631 }
12632
12633 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12634   MVT VT = Op.getSimpleValueType();
12635   EVT OpVT = VT;
12636   unsigned NumBits = VT.getSizeInBits();
12637   SDLoc dl(Op);
12638
12639   Op = Op.getOperand(0);
12640   if (VT == MVT::i8) {
12641     // Zero extend to i32 since there is not an i8 bsr.
12642     OpVT = MVT::i32;
12643     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12644   }
12645
12646   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12647   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12648   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12649
12650   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12651   SDValue Ops[] = {
12652     Op,
12653     DAG.getConstant(NumBits+NumBits-1, OpVT),
12654     DAG.getConstant(X86::COND_E, MVT::i8),
12655     Op.getValue(1)
12656   };
12657   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12658
12659   // Finally xor with NumBits-1.
12660   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12661
12662   if (VT == MVT::i8)
12663     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12664   return Op;
12665 }
12666
12667 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12668   MVT VT = Op.getSimpleValueType();
12669   EVT OpVT = VT;
12670   unsigned NumBits = VT.getSizeInBits();
12671   SDLoc dl(Op);
12672
12673   Op = Op.getOperand(0);
12674   if (VT == MVT::i8) {
12675     // Zero extend to i32 since there is not an i8 bsr.
12676     OpVT = MVT::i32;
12677     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12678   }
12679
12680   // Issue a bsr (scan bits in reverse).
12681   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12682   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12683
12684   // And xor with NumBits-1.
12685   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12686
12687   if (VT == MVT::i8)
12688     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12689   return Op;
12690 }
12691
12692 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12693   MVT VT = Op.getSimpleValueType();
12694   unsigned NumBits = VT.getSizeInBits();
12695   SDLoc dl(Op);
12696   Op = Op.getOperand(0);
12697
12698   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12699   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12700   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12701
12702   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12703   SDValue Ops[] = {
12704     Op,
12705     DAG.getConstant(NumBits, VT),
12706     DAG.getConstant(X86::COND_E, MVT::i8),
12707     Op.getValue(1)
12708   };
12709   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12710 }
12711
12712 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12713 // ones, and then concatenate the result back.
12714 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12715   MVT VT = Op.getSimpleValueType();
12716
12717   assert(VT.is256BitVector() && VT.isInteger() &&
12718          "Unsupported value type for operation");
12719
12720   unsigned NumElems = VT.getVectorNumElements();
12721   SDLoc dl(Op);
12722
12723   // Extract the LHS vectors
12724   SDValue LHS = Op.getOperand(0);
12725   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12726   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12727
12728   // Extract the RHS vectors
12729   SDValue RHS = Op.getOperand(1);
12730   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12731   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12732
12733   MVT EltVT = VT.getVectorElementType();
12734   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12735
12736   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12737                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12738                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12739 }
12740
12741 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12742   assert(Op.getSimpleValueType().is256BitVector() &&
12743          Op.getSimpleValueType().isInteger() &&
12744          "Only handle AVX 256-bit vector integer operation");
12745   return Lower256IntArith(Op, DAG);
12746 }
12747
12748 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12749   assert(Op.getSimpleValueType().is256BitVector() &&
12750          Op.getSimpleValueType().isInteger() &&
12751          "Only handle AVX 256-bit vector integer operation");
12752   return Lower256IntArith(Op, DAG);
12753 }
12754
12755 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12756                         SelectionDAG &DAG) {
12757   SDLoc dl(Op);
12758   MVT VT = Op.getSimpleValueType();
12759
12760   // Decompose 256-bit ops into smaller 128-bit ops.
12761   if (VT.is256BitVector() && !Subtarget->hasInt256())
12762     return Lower256IntArith(Op, DAG);
12763
12764   SDValue A = Op.getOperand(0);
12765   SDValue B = Op.getOperand(1);
12766
12767   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12768   if (VT == MVT::v4i32) {
12769     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12770            "Should not custom lower when pmuldq is available!");
12771
12772     // Extract the odd parts.
12773     static const int UnpackMask[] = { 1, -1, 3, -1 };
12774     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12775     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12776
12777     // Multiply the even parts.
12778     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12779     // Now multiply odd parts.
12780     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12781
12782     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12783     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12784
12785     // Merge the two vectors back together with a shuffle. This expands into 2
12786     // shuffles.
12787     static const int ShufMask[] = { 0, 4, 2, 6 };
12788     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12789   }
12790
12791   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12792          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12793
12794   //  Ahi = psrlqi(a, 32);
12795   //  Bhi = psrlqi(b, 32);
12796   //
12797   //  AloBlo = pmuludq(a, b);
12798   //  AloBhi = pmuludq(a, Bhi);
12799   //  AhiBlo = pmuludq(Ahi, b);
12800
12801   //  AloBhi = psllqi(AloBhi, 32);
12802   //  AhiBlo = psllqi(AhiBlo, 32);
12803   //  return AloBlo + AloBhi + AhiBlo;
12804
12805   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12806   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12807
12808   // Bit cast to 32-bit vectors for MULUDQ
12809   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12810                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12811   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12812   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12813   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12814   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12815
12816   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12817   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12818   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12819
12820   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12821   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12822
12823   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12824   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12825 }
12826
12827 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12828   MVT VT = Op.getSimpleValueType();
12829   MVT EltTy = VT.getVectorElementType();
12830   unsigned NumElts = VT.getVectorNumElements();
12831   SDValue N0 = Op.getOperand(0);
12832   SDLoc dl(Op);
12833
12834   // Lower sdiv X, pow2-const.
12835   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12836   if (!C)
12837     return SDValue();
12838
12839   APInt SplatValue, SplatUndef;
12840   unsigned SplatBitSize;
12841   bool HasAnyUndefs;
12842   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12843                           HasAnyUndefs) ||
12844       EltTy.getSizeInBits() < SplatBitSize)
12845     return SDValue();
12846
12847   if ((SplatValue != 0) &&
12848       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12849     unsigned Lg2 = SplatValue.countTrailingZeros();
12850     // Splat the sign bit.
12851     SmallVector<SDValue, 16> Sz(NumElts,
12852                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12853                                                 EltTy));
12854     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12855                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12856                                           NumElts));
12857     // Add (N0 < 0) ? abs2 - 1 : 0;
12858     SmallVector<SDValue, 16> Amt(NumElts,
12859                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12860                                                  EltTy));
12861     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12862                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12863                                           NumElts));
12864     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12865     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12866     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12867                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12868                                           NumElts));
12869
12870     // If we're dividing by a positive value, we're done.  Otherwise, we must
12871     // negate the result.
12872     if (SplatValue.isNonNegative())
12873       return SRA;
12874
12875     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12876     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12877     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12878   }
12879   return SDValue();
12880 }
12881
12882 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12883                                          const X86Subtarget *Subtarget) {
12884   MVT VT = Op.getSimpleValueType();
12885   SDLoc dl(Op);
12886   SDValue R = Op.getOperand(0);
12887   SDValue Amt = Op.getOperand(1);
12888
12889   // Optimize shl/srl/sra with constant shift amount.
12890   if (isSplatVector(Amt.getNode())) {
12891     SDValue SclrAmt = Amt->getOperand(0);
12892     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12893       uint64_t ShiftAmt = C->getZExtValue();
12894
12895       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12896           (Subtarget->hasInt256() &&
12897            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12898           (Subtarget->hasAVX512() &&
12899            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12900         if (Op.getOpcode() == ISD::SHL)
12901           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12902                                             DAG);
12903         if (Op.getOpcode() == ISD::SRL)
12904           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12905                                             DAG);
12906         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12907           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12908                                             DAG);
12909       }
12910
12911       if (VT == MVT::v16i8) {
12912         if (Op.getOpcode() == ISD::SHL) {
12913           // Make a large shift.
12914           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12915                                                    MVT::v8i16, R, ShiftAmt,
12916                                                    DAG);
12917           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12918           // Zero out the rightmost bits.
12919           SmallVector<SDValue, 16> V(16,
12920                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12921                                                      MVT::i8));
12922           return DAG.getNode(ISD::AND, dl, VT, SHL,
12923                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12924         }
12925         if (Op.getOpcode() == ISD::SRL) {
12926           // Make a large shift.
12927           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12928                                                    MVT::v8i16, R, ShiftAmt,
12929                                                    DAG);
12930           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12931           // Zero out the leftmost bits.
12932           SmallVector<SDValue, 16> V(16,
12933                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12934                                                      MVT::i8));
12935           return DAG.getNode(ISD::AND, dl, VT, SRL,
12936                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12937         }
12938         if (Op.getOpcode() == ISD::SRA) {
12939           if (ShiftAmt == 7) {
12940             // R s>> 7  ===  R s< 0
12941             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12942             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12943           }
12944
12945           // R s>> a === ((R u>> a) ^ m) - m
12946           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12947           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12948                                                          MVT::i8));
12949           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12950           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12951           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12952           return Res;
12953         }
12954         llvm_unreachable("Unknown shift opcode.");
12955       }
12956
12957       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12958         if (Op.getOpcode() == ISD::SHL) {
12959           // Make a large shift.
12960           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12961                                                    MVT::v16i16, R, ShiftAmt,
12962                                                    DAG);
12963           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12964           // Zero out the rightmost bits.
12965           SmallVector<SDValue, 32> V(32,
12966                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12967                                                      MVT::i8));
12968           return DAG.getNode(ISD::AND, dl, VT, SHL,
12969                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12970         }
12971         if (Op.getOpcode() == ISD::SRL) {
12972           // Make a large shift.
12973           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12974                                                    MVT::v16i16, R, ShiftAmt,
12975                                                    DAG);
12976           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12977           // Zero out the leftmost bits.
12978           SmallVector<SDValue, 32> V(32,
12979                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12980                                                      MVT::i8));
12981           return DAG.getNode(ISD::AND, dl, VT, SRL,
12982                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12983         }
12984         if (Op.getOpcode() == ISD::SRA) {
12985           if (ShiftAmt == 7) {
12986             // R s>> 7  ===  R s< 0
12987             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12988             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12989           }
12990
12991           // R s>> a === ((R u>> a) ^ m) - m
12992           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12993           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12994                                                          MVT::i8));
12995           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12996           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12997           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12998           return Res;
12999         }
13000         llvm_unreachable("Unknown shift opcode.");
13001       }
13002     }
13003   }
13004
13005   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13006   if (!Subtarget->is64Bit() &&
13007       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13008       Amt.getOpcode() == ISD::BITCAST &&
13009       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13010     Amt = Amt.getOperand(0);
13011     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13012                      VT.getVectorNumElements();
13013     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13014     uint64_t ShiftAmt = 0;
13015     for (unsigned i = 0; i != Ratio; ++i) {
13016       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13017       if (C == 0)
13018         return SDValue();
13019       // 6 == Log2(64)
13020       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13021     }
13022     // Check remaining shift amounts.
13023     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13024       uint64_t ShAmt = 0;
13025       for (unsigned j = 0; j != Ratio; ++j) {
13026         ConstantSDNode *C =
13027           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13028         if (C == 0)
13029           return SDValue();
13030         // 6 == Log2(64)
13031         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13032       }
13033       if (ShAmt != ShiftAmt)
13034         return SDValue();
13035     }
13036     switch (Op.getOpcode()) {
13037     default:
13038       llvm_unreachable("Unknown shift opcode!");
13039     case ISD::SHL:
13040       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13041                                         DAG);
13042     case ISD::SRL:
13043       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13044                                         DAG);
13045     case ISD::SRA:
13046       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13047                                         DAG);
13048     }
13049   }
13050
13051   return SDValue();
13052 }
13053
13054 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13055                                         const X86Subtarget* Subtarget) {
13056   MVT VT = Op.getSimpleValueType();
13057   SDLoc dl(Op);
13058   SDValue R = Op.getOperand(0);
13059   SDValue Amt = Op.getOperand(1);
13060
13061   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13062       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13063       (Subtarget->hasInt256() &&
13064        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13065         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13066        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13067     SDValue BaseShAmt;
13068     EVT EltVT = VT.getVectorElementType();
13069
13070     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13071       unsigned NumElts = VT.getVectorNumElements();
13072       unsigned i, j;
13073       for (i = 0; i != NumElts; ++i) {
13074         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13075           continue;
13076         break;
13077       }
13078       for (j = i; j != NumElts; ++j) {
13079         SDValue Arg = Amt.getOperand(j);
13080         if (Arg.getOpcode() == ISD::UNDEF) continue;
13081         if (Arg != Amt.getOperand(i))
13082           break;
13083       }
13084       if (i != NumElts && j == NumElts)
13085         BaseShAmt = Amt.getOperand(i);
13086     } else {
13087       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13088         Amt = Amt.getOperand(0);
13089       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13090                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13091         SDValue InVec = Amt.getOperand(0);
13092         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13093           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13094           unsigned i = 0;
13095           for (; i != NumElts; ++i) {
13096             SDValue Arg = InVec.getOperand(i);
13097             if (Arg.getOpcode() == ISD::UNDEF) continue;
13098             BaseShAmt = Arg;
13099             break;
13100           }
13101         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13102            if (ConstantSDNode *C =
13103                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13104              unsigned SplatIdx =
13105                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13106              if (C->getZExtValue() == SplatIdx)
13107                BaseShAmt = InVec.getOperand(1);
13108            }
13109         }
13110         if (BaseShAmt.getNode() == 0)
13111           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13112                                   DAG.getIntPtrConstant(0));
13113       }
13114     }
13115
13116     if (BaseShAmt.getNode()) {
13117       if (EltVT.bitsGT(MVT::i32))
13118         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13119       else if (EltVT.bitsLT(MVT::i32))
13120         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13121
13122       switch (Op.getOpcode()) {
13123       default:
13124         llvm_unreachable("Unknown shift opcode!");
13125       case ISD::SHL:
13126         switch (VT.SimpleTy) {
13127         default: return SDValue();
13128         case MVT::v2i64:
13129         case MVT::v4i32:
13130         case MVT::v8i16:
13131         case MVT::v4i64:
13132         case MVT::v8i32:
13133         case MVT::v16i16:
13134         case MVT::v16i32:
13135         case MVT::v8i64:
13136           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13137         }
13138       case ISD::SRA:
13139         switch (VT.SimpleTy) {
13140         default: return SDValue();
13141         case MVT::v4i32:
13142         case MVT::v8i16:
13143         case MVT::v8i32:
13144         case MVT::v16i16:
13145         case MVT::v16i32:
13146         case MVT::v8i64:
13147           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13148         }
13149       case ISD::SRL:
13150         switch (VT.SimpleTy) {
13151         default: return SDValue();
13152         case MVT::v2i64:
13153         case MVT::v4i32:
13154         case MVT::v8i16:
13155         case MVT::v4i64:
13156         case MVT::v8i32:
13157         case MVT::v16i16:
13158         case MVT::v16i32:
13159         case MVT::v8i64:
13160           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13161         }
13162       }
13163     }
13164   }
13165
13166   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13167   if (!Subtarget->is64Bit() &&
13168       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13169       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13170       Amt.getOpcode() == ISD::BITCAST &&
13171       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13172     Amt = Amt.getOperand(0);
13173     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13174                      VT.getVectorNumElements();
13175     std::vector<SDValue> Vals(Ratio);
13176     for (unsigned i = 0; i != Ratio; ++i)
13177       Vals[i] = Amt.getOperand(i);
13178     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13179       for (unsigned j = 0; j != Ratio; ++j)
13180         if (Vals[j] != Amt.getOperand(i + j))
13181           return SDValue();
13182     }
13183     switch (Op.getOpcode()) {
13184     default:
13185       llvm_unreachable("Unknown shift opcode!");
13186     case ISD::SHL:
13187       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13188     case ISD::SRL:
13189       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13190     case ISD::SRA:
13191       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13192     }
13193   }
13194
13195   return SDValue();
13196 }
13197
13198 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13199                           SelectionDAG &DAG) {
13200
13201   MVT VT = Op.getSimpleValueType();
13202   SDLoc dl(Op);
13203   SDValue R = Op.getOperand(0);
13204   SDValue Amt = Op.getOperand(1);
13205   SDValue V;
13206
13207   if (!Subtarget->hasSSE2())
13208     return SDValue();
13209
13210   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13211   if (V.getNode())
13212     return V;
13213
13214   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13215   if (V.getNode())
13216       return V;
13217
13218   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13219     return Op;
13220   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13221   if (Subtarget->hasInt256()) {
13222     if (Op.getOpcode() == ISD::SRL &&
13223         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13224          VT == MVT::v4i64 || VT == MVT::v8i32))
13225       return Op;
13226     if (Op.getOpcode() == ISD::SHL &&
13227         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13228          VT == MVT::v4i64 || VT == MVT::v8i32))
13229       return Op;
13230     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13231       return Op;
13232   }
13233
13234   // If possible, lower this packed shift into a vector multiply instead of
13235   // expanding it into a sequence of scalar shifts.
13236   // Do this only if the vector shift count is a constant build_vector.
13237   if (Op.getOpcode() == ISD::SHL && 
13238       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13239        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13240       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13241     SmallVector<SDValue, 8> Elts;
13242     EVT SVT = VT.getScalarType();
13243     unsigned SVTBits = SVT.getSizeInBits();
13244     const APInt &One = APInt(SVTBits, 1);
13245     unsigned NumElems = VT.getVectorNumElements();
13246
13247     for (unsigned i=0; i !=NumElems; ++i) {
13248       SDValue Op = Amt->getOperand(i);
13249       if (Op->getOpcode() == ISD::UNDEF) {
13250         Elts.push_back(Op);
13251         continue;
13252       }
13253
13254       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13255       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13256       uint64_t ShAmt = C.getZExtValue();
13257       if (ShAmt >= SVTBits) {
13258         Elts.push_back(DAG.getUNDEF(SVT));
13259         continue;
13260       }
13261       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13262     }
13263     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13264     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13265   }
13266
13267   // Lower SHL with variable shift amount.
13268   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13269     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13270
13271     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13272     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13273     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13274     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13275   }
13276
13277   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13278     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13279
13280     // a = a << 5;
13281     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13282     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13283
13284     // Turn 'a' into a mask suitable for VSELECT
13285     SDValue VSelM = DAG.getConstant(0x80, VT);
13286     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13287     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13288
13289     SDValue CM1 = DAG.getConstant(0x0f, VT);
13290     SDValue CM2 = DAG.getConstant(0x3f, VT);
13291
13292     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13293     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13294     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13295     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13296     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13297
13298     // a += a
13299     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13300     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13301     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13302
13303     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13304     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13305     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13306     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13307     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13308
13309     // a += a
13310     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13311     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13312     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13313
13314     // return VSELECT(r, r+r, a);
13315     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13316                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13317     return R;
13318   }
13319
13320   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13321   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13322   // solution better.
13323   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13324     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13325     unsigned ExtOpc =
13326         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13327     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13328     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13329     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13330                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13331     }
13332
13333   // Decompose 256-bit shifts into smaller 128-bit shifts.
13334   if (VT.is256BitVector()) {
13335     unsigned NumElems = VT.getVectorNumElements();
13336     MVT EltVT = VT.getVectorElementType();
13337     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13338
13339     // Extract the two vectors
13340     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13341     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13342
13343     // Recreate the shift amount vectors
13344     SDValue Amt1, Amt2;
13345     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13346       // Constant shift amount
13347       SmallVector<SDValue, 4> Amt1Csts;
13348       SmallVector<SDValue, 4> Amt2Csts;
13349       for (unsigned i = 0; i != NumElems/2; ++i)
13350         Amt1Csts.push_back(Amt->getOperand(i));
13351       for (unsigned i = NumElems/2; i != NumElems; ++i)
13352         Amt2Csts.push_back(Amt->getOperand(i));
13353
13354       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13355                                  &Amt1Csts[0], NumElems/2);
13356       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13357                                  &Amt2Csts[0], NumElems/2);
13358     } else {
13359       // Variable shift amount
13360       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13361       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13362     }
13363
13364     // Issue new vector shifts for the smaller types
13365     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13366     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13367
13368     // Concatenate the result back
13369     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13370   }
13371
13372   return SDValue();
13373 }
13374
13375 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13376   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13377   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13378   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13379   // has only one use.
13380   SDNode *N = Op.getNode();
13381   SDValue LHS = N->getOperand(0);
13382   SDValue RHS = N->getOperand(1);
13383   unsigned BaseOp = 0;
13384   unsigned Cond = 0;
13385   SDLoc DL(Op);
13386   switch (Op.getOpcode()) {
13387   default: llvm_unreachable("Unknown ovf instruction!");
13388   case ISD::SADDO:
13389     // A subtract of one will be selected as a INC. Note that INC doesn't
13390     // set CF, so we can't do this for UADDO.
13391     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13392       if (C->isOne()) {
13393         BaseOp = X86ISD::INC;
13394         Cond = X86::COND_O;
13395         break;
13396       }
13397     BaseOp = X86ISD::ADD;
13398     Cond = X86::COND_O;
13399     break;
13400   case ISD::UADDO:
13401     BaseOp = X86ISD::ADD;
13402     Cond = X86::COND_B;
13403     break;
13404   case ISD::SSUBO:
13405     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13406     // set CF, so we can't do this for USUBO.
13407     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13408       if (C->isOne()) {
13409         BaseOp = X86ISD::DEC;
13410         Cond = X86::COND_O;
13411         break;
13412       }
13413     BaseOp = X86ISD::SUB;
13414     Cond = X86::COND_O;
13415     break;
13416   case ISD::USUBO:
13417     BaseOp = X86ISD::SUB;
13418     Cond = X86::COND_B;
13419     break;
13420   case ISD::SMULO:
13421     BaseOp = X86ISD::SMUL;
13422     Cond = X86::COND_O;
13423     break;
13424   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13425     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13426                                  MVT::i32);
13427     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13428
13429     SDValue SetCC =
13430       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13431                   DAG.getConstant(X86::COND_O, MVT::i32),
13432                   SDValue(Sum.getNode(), 2));
13433
13434     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13435   }
13436   }
13437
13438   // Also sets EFLAGS.
13439   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13440   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13441
13442   SDValue SetCC =
13443     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13444                 DAG.getConstant(Cond, MVT::i32),
13445                 SDValue(Sum.getNode(), 1));
13446
13447   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13448 }
13449
13450 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13451                                                   SelectionDAG &DAG) const {
13452   SDLoc dl(Op);
13453   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13454   MVT VT = Op.getSimpleValueType();
13455
13456   if (!Subtarget->hasSSE2() || !VT.isVector())
13457     return SDValue();
13458
13459   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13460                       ExtraVT.getScalarType().getSizeInBits();
13461
13462   switch (VT.SimpleTy) {
13463     default: return SDValue();
13464     case MVT::v8i32:
13465     case MVT::v16i16:
13466       if (!Subtarget->hasFp256())
13467         return SDValue();
13468       if (!Subtarget->hasInt256()) {
13469         // needs to be split
13470         unsigned NumElems = VT.getVectorNumElements();
13471
13472         // Extract the LHS vectors
13473         SDValue LHS = Op.getOperand(0);
13474         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13475         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13476
13477         MVT EltVT = VT.getVectorElementType();
13478         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13479
13480         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13481         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13482         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13483                                    ExtraNumElems/2);
13484         SDValue Extra = DAG.getValueType(ExtraVT);
13485
13486         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13487         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13488
13489         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13490       }
13491       // fall through
13492     case MVT::v4i32:
13493     case MVT::v8i16: {
13494       SDValue Op0 = Op.getOperand(0);
13495       SDValue Op00 = Op0.getOperand(0);
13496       SDValue Tmp1;
13497       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13498       if (Op0.getOpcode() == ISD::BITCAST &&
13499           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13500         // (sext (vzext x)) -> (vsext x)
13501         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13502         if (Tmp1.getNode()) {
13503           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13504           // This folding is only valid when the in-reg type is a vector of i8,
13505           // i16, or i32.
13506           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13507               ExtraEltVT == MVT::i32) {
13508             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13509             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13510                    "This optimization is invalid without a VZEXT.");
13511             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13512           }
13513           Op0 = Tmp1;
13514         }
13515       }
13516
13517       // If the above didn't work, then just use Shift-Left + Shift-Right.
13518       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13519                                         DAG);
13520       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13521                                         DAG);
13522     }
13523   }
13524 }
13525
13526 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13527                                  SelectionDAG &DAG) {
13528   SDLoc dl(Op);
13529   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13530     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13531   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13532     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13533
13534   // The only fence that needs an instruction is a sequentially-consistent
13535   // cross-thread fence.
13536   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13537     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13538     // no-sse2). There isn't any reason to disable it if the target processor
13539     // supports it.
13540     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13541       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13542
13543     SDValue Chain = Op.getOperand(0);
13544     SDValue Zero = DAG.getConstant(0, MVT::i32);
13545     SDValue Ops[] = {
13546       DAG.getRegister(X86::ESP, MVT::i32), // Base
13547       DAG.getTargetConstant(1, MVT::i8),   // Scale
13548       DAG.getRegister(0, MVT::i32),        // Index
13549       DAG.getTargetConstant(0, MVT::i32),  // Disp
13550       DAG.getRegister(0, MVT::i32),        // Segment.
13551       Zero,
13552       Chain
13553     };
13554     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13555     return SDValue(Res, 0);
13556   }
13557
13558   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13559   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13560 }
13561
13562 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13563                              SelectionDAG &DAG) {
13564   MVT T = Op.getSimpleValueType();
13565   SDLoc DL(Op);
13566   unsigned Reg = 0;
13567   unsigned size = 0;
13568   switch(T.SimpleTy) {
13569   default: llvm_unreachable("Invalid value type!");
13570   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13571   case MVT::i16: Reg = X86::AX;  size = 2; break;
13572   case MVT::i32: Reg = X86::EAX; size = 4; break;
13573   case MVT::i64:
13574     assert(Subtarget->is64Bit() && "Node not type legal!");
13575     Reg = X86::RAX; size = 8;
13576     break;
13577   }
13578   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13579                                     Op.getOperand(2), SDValue());
13580   SDValue Ops[] = { cpIn.getValue(0),
13581                     Op.getOperand(1),
13582                     Op.getOperand(3),
13583                     DAG.getTargetConstant(size, MVT::i8),
13584                     cpIn.getValue(1) };
13585   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13586   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13587   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13588                                            Ops, array_lengthof(Ops), T, MMO);
13589   SDValue cpOut =
13590     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13591   return cpOut;
13592 }
13593
13594 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13595                                      SelectionDAG &DAG) {
13596   assert(Subtarget->is64Bit() && "Result not type legalized?");
13597   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13598   SDValue TheChain = Op.getOperand(0);
13599   SDLoc dl(Op);
13600   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13601   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13602   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13603                                    rax.getValue(2));
13604   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13605                             DAG.getConstant(32, MVT::i8));
13606   SDValue Ops[] = {
13607     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13608     rdx.getValue(1)
13609   };
13610   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13611 }
13612
13613 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13614                             SelectionDAG &DAG) {
13615   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13616   MVT DstVT = Op.getSimpleValueType();
13617   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13618          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13619   assert((DstVT == MVT::i64 ||
13620           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13621          "Unexpected custom BITCAST");
13622   // i64 <=> MMX conversions are Legal.
13623   if (SrcVT==MVT::i64 && DstVT.isVector())
13624     return Op;
13625   if (DstVT==MVT::i64 && SrcVT.isVector())
13626     return Op;
13627   // MMX <=> MMX conversions are Legal.
13628   if (SrcVT.isVector() && DstVT.isVector())
13629     return Op;
13630   // All other conversions need to be expanded.
13631   return SDValue();
13632 }
13633
13634 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13635   SDNode *Node = Op.getNode();
13636   SDLoc dl(Node);
13637   EVT T = Node->getValueType(0);
13638   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13639                               DAG.getConstant(0, T), Node->getOperand(2));
13640   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13641                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13642                        Node->getOperand(0),
13643                        Node->getOperand(1), negOp,
13644                        cast<AtomicSDNode>(Node)->getSrcValue(),
13645                        cast<AtomicSDNode>(Node)->getAlignment(),
13646                        cast<AtomicSDNode>(Node)->getOrdering(),
13647                        cast<AtomicSDNode>(Node)->getSynchScope());
13648 }
13649
13650 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13651   SDNode *Node = Op.getNode();
13652   SDLoc dl(Node);
13653   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13654
13655   // Convert seq_cst store -> xchg
13656   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13657   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13658   //        (The only way to get a 16-byte store is cmpxchg16b)
13659   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13660   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13661       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13662     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13663                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13664                                  Node->getOperand(0),
13665                                  Node->getOperand(1), Node->getOperand(2),
13666                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13667                                  cast<AtomicSDNode>(Node)->getOrdering(),
13668                                  cast<AtomicSDNode>(Node)->getSynchScope());
13669     return Swap.getValue(1);
13670   }
13671   // Other atomic stores have a simple pattern.
13672   return Op;
13673 }
13674
13675 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13676   EVT VT = Op.getNode()->getSimpleValueType(0);
13677
13678   // Let legalize expand this if it isn't a legal type yet.
13679   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13680     return SDValue();
13681
13682   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13683
13684   unsigned Opc;
13685   bool ExtraOp = false;
13686   switch (Op.getOpcode()) {
13687   default: llvm_unreachable("Invalid code");
13688   case ISD::ADDC: Opc = X86ISD::ADD; break;
13689   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13690   case ISD::SUBC: Opc = X86ISD::SUB; break;
13691   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13692   }
13693
13694   if (!ExtraOp)
13695     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13696                        Op.getOperand(1));
13697   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13698                      Op.getOperand(1), Op.getOperand(2));
13699 }
13700
13701 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13702                             SelectionDAG &DAG) {
13703   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13704
13705   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13706   // which returns the values as { float, float } (in XMM0) or
13707   // { double, double } (which is returned in XMM0, XMM1).
13708   SDLoc dl(Op);
13709   SDValue Arg = Op.getOperand(0);
13710   EVT ArgVT = Arg.getValueType();
13711   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13712
13713   TargetLowering::ArgListTy Args;
13714   TargetLowering::ArgListEntry Entry;
13715
13716   Entry.Node = Arg;
13717   Entry.Ty = ArgTy;
13718   Entry.isSExt = false;
13719   Entry.isZExt = false;
13720   Args.push_back(Entry);
13721
13722   bool isF64 = ArgVT == MVT::f64;
13723   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13724   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13725   // the results are returned via SRet in memory.
13726   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13728   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13729
13730   Type *RetTy = isF64
13731     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13732     : (Type*)VectorType::get(ArgTy, 4);
13733   TargetLowering::
13734     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13735                          false, false, false, false, 0,
13736                          CallingConv::C, /*isTaillCall=*/false,
13737                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13738                          Callee, Args, DAG, dl);
13739   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13740
13741   if (isF64)
13742     // Returned in xmm0 and xmm1.
13743     return CallResult.first;
13744
13745   // Returned in bits 0:31 and 32:64 xmm0.
13746   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13747                                CallResult.first, DAG.getIntPtrConstant(0));
13748   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13749                                CallResult.first, DAG.getIntPtrConstant(1));
13750   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13751   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13752 }
13753
13754 /// LowerOperation - Provide custom lowering hooks for some operations.
13755 ///
13756 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13757   switch (Op.getOpcode()) {
13758   default: llvm_unreachable("Should not custom lower this!");
13759   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13760   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13761   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13762   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13763   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13764   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13765   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13766   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13767   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13768   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13769   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13770   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13771   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13772   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13773   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13774   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13775   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13776   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13777   case ISD::SHL_PARTS:
13778   case ISD::SRA_PARTS:
13779   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13780   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13781   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13782   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13783   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13784   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13785   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13786   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13787   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13788   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13789   case ISD::FABS:               return LowerFABS(Op, DAG);
13790   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13791   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13792   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13793   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13794   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13795   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13796   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13797   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13798   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13799   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13800   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13801   case ISD::INTRINSIC_VOID:
13802   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13803   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13804   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13805   case ISD::FRAME_TO_ARGS_OFFSET:
13806                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13807   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13808   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13809   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13810   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13811   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13812   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13813   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13814   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13815   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13816   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13817   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13818   case ISD::SRA:
13819   case ISD::SRL:
13820   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13821   case ISD::SADDO:
13822   case ISD::UADDO:
13823   case ISD::SSUBO:
13824   case ISD::USUBO:
13825   case ISD::SMULO:
13826   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13827   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13828   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13829   case ISD::ADDC:
13830   case ISD::ADDE:
13831   case ISD::SUBC:
13832   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13833   case ISD::ADD:                return LowerADD(Op, DAG);
13834   case ISD::SUB:                return LowerSUB(Op, DAG);
13835   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13836   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13837   }
13838 }
13839
13840 static void ReplaceATOMIC_LOAD(SDNode *Node,
13841                                   SmallVectorImpl<SDValue> &Results,
13842                                   SelectionDAG &DAG) {
13843   SDLoc dl(Node);
13844   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13845
13846   // Convert wide load -> cmpxchg8b/cmpxchg16b
13847   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13848   //        (The only way to get a 16-byte load is cmpxchg16b)
13849   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13850   SDValue Zero = DAG.getConstant(0, VT);
13851   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13852                                Node->getOperand(0),
13853                                Node->getOperand(1), Zero, Zero,
13854                                cast<AtomicSDNode>(Node)->getMemOperand(),
13855                                cast<AtomicSDNode>(Node)->getOrdering(),
13856                                cast<AtomicSDNode>(Node)->getOrdering(),
13857                                cast<AtomicSDNode>(Node)->getSynchScope());
13858   Results.push_back(Swap.getValue(0));
13859   Results.push_back(Swap.getValue(1));
13860 }
13861
13862 static void
13863 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13864                         SelectionDAG &DAG, unsigned NewOp) {
13865   SDLoc dl(Node);
13866   assert (Node->getValueType(0) == MVT::i64 &&
13867           "Only know how to expand i64 atomics");
13868
13869   SDValue Chain = Node->getOperand(0);
13870   SDValue In1 = Node->getOperand(1);
13871   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13872                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13873   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13874                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13875   SDValue Ops[] = { Chain, In1, In2L, In2H };
13876   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13877   SDValue Result =
13878     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13879                             cast<MemSDNode>(Node)->getMemOperand());
13880   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13881   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13882   Results.push_back(Result.getValue(2));
13883 }
13884
13885 /// ReplaceNodeResults - Replace a node with an illegal result type
13886 /// with a new node built out of custom code.
13887 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13888                                            SmallVectorImpl<SDValue>&Results,
13889                                            SelectionDAG &DAG) const {
13890   SDLoc dl(N);
13891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13892   switch (N->getOpcode()) {
13893   default:
13894     llvm_unreachable("Do not know how to custom type legalize this operation!");
13895   case ISD::SIGN_EXTEND_INREG:
13896   case ISD::ADDC:
13897   case ISD::ADDE:
13898   case ISD::SUBC:
13899   case ISD::SUBE:
13900     // We don't want to expand or promote these.
13901     return;
13902   case ISD::FP_TO_SINT:
13903   case ISD::FP_TO_UINT: {
13904     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13905
13906     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13907       return;
13908
13909     std::pair<SDValue,SDValue> Vals =
13910         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13911     SDValue FIST = Vals.first, StackSlot = Vals.second;
13912     if (FIST.getNode() != 0) {
13913       EVT VT = N->getValueType(0);
13914       // Return a load from the stack slot.
13915       if (StackSlot.getNode() != 0)
13916         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13917                                       MachinePointerInfo(),
13918                                       false, false, false, 0));
13919       else
13920         Results.push_back(FIST);
13921     }
13922     return;
13923   }
13924   case ISD::UINT_TO_FP: {
13925     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13926     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13927         N->getValueType(0) != MVT::v2f32)
13928       return;
13929     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13930                                  N->getOperand(0));
13931     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13932                                      MVT::f64);
13933     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13934     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13935                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13936     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13937     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13938     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13939     return;
13940   }
13941   case ISD::FP_ROUND: {
13942     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13943         return;
13944     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13945     Results.push_back(V);
13946     return;
13947   }
13948   case ISD::READCYCLECOUNTER: {
13949     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13950     SDValue TheChain = N->getOperand(0);
13951     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13952     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13953                                      rd.getValue(1));
13954     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13955                                      eax.getValue(2));
13956     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13957     SDValue Ops[] = { eax, edx };
13958     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13959                                   array_lengthof(Ops)));
13960     Results.push_back(edx.getValue(1));
13961     return;
13962   }
13963   case ISD::ATOMIC_CMP_SWAP: {
13964     EVT T = N->getValueType(0);
13965     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13966     bool Regs64bit = T == MVT::i128;
13967     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13968     SDValue cpInL, cpInH;
13969     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13970                         DAG.getConstant(0, HalfT));
13971     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13972                         DAG.getConstant(1, HalfT));
13973     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13974                              Regs64bit ? X86::RAX : X86::EAX,
13975                              cpInL, SDValue());
13976     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13977                              Regs64bit ? X86::RDX : X86::EDX,
13978                              cpInH, cpInL.getValue(1));
13979     SDValue swapInL, swapInH;
13980     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13981                           DAG.getConstant(0, HalfT));
13982     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13983                           DAG.getConstant(1, HalfT));
13984     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13985                                Regs64bit ? X86::RBX : X86::EBX,
13986                                swapInL, cpInH.getValue(1));
13987     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13988                                Regs64bit ? X86::RCX : X86::ECX,
13989                                swapInH, swapInL.getValue(1));
13990     SDValue Ops[] = { swapInH.getValue(0),
13991                       N->getOperand(1),
13992                       swapInH.getValue(1) };
13993     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13994     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13995     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13996                                   X86ISD::LCMPXCHG8_DAG;
13997     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13998                                              Ops, array_lengthof(Ops), T, MMO);
13999     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14000                                         Regs64bit ? X86::RAX : X86::EAX,
14001                                         HalfT, Result.getValue(1));
14002     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14003                                         Regs64bit ? X86::RDX : X86::EDX,
14004                                         HalfT, cpOutL.getValue(2));
14005     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14006     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14007     Results.push_back(cpOutH.getValue(1));
14008     return;
14009   }
14010   case ISD::ATOMIC_LOAD_ADD:
14011   case ISD::ATOMIC_LOAD_AND:
14012   case ISD::ATOMIC_LOAD_NAND:
14013   case ISD::ATOMIC_LOAD_OR:
14014   case ISD::ATOMIC_LOAD_SUB:
14015   case ISD::ATOMIC_LOAD_XOR:
14016   case ISD::ATOMIC_LOAD_MAX:
14017   case ISD::ATOMIC_LOAD_MIN:
14018   case ISD::ATOMIC_LOAD_UMAX:
14019   case ISD::ATOMIC_LOAD_UMIN:
14020   case ISD::ATOMIC_SWAP: {
14021     unsigned Opc;
14022     switch (N->getOpcode()) {
14023     default: llvm_unreachable("Unexpected opcode");
14024     case ISD::ATOMIC_LOAD_ADD:
14025       Opc = X86ISD::ATOMADD64_DAG;
14026       break;
14027     case ISD::ATOMIC_LOAD_AND:
14028       Opc = X86ISD::ATOMAND64_DAG;
14029       break;
14030     case ISD::ATOMIC_LOAD_NAND:
14031       Opc = X86ISD::ATOMNAND64_DAG;
14032       break;
14033     case ISD::ATOMIC_LOAD_OR:
14034       Opc = X86ISD::ATOMOR64_DAG;
14035       break;
14036     case ISD::ATOMIC_LOAD_SUB:
14037       Opc = X86ISD::ATOMSUB64_DAG;
14038       break;
14039     case ISD::ATOMIC_LOAD_XOR:
14040       Opc = X86ISD::ATOMXOR64_DAG;
14041       break;
14042     case ISD::ATOMIC_LOAD_MAX:
14043       Opc = X86ISD::ATOMMAX64_DAG;
14044       break;
14045     case ISD::ATOMIC_LOAD_MIN:
14046       Opc = X86ISD::ATOMMIN64_DAG;
14047       break;
14048     case ISD::ATOMIC_LOAD_UMAX:
14049       Opc = X86ISD::ATOMUMAX64_DAG;
14050       break;
14051     case ISD::ATOMIC_LOAD_UMIN:
14052       Opc = X86ISD::ATOMUMIN64_DAG;
14053       break;
14054     case ISD::ATOMIC_SWAP:
14055       Opc = X86ISD::ATOMSWAP64_DAG;
14056       break;
14057     }
14058     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14059     return;
14060   }
14061   case ISD::ATOMIC_LOAD:
14062     ReplaceATOMIC_LOAD(N, Results, DAG);
14063   }
14064 }
14065
14066 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14067   switch (Opcode) {
14068   default: return NULL;
14069   case X86ISD::BSF:                return "X86ISD::BSF";
14070   case X86ISD::BSR:                return "X86ISD::BSR";
14071   case X86ISD::SHLD:               return "X86ISD::SHLD";
14072   case X86ISD::SHRD:               return "X86ISD::SHRD";
14073   case X86ISD::FAND:               return "X86ISD::FAND";
14074   case X86ISD::FANDN:              return "X86ISD::FANDN";
14075   case X86ISD::FOR:                return "X86ISD::FOR";
14076   case X86ISD::FXOR:               return "X86ISD::FXOR";
14077   case X86ISD::FSRL:               return "X86ISD::FSRL";
14078   case X86ISD::FILD:               return "X86ISD::FILD";
14079   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14080   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14081   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14082   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14083   case X86ISD::FLD:                return "X86ISD::FLD";
14084   case X86ISD::FST:                return "X86ISD::FST";
14085   case X86ISD::CALL:               return "X86ISD::CALL";
14086   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14087   case X86ISD::BT:                 return "X86ISD::BT";
14088   case X86ISD::CMP:                return "X86ISD::CMP";
14089   case X86ISD::COMI:               return "X86ISD::COMI";
14090   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14091   case X86ISD::CMPM:               return "X86ISD::CMPM";
14092   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14093   case X86ISD::SETCC:              return "X86ISD::SETCC";
14094   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14095   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14096   case X86ISD::CMOV:               return "X86ISD::CMOV";
14097   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14098   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14099   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14100   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14101   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14102   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14103   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14104   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14105   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14106   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14107   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14108   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14109   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14110   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14111   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14112   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14113   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14114   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14115   case X86ISD::HADD:               return "X86ISD::HADD";
14116   case X86ISD::HSUB:               return "X86ISD::HSUB";
14117   case X86ISD::FHADD:              return "X86ISD::FHADD";
14118   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14119   case X86ISD::UMAX:               return "X86ISD::UMAX";
14120   case X86ISD::UMIN:               return "X86ISD::UMIN";
14121   case X86ISD::SMAX:               return "X86ISD::SMAX";
14122   case X86ISD::SMIN:               return "X86ISD::SMIN";
14123   case X86ISD::FMAX:               return "X86ISD::FMAX";
14124   case X86ISD::FMIN:               return "X86ISD::FMIN";
14125   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14126   case X86ISD::FMINC:              return "X86ISD::FMINC";
14127   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14128   case X86ISD::FRCP:               return "X86ISD::FRCP";
14129   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14130   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14131   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14132   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14133   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14134   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14135   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14136   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14137   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14138   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14139   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14140   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14141   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14142   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14143   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14144   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14145   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14146   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14147   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14148   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14149   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14150   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14151   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14152   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14153   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14154   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14155   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14156   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14157   case X86ISD::VSHL:               return "X86ISD::VSHL";
14158   case X86ISD::VSRL:               return "X86ISD::VSRL";
14159   case X86ISD::VSRA:               return "X86ISD::VSRA";
14160   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14161   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14162   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14163   case X86ISD::CMPP:               return "X86ISD::CMPP";
14164   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14165   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14166   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14167   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14168   case X86ISD::ADD:                return "X86ISD::ADD";
14169   case X86ISD::SUB:                return "X86ISD::SUB";
14170   case X86ISD::ADC:                return "X86ISD::ADC";
14171   case X86ISD::SBB:                return "X86ISD::SBB";
14172   case X86ISD::SMUL:               return "X86ISD::SMUL";
14173   case X86ISD::UMUL:               return "X86ISD::UMUL";
14174   case X86ISD::INC:                return "X86ISD::INC";
14175   case X86ISD::DEC:                return "X86ISD::DEC";
14176   case X86ISD::OR:                 return "X86ISD::OR";
14177   case X86ISD::XOR:                return "X86ISD::XOR";
14178   case X86ISD::AND:                return "X86ISD::AND";
14179   case X86ISD::BZHI:               return "X86ISD::BZHI";
14180   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14181   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14182   case X86ISD::PTEST:              return "X86ISD::PTEST";
14183   case X86ISD::TESTP:              return "X86ISD::TESTP";
14184   case X86ISD::TESTM:              return "X86ISD::TESTM";
14185   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14186   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14187   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14188   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14189   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14190   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14191   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14192   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14193   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14194   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14195   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14196   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14197   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14198   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14199   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14200   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14201   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14202   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14203   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14204   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14205   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14206   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14207   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14208   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14209   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14210   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14211   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14212   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14213   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14214   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14215   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14216   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14217   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14218   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14219   case X86ISD::SAHF:               return "X86ISD::SAHF";
14220   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14221   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14222   case X86ISD::FMADD:              return "X86ISD::FMADD";
14223   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14224   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14225   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14226   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14227   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14228   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14229   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14230   case X86ISD::XTEST:              return "X86ISD::XTEST";
14231   }
14232 }
14233
14234 // isLegalAddressingMode - Return true if the addressing mode represented
14235 // by AM is legal for this target, for a load/store of the specified type.
14236 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14237                                               Type *Ty) const {
14238   // X86 supports extremely general addressing modes.
14239   CodeModel::Model M = getTargetMachine().getCodeModel();
14240   Reloc::Model R = getTargetMachine().getRelocationModel();
14241
14242   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14243   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14244     return false;
14245
14246   if (AM.BaseGV) {
14247     unsigned GVFlags =
14248       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14249
14250     // If a reference to this global requires an extra load, we can't fold it.
14251     if (isGlobalStubReference(GVFlags))
14252       return false;
14253
14254     // If BaseGV requires a register for the PIC base, we cannot also have a
14255     // BaseReg specified.
14256     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14257       return false;
14258
14259     // If lower 4G is not available, then we must use rip-relative addressing.
14260     if ((M != CodeModel::Small || R != Reloc::Static) &&
14261         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14262       return false;
14263   }
14264
14265   switch (AM.Scale) {
14266   case 0:
14267   case 1:
14268   case 2:
14269   case 4:
14270   case 8:
14271     // These scales always work.
14272     break;
14273   case 3:
14274   case 5:
14275   case 9:
14276     // These scales are formed with basereg+scalereg.  Only accept if there is
14277     // no basereg yet.
14278     if (AM.HasBaseReg)
14279       return false;
14280     break;
14281   default:  // Other stuff never works.
14282     return false;
14283   }
14284
14285   return true;
14286 }
14287
14288 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14289   unsigned Bits = Ty->getScalarSizeInBits();
14290
14291   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14292   // particularly cheaper than those without.
14293   if (Bits == 8)
14294     return false;
14295
14296   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14297   // variable shifts just as cheap as scalar ones.
14298   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14299     return false;
14300
14301   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14302   // fully general vector.
14303   return true;
14304 }
14305
14306 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14307   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14308     return false;
14309   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14310   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14311   return NumBits1 > NumBits2;
14312 }
14313
14314 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14315   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14316     return false;
14317
14318   if (!isTypeLegal(EVT::getEVT(Ty1)))
14319     return false;
14320
14321   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14322
14323   // Assuming the caller doesn't have a zeroext or signext return parameter,
14324   // truncation all the way down to i1 is valid.
14325   return true;
14326 }
14327
14328 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14329   return isInt<32>(Imm);
14330 }
14331
14332 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14333   // Can also use sub to handle negated immediates.
14334   return isInt<32>(Imm);
14335 }
14336
14337 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14338   if (!VT1.isInteger() || !VT2.isInteger())
14339     return false;
14340   unsigned NumBits1 = VT1.getSizeInBits();
14341   unsigned NumBits2 = VT2.getSizeInBits();
14342   return NumBits1 > NumBits2;
14343 }
14344
14345 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14346   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14347   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14348 }
14349
14350 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14351   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14352   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14353 }
14354
14355 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14356   EVT VT1 = Val.getValueType();
14357   if (isZExtFree(VT1, VT2))
14358     return true;
14359
14360   if (Val.getOpcode() != ISD::LOAD)
14361     return false;
14362
14363   if (!VT1.isSimple() || !VT1.isInteger() ||
14364       !VT2.isSimple() || !VT2.isInteger())
14365     return false;
14366
14367   switch (VT1.getSimpleVT().SimpleTy) {
14368   default: break;
14369   case MVT::i8:
14370   case MVT::i16:
14371   case MVT::i32:
14372     // X86 has 8, 16, and 32-bit zero-extending loads.
14373     return true;
14374   }
14375
14376   return false;
14377 }
14378
14379 bool
14380 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14381   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14382     return false;
14383
14384   VT = VT.getScalarType();
14385
14386   if (!VT.isSimple())
14387     return false;
14388
14389   switch (VT.getSimpleVT().SimpleTy) {
14390   case MVT::f32:
14391   case MVT::f64:
14392     return true;
14393   default:
14394     break;
14395   }
14396
14397   return false;
14398 }
14399
14400 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14401   // i16 instructions are longer (0x66 prefix) and potentially slower.
14402   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14403 }
14404
14405 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14406 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14407 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14408 /// are assumed to be legal.
14409 bool
14410 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14411                                       EVT VT) const {
14412   if (!VT.isSimple())
14413     return false;
14414
14415   MVT SVT = VT.getSimpleVT();
14416
14417   // Very little shuffling can be done for 64-bit vectors right now.
14418   if (VT.getSizeInBits() == 64)
14419     return false;
14420
14421   // FIXME: pshufb, blends, shifts.
14422   return (SVT.getVectorNumElements() == 2 ||
14423           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14424           isMOVLMask(M, SVT) ||
14425           isSHUFPMask(M, SVT) ||
14426           isPSHUFDMask(M, SVT) ||
14427           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14428           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14429           isPALIGNRMask(M, SVT, Subtarget) ||
14430           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14431           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14432           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14433           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14434 }
14435
14436 bool
14437 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14438                                           EVT VT) const {
14439   if (!VT.isSimple())
14440     return false;
14441
14442   MVT SVT = VT.getSimpleVT();
14443   unsigned NumElts = SVT.getVectorNumElements();
14444   // FIXME: This collection of masks seems suspect.
14445   if (NumElts == 2)
14446     return true;
14447   if (NumElts == 4 && SVT.is128BitVector()) {
14448     return (isMOVLMask(Mask, SVT)  ||
14449             isCommutedMOVLMask(Mask, SVT, true) ||
14450             isSHUFPMask(Mask, SVT) ||
14451             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14452   }
14453   return false;
14454 }
14455
14456 //===----------------------------------------------------------------------===//
14457 //                           X86 Scheduler Hooks
14458 //===----------------------------------------------------------------------===//
14459
14460 /// Utility function to emit xbegin specifying the start of an RTM region.
14461 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14462                                      const TargetInstrInfo *TII) {
14463   DebugLoc DL = MI->getDebugLoc();
14464
14465   const BasicBlock *BB = MBB->getBasicBlock();
14466   MachineFunction::iterator I = MBB;
14467   ++I;
14468
14469   // For the v = xbegin(), we generate
14470   //
14471   // thisMBB:
14472   //  xbegin sinkMBB
14473   //
14474   // mainMBB:
14475   //  eax = -1
14476   //
14477   // sinkMBB:
14478   //  v = eax
14479
14480   MachineBasicBlock *thisMBB = MBB;
14481   MachineFunction *MF = MBB->getParent();
14482   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14483   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14484   MF->insert(I, mainMBB);
14485   MF->insert(I, sinkMBB);
14486
14487   // Transfer the remainder of BB and its successor edges to sinkMBB.
14488   sinkMBB->splice(sinkMBB->begin(), MBB,
14489                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14490   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14491
14492   // thisMBB:
14493   //  xbegin sinkMBB
14494   //  # fallthrough to mainMBB
14495   //  # abortion to sinkMBB
14496   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14497   thisMBB->addSuccessor(mainMBB);
14498   thisMBB->addSuccessor(sinkMBB);
14499
14500   // mainMBB:
14501   //  EAX = -1
14502   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14503   mainMBB->addSuccessor(sinkMBB);
14504
14505   // sinkMBB:
14506   // EAX is live into the sinkMBB
14507   sinkMBB->addLiveIn(X86::EAX);
14508   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14509           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14510     .addReg(X86::EAX);
14511
14512   MI->eraseFromParent();
14513   return sinkMBB;
14514 }
14515
14516 // Get CMPXCHG opcode for the specified data type.
14517 static unsigned getCmpXChgOpcode(EVT VT) {
14518   switch (VT.getSimpleVT().SimpleTy) {
14519   case MVT::i8:  return X86::LCMPXCHG8;
14520   case MVT::i16: return X86::LCMPXCHG16;
14521   case MVT::i32: return X86::LCMPXCHG32;
14522   case MVT::i64: return X86::LCMPXCHG64;
14523   default:
14524     break;
14525   }
14526   llvm_unreachable("Invalid operand size!");
14527 }
14528
14529 // Get LOAD opcode for the specified data type.
14530 static unsigned getLoadOpcode(EVT VT) {
14531   switch (VT.getSimpleVT().SimpleTy) {
14532   case MVT::i8:  return X86::MOV8rm;
14533   case MVT::i16: return X86::MOV16rm;
14534   case MVT::i32: return X86::MOV32rm;
14535   case MVT::i64: return X86::MOV64rm;
14536   default:
14537     break;
14538   }
14539   llvm_unreachable("Invalid operand size!");
14540 }
14541
14542 // Get opcode of the non-atomic one from the specified atomic instruction.
14543 static unsigned getNonAtomicOpcode(unsigned Opc) {
14544   switch (Opc) {
14545   case X86::ATOMAND8:  return X86::AND8rr;
14546   case X86::ATOMAND16: return X86::AND16rr;
14547   case X86::ATOMAND32: return X86::AND32rr;
14548   case X86::ATOMAND64: return X86::AND64rr;
14549   case X86::ATOMOR8:   return X86::OR8rr;
14550   case X86::ATOMOR16:  return X86::OR16rr;
14551   case X86::ATOMOR32:  return X86::OR32rr;
14552   case X86::ATOMOR64:  return X86::OR64rr;
14553   case X86::ATOMXOR8:  return X86::XOR8rr;
14554   case X86::ATOMXOR16: return X86::XOR16rr;
14555   case X86::ATOMXOR32: return X86::XOR32rr;
14556   case X86::ATOMXOR64: return X86::XOR64rr;
14557   }
14558   llvm_unreachable("Unhandled atomic-load-op opcode!");
14559 }
14560
14561 // Get opcode of the non-atomic one from the specified atomic instruction with
14562 // extra opcode.
14563 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14564                                                unsigned &ExtraOpc) {
14565   switch (Opc) {
14566   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14567   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14568   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14569   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14570   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14571   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14572   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14573   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14574   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14575   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14576   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14577   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14578   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14579   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14580   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14581   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14582   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14583   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14584   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14585   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14586   }
14587   llvm_unreachable("Unhandled atomic-load-op opcode!");
14588 }
14589
14590 // Get opcode of the non-atomic one from the specified atomic instruction for
14591 // 64-bit data type on 32-bit target.
14592 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14593   switch (Opc) {
14594   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14595   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14596   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14597   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14598   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14599   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14600   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14601   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14602   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14603   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14604   }
14605   llvm_unreachable("Unhandled atomic-load-op opcode!");
14606 }
14607
14608 // Get opcode of the non-atomic one from the specified atomic instruction for
14609 // 64-bit data type on 32-bit target with extra opcode.
14610 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14611                                                    unsigned &HiOpc,
14612                                                    unsigned &ExtraOpc) {
14613   switch (Opc) {
14614   case X86::ATOMNAND6432:
14615     ExtraOpc = X86::NOT32r;
14616     HiOpc = X86::AND32rr;
14617     return X86::AND32rr;
14618   }
14619   llvm_unreachable("Unhandled atomic-load-op opcode!");
14620 }
14621
14622 // Get pseudo CMOV opcode from the specified data type.
14623 static unsigned getPseudoCMOVOpc(EVT VT) {
14624   switch (VT.getSimpleVT().SimpleTy) {
14625   case MVT::i8:  return X86::CMOV_GR8;
14626   case MVT::i16: return X86::CMOV_GR16;
14627   case MVT::i32: return X86::CMOV_GR32;
14628   default:
14629     break;
14630   }
14631   llvm_unreachable("Unknown CMOV opcode!");
14632 }
14633
14634 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14635 // They will be translated into a spin-loop or compare-exchange loop from
14636 //
14637 //    ...
14638 //    dst = atomic-fetch-op MI.addr, MI.val
14639 //    ...
14640 //
14641 // to
14642 //
14643 //    ...
14644 //    t1 = LOAD MI.addr
14645 // loop:
14646 //    t4 = phi(t1, t3 / loop)
14647 //    t2 = OP MI.val, t4
14648 //    EAX = t4
14649 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14650 //    t3 = EAX
14651 //    JNE loop
14652 // sink:
14653 //    dst = t3
14654 //    ...
14655 MachineBasicBlock *
14656 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14657                                        MachineBasicBlock *MBB) const {
14658   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14659   DebugLoc DL = MI->getDebugLoc();
14660
14661   MachineFunction *MF = MBB->getParent();
14662   MachineRegisterInfo &MRI = MF->getRegInfo();
14663
14664   const BasicBlock *BB = MBB->getBasicBlock();
14665   MachineFunction::iterator I = MBB;
14666   ++I;
14667
14668   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14669          "Unexpected number of operands");
14670
14671   assert(MI->hasOneMemOperand() &&
14672          "Expected atomic-load-op to have one memoperand");
14673
14674   // Memory Reference
14675   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14676   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14677
14678   unsigned DstReg, SrcReg;
14679   unsigned MemOpndSlot;
14680
14681   unsigned CurOp = 0;
14682
14683   DstReg = MI->getOperand(CurOp++).getReg();
14684   MemOpndSlot = CurOp;
14685   CurOp += X86::AddrNumOperands;
14686   SrcReg = MI->getOperand(CurOp++).getReg();
14687
14688   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14689   MVT::SimpleValueType VT = *RC->vt_begin();
14690   unsigned t1 = MRI.createVirtualRegister(RC);
14691   unsigned t2 = MRI.createVirtualRegister(RC);
14692   unsigned t3 = MRI.createVirtualRegister(RC);
14693   unsigned t4 = MRI.createVirtualRegister(RC);
14694   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14695
14696   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14697   unsigned LOADOpc = getLoadOpcode(VT);
14698
14699   // For the atomic load-arith operator, we generate
14700   //
14701   //  thisMBB:
14702   //    t1 = LOAD [MI.addr]
14703   //  mainMBB:
14704   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14705   //    t1 = OP MI.val, EAX
14706   //    EAX = t4
14707   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14708   //    t3 = EAX
14709   //    JNE mainMBB
14710   //  sinkMBB:
14711   //    dst = t3
14712
14713   MachineBasicBlock *thisMBB = MBB;
14714   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14715   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14716   MF->insert(I, mainMBB);
14717   MF->insert(I, sinkMBB);
14718
14719   MachineInstrBuilder MIB;
14720
14721   // Transfer the remainder of BB and its successor edges to sinkMBB.
14722   sinkMBB->splice(sinkMBB->begin(), MBB,
14723                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14724   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14725
14726   // thisMBB:
14727   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14728   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14729     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14730     if (NewMO.isReg())
14731       NewMO.setIsKill(false);
14732     MIB.addOperand(NewMO);
14733   }
14734   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14735     unsigned flags = (*MMOI)->getFlags();
14736     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14737     MachineMemOperand *MMO =
14738       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14739                                (*MMOI)->getSize(),
14740                                (*MMOI)->getBaseAlignment(),
14741                                (*MMOI)->getTBAAInfo(),
14742                                (*MMOI)->getRanges());
14743     MIB.addMemOperand(MMO);
14744   }
14745
14746   thisMBB->addSuccessor(mainMBB);
14747
14748   // mainMBB:
14749   MachineBasicBlock *origMainMBB = mainMBB;
14750
14751   // Add a PHI.
14752   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14753                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14754
14755   unsigned Opc = MI->getOpcode();
14756   switch (Opc) {
14757   default:
14758     llvm_unreachable("Unhandled atomic-load-op opcode!");
14759   case X86::ATOMAND8:
14760   case X86::ATOMAND16:
14761   case X86::ATOMAND32:
14762   case X86::ATOMAND64:
14763   case X86::ATOMOR8:
14764   case X86::ATOMOR16:
14765   case X86::ATOMOR32:
14766   case X86::ATOMOR64:
14767   case X86::ATOMXOR8:
14768   case X86::ATOMXOR16:
14769   case X86::ATOMXOR32:
14770   case X86::ATOMXOR64: {
14771     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14772     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14773       .addReg(t4);
14774     break;
14775   }
14776   case X86::ATOMNAND8:
14777   case X86::ATOMNAND16:
14778   case X86::ATOMNAND32:
14779   case X86::ATOMNAND64: {
14780     unsigned Tmp = MRI.createVirtualRegister(RC);
14781     unsigned NOTOpc;
14782     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14783     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14784       .addReg(t4);
14785     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14786     break;
14787   }
14788   case X86::ATOMMAX8:
14789   case X86::ATOMMAX16:
14790   case X86::ATOMMAX32:
14791   case X86::ATOMMAX64:
14792   case X86::ATOMMIN8:
14793   case X86::ATOMMIN16:
14794   case X86::ATOMMIN32:
14795   case X86::ATOMMIN64:
14796   case X86::ATOMUMAX8:
14797   case X86::ATOMUMAX16:
14798   case X86::ATOMUMAX32:
14799   case X86::ATOMUMAX64:
14800   case X86::ATOMUMIN8:
14801   case X86::ATOMUMIN16:
14802   case X86::ATOMUMIN32:
14803   case X86::ATOMUMIN64: {
14804     unsigned CMPOpc;
14805     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14806
14807     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14808       .addReg(SrcReg)
14809       .addReg(t4);
14810
14811     if (Subtarget->hasCMov()) {
14812       if (VT != MVT::i8) {
14813         // Native support
14814         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14815           .addReg(SrcReg)
14816           .addReg(t4);
14817       } else {
14818         // Promote i8 to i32 to use CMOV32
14819         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14820         const TargetRegisterClass *RC32 =
14821           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14822         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14823         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14824         unsigned Tmp = MRI.createVirtualRegister(RC32);
14825
14826         unsigned Undef = MRI.createVirtualRegister(RC32);
14827         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14828
14829         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14830           .addReg(Undef)
14831           .addReg(SrcReg)
14832           .addImm(X86::sub_8bit);
14833         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14834           .addReg(Undef)
14835           .addReg(t4)
14836           .addImm(X86::sub_8bit);
14837
14838         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14839           .addReg(SrcReg32)
14840           .addReg(AccReg32);
14841
14842         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14843           .addReg(Tmp, 0, X86::sub_8bit);
14844       }
14845     } else {
14846       // Use pseudo select and lower them.
14847       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14848              "Invalid atomic-load-op transformation!");
14849       unsigned SelOpc = getPseudoCMOVOpc(VT);
14850       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14851       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14852       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14853               .addReg(SrcReg).addReg(t4)
14854               .addImm(CC);
14855       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14856       // Replace the original PHI node as mainMBB is changed after CMOV
14857       // lowering.
14858       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14859         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14860       Phi->eraseFromParent();
14861     }
14862     break;
14863   }
14864   }
14865
14866   // Copy PhyReg back from virtual register.
14867   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14868     .addReg(t4);
14869
14870   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14871   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14872     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14873     if (NewMO.isReg())
14874       NewMO.setIsKill(false);
14875     MIB.addOperand(NewMO);
14876   }
14877   MIB.addReg(t2);
14878   MIB.setMemRefs(MMOBegin, MMOEnd);
14879
14880   // Copy PhyReg back to virtual register.
14881   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14882     .addReg(PhyReg);
14883
14884   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14885
14886   mainMBB->addSuccessor(origMainMBB);
14887   mainMBB->addSuccessor(sinkMBB);
14888
14889   // sinkMBB:
14890   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14891           TII->get(TargetOpcode::COPY), DstReg)
14892     .addReg(t3);
14893
14894   MI->eraseFromParent();
14895   return sinkMBB;
14896 }
14897
14898 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14899 // instructions. They will be translated into a spin-loop or compare-exchange
14900 // loop from
14901 //
14902 //    ...
14903 //    dst = atomic-fetch-op MI.addr, MI.val
14904 //    ...
14905 //
14906 // to
14907 //
14908 //    ...
14909 //    t1L = LOAD [MI.addr + 0]
14910 //    t1H = LOAD [MI.addr + 4]
14911 // loop:
14912 //    t4L = phi(t1L, t3L / loop)
14913 //    t4H = phi(t1H, t3H / loop)
14914 //    t2L = OP MI.val.lo, t4L
14915 //    t2H = OP MI.val.hi, t4H
14916 //    EAX = t4L
14917 //    EDX = t4H
14918 //    EBX = t2L
14919 //    ECX = t2H
14920 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14921 //    t3L = EAX
14922 //    t3H = EDX
14923 //    JNE loop
14924 // sink:
14925 //    dstL = t3L
14926 //    dstH = t3H
14927 //    ...
14928 MachineBasicBlock *
14929 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14930                                            MachineBasicBlock *MBB) const {
14931   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14932   DebugLoc DL = MI->getDebugLoc();
14933
14934   MachineFunction *MF = MBB->getParent();
14935   MachineRegisterInfo &MRI = MF->getRegInfo();
14936
14937   const BasicBlock *BB = MBB->getBasicBlock();
14938   MachineFunction::iterator I = MBB;
14939   ++I;
14940
14941   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14942          "Unexpected number of operands");
14943
14944   assert(MI->hasOneMemOperand() &&
14945          "Expected atomic-load-op32 to have one memoperand");
14946
14947   // Memory Reference
14948   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14949   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14950
14951   unsigned DstLoReg, DstHiReg;
14952   unsigned SrcLoReg, SrcHiReg;
14953   unsigned MemOpndSlot;
14954
14955   unsigned CurOp = 0;
14956
14957   DstLoReg = MI->getOperand(CurOp++).getReg();
14958   DstHiReg = MI->getOperand(CurOp++).getReg();
14959   MemOpndSlot = CurOp;
14960   CurOp += X86::AddrNumOperands;
14961   SrcLoReg = MI->getOperand(CurOp++).getReg();
14962   SrcHiReg = MI->getOperand(CurOp++).getReg();
14963
14964   const TargetRegisterClass *RC = &X86::GR32RegClass;
14965   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14966
14967   unsigned t1L = MRI.createVirtualRegister(RC);
14968   unsigned t1H = MRI.createVirtualRegister(RC);
14969   unsigned t2L = MRI.createVirtualRegister(RC);
14970   unsigned t2H = MRI.createVirtualRegister(RC);
14971   unsigned t3L = MRI.createVirtualRegister(RC);
14972   unsigned t3H = MRI.createVirtualRegister(RC);
14973   unsigned t4L = MRI.createVirtualRegister(RC);
14974   unsigned t4H = MRI.createVirtualRegister(RC);
14975
14976   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14977   unsigned LOADOpc = X86::MOV32rm;
14978
14979   // For the atomic load-arith operator, we generate
14980   //
14981   //  thisMBB:
14982   //    t1L = LOAD [MI.addr + 0]
14983   //    t1H = LOAD [MI.addr + 4]
14984   //  mainMBB:
14985   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14986   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14987   //    t2L = OP MI.val.lo, t4L
14988   //    t2H = OP MI.val.hi, t4H
14989   //    EBX = t2L
14990   //    ECX = t2H
14991   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14992   //    t3L = EAX
14993   //    t3H = EDX
14994   //    JNE loop
14995   //  sinkMBB:
14996   //    dstL = t3L
14997   //    dstH = t3H
14998
14999   MachineBasicBlock *thisMBB = MBB;
15000   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15001   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15002   MF->insert(I, mainMBB);
15003   MF->insert(I, sinkMBB);
15004
15005   MachineInstrBuilder MIB;
15006
15007   // Transfer the remainder of BB and its successor edges to sinkMBB.
15008   sinkMBB->splice(sinkMBB->begin(), MBB,
15009                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15010   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15011
15012   // thisMBB:
15013   // Lo
15014   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15015   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15016     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15017     if (NewMO.isReg())
15018       NewMO.setIsKill(false);
15019     MIB.addOperand(NewMO);
15020   }
15021   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15022     unsigned flags = (*MMOI)->getFlags();
15023     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15024     MachineMemOperand *MMO =
15025       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15026                                (*MMOI)->getSize(),
15027                                (*MMOI)->getBaseAlignment(),
15028                                (*MMOI)->getTBAAInfo(),
15029                                (*MMOI)->getRanges());
15030     MIB.addMemOperand(MMO);
15031   };
15032   MachineInstr *LowMI = MIB;
15033
15034   // Hi
15035   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15036   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15037     if (i == X86::AddrDisp) {
15038       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15039     } else {
15040       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15041       if (NewMO.isReg())
15042         NewMO.setIsKill(false);
15043       MIB.addOperand(NewMO);
15044     }
15045   }
15046   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15047
15048   thisMBB->addSuccessor(mainMBB);
15049
15050   // mainMBB:
15051   MachineBasicBlock *origMainMBB = mainMBB;
15052
15053   // Add PHIs.
15054   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15055                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15056   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15057                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15058
15059   unsigned Opc = MI->getOpcode();
15060   switch (Opc) {
15061   default:
15062     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15063   case X86::ATOMAND6432:
15064   case X86::ATOMOR6432:
15065   case X86::ATOMXOR6432:
15066   case X86::ATOMADD6432:
15067   case X86::ATOMSUB6432: {
15068     unsigned HiOpc;
15069     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15070     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15071       .addReg(SrcLoReg);
15072     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15073       .addReg(SrcHiReg);
15074     break;
15075   }
15076   case X86::ATOMNAND6432: {
15077     unsigned HiOpc, NOTOpc;
15078     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15079     unsigned TmpL = MRI.createVirtualRegister(RC);
15080     unsigned TmpH = MRI.createVirtualRegister(RC);
15081     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15082       .addReg(t4L);
15083     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15084       .addReg(t4H);
15085     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15086     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15087     break;
15088   }
15089   case X86::ATOMMAX6432:
15090   case X86::ATOMMIN6432:
15091   case X86::ATOMUMAX6432:
15092   case X86::ATOMUMIN6432: {
15093     unsigned HiOpc;
15094     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15095     unsigned cL = MRI.createVirtualRegister(RC8);
15096     unsigned cH = MRI.createVirtualRegister(RC8);
15097     unsigned cL32 = MRI.createVirtualRegister(RC);
15098     unsigned cH32 = MRI.createVirtualRegister(RC);
15099     unsigned cc = MRI.createVirtualRegister(RC);
15100     // cl := cmp src_lo, lo
15101     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15102       .addReg(SrcLoReg).addReg(t4L);
15103     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15104     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15105     // ch := cmp src_hi, hi
15106     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15107       .addReg(SrcHiReg).addReg(t4H);
15108     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15109     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15110     // cc := if (src_hi == hi) ? cl : ch;
15111     if (Subtarget->hasCMov()) {
15112       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15113         .addReg(cH32).addReg(cL32);
15114     } else {
15115       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15116               .addReg(cH32).addReg(cL32)
15117               .addImm(X86::COND_E);
15118       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15119     }
15120     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15121     if (Subtarget->hasCMov()) {
15122       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15123         .addReg(SrcLoReg).addReg(t4L);
15124       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15125         .addReg(SrcHiReg).addReg(t4H);
15126     } else {
15127       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15128               .addReg(SrcLoReg).addReg(t4L)
15129               .addImm(X86::COND_NE);
15130       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15131       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15132       // 2nd CMOV lowering.
15133       mainMBB->addLiveIn(X86::EFLAGS);
15134       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15135               .addReg(SrcHiReg).addReg(t4H)
15136               .addImm(X86::COND_NE);
15137       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15138       // Replace the original PHI node as mainMBB is changed after CMOV
15139       // lowering.
15140       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15141         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15142       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15143         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15144       PhiL->eraseFromParent();
15145       PhiH->eraseFromParent();
15146     }
15147     break;
15148   }
15149   case X86::ATOMSWAP6432: {
15150     unsigned HiOpc;
15151     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15152     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15153     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15154     break;
15155   }
15156   }
15157
15158   // Copy EDX:EAX back from HiReg:LoReg
15159   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15160   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15161   // Copy ECX:EBX from t1H:t1L
15162   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15163   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15164
15165   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15166   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15167     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15168     if (NewMO.isReg())
15169       NewMO.setIsKill(false);
15170     MIB.addOperand(NewMO);
15171   }
15172   MIB.setMemRefs(MMOBegin, MMOEnd);
15173
15174   // Copy EDX:EAX back to t3H:t3L
15175   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15176   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15177
15178   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15179
15180   mainMBB->addSuccessor(origMainMBB);
15181   mainMBB->addSuccessor(sinkMBB);
15182
15183   // sinkMBB:
15184   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15185           TII->get(TargetOpcode::COPY), DstLoReg)
15186     .addReg(t3L);
15187   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15188           TII->get(TargetOpcode::COPY), DstHiReg)
15189     .addReg(t3H);
15190
15191   MI->eraseFromParent();
15192   return sinkMBB;
15193 }
15194
15195 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15196 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15197 // in the .td file.
15198 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15199                                        const TargetInstrInfo *TII) {
15200   unsigned Opc;
15201   switch (MI->getOpcode()) {
15202   default: llvm_unreachable("illegal opcode!");
15203   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15204   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15205   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15206   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15207   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15208   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15209   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15210   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15211   }
15212
15213   DebugLoc dl = MI->getDebugLoc();
15214   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15215
15216   unsigned NumArgs = MI->getNumOperands();
15217   for (unsigned i = 1; i < NumArgs; ++i) {
15218     MachineOperand &Op = MI->getOperand(i);
15219     if (!(Op.isReg() && Op.isImplicit()))
15220       MIB.addOperand(Op);
15221   }
15222   if (MI->hasOneMemOperand())
15223     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15224
15225   BuildMI(*BB, MI, dl,
15226     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15227     .addReg(X86::XMM0);
15228
15229   MI->eraseFromParent();
15230   return BB;
15231 }
15232
15233 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15234 // defs in an instruction pattern
15235 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15236                                        const TargetInstrInfo *TII) {
15237   unsigned Opc;
15238   switch (MI->getOpcode()) {
15239   default: llvm_unreachable("illegal opcode!");
15240   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15241   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15242   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15243   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15244   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15245   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15246   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15247   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15248   }
15249
15250   DebugLoc dl = MI->getDebugLoc();
15251   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15252
15253   unsigned NumArgs = MI->getNumOperands(); // remove the results
15254   for (unsigned i = 1; i < NumArgs; ++i) {
15255     MachineOperand &Op = MI->getOperand(i);
15256     if (!(Op.isReg() && Op.isImplicit()))
15257       MIB.addOperand(Op);
15258   }
15259   if (MI->hasOneMemOperand())
15260     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15261
15262   BuildMI(*BB, MI, dl,
15263     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15264     .addReg(X86::ECX);
15265
15266   MI->eraseFromParent();
15267   return BB;
15268 }
15269
15270 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15271                                        const TargetInstrInfo *TII,
15272                                        const X86Subtarget* Subtarget) {
15273   DebugLoc dl = MI->getDebugLoc();
15274
15275   // Address into RAX/EAX, other two args into ECX, EDX.
15276   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15277   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15278   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15279   for (int i = 0; i < X86::AddrNumOperands; ++i)
15280     MIB.addOperand(MI->getOperand(i));
15281
15282   unsigned ValOps = X86::AddrNumOperands;
15283   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15284     .addReg(MI->getOperand(ValOps).getReg());
15285   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15286     .addReg(MI->getOperand(ValOps+1).getReg());
15287
15288   // The instruction doesn't actually take any operands though.
15289   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15290
15291   MI->eraseFromParent(); // The pseudo is gone now.
15292   return BB;
15293 }
15294
15295 MachineBasicBlock *
15296 X86TargetLowering::EmitVAARG64WithCustomInserter(
15297                    MachineInstr *MI,
15298                    MachineBasicBlock *MBB) const {
15299   // Emit va_arg instruction on X86-64.
15300
15301   // Operands to this pseudo-instruction:
15302   // 0  ) Output        : destination address (reg)
15303   // 1-5) Input         : va_list address (addr, i64mem)
15304   // 6  ) ArgSize       : Size (in bytes) of vararg type
15305   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15306   // 8  ) Align         : Alignment of type
15307   // 9  ) EFLAGS (implicit-def)
15308
15309   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15310   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15311
15312   unsigned DestReg = MI->getOperand(0).getReg();
15313   MachineOperand &Base = MI->getOperand(1);
15314   MachineOperand &Scale = MI->getOperand(2);
15315   MachineOperand &Index = MI->getOperand(3);
15316   MachineOperand &Disp = MI->getOperand(4);
15317   MachineOperand &Segment = MI->getOperand(5);
15318   unsigned ArgSize = MI->getOperand(6).getImm();
15319   unsigned ArgMode = MI->getOperand(7).getImm();
15320   unsigned Align = MI->getOperand(8).getImm();
15321
15322   // Memory Reference
15323   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15324   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15325   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15326
15327   // Machine Information
15328   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15329   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15330   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15331   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15332   DebugLoc DL = MI->getDebugLoc();
15333
15334   // struct va_list {
15335   //   i32   gp_offset
15336   //   i32   fp_offset
15337   //   i64   overflow_area (address)
15338   //   i64   reg_save_area (address)
15339   // }
15340   // sizeof(va_list) = 24
15341   // alignment(va_list) = 8
15342
15343   unsigned TotalNumIntRegs = 6;
15344   unsigned TotalNumXMMRegs = 8;
15345   bool UseGPOffset = (ArgMode == 1);
15346   bool UseFPOffset = (ArgMode == 2);
15347   unsigned MaxOffset = TotalNumIntRegs * 8 +
15348                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15349
15350   /* Align ArgSize to a multiple of 8 */
15351   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15352   bool NeedsAlign = (Align > 8);
15353
15354   MachineBasicBlock *thisMBB = MBB;
15355   MachineBasicBlock *overflowMBB;
15356   MachineBasicBlock *offsetMBB;
15357   MachineBasicBlock *endMBB;
15358
15359   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15360   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15361   unsigned OffsetReg = 0;
15362
15363   if (!UseGPOffset && !UseFPOffset) {
15364     // If we only pull from the overflow region, we don't create a branch.
15365     // We don't need to alter control flow.
15366     OffsetDestReg = 0; // unused
15367     OverflowDestReg = DestReg;
15368
15369     offsetMBB = NULL;
15370     overflowMBB = thisMBB;
15371     endMBB = thisMBB;
15372   } else {
15373     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15374     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15375     // If not, pull from overflow_area. (branch to overflowMBB)
15376     //
15377     //       thisMBB
15378     //         |     .
15379     //         |        .
15380     //     offsetMBB   overflowMBB
15381     //         |        .
15382     //         |     .
15383     //        endMBB
15384
15385     // Registers for the PHI in endMBB
15386     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15387     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15388
15389     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15390     MachineFunction *MF = MBB->getParent();
15391     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15392     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15393     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15394
15395     MachineFunction::iterator MBBIter = MBB;
15396     ++MBBIter;
15397
15398     // Insert the new basic blocks
15399     MF->insert(MBBIter, offsetMBB);
15400     MF->insert(MBBIter, overflowMBB);
15401     MF->insert(MBBIter, endMBB);
15402
15403     // Transfer the remainder of MBB and its successor edges to endMBB.
15404     endMBB->splice(endMBB->begin(), thisMBB,
15405                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15406     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15407
15408     // Make offsetMBB and overflowMBB successors of thisMBB
15409     thisMBB->addSuccessor(offsetMBB);
15410     thisMBB->addSuccessor(overflowMBB);
15411
15412     // endMBB is a successor of both offsetMBB and overflowMBB
15413     offsetMBB->addSuccessor(endMBB);
15414     overflowMBB->addSuccessor(endMBB);
15415
15416     // Load the offset value into a register
15417     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15418     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15419       .addOperand(Base)
15420       .addOperand(Scale)
15421       .addOperand(Index)
15422       .addDisp(Disp, UseFPOffset ? 4 : 0)
15423       .addOperand(Segment)
15424       .setMemRefs(MMOBegin, MMOEnd);
15425
15426     // Check if there is enough room left to pull this argument.
15427     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15428       .addReg(OffsetReg)
15429       .addImm(MaxOffset + 8 - ArgSizeA8);
15430
15431     // Branch to "overflowMBB" if offset >= max
15432     // Fall through to "offsetMBB" otherwise
15433     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15434       .addMBB(overflowMBB);
15435   }
15436
15437   // In offsetMBB, emit code to use the reg_save_area.
15438   if (offsetMBB) {
15439     assert(OffsetReg != 0);
15440
15441     // Read the reg_save_area address.
15442     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15443     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15444       .addOperand(Base)
15445       .addOperand(Scale)
15446       .addOperand(Index)
15447       .addDisp(Disp, 16)
15448       .addOperand(Segment)
15449       .setMemRefs(MMOBegin, MMOEnd);
15450
15451     // Zero-extend the offset
15452     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15453       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15454         .addImm(0)
15455         .addReg(OffsetReg)
15456         .addImm(X86::sub_32bit);
15457
15458     // Add the offset to the reg_save_area to get the final address.
15459     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15460       .addReg(OffsetReg64)
15461       .addReg(RegSaveReg);
15462
15463     // Compute the offset for the next argument
15464     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15465     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15466       .addReg(OffsetReg)
15467       .addImm(UseFPOffset ? 16 : 8);
15468
15469     // Store it back into the va_list.
15470     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15471       .addOperand(Base)
15472       .addOperand(Scale)
15473       .addOperand(Index)
15474       .addDisp(Disp, UseFPOffset ? 4 : 0)
15475       .addOperand(Segment)
15476       .addReg(NextOffsetReg)
15477       .setMemRefs(MMOBegin, MMOEnd);
15478
15479     // Jump to endMBB
15480     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15481       .addMBB(endMBB);
15482   }
15483
15484   //
15485   // Emit code to use overflow area
15486   //
15487
15488   // Load the overflow_area address into a register.
15489   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15490   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15491     .addOperand(Base)
15492     .addOperand(Scale)
15493     .addOperand(Index)
15494     .addDisp(Disp, 8)
15495     .addOperand(Segment)
15496     .setMemRefs(MMOBegin, MMOEnd);
15497
15498   // If we need to align it, do so. Otherwise, just copy the address
15499   // to OverflowDestReg.
15500   if (NeedsAlign) {
15501     // Align the overflow address
15502     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15503     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15504
15505     // aligned_addr = (addr + (align-1)) & ~(align-1)
15506     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15507       .addReg(OverflowAddrReg)
15508       .addImm(Align-1);
15509
15510     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15511       .addReg(TmpReg)
15512       .addImm(~(uint64_t)(Align-1));
15513   } else {
15514     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15515       .addReg(OverflowAddrReg);
15516   }
15517
15518   // Compute the next overflow address after this argument.
15519   // (the overflow address should be kept 8-byte aligned)
15520   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15521   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15522     .addReg(OverflowDestReg)
15523     .addImm(ArgSizeA8);
15524
15525   // Store the new overflow address.
15526   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15527     .addOperand(Base)
15528     .addOperand(Scale)
15529     .addOperand(Index)
15530     .addDisp(Disp, 8)
15531     .addOperand(Segment)
15532     .addReg(NextAddrReg)
15533     .setMemRefs(MMOBegin, MMOEnd);
15534
15535   // If we branched, emit the PHI to the front of endMBB.
15536   if (offsetMBB) {
15537     BuildMI(*endMBB, endMBB->begin(), DL,
15538             TII->get(X86::PHI), DestReg)
15539       .addReg(OffsetDestReg).addMBB(offsetMBB)
15540       .addReg(OverflowDestReg).addMBB(overflowMBB);
15541   }
15542
15543   // Erase the pseudo instruction
15544   MI->eraseFromParent();
15545
15546   return endMBB;
15547 }
15548
15549 MachineBasicBlock *
15550 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15551                                                  MachineInstr *MI,
15552                                                  MachineBasicBlock *MBB) const {
15553   // Emit code to save XMM registers to the stack. The ABI says that the
15554   // number of registers to save is given in %al, so it's theoretically
15555   // possible to do an indirect jump trick to avoid saving all of them,
15556   // however this code takes a simpler approach and just executes all
15557   // of the stores if %al is non-zero. It's less code, and it's probably
15558   // easier on the hardware branch predictor, and stores aren't all that
15559   // expensive anyway.
15560
15561   // Create the new basic blocks. One block contains all the XMM stores,
15562   // and one block is the final destination regardless of whether any
15563   // stores were performed.
15564   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15565   MachineFunction *F = MBB->getParent();
15566   MachineFunction::iterator MBBIter = MBB;
15567   ++MBBIter;
15568   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15569   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15570   F->insert(MBBIter, XMMSaveMBB);
15571   F->insert(MBBIter, EndMBB);
15572
15573   // Transfer the remainder of MBB and its successor edges to EndMBB.
15574   EndMBB->splice(EndMBB->begin(), MBB,
15575                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15576   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15577
15578   // The original block will now fall through to the XMM save block.
15579   MBB->addSuccessor(XMMSaveMBB);
15580   // The XMMSaveMBB will fall through to the end block.
15581   XMMSaveMBB->addSuccessor(EndMBB);
15582
15583   // Now add the instructions.
15584   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15585   DebugLoc DL = MI->getDebugLoc();
15586
15587   unsigned CountReg = MI->getOperand(0).getReg();
15588   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15589   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15590
15591   if (!Subtarget->isTargetWin64()) {
15592     // If %al is 0, branch around the XMM save block.
15593     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15594     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15595     MBB->addSuccessor(EndMBB);
15596   }
15597
15598   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15599   // that was just emitted, but clearly shouldn't be "saved".
15600   assert((MI->getNumOperands() <= 3 ||
15601           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15602           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15603          && "Expected last argument to be EFLAGS");
15604   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15605   // In the XMM save block, save all the XMM argument registers.
15606   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15607     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15608     MachineMemOperand *MMO =
15609       F->getMachineMemOperand(
15610           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15611         MachineMemOperand::MOStore,
15612         /*Size=*/16, /*Align=*/16);
15613     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15614       .addFrameIndex(RegSaveFrameIndex)
15615       .addImm(/*Scale=*/1)
15616       .addReg(/*IndexReg=*/0)
15617       .addImm(/*Disp=*/Offset)
15618       .addReg(/*Segment=*/0)
15619       .addReg(MI->getOperand(i).getReg())
15620       .addMemOperand(MMO);
15621   }
15622
15623   MI->eraseFromParent();   // The pseudo instruction is gone now.
15624
15625   return EndMBB;
15626 }
15627
15628 // The EFLAGS operand of SelectItr might be missing a kill marker
15629 // because there were multiple uses of EFLAGS, and ISel didn't know
15630 // which to mark. Figure out whether SelectItr should have had a
15631 // kill marker, and set it if it should. Returns the correct kill
15632 // marker value.
15633 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15634                                      MachineBasicBlock* BB,
15635                                      const TargetRegisterInfo* TRI) {
15636   // Scan forward through BB for a use/def of EFLAGS.
15637   MachineBasicBlock::iterator miI(std::next(SelectItr));
15638   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15639     const MachineInstr& mi = *miI;
15640     if (mi.readsRegister(X86::EFLAGS))
15641       return false;
15642     if (mi.definesRegister(X86::EFLAGS))
15643       break; // Should have kill-flag - update below.
15644   }
15645
15646   // If we hit the end of the block, check whether EFLAGS is live into a
15647   // successor.
15648   if (miI == BB->end()) {
15649     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15650                                           sEnd = BB->succ_end();
15651          sItr != sEnd; ++sItr) {
15652       MachineBasicBlock* succ = *sItr;
15653       if (succ->isLiveIn(X86::EFLAGS))
15654         return false;
15655     }
15656   }
15657
15658   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15659   // out. SelectMI should have a kill flag on EFLAGS.
15660   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15661   return true;
15662 }
15663
15664 MachineBasicBlock *
15665 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15666                                      MachineBasicBlock *BB) const {
15667   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15668   DebugLoc DL = MI->getDebugLoc();
15669
15670   // To "insert" a SELECT_CC instruction, we actually have to insert the
15671   // diamond control-flow pattern.  The incoming instruction knows the
15672   // destination vreg to set, the condition code register to branch on, the
15673   // true/false values to select between, and a branch opcode to use.
15674   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15675   MachineFunction::iterator It = BB;
15676   ++It;
15677
15678   //  thisMBB:
15679   //  ...
15680   //   TrueVal = ...
15681   //   cmpTY ccX, r1, r2
15682   //   bCC copy1MBB
15683   //   fallthrough --> copy0MBB
15684   MachineBasicBlock *thisMBB = BB;
15685   MachineFunction *F = BB->getParent();
15686   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15687   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15688   F->insert(It, copy0MBB);
15689   F->insert(It, sinkMBB);
15690
15691   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15692   // live into the sink and copy blocks.
15693   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15694   if (!MI->killsRegister(X86::EFLAGS) &&
15695       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15696     copy0MBB->addLiveIn(X86::EFLAGS);
15697     sinkMBB->addLiveIn(X86::EFLAGS);
15698   }
15699
15700   // Transfer the remainder of BB and its successor edges to sinkMBB.
15701   sinkMBB->splice(sinkMBB->begin(), BB,
15702                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
15703   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15704
15705   // Add the true and fallthrough blocks as its successors.
15706   BB->addSuccessor(copy0MBB);
15707   BB->addSuccessor(sinkMBB);
15708
15709   // Create the conditional branch instruction.
15710   unsigned Opc =
15711     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15712   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15713
15714   //  copy0MBB:
15715   //   %FalseValue = ...
15716   //   # fallthrough to sinkMBB
15717   copy0MBB->addSuccessor(sinkMBB);
15718
15719   //  sinkMBB:
15720   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15721   //  ...
15722   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15723           TII->get(X86::PHI), MI->getOperand(0).getReg())
15724     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15725     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15726
15727   MI->eraseFromParent();   // The pseudo instruction is gone now.
15728   return sinkMBB;
15729 }
15730
15731 MachineBasicBlock *
15732 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15733                                         bool Is64Bit) const {
15734   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15735   DebugLoc DL = MI->getDebugLoc();
15736   MachineFunction *MF = BB->getParent();
15737   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15738
15739   assert(getTargetMachine().Options.EnableSegmentedStacks);
15740
15741   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15742   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15743
15744   // BB:
15745   //  ... [Till the alloca]
15746   // If stacklet is not large enough, jump to mallocMBB
15747   //
15748   // bumpMBB:
15749   //  Allocate by subtracting from RSP
15750   //  Jump to continueMBB
15751   //
15752   // mallocMBB:
15753   //  Allocate by call to runtime
15754   //
15755   // continueMBB:
15756   //  ...
15757   //  [rest of original BB]
15758   //
15759
15760   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15761   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15762   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15763
15764   MachineRegisterInfo &MRI = MF->getRegInfo();
15765   const TargetRegisterClass *AddrRegClass =
15766     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15767
15768   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15769     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15770     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15771     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15772     sizeVReg = MI->getOperand(1).getReg(),
15773     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15774
15775   MachineFunction::iterator MBBIter = BB;
15776   ++MBBIter;
15777
15778   MF->insert(MBBIter, bumpMBB);
15779   MF->insert(MBBIter, mallocMBB);
15780   MF->insert(MBBIter, continueMBB);
15781
15782   continueMBB->splice(continueMBB->begin(), BB,
15783                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
15784   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15785
15786   // Add code to the main basic block to check if the stack limit has been hit,
15787   // and if so, jump to mallocMBB otherwise to bumpMBB.
15788   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15789   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15790     .addReg(tmpSPVReg).addReg(sizeVReg);
15791   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15792     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15793     .addReg(SPLimitVReg);
15794   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15795
15796   // bumpMBB simply decreases the stack pointer, since we know the current
15797   // stacklet has enough space.
15798   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15799     .addReg(SPLimitVReg);
15800   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15801     .addReg(SPLimitVReg);
15802   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15803
15804   // Calls into a routine in libgcc to allocate more space from the heap.
15805   const uint32_t *RegMask =
15806     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15807   if (Is64Bit) {
15808     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15809       .addReg(sizeVReg);
15810     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15811       .addExternalSymbol("__morestack_allocate_stack_space")
15812       .addRegMask(RegMask)
15813       .addReg(X86::RDI, RegState::Implicit)
15814       .addReg(X86::RAX, RegState::ImplicitDefine);
15815   } else {
15816     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15817       .addImm(12);
15818     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15819     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15820       .addExternalSymbol("__morestack_allocate_stack_space")
15821       .addRegMask(RegMask)
15822       .addReg(X86::EAX, RegState::ImplicitDefine);
15823   }
15824
15825   if (!Is64Bit)
15826     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15827       .addImm(16);
15828
15829   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15830     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15831   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15832
15833   // Set up the CFG correctly.
15834   BB->addSuccessor(bumpMBB);
15835   BB->addSuccessor(mallocMBB);
15836   mallocMBB->addSuccessor(continueMBB);
15837   bumpMBB->addSuccessor(continueMBB);
15838
15839   // Take care of the PHI nodes.
15840   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15841           MI->getOperand(0).getReg())
15842     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15843     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15844
15845   // Delete the original pseudo instruction.
15846   MI->eraseFromParent();
15847
15848   // And we're done.
15849   return continueMBB;
15850 }
15851
15852 MachineBasicBlock *
15853 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15854                                           MachineBasicBlock *BB) const {
15855   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15856   DebugLoc DL = MI->getDebugLoc();
15857
15858   assert(!Subtarget->isTargetMacho());
15859
15860   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15861   // non-trivial part is impdef of ESP.
15862
15863   if (Subtarget->isTargetWin64()) {
15864     if (Subtarget->isTargetCygMing()) {
15865       // ___chkstk(Mingw64):
15866       // Clobbers R10, R11, RAX and EFLAGS.
15867       // Updates RSP.
15868       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15869         .addExternalSymbol("___chkstk")
15870         .addReg(X86::RAX, RegState::Implicit)
15871         .addReg(X86::RSP, RegState::Implicit)
15872         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15873         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15874         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15875     } else {
15876       // __chkstk(MSVCRT): does not update stack pointer.
15877       // Clobbers R10, R11 and EFLAGS.
15878       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15879         .addExternalSymbol("__chkstk")
15880         .addReg(X86::RAX, RegState::Implicit)
15881         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15882       // RAX has the offset to be subtracted from RSP.
15883       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15884         .addReg(X86::RSP)
15885         .addReg(X86::RAX);
15886     }
15887   } else {
15888     const char *StackProbeSymbol =
15889       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
15890
15891     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15892       .addExternalSymbol(StackProbeSymbol)
15893       .addReg(X86::EAX, RegState::Implicit)
15894       .addReg(X86::ESP, RegState::Implicit)
15895       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15896       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15897       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15898   }
15899
15900   MI->eraseFromParent();   // The pseudo instruction is gone now.
15901   return BB;
15902 }
15903
15904 MachineBasicBlock *
15905 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15906                                       MachineBasicBlock *BB) const {
15907   // This is pretty easy.  We're taking the value that we received from
15908   // our load from the relocation, sticking it in either RDI (x86-64)
15909   // or EAX and doing an indirect call.  The return value will then
15910   // be in the normal return register.
15911   const X86InstrInfo *TII
15912     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15913   DebugLoc DL = MI->getDebugLoc();
15914   MachineFunction *F = BB->getParent();
15915
15916   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15917   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15918
15919   // Get a register mask for the lowered call.
15920   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15921   // proper register mask.
15922   const uint32_t *RegMask =
15923     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15924   if (Subtarget->is64Bit()) {
15925     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15926                                       TII->get(X86::MOV64rm), X86::RDI)
15927     .addReg(X86::RIP)
15928     .addImm(0).addReg(0)
15929     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15930                       MI->getOperand(3).getTargetFlags())
15931     .addReg(0);
15932     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15933     addDirectMem(MIB, X86::RDI);
15934     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15935   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15936     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15937                                       TII->get(X86::MOV32rm), X86::EAX)
15938     .addReg(0)
15939     .addImm(0).addReg(0)
15940     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15941                       MI->getOperand(3).getTargetFlags())
15942     .addReg(0);
15943     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15944     addDirectMem(MIB, X86::EAX);
15945     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15946   } else {
15947     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15948                                       TII->get(X86::MOV32rm), X86::EAX)
15949     .addReg(TII->getGlobalBaseReg(F))
15950     .addImm(0).addReg(0)
15951     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15952                       MI->getOperand(3).getTargetFlags())
15953     .addReg(0);
15954     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15955     addDirectMem(MIB, X86::EAX);
15956     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15957   }
15958
15959   MI->eraseFromParent(); // The pseudo instruction is gone now.
15960   return BB;
15961 }
15962
15963 MachineBasicBlock *
15964 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15965                                     MachineBasicBlock *MBB) const {
15966   DebugLoc DL = MI->getDebugLoc();
15967   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15968
15969   MachineFunction *MF = MBB->getParent();
15970   MachineRegisterInfo &MRI = MF->getRegInfo();
15971
15972   const BasicBlock *BB = MBB->getBasicBlock();
15973   MachineFunction::iterator I = MBB;
15974   ++I;
15975
15976   // Memory Reference
15977   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15978   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15979
15980   unsigned DstReg;
15981   unsigned MemOpndSlot = 0;
15982
15983   unsigned CurOp = 0;
15984
15985   DstReg = MI->getOperand(CurOp++).getReg();
15986   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15987   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15988   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15989   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15990
15991   MemOpndSlot = CurOp;
15992
15993   MVT PVT = getPointerTy();
15994   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15995          "Invalid Pointer Size!");
15996
15997   // For v = setjmp(buf), we generate
15998   //
15999   // thisMBB:
16000   //  buf[LabelOffset] = restoreMBB
16001   //  SjLjSetup restoreMBB
16002   //
16003   // mainMBB:
16004   //  v_main = 0
16005   //
16006   // sinkMBB:
16007   //  v = phi(main, restore)
16008   //
16009   // restoreMBB:
16010   //  v_restore = 1
16011
16012   MachineBasicBlock *thisMBB = MBB;
16013   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16014   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16015   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16016   MF->insert(I, mainMBB);
16017   MF->insert(I, sinkMBB);
16018   MF->push_back(restoreMBB);
16019
16020   MachineInstrBuilder MIB;
16021
16022   // Transfer the remainder of BB and its successor edges to sinkMBB.
16023   sinkMBB->splice(sinkMBB->begin(), MBB,
16024                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16025   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16026
16027   // thisMBB:
16028   unsigned PtrStoreOpc = 0;
16029   unsigned LabelReg = 0;
16030   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16031   Reloc::Model RM = getTargetMachine().getRelocationModel();
16032   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16033                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16034
16035   // Prepare IP either in reg or imm.
16036   if (!UseImmLabel) {
16037     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16038     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16039     LabelReg = MRI.createVirtualRegister(PtrRC);
16040     if (Subtarget->is64Bit()) {
16041       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16042               .addReg(X86::RIP)
16043               .addImm(0)
16044               .addReg(0)
16045               .addMBB(restoreMBB)
16046               .addReg(0);
16047     } else {
16048       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16049       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16050               .addReg(XII->getGlobalBaseReg(MF))
16051               .addImm(0)
16052               .addReg(0)
16053               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16054               .addReg(0);
16055     }
16056   } else
16057     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16058   // Store IP
16059   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16060   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16061     if (i == X86::AddrDisp)
16062       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16063     else
16064       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16065   }
16066   if (!UseImmLabel)
16067     MIB.addReg(LabelReg);
16068   else
16069     MIB.addMBB(restoreMBB);
16070   MIB.setMemRefs(MMOBegin, MMOEnd);
16071   // Setup
16072   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16073           .addMBB(restoreMBB);
16074
16075   const X86RegisterInfo *RegInfo =
16076     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16077   MIB.addRegMask(RegInfo->getNoPreservedMask());
16078   thisMBB->addSuccessor(mainMBB);
16079   thisMBB->addSuccessor(restoreMBB);
16080
16081   // mainMBB:
16082   //  EAX = 0
16083   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16084   mainMBB->addSuccessor(sinkMBB);
16085
16086   // sinkMBB:
16087   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16088           TII->get(X86::PHI), DstReg)
16089     .addReg(mainDstReg).addMBB(mainMBB)
16090     .addReg(restoreDstReg).addMBB(restoreMBB);
16091
16092   // restoreMBB:
16093   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16094   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16095   restoreMBB->addSuccessor(sinkMBB);
16096
16097   MI->eraseFromParent();
16098   return sinkMBB;
16099 }
16100
16101 MachineBasicBlock *
16102 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16103                                      MachineBasicBlock *MBB) const {
16104   DebugLoc DL = MI->getDebugLoc();
16105   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16106
16107   MachineFunction *MF = MBB->getParent();
16108   MachineRegisterInfo &MRI = MF->getRegInfo();
16109
16110   // Memory Reference
16111   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16112   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16113
16114   MVT PVT = getPointerTy();
16115   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16116          "Invalid Pointer Size!");
16117
16118   const TargetRegisterClass *RC =
16119     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16120   unsigned Tmp = MRI.createVirtualRegister(RC);
16121   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16122   const X86RegisterInfo *RegInfo =
16123     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16124   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16125   unsigned SP = RegInfo->getStackRegister();
16126
16127   MachineInstrBuilder MIB;
16128
16129   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16130   const int64_t SPOffset = 2 * PVT.getStoreSize();
16131
16132   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16133   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16134
16135   // Reload FP
16136   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16137   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16138     MIB.addOperand(MI->getOperand(i));
16139   MIB.setMemRefs(MMOBegin, MMOEnd);
16140   // Reload IP
16141   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16142   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16143     if (i == X86::AddrDisp)
16144       MIB.addDisp(MI->getOperand(i), LabelOffset);
16145     else
16146       MIB.addOperand(MI->getOperand(i));
16147   }
16148   MIB.setMemRefs(MMOBegin, MMOEnd);
16149   // Reload SP
16150   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16151   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16152     if (i == X86::AddrDisp)
16153       MIB.addDisp(MI->getOperand(i), SPOffset);
16154     else
16155       MIB.addOperand(MI->getOperand(i));
16156   }
16157   MIB.setMemRefs(MMOBegin, MMOEnd);
16158   // Jump
16159   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16160
16161   MI->eraseFromParent();
16162   return MBB;
16163 }
16164
16165 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16166 // accumulator loops. Writing back to the accumulator allows the coalescer
16167 // to remove extra copies in the loop.   
16168 MachineBasicBlock *
16169 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16170                                  MachineBasicBlock *MBB) const {
16171   MachineOperand &AddendOp = MI->getOperand(3);
16172
16173   // Bail out early if the addend isn't a register - we can't switch these.
16174   if (!AddendOp.isReg())
16175     return MBB;
16176
16177   MachineFunction &MF = *MBB->getParent();
16178   MachineRegisterInfo &MRI = MF.getRegInfo();
16179
16180   // Check whether the addend is defined by a PHI:
16181   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16182   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16183   if (!AddendDef.isPHI())
16184     return MBB;
16185
16186   // Look for the following pattern:
16187   // loop:
16188   //   %addend = phi [%entry, 0], [%loop, %result]
16189   //   ...
16190   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16191
16192   // Replace with:
16193   //   loop:
16194   //   %addend = phi [%entry, 0], [%loop, %result]
16195   //   ...
16196   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16197
16198   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16199     assert(AddendDef.getOperand(i).isReg());
16200     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16201     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16202     if (&PHISrcInst == MI) {
16203       // Found a matching instruction.
16204       unsigned NewFMAOpc = 0;
16205       switch (MI->getOpcode()) {
16206         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16207         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16208         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16209         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16210         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16211         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16212         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16213         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16214         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16215         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16216         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16217         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16218         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16219         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16220         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16221         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16222         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16223         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16224         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16225         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16226         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16227         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16228         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16229         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16230         default: llvm_unreachable("Unrecognized FMA variant.");
16231       }
16232
16233       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16234       MachineInstrBuilder MIB =
16235         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16236         .addOperand(MI->getOperand(0))
16237         .addOperand(MI->getOperand(3))
16238         .addOperand(MI->getOperand(2))
16239         .addOperand(MI->getOperand(1));
16240       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16241       MI->eraseFromParent();
16242     }
16243   }
16244
16245   return MBB;
16246 }
16247
16248 MachineBasicBlock *
16249 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16250                                                MachineBasicBlock *BB) const {
16251   switch (MI->getOpcode()) {
16252   default: llvm_unreachable("Unexpected instr type to insert");
16253   case X86::TAILJMPd64:
16254   case X86::TAILJMPr64:
16255   case X86::TAILJMPm64:
16256     llvm_unreachable("TAILJMP64 would not be touched here.");
16257   case X86::TCRETURNdi64:
16258   case X86::TCRETURNri64:
16259   case X86::TCRETURNmi64:
16260     return BB;
16261   case X86::WIN_ALLOCA:
16262     return EmitLoweredWinAlloca(MI, BB);
16263   case X86::SEG_ALLOCA_32:
16264     return EmitLoweredSegAlloca(MI, BB, false);
16265   case X86::SEG_ALLOCA_64:
16266     return EmitLoweredSegAlloca(MI, BB, true);
16267   case X86::TLSCall_32:
16268   case X86::TLSCall_64:
16269     return EmitLoweredTLSCall(MI, BB);
16270   case X86::CMOV_GR8:
16271   case X86::CMOV_FR32:
16272   case X86::CMOV_FR64:
16273   case X86::CMOV_V4F32:
16274   case X86::CMOV_V2F64:
16275   case X86::CMOV_V2I64:
16276   case X86::CMOV_V8F32:
16277   case X86::CMOV_V4F64:
16278   case X86::CMOV_V4I64:
16279   case X86::CMOV_V16F32:
16280   case X86::CMOV_V8F64:
16281   case X86::CMOV_V8I64:
16282   case X86::CMOV_GR16:
16283   case X86::CMOV_GR32:
16284   case X86::CMOV_RFP32:
16285   case X86::CMOV_RFP64:
16286   case X86::CMOV_RFP80:
16287     return EmitLoweredSelect(MI, BB);
16288
16289   case X86::FP32_TO_INT16_IN_MEM:
16290   case X86::FP32_TO_INT32_IN_MEM:
16291   case X86::FP32_TO_INT64_IN_MEM:
16292   case X86::FP64_TO_INT16_IN_MEM:
16293   case X86::FP64_TO_INT32_IN_MEM:
16294   case X86::FP64_TO_INT64_IN_MEM:
16295   case X86::FP80_TO_INT16_IN_MEM:
16296   case X86::FP80_TO_INT32_IN_MEM:
16297   case X86::FP80_TO_INT64_IN_MEM: {
16298     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16299     DebugLoc DL = MI->getDebugLoc();
16300
16301     // Change the floating point control register to use "round towards zero"
16302     // mode when truncating to an integer value.
16303     MachineFunction *F = BB->getParent();
16304     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16305     addFrameReference(BuildMI(*BB, MI, DL,
16306                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16307
16308     // Load the old value of the high byte of the control word...
16309     unsigned OldCW =
16310       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16311     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16312                       CWFrameIdx);
16313
16314     // Set the high part to be round to zero...
16315     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16316       .addImm(0xC7F);
16317
16318     // Reload the modified control word now...
16319     addFrameReference(BuildMI(*BB, MI, DL,
16320                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16321
16322     // Restore the memory image of control word to original value
16323     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16324       .addReg(OldCW);
16325
16326     // Get the X86 opcode to use.
16327     unsigned Opc;
16328     switch (MI->getOpcode()) {
16329     default: llvm_unreachable("illegal opcode!");
16330     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16331     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16332     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16333     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16334     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16335     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16336     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16337     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16338     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16339     }
16340
16341     X86AddressMode AM;
16342     MachineOperand &Op = MI->getOperand(0);
16343     if (Op.isReg()) {
16344       AM.BaseType = X86AddressMode::RegBase;
16345       AM.Base.Reg = Op.getReg();
16346     } else {
16347       AM.BaseType = X86AddressMode::FrameIndexBase;
16348       AM.Base.FrameIndex = Op.getIndex();
16349     }
16350     Op = MI->getOperand(1);
16351     if (Op.isImm())
16352       AM.Scale = Op.getImm();
16353     Op = MI->getOperand(2);
16354     if (Op.isImm())
16355       AM.IndexReg = Op.getImm();
16356     Op = MI->getOperand(3);
16357     if (Op.isGlobal()) {
16358       AM.GV = Op.getGlobal();
16359     } else {
16360       AM.Disp = Op.getImm();
16361     }
16362     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16363                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16364
16365     // Reload the original control word now.
16366     addFrameReference(BuildMI(*BB, MI, DL,
16367                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16368
16369     MI->eraseFromParent();   // The pseudo instruction is gone now.
16370     return BB;
16371   }
16372     // String/text processing lowering.
16373   case X86::PCMPISTRM128REG:
16374   case X86::VPCMPISTRM128REG:
16375   case X86::PCMPISTRM128MEM:
16376   case X86::VPCMPISTRM128MEM:
16377   case X86::PCMPESTRM128REG:
16378   case X86::VPCMPESTRM128REG:
16379   case X86::PCMPESTRM128MEM:
16380   case X86::VPCMPESTRM128MEM:
16381     assert(Subtarget->hasSSE42() &&
16382            "Target must have SSE4.2 or AVX features enabled");
16383     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16384
16385   // String/text processing lowering.
16386   case X86::PCMPISTRIREG:
16387   case X86::VPCMPISTRIREG:
16388   case X86::PCMPISTRIMEM:
16389   case X86::VPCMPISTRIMEM:
16390   case X86::PCMPESTRIREG:
16391   case X86::VPCMPESTRIREG:
16392   case X86::PCMPESTRIMEM:
16393   case X86::VPCMPESTRIMEM:
16394     assert(Subtarget->hasSSE42() &&
16395            "Target must have SSE4.2 or AVX features enabled");
16396     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16397
16398   // Thread synchronization.
16399   case X86::MONITOR:
16400     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16401
16402   // xbegin
16403   case X86::XBEGIN:
16404     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16405
16406   // Atomic Lowering.
16407   case X86::ATOMAND8:
16408   case X86::ATOMAND16:
16409   case X86::ATOMAND32:
16410   case X86::ATOMAND64:
16411     // Fall through
16412   case X86::ATOMOR8:
16413   case X86::ATOMOR16:
16414   case X86::ATOMOR32:
16415   case X86::ATOMOR64:
16416     // Fall through
16417   case X86::ATOMXOR16:
16418   case X86::ATOMXOR8:
16419   case X86::ATOMXOR32:
16420   case X86::ATOMXOR64:
16421     // Fall through
16422   case X86::ATOMNAND8:
16423   case X86::ATOMNAND16:
16424   case X86::ATOMNAND32:
16425   case X86::ATOMNAND64:
16426     // Fall through
16427   case X86::ATOMMAX8:
16428   case X86::ATOMMAX16:
16429   case X86::ATOMMAX32:
16430   case X86::ATOMMAX64:
16431     // Fall through
16432   case X86::ATOMMIN8:
16433   case X86::ATOMMIN16:
16434   case X86::ATOMMIN32:
16435   case X86::ATOMMIN64:
16436     // Fall through
16437   case X86::ATOMUMAX8:
16438   case X86::ATOMUMAX16:
16439   case X86::ATOMUMAX32:
16440   case X86::ATOMUMAX64:
16441     // Fall through
16442   case X86::ATOMUMIN8:
16443   case X86::ATOMUMIN16:
16444   case X86::ATOMUMIN32:
16445   case X86::ATOMUMIN64:
16446     return EmitAtomicLoadArith(MI, BB);
16447
16448   // This group does 64-bit operations on a 32-bit host.
16449   case X86::ATOMAND6432:
16450   case X86::ATOMOR6432:
16451   case X86::ATOMXOR6432:
16452   case X86::ATOMNAND6432:
16453   case X86::ATOMADD6432:
16454   case X86::ATOMSUB6432:
16455   case X86::ATOMMAX6432:
16456   case X86::ATOMMIN6432:
16457   case X86::ATOMUMAX6432:
16458   case X86::ATOMUMIN6432:
16459   case X86::ATOMSWAP6432:
16460     return EmitAtomicLoadArith6432(MI, BB);
16461
16462   case X86::VASTART_SAVE_XMM_REGS:
16463     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16464
16465   case X86::VAARG_64:
16466     return EmitVAARG64WithCustomInserter(MI, BB);
16467
16468   case X86::EH_SjLj_SetJmp32:
16469   case X86::EH_SjLj_SetJmp64:
16470     return emitEHSjLjSetJmp(MI, BB);
16471
16472   case X86::EH_SjLj_LongJmp32:
16473   case X86::EH_SjLj_LongJmp64:
16474     return emitEHSjLjLongJmp(MI, BB);
16475
16476   case TargetOpcode::STACKMAP:
16477   case TargetOpcode::PATCHPOINT:
16478     return emitPatchPoint(MI, BB);
16479
16480   case X86::VFMADDPDr213r:
16481   case X86::VFMADDPSr213r:
16482   case X86::VFMADDSDr213r:
16483   case X86::VFMADDSSr213r:
16484   case X86::VFMSUBPDr213r:
16485   case X86::VFMSUBPSr213r:
16486   case X86::VFMSUBSDr213r:
16487   case X86::VFMSUBSSr213r:
16488   case X86::VFNMADDPDr213r:
16489   case X86::VFNMADDPSr213r:
16490   case X86::VFNMADDSDr213r:
16491   case X86::VFNMADDSSr213r:
16492   case X86::VFNMSUBPDr213r:
16493   case X86::VFNMSUBPSr213r:
16494   case X86::VFNMSUBSDr213r:
16495   case X86::VFNMSUBSSr213r:
16496   case X86::VFMADDPDr213rY:
16497   case X86::VFMADDPSr213rY:
16498   case X86::VFMSUBPDr213rY:
16499   case X86::VFMSUBPSr213rY:
16500   case X86::VFNMADDPDr213rY:
16501   case X86::VFNMADDPSr213rY:
16502   case X86::VFNMSUBPDr213rY:
16503   case X86::VFNMSUBPSr213rY:
16504     return emitFMA3Instr(MI, BB);
16505   }
16506 }
16507
16508 //===----------------------------------------------------------------------===//
16509 //                           X86 Optimization Hooks
16510 //===----------------------------------------------------------------------===//
16511
16512 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16513                                                        APInt &KnownZero,
16514                                                        APInt &KnownOne,
16515                                                        const SelectionDAG &DAG,
16516                                                        unsigned Depth) const {
16517   unsigned BitWidth = KnownZero.getBitWidth();
16518   unsigned Opc = Op.getOpcode();
16519   assert((Opc >= ISD::BUILTIN_OP_END ||
16520           Opc == ISD::INTRINSIC_WO_CHAIN ||
16521           Opc == ISD::INTRINSIC_W_CHAIN ||
16522           Opc == ISD::INTRINSIC_VOID) &&
16523          "Should use MaskedValueIsZero if you don't know whether Op"
16524          " is a target node!");
16525
16526   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16527   switch (Opc) {
16528   default: break;
16529   case X86ISD::ADD:
16530   case X86ISD::SUB:
16531   case X86ISD::ADC:
16532   case X86ISD::SBB:
16533   case X86ISD::SMUL:
16534   case X86ISD::UMUL:
16535   case X86ISD::INC:
16536   case X86ISD::DEC:
16537   case X86ISD::OR:
16538   case X86ISD::XOR:
16539   case X86ISD::AND:
16540     // These nodes' second result is a boolean.
16541     if (Op.getResNo() == 0)
16542       break;
16543     // Fallthrough
16544   case X86ISD::SETCC:
16545     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16546     break;
16547   case ISD::INTRINSIC_WO_CHAIN: {
16548     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16549     unsigned NumLoBits = 0;
16550     switch (IntId) {
16551     default: break;
16552     case Intrinsic::x86_sse_movmsk_ps:
16553     case Intrinsic::x86_avx_movmsk_ps_256:
16554     case Intrinsic::x86_sse2_movmsk_pd:
16555     case Intrinsic::x86_avx_movmsk_pd_256:
16556     case Intrinsic::x86_mmx_pmovmskb:
16557     case Intrinsic::x86_sse2_pmovmskb_128:
16558     case Intrinsic::x86_avx2_pmovmskb: {
16559       // High bits of movmskp{s|d}, pmovmskb are known zero.
16560       switch (IntId) {
16561         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16562         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16563         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16564         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16565         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16566         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16567         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16568         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16569       }
16570       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16571       break;
16572     }
16573     }
16574     break;
16575   }
16576   }
16577 }
16578
16579 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16580   SDValue Op,
16581   const SelectionDAG &,
16582   unsigned Depth) const {
16583   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16584   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16585     return Op.getValueType().getScalarType().getSizeInBits();
16586
16587   // Fallback case.
16588   return 1;
16589 }
16590
16591 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16592 /// node is a GlobalAddress + offset.
16593 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16594                                        const GlobalValue* &GA,
16595                                        int64_t &Offset) const {
16596   if (N->getOpcode() == X86ISD::Wrapper) {
16597     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16598       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16599       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16600       return true;
16601     }
16602   }
16603   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16604 }
16605
16606 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16607 /// same as extracting the high 128-bit part of 256-bit vector and then
16608 /// inserting the result into the low part of a new 256-bit vector
16609 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16610   EVT VT = SVOp->getValueType(0);
16611   unsigned NumElems = VT.getVectorNumElements();
16612
16613   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16614   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16615     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16616         SVOp->getMaskElt(j) >= 0)
16617       return false;
16618
16619   return true;
16620 }
16621
16622 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16623 /// same as extracting the low 128-bit part of 256-bit vector and then
16624 /// inserting the result into the high part of a new 256-bit vector
16625 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16626   EVT VT = SVOp->getValueType(0);
16627   unsigned NumElems = VT.getVectorNumElements();
16628
16629   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16630   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16631     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16632         SVOp->getMaskElt(j) >= 0)
16633       return false;
16634
16635   return true;
16636 }
16637
16638 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16639 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16640                                         TargetLowering::DAGCombinerInfo &DCI,
16641                                         const X86Subtarget* Subtarget) {
16642   SDLoc dl(N);
16643   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16644   SDValue V1 = SVOp->getOperand(0);
16645   SDValue V2 = SVOp->getOperand(1);
16646   EVT VT = SVOp->getValueType(0);
16647   unsigned NumElems = VT.getVectorNumElements();
16648
16649   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16650       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16651     //
16652     //                   0,0,0,...
16653     //                      |
16654     //    V      UNDEF    BUILD_VECTOR    UNDEF
16655     //     \      /           \           /
16656     //  CONCAT_VECTOR         CONCAT_VECTOR
16657     //         \                  /
16658     //          \                /
16659     //          RESULT: V + zero extended
16660     //
16661     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16662         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16663         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16664       return SDValue();
16665
16666     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16667       return SDValue();
16668
16669     // To match the shuffle mask, the first half of the mask should
16670     // be exactly the first vector, and all the rest a splat with the
16671     // first element of the second one.
16672     for (unsigned i = 0; i != NumElems/2; ++i)
16673       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16674           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16675         return SDValue();
16676
16677     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16678     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16679       if (Ld->hasNUsesOfValue(1, 0)) {
16680         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16681         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16682         SDValue ResNode =
16683           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16684                                   array_lengthof(Ops),
16685                                   Ld->getMemoryVT(),
16686                                   Ld->getPointerInfo(),
16687                                   Ld->getAlignment(),
16688                                   false/*isVolatile*/, true/*ReadMem*/,
16689                                   false/*WriteMem*/);
16690
16691         // Make sure the newly-created LOAD is in the same position as Ld in
16692         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16693         // and update uses of Ld's output chain to use the TokenFactor.
16694         if (Ld->hasAnyUseOfValue(1)) {
16695           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16696                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16697           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16698           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16699                                  SDValue(ResNode.getNode(), 1));
16700         }
16701
16702         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16703       }
16704     }
16705
16706     // Emit a zeroed vector and insert the desired subvector on its
16707     // first half.
16708     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16709     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16710     return DCI.CombineTo(N, InsV);
16711   }
16712
16713   //===--------------------------------------------------------------------===//
16714   // Combine some shuffles into subvector extracts and inserts:
16715   //
16716
16717   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16718   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16719     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16720     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16721     return DCI.CombineTo(N, InsV);
16722   }
16723
16724   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16725   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16726     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16727     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16728     return DCI.CombineTo(N, InsV);
16729   }
16730
16731   return SDValue();
16732 }
16733
16734 /// PerformShuffleCombine - Performs several different shuffle combines.
16735 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16736                                      TargetLowering::DAGCombinerInfo &DCI,
16737                                      const X86Subtarget *Subtarget) {
16738   SDLoc dl(N);
16739   EVT VT = N->getValueType(0);
16740
16741   // Don't create instructions with illegal types after legalize types has run.
16742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16743   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16744     return SDValue();
16745
16746   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16747   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16748       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16749     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16750
16751   // Only handle 128 wide vector from here on.
16752   if (!VT.is128BitVector())
16753     return SDValue();
16754
16755   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16756   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16757   // consecutive, non-overlapping, and in the right order.
16758   SmallVector<SDValue, 16> Elts;
16759   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16760     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16761
16762   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16763 }
16764
16765 /// PerformTruncateCombine - Converts truncate operation to
16766 /// a sequence of vector shuffle operations.
16767 /// It is possible when we truncate 256-bit vector to 128-bit vector
16768 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16769                                       TargetLowering::DAGCombinerInfo &DCI,
16770                                       const X86Subtarget *Subtarget)  {
16771   return SDValue();
16772 }
16773
16774 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16775 /// specific shuffle of a load can be folded into a single element load.
16776 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16777 /// shuffles have been customed lowered so we need to handle those here.
16778 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16779                                          TargetLowering::DAGCombinerInfo &DCI) {
16780   if (DCI.isBeforeLegalizeOps())
16781     return SDValue();
16782
16783   SDValue InVec = N->getOperand(0);
16784   SDValue EltNo = N->getOperand(1);
16785
16786   if (!isa<ConstantSDNode>(EltNo))
16787     return SDValue();
16788
16789   EVT VT = InVec.getValueType();
16790
16791   bool HasShuffleIntoBitcast = false;
16792   if (InVec.getOpcode() == ISD::BITCAST) {
16793     // Don't duplicate a load with other uses.
16794     if (!InVec.hasOneUse())
16795       return SDValue();
16796     EVT BCVT = InVec.getOperand(0).getValueType();
16797     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16798       return SDValue();
16799     InVec = InVec.getOperand(0);
16800     HasShuffleIntoBitcast = true;
16801   }
16802
16803   if (!isTargetShuffle(InVec.getOpcode()))
16804     return SDValue();
16805
16806   // Don't duplicate a load with other uses.
16807   if (!InVec.hasOneUse())
16808     return SDValue();
16809
16810   SmallVector<int, 16> ShuffleMask;
16811   bool UnaryShuffle;
16812   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16813                             UnaryShuffle))
16814     return SDValue();
16815
16816   // Select the input vector, guarding against out of range extract vector.
16817   unsigned NumElems = VT.getVectorNumElements();
16818   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16819   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16820   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16821                                          : InVec.getOperand(1);
16822
16823   // If inputs to shuffle are the same for both ops, then allow 2 uses
16824   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16825
16826   if (LdNode.getOpcode() == ISD::BITCAST) {
16827     // Don't duplicate a load with other uses.
16828     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16829       return SDValue();
16830
16831     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16832     LdNode = LdNode.getOperand(0);
16833   }
16834
16835   if (!ISD::isNormalLoad(LdNode.getNode()))
16836     return SDValue();
16837
16838   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16839
16840   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16841     return SDValue();
16842
16843   if (HasShuffleIntoBitcast) {
16844     // If there's a bitcast before the shuffle, check if the load type and
16845     // alignment is valid.
16846     unsigned Align = LN0->getAlignment();
16847     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16848     unsigned NewAlign = TLI.getDataLayout()->
16849       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16850
16851     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16852       return SDValue();
16853   }
16854
16855   // All checks match so transform back to vector_shuffle so that DAG combiner
16856   // can finish the job
16857   SDLoc dl(N);
16858
16859   // Create shuffle node taking into account the case that its a unary shuffle
16860   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16861   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16862                                  InVec.getOperand(0), Shuffle,
16863                                  &ShuffleMask[0]);
16864   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16865   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16866                      EltNo);
16867 }
16868
16869 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16870 /// generation and convert it from being a bunch of shuffles and extracts
16871 /// to a simple store and scalar loads to extract the elements.
16872 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16873                                          TargetLowering::DAGCombinerInfo &DCI) {
16874   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16875   if (NewOp.getNode())
16876     return NewOp;
16877
16878   SDValue InputVector = N->getOperand(0);
16879
16880   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16881   // from mmx to v2i32 has a single usage.
16882   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16883       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16884       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16885     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16886                        N->getValueType(0),
16887                        InputVector.getNode()->getOperand(0));
16888
16889   // Only operate on vectors of 4 elements, where the alternative shuffling
16890   // gets to be more expensive.
16891   if (InputVector.getValueType() != MVT::v4i32)
16892     return SDValue();
16893
16894   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16895   // single use which is a sign-extend or zero-extend, and all elements are
16896   // used.
16897   SmallVector<SDNode *, 4> Uses;
16898   unsigned ExtractedElements = 0;
16899   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16900        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16901     if (UI.getUse().getResNo() != InputVector.getResNo())
16902       return SDValue();
16903
16904     SDNode *Extract = *UI;
16905     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16906       return SDValue();
16907
16908     if (Extract->getValueType(0) != MVT::i32)
16909       return SDValue();
16910     if (!Extract->hasOneUse())
16911       return SDValue();
16912     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16913         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16914       return SDValue();
16915     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16916       return SDValue();
16917
16918     // Record which element was extracted.
16919     ExtractedElements |=
16920       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16921
16922     Uses.push_back(Extract);
16923   }
16924
16925   // If not all the elements were used, this may not be worthwhile.
16926   if (ExtractedElements != 15)
16927     return SDValue();
16928
16929   // Ok, we've now decided to do the transformation.
16930   SDLoc dl(InputVector);
16931
16932   // Store the value to a temporary stack slot.
16933   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16934   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16935                             MachinePointerInfo(), false, false, 0);
16936
16937   // Replace each use (extract) with a load of the appropriate element.
16938   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16939        UE = Uses.end(); UI != UE; ++UI) {
16940     SDNode *Extract = *UI;
16941
16942     // cOMpute the element's address.
16943     SDValue Idx = Extract->getOperand(1);
16944     unsigned EltSize =
16945         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16946     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16947     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16948     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16949
16950     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16951                                      StackPtr, OffsetVal);
16952
16953     // Load the scalar.
16954     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16955                                      ScalarAddr, MachinePointerInfo(),
16956                                      false, false, false, 0);
16957
16958     // Replace the exact with the load.
16959     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16960   }
16961
16962   // The replacement was made in place; don't return anything.
16963   return SDValue();
16964 }
16965
16966 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16967 static std::pair<unsigned, bool>
16968 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16969                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16970   if (!VT.isVector())
16971     return std::make_pair(0, false);
16972
16973   bool NeedSplit = false;
16974   switch (VT.getSimpleVT().SimpleTy) {
16975   default: return std::make_pair(0, false);
16976   case MVT::v32i8:
16977   case MVT::v16i16:
16978   case MVT::v8i32:
16979     if (!Subtarget->hasAVX2())
16980       NeedSplit = true;
16981     if (!Subtarget->hasAVX())
16982       return std::make_pair(0, false);
16983     break;
16984   case MVT::v16i8:
16985   case MVT::v8i16:
16986   case MVT::v4i32:
16987     if (!Subtarget->hasSSE2())
16988       return std::make_pair(0, false);
16989   }
16990
16991   // SSE2 has only a small subset of the operations.
16992   bool hasUnsigned = Subtarget->hasSSE41() ||
16993                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16994   bool hasSigned = Subtarget->hasSSE41() ||
16995                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16996
16997   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16998
16999   unsigned Opc = 0;
17000   // Check for x CC y ? x : y.
17001   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17002       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17003     switch (CC) {
17004     default: break;
17005     case ISD::SETULT:
17006     case ISD::SETULE:
17007       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17008     case ISD::SETUGT:
17009     case ISD::SETUGE:
17010       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17011     case ISD::SETLT:
17012     case ISD::SETLE:
17013       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17014     case ISD::SETGT:
17015     case ISD::SETGE:
17016       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17017     }
17018   // Check for x CC y ? y : x -- a min/max with reversed arms.
17019   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17020              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17021     switch (CC) {
17022     default: break;
17023     case ISD::SETULT:
17024     case ISD::SETULE:
17025       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17026     case ISD::SETUGT:
17027     case ISD::SETUGE:
17028       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17029     case ISD::SETLT:
17030     case ISD::SETLE:
17031       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17032     case ISD::SETGT:
17033     case ISD::SETGE:
17034       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17035     }
17036   }
17037
17038   return std::make_pair(Opc, NeedSplit);
17039 }
17040
17041 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17042 /// nodes.
17043 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17044                                     TargetLowering::DAGCombinerInfo &DCI,
17045                                     const X86Subtarget *Subtarget) {
17046   SDLoc DL(N);
17047   SDValue Cond = N->getOperand(0);
17048   // Get the LHS/RHS of the select.
17049   SDValue LHS = N->getOperand(1);
17050   SDValue RHS = N->getOperand(2);
17051   EVT VT = LHS.getValueType();
17052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17053
17054   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17055   // instructions match the semantics of the common C idiom x<y?x:y but not
17056   // x<=y?x:y, because of how they handle negative zero (which can be
17057   // ignored in unsafe-math mode).
17058   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17059       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17060       (Subtarget->hasSSE2() ||
17061        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17062     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17063
17064     unsigned Opcode = 0;
17065     // Check for x CC y ? x : y.
17066     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17067         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17068       switch (CC) {
17069       default: break;
17070       case ISD::SETULT:
17071         // Converting this to a min would handle NaNs incorrectly, and swapping
17072         // the operands would cause it to handle comparisons between positive
17073         // and negative zero incorrectly.
17074         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17075           if (!DAG.getTarget().Options.UnsafeFPMath &&
17076               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17077             break;
17078           std::swap(LHS, RHS);
17079         }
17080         Opcode = X86ISD::FMIN;
17081         break;
17082       case ISD::SETOLE:
17083         // Converting this to a min would handle comparisons between positive
17084         // and negative zero incorrectly.
17085         if (!DAG.getTarget().Options.UnsafeFPMath &&
17086             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17087           break;
17088         Opcode = X86ISD::FMIN;
17089         break;
17090       case ISD::SETULE:
17091         // Converting this to a min would handle both negative zeros and NaNs
17092         // incorrectly, but we can swap the operands to fix both.
17093         std::swap(LHS, RHS);
17094       case ISD::SETOLT:
17095       case ISD::SETLT:
17096       case ISD::SETLE:
17097         Opcode = X86ISD::FMIN;
17098         break;
17099
17100       case ISD::SETOGE:
17101         // Converting this to a max would handle comparisons between positive
17102         // and negative zero incorrectly.
17103         if (!DAG.getTarget().Options.UnsafeFPMath &&
17104             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17105           break;
17106         Opcode = X86ISD::FMAX;
17107         break;
17108       case ISD::SETUGT:
17109         // Converting this to a max would handle NaNs incorrectly, and swapping
17110         // the operands would cause it to handle comparisons between positive
17111         // and negative zero incorrectly.
17112         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17113           if (!DAG.getTarget().Options.UnsafeFPMath &&
17114               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17115             break;
17116           std::swap(LHS, RHS);
17117         }
17118         Opcode = X86ISD::FMAX;
17119         break;
17120       case ISD::SETUGE:
17121         // Converting this to a max would handle both negative zeros and NaNs
17122         // incorrectly, but we can swap the operands to fix both.
17123         std::swap(LHS, RHS);
17124       case ISD::SETOGT:
17125       case ISD::SETGT:
17126       case ISD::SETGE:
17127         Opcode = X86ISD::FMAX;
17128         break;
17129       }
17130     // Check for x CC y ? y : x -- a min/max with reversed arms.
17131     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17132                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17133       switch (CC) {
17134       default: break;
17135       case ISD::SETOGE:
17136         // Converting this to a min would handle comparisons between positive
17137         // and negative zero incorrectly, and swapping the operands would
17138         // cause it to handle NaNs incorrectly.
17139         if (!DAG.getTarget().Options.UnsafeFPMath &&
17140             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17141           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17142             break;
17143           std::swap(LHS, RHS);
17144         }
17145         Opcode = X86ISD::FMIN;
17146         break;
17147       case ISD::SETUGT:
17148         // Converting this to a min would handle NaNs incorrectly.
17149         if (!DAG.getTarget().Options.UnsafeFPMath &&
17150             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17151           break;
17152         Opcode = X86ISD::FMIN;
17153         break;
17154       case ISD::SETUGE:
17155         // Converting this to a min would handle both negative zeros and NaNs
17156         // incorrectly, but we can swap the operands to fix both.
17157         std::swap(LHS, RHS);
17158       case ISD::SETOGT:
17159       case ISD::SETGT:
17160       case ISD::SETGE:
17161         Opcode = X86ISD::FMIN;
17162         break;
17163
17164       case ISD::SETULT:
17165         // Converting this to a max would handle NaNs incorrectly.
17166         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17167           break;
17168         Opcode = X86ISD::FMAX;
17169         break;
17170       case ISD::SETOLE:
17171         // Converting this to a max would handle comparisons between positive
17172         // and negative zero incorrectly, and swapping the operands would
17173         // cause it to handle NaNs incorrectly.
17174         if (!DAG.getTarget().Options.UnsafeFPMath &&
17175             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17176           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17177             break;
17178           std::swap(LHS, RHS);
17179         }
17180         Opcode = X86ISD::FMAX;
17181         break;
17182       case ISD::SETULE:
17183         // Converting this to a max would handle both negative zeros and NaNs
17184         // incorrectly, but we can swap the operands to fix both.
17185         std::swap(LHS, RHS);
17186       case ISD::SETOLT:
17187       case ISD::SETLT:
17188       case ISD::SETLE:
17189         Opcode = X86ISD::FMAX;
17190         break;
17191       }
17192     }
17193
17194     if (Opcode)
17195       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17196   }
17197
17198   EVT CondVT = Cond.getValueType();
17199   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17200       CondVT.getVectorElementType() == MVT::i1) {
17201     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17202     // lowering on AVX-512. In this case we convert it to
17203     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17204     // The same situation for all 128 and 256-bit vectors of i8 and i16
17205     EVT OpVT = LHS.getValueType();
17206     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17207         (OpVT.getVectorElementType() == MVT::i8 ||
17208          OpVT.getVectorElementType() == MVT::i16)) {
17209       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17210       DCI.AddToWorklist(Cond.getNode());
17211       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17212     }
17213   }
17214   // If this is a select between two integer constants, try to do some
17215   // optimizations.
17216   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17217     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17218       // Don't do this for crazy integer types.
17219       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17220         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17221         // so that TrueC (the true value) is larger than FalseC.
17222         bool NeedsCondInvert = false;
17223
17224         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17225             // Efficiently invertible.
17226             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17227              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17228               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17229           NeedsCondInvert = true;
17230           std::swap(TrueC, FalseC);
17231         }
17232
17233         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17234         if (FalseC->getAPIntValue() == 0 &&
17235             TrueC->getAPIntValue().isPowerOf2()) {
17236           if (NeedsCondInvert) // Invert the condition if needed.
17237             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17238                                DAG.getConstant(1, Cond.getValueType()));
17239
17240           // Zero extend the condition if needed.
17241           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17242
17243           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17244           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17245                              DAG.getConstant(ShAmt, MVT::i8));
17246         }
17247
17248         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17249         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17250           if (NeedsCondInvert) // Invert the condition if needed.
17251             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17252                                DAG.getConstant(1, Cond.getValueType()));
17253
17254           // Zero extend the condition if needed.
17255           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17256                              FalseC->getValueType(0), Cond);
17257           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17258                              SDValue(FalseC, 0));
17259         }
17260
17261         // Optimize cases that will turn into an LEA instruction.  This requires
17262         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17263         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17264           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17265           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17266
17267           bool isFastMultiplier = false;
17268           if (Diff < 10) {
17269             switch ((unsigned char)Diff) {
17270               default: break;
17271               case 1:  // result = add base, cond
17272               case 2:  // result = lea base(    , cond*2)
17273               case 3:  // result = lea base(cond, cond*2)
17274               case 4:  // result = lea base(    , cond*4)
17275               case 5:  // result = lea base(cond, cond*4)
17276               case 8:  // result = lea base(    , cond*8)
17277               case 9:  // result = lea base(cond, cond*8)
17278                 isFastMultiplier = true;
17279                 break;
17280             }
17281           }
17282
17283           if (isFastMultiplier) {
17284             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17285             if (NeedsCondInvert) // Invert the condition if needed.
17286               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17287                                  DAG.getConstant(1, Cond.getValueType()));
17288
17289             // Zero extend the condition if needed.
17290             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17291                                Cond);
17292             // Scale the condition by the difference.
17293             if (Diff != 1)
17294               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17295                                  DAG.getConstant(Diff, Cond.getValueType()));
17296
17297             // Add the base if non-zero.
17298             if (FalseC->getAPIntValue() != 0)
17299               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17300                                  SDValue(FalseC, 0));
17301             return Cond;
17302           }
17303         }
17304       }
17305   }
17306
17307   // Canonicalize max and min:
17308   // (x > y) ? x : y -> (x >= y) ? x : y
17309   // (x < y) ? x : y -> (x <= y) ? x : y
17310   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17311   // the need for an extra compare
17312   // against zero. e.g.
17313   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17314   // subl   %esi, %edi
17315   // testl  %edi, %edi
17316   // movl   $0, %eax
17317   // cmovgl %edi, %eax
17318   // =>
17319   // xorl   %eax, %eax
17320   // subl   %esi, $edi
17321   // cmovsl %eax, %edi
17322   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17323       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17324       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17325     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17326     switch (CC) {
17327     default: break;
17328     case ISD::SETLT:
17329     case ISD::SETGT: {
17330       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17331       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17332                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17333       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17334     }
17335     }
17336   }
17337
17338   // Early exit check
17339   if (!TLI.isTypeLegal(VT))
17340     return SDValue();
17341
17342   // Match VSELECTs into subs with unsigned saturation.
17343   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17344       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17345       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17346        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17347     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17348
17349     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17350     // left side invert the predicate to simplify logic below.
17351     SDValue Other;
17352     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17353       Other = RHS;
17354       CC = ISD::getSetCCInverse(CC, true);
17355     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17356       Other = LHS;
17357     }
17358
17359     if (Other.getNode() && Other->getNumOperands() == 2 &&
17360         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17361       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17362       SDValue CondRHS = Cond->getOperand(1);
17363
17364       // Look for a general sub with unsigned saturation first.
17365       // x >= y ? x-y : 0 --> subus x, y
17366       // x >  y ? x-y : 0 --> subus x, y
17367       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17368           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17369         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17370
17371       // If the RHS is a constant we have to reverse the const canonicalization.
17372       // x > C-1 ? x+-C : 0 --> subus x, C
17373       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17374           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17375         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17376         if (CondRHS.getConstantOperandVal(0) == -A-1)
17377           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17378                              DAG.getConstant(-A, VT));
17379       }
17380
17381       // Another special case: If C was a sign bit, the sub has been
17382       // canonicalized into a xor.
17383       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17384       //        it's safe to decanonicalize the xor?
17385       // x s< 0 ? x^C : 0 --> subus x, C
17386       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17387           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17388           isSplatVector(OpRHS.getNode())) {
17389         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17390         if (A.isSignBit())
17391           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17392       }
17393     }
17394   }
17395
17396   // Try to match a min/max vector operation.
17397   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17398     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17399     unsigned Opc = ret.first;
17400     bool NeedSplit = ret.second;
17401
17402     if (Opc && NeedSplit) {
17403       unsigned NumElems = VT.getVectorNumElements();
17404       // Extract the LHS vectors
17405       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17406       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17407
17408       // Extract the RHS vectors
17409       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17410       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17411
17412       // Create min/max for each subvector
17413       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17414       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17415
17416       // Merge the result
17417       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17418     } else if (Opc)
17419       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17420   }
17421
17422   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17423   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17424       // Check if SETCC has already been promoted
17425       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17426       // Check that condition value type matches vselect operand type
17427       CondVT == VT) { 
17428
17429     assert(Cond.getValueType().isVector() &&
17430            "vector select expects a vector selector!");
17431
17432     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17433     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17434
17435     if (!TValIsAllOnes && !FValIsAllZeros) {
17436       // Try invert the condition if true value is not all 1s and false value
17437       // is not all 0s.
17438       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17439       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17440
17441       if (TValIsAllZeros || FValIsAllOnes) {
17442         SDValue CC = Cond.getOperand(2);
17443         ISD::CondCode NewCC =
17444           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17445                                Cond.getOperand(0).getValueType().isInteger());
17446         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17447         std::swap(LHS, RHS);
17448         TValIsAllOnes = FValIsAllOnes;
17449         FValIsAllZeros = TValIsAllZeros;
17450       }
17451     }
17452
17453     if (TValIsAllOnes || FValIsAllZeros) {
17454       SDValue Ret;
17455
17456       if (TValIsAllOnes && FValIsAllZeros)
17457         Ret = Cond;
17458       else if (TValIsAllOnes)
17459         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17460                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17461       else if (FValIsAllZeros)
17462         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17463                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17464
17465       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17466     }
17467   }
17468
17469   // Try to fold this VSELECT into a MOVSS/MOVSD
17470   if (N->getOpcode() == ISD::VSELECT &&
17471       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17472     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17473         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17474       bool CanFold = false;
17475       unsigned NumElems = Cond.getNumOperands();
17476       SDValue A = LHS;
17477       SDValue B = RHS;
17478       
17479       if (isZero(Cond.getOperand(0))) {
17480         CanFold = true;
17481
17482         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17483         // fold (vselect <0,-1> -> (movsd A, B)
17484         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17485           CanFold = isAllOnes(Cond.getOperand(i));
17486       } else if (isAllOnes(Cond.getOperand(0))) {
17487         CanFold = true;
17488         std::swap(A, B);
17489
17490         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17491         // fold (vselect <-1,0> -> (movsd B, A)
17492         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17493           CanFold = isZero(Cond.getOperand(i));
17494       }
17495
17496       if (CanFold) {
17497         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17498           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17499         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17500       }
17501
17502       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17503         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17504         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17505         //                             (v2i64 (bitcast B)))))
17506         //
17507         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17508         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17509         //                             (v2f64 (bitcast B)))))
17510         //
17511         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17512         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17513         //                             (v2i64 (bitcast A)))))
17514         //
17515         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17516         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17517         //                             (v2f64 (bitcast A)))))
17518
17519         CanFold = (isZero(Cond.getOperand(0)) &&
17520                    isZero(Cond.getOperand(1)) &&
17521                    isAllOnes(Cond.getOperand(2)) &&
17522                    isAllOnes(Cond.getOperand(3)));
17523
17524         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17525             isAllOnes(Cond.getOperand(1)) &&
17526             isZero(Cond.getOperand(2)) &&
17527             isZero(Cond.getOperand(3))) {
17528           CanFold = true;
17529           std::swap(LHS, RHS);
17530         }
17531
17532         if (CanFold) {
17533           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17534           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17535           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17536           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17537                                                 NewB, DAG);
17538           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17539         }
17540       }
17541     }
17542   }
17543
17544   // If we know that this node is legal then we know that it is going to be
17545   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17546   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17547   // to simplify previous instructions.
17548   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17549       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17550     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17551
17552     // Don't optimize vector selects that map to mask-registers.
17553     if (BitWidth == 1)
17554       return SDValue();
17555
17556     // Check all uses of that condition operand to check whether it will be
17557     // consumed by non-BLEND instructions, which may depend on all bits are set
17558     // properly.
17559     for (SDNode::use_iterator I = Cond->use_begin(),
17560                               E = Cond->use_end(); I != E; ++I)
17561       if (I->getOpcode() != ISD::VSELECT)
17562         // TODO: Add other opcodes eventually lowered into BLEND.
17563         return SDValue();
17564
17565     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17566     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17567
17568     APInt KnownZero, KnownOne;
17569     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17570                                           DCI.isBeforeLegalizeOps());
17571     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17572         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17573       DCI.CommitTargetLoweringOpt(TLO);
17574   }
17575
17576   return SDValue();
17577 }
17578
17579 // Check whether a boolean test is testing a boolean value generated by
17580 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17581 // code.
17582 //
17583 // Simplify the following patterns:
17584 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17585 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17586 // to (Op EFLAGS Cond)
17587 //
17588 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17589 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17590 // to (Op EFLAGS !Cond)
17591 //
17592 // where Op could be BRCOND or CMOV.
17593 //
17594 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17595   // Quit if not CMP and SUB with its value result used.
17596   if (Cmp.getOpcode() != X86ISD::CMP &&
17597       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17598       return SDValue();
17599
17600   // Quit if not used as a boolean value.
17601   if (CC != X86::COND_E && CC != X86::COND_NE)
17602     return SDValue();
17603
17604   // Check CMP operands. One of them should be 0 or 1 and the other should be
17605   // an SetCC or extended from it.
17606   SDValue Op1 = Cmp.getOperand(0);
17607   SDValue Op2 = Cmp.getOperand(1);
17608
17609   SDValue SetCC;
17610   const ConstantSDNode* C = 0;
17611   bool needOppositeCond = (CC == X86::COND_E);
17612   bool checkAgainstTrue = false; // Is it a comparison against 1?
17613
17614   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17615     SetCC = Op2;
17616   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17617     SetCC = Op1;
17618   else // Quit if all operands are not constants.
17619     return SDValue();
17620
17621   if (C->getZExtValue() == 1) {
17622     needOppositeCond = !needOppositeCond;
17623     checkAgainstTrue = true;
17624   } else if (C->getZExtValue() != 0)
17625     // Quit if the constant is neither 0 or 1.
17626     return SDValue();
17627
17628   bool truncatedToBoolWithAnd = false;
17629   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17630   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17631          SetCC.getOpcode() == ISD::TRUNCATE ||
17632          SetCC.getOpcode() == ISD::AND) {
17633     if (SetCC.getOpcode() == ISD::AND) {
17634       int OpIdx = -1;
17635       ConstantSDNode *CS;
17636       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17637           CS->getZExtValue() == 1)
17638         OpIdx = 1;
17639       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17640           CS->getZExtValue() == 1)
17641         OpIdx = 0;
17642       if (OpIdx == -1)
17643         break;
17644       SetCC = SetCC.getOperand(OpIdx);
17645       truncatedToBoolWithAnd = true;
17646     } else
17647       SetCC = SetCC.getOperand(0);
17648   }
17649
17650   switch (SetCC.getOpcode()) {
17651   case X86ISD::SETCC_CARRY:
17652     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17653     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17654     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17655     // truncated to i1 using 'and'.
17656     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17657       break;
17658     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17659            "Invalid use of SETCC_CARRY!");
17660     // FALL THROUGH
17661   case X86ISD::SETCC:
17662     // Set the condition code or opposite one if necessary.
17663     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17664     if (needOppositeCond)
17665       CC = X86::GetOppositeBranchCondition(CC);
17666     return SetCC.getOperand(1);
17667   case X86ISD::CMOV: {
17668     // Check whether false/true value has canonical one, i.e. 0 or 1.
17669     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17670     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17671     // Quit if true value is not a constant.
17672     if (!TVal)
17673       return SDValue();
17674     // Quit if false value is not a constant.
17675     if (!FVal) {
17676       SDValue Op = SetCC.getOperand(0);
17677       // Skip 'zext' or 'trunc' node.
17678       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17679           Op.getOpcode() == ISD::TRUNCATE)
17680         Op = Op.getOperand(0);
17681       // A special case for rdrand/rdseed, where 0 is set if false cond is
17682       // found.
17683       if ((Op.getOpcode() != X86ISD::RDRAND &&
17684            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17685         return SDValue();
17686     }
17687     // Quit if false value is not the constant 0 or 1.
17688     bool FValIsFalse = true;
17689     if (FVal && FVal->getZExtValue() != 0) {
17690       if (FVal->getZExtValue() != 1)
17691         return SDValue();
17692       // If FVal is 1, opposite cond is needed.
17693       needOppositeCond = !needOppositeCond;
17694       FValIsFalse = false;
17695     }
17696     // Quit if TVal is not the constant opposite of FVal.
17697     if (FValIsFalse && TVal->getZExtValue() != 1)
17698       return SDValue();
17699     if (!FValIsFalse && TVal->getZExtValue() != 0)
17700       return SDValue();
17701     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17702     if (needOppositeCond)
17703       CC = X86::GetOppositeBranchCondition(CC);
17704     return SetCC.getOperand(3);
17705   }
17706   }
17707
17708   return SDValue();
17709 }
17710
17711 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17712 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17713                                   TargetLowering::DAGCombinerInfo &DCI,
17714                                   const X86Subtarget *Subtarget) {
17715   SDLoc DL(N);
17716
17717   // If the flag operand isn't dead, don't touch this CMOV.
17718   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17719     return SDValue();
17720
17721   SDValue FalseOp = N->getOperand(0);
17722   SDValue TrueOp = N->getOperand(1);
17723   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17724   SDValue Cond = N->getOperand(3);
17725
17726   if (CC == X86::COND_E || CC == X86::COND_NE) {
17727     switch (Cond.getOpcode()) {
17728     default: break;
17729     case X86ISD::BSR:
17730     case X86ISD::BSF:
17731       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17732       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17733         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17734     }
17735   }
17736
17737   SDValue Flags;
17738
17739   Flags = checkBoolTestSetCCCombine(Cond, CC);
17740   if (Flags.getNode() &&
17741       // Extra check as FCMOV only supports a subset of X86 cond.
17742       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17743     SDValue Ops[] = { FalseOp, TrueOp,
17744                       DAG.getConstant(CC, MVT::i8), Flags };
17745     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17746                        Ops, array_lengthof(Ops));
17747   }
17748
17749   // If this is a select between two integer constants, try to do some
17750   // optimizations.  Note that the operands are ordered the opposite of SELECT
17751   // operands.
17752   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17753     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17754       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17755       // larger than FalseC (the false value).
17756       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17757         CC = X86::GetOppositeBranchCondition(CC);
17758         std::swap(TrueC, FalseC);
17759         std::swap(TrueOp, FalseOp);
17760       }
17761
17762       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17763       // This is efficient for any integer data type (including i8/i16) and
17764       // shift amount.
17765       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17766         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17767                            DAG.getConstant(CC, MVT::i8), Cond);
17768
17769         // Zero extend the condition if needed.
17770         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17771
17772         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17773         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17774                            DAG.getConstant(ShAmt, MVT::i8));
17775         if (N->getNumValues() == 2)  // Dead flag value?
17776           return DCI.CombineTo(N, Cond, SDValue());
17777         return Cond;
17778       }
17779
17780       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17781       // for any integer data type, including i8/i16.
17782       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17783         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17784                            DAG.getConstant(CC, MVT::i8), Cond);
17785
17786         // Zero extend the condition if needed.
17787         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17788                            FalseC->getValueType(0), Cond);
17789         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17790                            SDValue(FalseC, 0));
17791
17792         if (N->getNumValues() == 2)  // Dead flag value?
17793           return DCI.CombineTo(N, Cond, SDValue());
17794         return Cond;
17795       }
17796
17797       // Optimize cases that will turn into an LEA instruction.  This requires
17798       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17799       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17800         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17801         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17802
17803         bool isFastMultiplier = false;
17804         if (Diff < 10) {
17805           switch ((unsigned char)Diff) {
17806           default: break;
17807           case 1:  // result = add base, cond
17808           case 2:  // result = lea base(    , cond*2)
17809           case 3:  // result = lea base(cond, cond*2)
17810           case 4:  // result = lea base(    , cond*4)
17811           case 5:  // result = lea base(cond, cond*4)
17812           case 8:  // result = lea base(    , cond*8)
17813           case 9:  // result = lea base(cond, cond*8)
17814             isFastMultiplier = true;
17815             break;
17816           }
17817         }
17818
17819         if (isFastMultiplier) {
17820           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17821           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17822                              DAG.getConstant(CC, MVT::i8), Cond);
17823           // Zero extend the condition if needed.
17824           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17825                              Cond);
17826           // Scale the condition by the difference.
17827           if (Diff != 1)
17828             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17829                                DAG.getConstant(Diff, Cond.getValueType()));
17830
17831           // Add the base if non-zero.
17832           if (FalseC->getAPIntValue() != 0)
17833             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17834                                SDValue(FalseC, 0));
17835           if (N->getNumValues() == 2)  // Dead flag value?
17836             return DCI.CombineTo(N, Cond, SDValue());
17837           return Cond;
17838         }
17839       }
17840     }
17841   }
17842
17843   // Handle these cases:
17844   //   (select (x != c), e, c) -> select (x != c), e, x),
17845   //   (select (x == c), c, e) -> select (x == c), x, e)
17846   // where the c is an integer constant, and the "select" is the combination
17847   // of CMOV and CMP.
17848   //
17849   // The rationale for this change is that the conditional-move from a constant
17850   // needs two instructions, however, conditional-move from a register needs
17851   // only one instruction.
17852   //
17853   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17854   //  some instruction-combining opportunities. This opt needs to be
17855   //  postponed as late as possible.
17856   //
17857   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17858     // the DCI.xxxx conditions are provided to postpone the optimization as
17859     // late as possible.
17860
17861     ConstantSDNode *CmpAgainst = 0;
17862     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17863         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17864         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17865
17866       if (CC == X86::COND_NE &&
17867           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17868         CC = X86::GetOppositeBranchCondition(CC);
17869         std::swap(TrueOp, FalseOp);
17870       }
17871
17872       if (CC == X86::COND_E &&
17873           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17874         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17875                           DAG.getConstant(CC, MVT::i8), Cond };
17876         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17877                            array_lengthof(Ops));
17878       }
17879     }
17880   }
17881
17882   return SDValue();
17883 }
17884
17885 /// PerformMulCombine - Optimize a single multiply with constant into two
17886 /// in order to implement it with two cheaper instructions, e.g.
17887 /// LEA + SHL, LEA + LEA.
17888 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17889                                  TargetLowering::DAGCombinerInfo &DCI) {
17890   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17891     return SDValue();
17892
17893   EVT VT = N->getValueType(0);
17894   if (VT != MVT::i64)
17895     return SDValue();
17896
17897   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17898   if (!C)
17899     return SDValue();
17900   uint64_t MulAmt = C->getZExtValue();
17901   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17902     return SDValue();
17903
17904   uint64_t MulAmt1 = 0;
17905   uint64_t MulAmt2 = 0;
17906   if ((MulAmt % 9) == 0) {
17907     MulAmt1 = 9;
17908     MulAmt2 = MulAmt / 9;
17909   } else if ((MulAmt % 5) == 0) {
17910     MulAmt1 = 5;
17911     MulAmt2 = MulAmt / 5;
17912   } else if ((MulAmt % 3) == 0) {
17913     MulAmt1 = 3;
17914     MulAmt2 = MulAmt / 3;
17915   }
17916   if (MulAmt2 &&
17917       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17918     SDLoc DL(N);
17919
17920     if (isPowerOf2_64(MulAmt2) &&
17921         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17922       // If second multiplifer is pow2, issue it first. We want the multiply by
17923       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17924       // is an add.
17925       std::swap(MulAmt1, MulAmt2);
17926
17927     SDValue NewMul;
17928     if (isPowerOf2_64(MulAmt1))
17929       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17930                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17931     else
17932       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17933                            DAG.getConstant(MulAmt1, VT));
17934
17935     if (isPowerOf2_64(MulAmt2))
17936       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17937                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17938     else
17939       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17940                            DAG.getConstant(MulAmt2, VT));
17941
17942     // Do not add new nodes to DAG combiner worklist.
17943     DCI.CombineTo(N, NewMul, false);
17944   }
17945   return SDValue();
17946 }
17947
17948 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17949   SDValue N0 = N->getOperand(0);
17950   SDValue N1 = N->getOperand(1);
17951   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17952   EVT VT = N0.getValueType();
17953
17954   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17955   // since the result of setcc_c is all zero's or all ones.
17956   if (VT.isInteger() && !VT.isVector() &&
17957       N1C && N0.getOpcode() == ISD::AND &&
17958       N0.getOperand(1).getOpcode() == ISD::Constant) {
17959     SDValue N00 = N0.getOperand(0);
17960     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17961         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17962           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17963          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17964       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17965       APInt ShAmt = N1C->getAPIntValue();
17966       Mask = Mask.shl(ShAmt);
17967       if (Mask != 0)
17968         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17969                            N00, DAG.getConstant(Mask, VT));
17970     }
17971   }
17972
17973   // Hardware support for vector shifts is sparse which makes us scalarize the
17974   // vector operations in many cases. Also, on sandybridge ADD is faster than
17975   // shl.
17976   // (shl V, 1) -> add V,V
17977   if (isSplatVector(N1.getNode())) {
17978     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17979     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17980     // We shift all of the values by one. In many cases we do not have
17981     // hardware support for this operation. This is better expressed as an ADD
17982     // of two values.
17983     if (N1C && (1 == N1C->getZExtValue())) {
17984       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17985     }
17986   }
17987
17988   return SDValue();
17989 }
17990
17991 /// \brief Returns a vector of 0s if the node in input is a vector logical
17992 /// shift by a constant amount which is known to be bigger than or equal
17993 /// to the vector element size in bits.
17994 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17995                                       const X86Subtarget *Subtarget) {
17996   EVT VT = N->getValueType(0);
17997
17998   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17999       (!Subtarget->hasInt256() ||
18000        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18001     return SDValue();
18002
18003   SDValue Amt = N->getOperand(1);
18004   SDLoc DL(N);
18005   if (isSplatVector(Amt.getNode())) {
18006     SDValue SclrAmt = Amt->getOperand(0);
18007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18008       APInt ShiftAmt = C->getAPIntValue();
18009       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18010
18011       // SSE2/AVX2 logical shifts always return a vector of 0s
18012       // if the shift amount is bigger than or equal to
18013       // the element size. The constant shift amount will be
18014       // encoded as a 8-bit immediate.
18015       if (ShiftAmt.trunc(8).uge(MaxAmount))
18016         return getZeroVector(VT, Subtarget, DAG, DL);
18017     }
18018   }
18019
18020   return SDValue();
18021 }
18022
18023 /// PerformShiftCombine - Combine shifts.
18024 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18025                                    TargetLowering::DAGCombinerInfo &DCI,
18026                                    const X86Subtarget *Subtarget) {
18027   if (N->getOpcode() == ISD::SHL) {
18028     SDValue V = PerformSHLCombine(N, DAG);
18029     if (V.getNode()) return V;
18030   }
18031
18032   if (N->getOpcode() != ISD::SRA) {
18033     // Try to fold this logical shift into a zero vector.
18034     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18035     if (V.getNode()) return V;
18036   }
18037
18038   return SDValue();
18039 }
18040
18041 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18042 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18043 // and friends.  Likewise for OR -> CMPNEQSS.
18044 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18045                             TargetLowering::DAGCombinerInfo &DCI,
18046                             const X86Subtarget *Subtarget) {
18047   unsigned opcode;
18048
18049   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18050   // we're requiring SSE2 for both.
18051   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18052     SDValue N0 = N->getOperand(0);
18053     SDValue N1 = N->getOperand(1);
18054     SDValue CMP0 = N0->getOperand(1);
18055     SDValue CMP1 = N1->getOperand(1);
18056     SDLoc DL(N);
18057
18058     // The SETCCs should both refer to the same CMP.
18059     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18060       return SDValue();
18061
18062     SDValue CMP00 = CMP0->getOperand(0);
18063     SDValue CMP01 = CMP0->getOperand(1);
18064     EVT     VT    = CMP00.getValueType();
18065
18066     if (VT == MVT::f32 || VT == MVT::f64) {
18067       bool ExpectingFlags = false;
18068       // Check for any users that want flags:
18069       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18070            !ExpectingFlags && UI != UE; ++UI)
18071         switch (UI->getOpcode()) {
18072         default:
18073         case ISD::BR_CC:
18074         case ISD::BRCOND:
18075         case ISD::SELECT:
18076           ExpectingFlags = true;
18077           break;
18078         case ISD::CopyToReg:
18079         case ISD::SIGN_EXTEND:
18080         case ISD::ZERO_EXTEND:
18081         case ISD::ANY_EXTEND:
18082           break;
18083         }
18084
18085       if (!ExpectingFlags) {
18086         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18087         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18088
18089         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18090           X86::CondCode tmp = cc0;
18091           cc0 = cc1;
18092           cc1 = tmp;
18093         }
18094
18095         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18096             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18097           // FIXME: need symbolic constants for these magic numbers.
18098           // See X86ATTInstPrinter.cpp:printSSECC().
18099           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18100           if (Subtarget->hasAVX512()) {
18101             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18102                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18103             if (N->getValueType(0) != MVT::i1)
18104               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18105                                  FSetCC);
18106             return FSetCC;
18107           }
18108           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18109                                               CMP00.getValueType(), CMP00, CMP01,
18110                                               DAG.getConstant(x86cc, MVT::i8));
18111
18112           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18113           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18114
18115           if (is64BitFP && !Subtarget->is64Bit()) {
18116             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18117             // 64-bit integer, since that's not a legal type. Since
18118             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18119             // bits, but can do this little dance to extract the lowest 32 bits
18120             // and work with those going forward.
18121             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18122                                            OnesOrZeroesF);
18123             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18124                                            Vector64);
18125             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18126                                         Vector32, DAG.getIntPtrConstant(0));
18127             IntVT = MVT::i32;
18128           }
18129
18130           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18131           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18132                                       DAG.getConstant(1, IntVT));
18133           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18134           return OneBitOfTruth;
18135         }
18136       }
18137     }
18138   }
18139   return SDValue();
18140 }
18141
18142 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18143 /// so it can be folded inside ANDNP.
18144 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18145   EVT VT = N->getValueType(0);
18146
18147   // Match direct AllOnes for 128 and 256-bit vectors
18148   if (ISD::isBuildVectorAllOnes(N))
18149     return true;
18150
18151   // Look through a bit convert.
18152   if (N->getOpcode() == ISD::BITCAST)
18153     N = N->getOperand(0).getNode();
18154
18155   // Sometimes the operand may come from a insert_subvector building a 256-bit
18156   // allones vector
18157   if (VT.is256BitVector() &&
18158       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18159     SDValue V1 = N->getOperand(0);
18160     SDValue V2 = N->getOperand(1);
18161
18162     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18163         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18164         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18165         ISD::isBuildVectorAllOnes(V2.getNode()))
18166       return true;
18167   }
18168
18169   return false;
18170 }
18171
18172 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18173 // register. In most cases we actually compare or select YMM-sized registers
18174 // and mixing the two types creates horrible code. This method optimizes
18175 // some of the transition sequences.
18176 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18177                                  TargetLowering::DAGCombinerInfo &DCI,
18178                                  const X86Subtarget *Subtarget) {
18179   EVT VT = N->getValueType(0);
18180   if (!VT.is256BitVector())
18181     return SDValue();
18182
18183   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18184           N->getOpcode() == ISD::ZERO_EXTEND ||
18185           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18186
18187   SDValue Narrow = N->getOperand(0);
18188   EVT NarrowVT = Narrow->getValueType(0);
18189   if (!NarrowVT.is128BitVector())
18190     return SDValue();
18191
18192   if (Narrow->getOpcode() != ISD::XOR &&
18193       Narrow->getOpcode() != ISD::AND &&
18194       Narrow->getOpcode() != ISD::OR)
18195     return SDValue();
18196
18197   SDValue N0  = Narrow->getOperand(0);
18198   SDValue N1  = Narrow->getOperand(1);
18199   SDLoc DL(Narrow);
18200
18201   // The Left side has to be a trunc.
18202   if (N0.getOpcode() != ISD::TRUNCATE)
18203     return SDValue();
18204
18205   // The type of the truncated inputs.
18206   EVT WideVT = N0->getOperand(0)->getValueType(0);
18207   if (WideVT != VT)
18208     return SDValue();
18209
18210   // The right side has to be a 'trunc' or a constant vector.
18211   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18212   bool RHSConst = (isSplatVector(N1.getNode()) &&
18213                    isa<ConstantSDNode>(N1->getOperand(0)));
18214   if (!RHSTrunc && !RHSConst)
18215     return SDValue();
18216
18217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18218
18219   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18220     return SDValue();
18221
18222   // Set N0 and N1 to hold the inputs to the new wide operation.
18223   N0 = N0->getOperand(0);
18224   if (RHSConst) {
18225     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18226                      N1->getOperand(0));
18227     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18228     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18229   } else if (RHSTrunc) {
18230     N1 = N1->getOperand(0);
18231   }
18232
18233   // Generate the wide operation.
18234   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18235   unsigned Opcode = N->getOpcode();
18236   switch (Opcode) {
18237   case ISD::ANY_EXTEND:
18238     return Op;
18239   case ISD::ZERO_EXTEND: {
18240     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18241     APInt Mask = APInt::getAllOnesValue(InBits);
18242     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18243     return DAG.getNode(ISD::AND, DL, VT,
18244                        Op, DAG.getConstant(Mask, VT));
18245   }
18246   case ISD::SIGN_EXTEND:
18247     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18248                        Op, DAG.getValueType(NarrowVT));
18249   default:
18250     llvm_unreachable("Unexpected opcode");
18251   }
18252 }
18253
18254 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18255                                  TargetLowering::DAGCombinerInfo &DCI,
18256                                  const X86Subtarget *Subtarget) {
18257   EVT VT = N->getValueType(0);
18258   if (DCI.isBeforeLegalizeOps())
18259     return SDValue();
18260
18261   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18262   if (R.getNode())
18263     return R;
18264
18265   // Create BEXTR and BZHI instructions
18266   // BZHI is X & ((1 << Y) - 1)
18267   // BEXTR is ((X >> imm) & (2**size-1))
18268   if (VT == MVT::i32 || VT == MVT::i64) {
18269     SDValue N0 = N->getOperand(0);
18270     SDValue N1 = N->getOperand(1);
18271     SDLoc DL(N);
18272
18273     if (Subtarget->hasBMI2()) {
18274       // Check for (and (add (shl 1, Y), -1), X)
18275       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18276         SDValue N00 = N0.getOperand(0);
18277         if (N00.getOpcode() == ISD::SHL) {
18278           SDValue N001 = N00.getOperand(1);
18279           assert(N001.getValueType() == MVT::i8 && "unexpected type");
18280           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18281           if (C && C->getZExtValue() == 1)
18282             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18283         }
18284       }
18285
18286       // Check for (and X, (add (shl 1, Y), -1))
18287       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18288         SDValue N10 = N1.getOperand(0);
18289         if (N10.getOpcode() == ISD::SHL) {
18290           SDValue N101 = N10.getOperand(1);
18291           assert(N101.getValueType() == MVT::i8 && "unexpected type");
18292           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18293           if (C && C->getZExtValue() == 1)
18294             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18295         }
18296       }
18297     }
18298
18299     // Check for BEXTR.
18300     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18301         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18302       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18303       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18304       if (MaskNode && ShiftNode) {
18305         uint64_t Mask = MaskNode->getZExtValue();
18306         uint64_t Shift = ShiftNode->getZExtValue();
18307         if (isMask_64(Mask)) {
18308           uint64_t MaskSize = CountPopulation_64(Mask);
18309           if (Shift + MaskSize <= VT.getSizeInBits())
18310             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18311                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18312         }
18313       }
18314     } // BEXTR
18315
18316     return SDValue();
18317   }
18318
18319   // Want to form ANDNP nodes:
18320   // 1) In the hopes of then easily combining them with OR and AND nodes
18321   //    to form PBLEND/PSIGN.
18322   // 2) To match ANDN packed intrinsics
18323   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18324     return SDValue();
18325
18326   SDValue N0 = N->getOperand(0);
18327   SDValue N1 = N->getOperand(1);
18328   SDLoc DL(N);
18329
18330   // Check LHS for vnot
18331   if (N0.getOpcode() == ISD::XOR &&
18332       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18333       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18334     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18335
18336   // Check RHS for vnot
18337   if (N1.getOpcode() == ISD::XOR &&
18338       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18339       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18340     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18341
18342   return SDValue();
18343 }
18344
18345 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18346                                 TargetLowering::DAGCombinerInfo &DCI,
18347                                 const X86Subtarget *Subtarget) {
18348   if (DCI.isBeforeLegalizeOps())
18349     return SDValue();
18350
18351   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18352   if (R.getNode())
18353     return R;
18354
18355   SDValue N0 = N->getOperand(0);
18356   SDValue N1 = N->getOperand(1);
18357   EVT VT = N->getValueType(0);
18358
18359   // look for psign/blend
18360   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18361     if (!Subtarget->hasSSSE3() ||
18362         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18363       return SDValue();
18364
18365     // Canonicalize pandn to RHS
18366     if (N0.getOpcode() == X86ISD::ANDNP)
18367       std::swap(N0, N1);
18368     // or (and (m, y), (pandn m, x))
18369     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18370       SDValue Mask = N1.getOperand(0);
18371       SDValue X    = N1.getOperand(1);
18372       SDValue Y;
18373       if (N0.getOperand(0) == Mask)
18374         Y = N0.getOperand(1);
18375       if (N0.getOperand(1) == Mask)
18376         Y = N0.getOperand(0);
18377
18378       // Check to see if the mask appeared in both the AND and ANDNP and
18379       if (!Y.getNode())
18380         return SDValue();
18381
18382       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18383       // Look through mask bitcast.
18384       if (Mask.getOpcode() == ISD::BITCAST)
18385         Mask = Mask.getOperand(0);
18386       if (X.getOpcode() == ISD::BITCAST)
18387         X = X.getOperand(0);
18388       if (Y.getOpcode() == ISD::BITCAST)
18389         Y = Y.getOperand(0);
18390
18391       EVT MaskVT = Mask.getValueType();
18392
18393       // Validate that the Mask operand is a vector sra node.
18394       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18395       // there is no psrai.b
18396       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18397       unsigned SraAmt = ~0;
18398       if (Mask.getOpcode() == ISD::SRA) {
18399         SDValue Amt = Mask.getOperand(1);
18400         if (isSplatVector(Amt.getNode())) {
18401           SDValue SclrAmt = Amt->getOperand(0);
18402           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18403             SraAmt = C->getZExtValue();
18404         }
18405       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18406         SDValue SraC = Mask.getOperand(1);
18407         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18408       }
18409       if ((SraAmt + 1) != EltBits)
18410         return SDValue();
18411
18412       SDLoc DL(N);
18413
18414       // Now we know we at least have a plendvb with the mask val.  See if
18415       // we can form a psignb/w/d.
18416       // psign = x.type == y.type == mask.type && y = sub(0, x);
18417       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18418           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18419           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18420         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18421                "Unsupported VT for PSIGN");
18422         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18423         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18424       }
18425       // PBLENDVB only available on SSE 4.1
18426       if (!Subtarget->hasSSE41())
18427         return SDValue();
18428
18429       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18430
18431       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18432       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18433       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18434       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18435       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18436     }
18437   }
18438
18439   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18440     return SDValue();
18441
18442   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18443   MachineFunction &MF = DAG.getMachineFunction();
18444   bool OptForSize = MF.getFunction()->getAttributes().
18445     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18446
18447   // SHLD/SHRD instructions have lower register pressure, but on some
18448   // platforms they have higher latency than the equivalent
18449   // series of shifts/or that would otherwise be generated.
18450   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18451   // have higher latencies and we are not optimizing for size.
18452   if (!OptForSize && Subtarget->isSHLDSlow())
18453     return SDValue();
18454
18455   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18456     std::swap(N0, N1);
18457   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18458     return SDValue();
18459   if (!N0.hasOneUse() || !N1.hasOneUse())
18460     return SDValue();
18461
18462   SDValue ShAmt0 = N0.getOperand(1);
18463   if (ShAmt0.getValueType() != MVT::i8)
18464     return SDValue();
18465   SDValue ShAmt1 = N1.getOperand(1);
18466   if (ShAmt1.getValueType() != MVT::i8)
18467     return SDValue();
18468   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18469     ShAmt0 = ShAmt0.getOperand(0);
18470   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18471     ShAmt1 = ShAmt1.getOperand(0);
18472
18473   SDLoc DL(N);
18474   unsigned Opc = X86ISD::SHLD;
18475   SDValue Op0 = N0.getOperand(0);
18476   SDValue Op1 = N1.getOperand(0);
18477   if (ShAmt0.getOpcode() == ISD::SUB) {
18478     Opc = X86ISD::SHRD;
18479     std::swap(Op0, Op1);
18480     std::swap(ShAmt0, ShAmt1);
18481   }
18482
18483   unsigned Bits = VT.getSizeInBits();
18484   if (ShAmt1.getOpcode() == ISD::SUB) {
18485     SDValue Sum = ShAmt1.getOperand(0);
18486     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18487       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18488       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18489         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18490       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18491         return DAG.getNode(Opc, DL, VT,
18492                            Op0, Op1,
18493                            DAG.getNode(ISD::TRUNCATE, DL,
18494                                        MVT::i8, ShAmt0));
18495     }
18496   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18497     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18498     if (ShAmt0C &&
18499         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18500       return DAG.getNode(Opc, DL, VT,
18501                          N0.getOperand(0), N1.getOperand(0),
18502                          DAG.getNode(ISD::TRUNCATE, DL,
18503                                        MVT::i8, ShAmt0));
18504   }
18505
18506   return SDValue();
18507 }
18508
18509 // Generate NEG and CMOV for integer abs.
18510 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18511   EVT VT = N->getValueType(0);
18512
18513   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18514   // 8-bit integer abs to NEG and CMOV.
18515   if (VT.isInteger() && VT.getSizeInBits() == 8)
18516     return SDValue();
18517
18518   SDValue N0 = N->getOperand(0);
18519   SDValue N1 = N->getOperand(1);
18520   SDLoc DL(N);
18521
18522   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18523   // and change it to SUB and CMOV.
18524   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18525       N0.getOpcode() == ISD::ADD &&
18526       N0.getOperand(1) == N1 &&
18527       N1.getOpcode() == ISD::SRA &&
18528       N1.getOperand(0) == N0.getOperand(0))
18529     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18530       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18531         // Generate SUB & CMOV.
18532         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18533                                   DAG.getConstant(0, VT), N0.getOperand(0));
18534
18535         SDValue Ops[] = { N0.getOperand(0), Neg,
18536                           DAG.getConstant(X86::COND_GE, MVT::i8),
18537                           SDValue(Neg.getNode(), 1) };
18538         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18539                            Ops, array_lengthof(Ops));
18540       }
18541   return SDValue();
18542 }
18543
18544 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18545 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18546                                  TargetLowering::DAGCombinerInfo &DCI,
18547                                  const X86Subtarget *Subtarget) {
18548   if (DCI.isBeforeLegalizeOps())
18549     return SDValue();
18550
18551   if (Subtarget->hasCMov()) {
18552     SDValue RV = performIntegerAbsCombine(N, DAG);
18553     if (RV.getNode())
18554       return RV;
18555   }
18556
18557   return SDValue();
18558 }
18559
18560 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18561 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18562                                   TargetLowering::DAGCombinerInfo &DCI,
18563                                   const X86Subtarget *Subtarget) {
18564   LoadSDNode *Ld = cast<LoadSDNode>(N);
18565   EVT RegVT = Ld->getValueType(0);
18566   EVT MemVT = Ld->getMemoryVT();
18567   SDLoc dl(Ld);
18568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18569   unsigned RegSz = RegVT.getSizeInBits();
18570
18571   // On Sandybridge unaligned 256bit loads are inefficient.
18572   ISD::LoadExtType Ext = Ld->getExtensionType();
18573   unsigned Alignment = Ld->getAlignment();
18574   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18575   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18576       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18577     unsigned NumElems = RegVT.getVectorNumElements();
18578     if (NumElems < 2)
18579       return SDValue();
18580
18581     SDValue Ptr = Ld->getBasePtr();
18582     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18583
18584     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18585                                   NumElems/2);
18586     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18587                                 Ld->getPointerInfo(), Ld->isVolatile(),
18588                                 Ld->isNonTemporal(), Ld->isInvariant(),
18589                                 Alignment);
18590     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18591     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18592                                 Ld->getPointerInfo(), Ld->isVolatile(),
18593                                 Ld->isNonTemporal(), Ld->isInvariant(),
18594                                 std::min(16U, Alignment));
18595     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18596                              Load1.getValue(1),
18597                              Load2.getValue(1));
18598
18599     SDValue NewVec = DAG.getUNDEF(RegVT);
18600     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18601     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18602     return DCI.CombineTo(N, NewVec, TF, true);
18603   }
18604
18605   // If this is a vector EXT Load then attempt to optimize it using a
18606   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18607   // expansion is still better than scalar code.
18608   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18609   // emit a shuffle and a arithmetic shift.
18610   // TODO: It is possible to support ZExt by zeroing the undef values
18611   // during the shuffle phase or after the shuffle.
18612   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18613       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18614     assert(MemVT != RegVT && "Cannot extend to the same type");
18615     assert(MemVT.isVector() && "Must load a vector from memory");
18616
18617     unsigned NumElems = RegVT.getVectorNumElements();
18618     unsigned MemSz = MemVT.getSizeInBits();
18619     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18620
18621     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18622       return SDValue();
18623
18624     // All sizes must be a power of two.
18625     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18626       return SDValue();
18627
18628     // Attempt to load the original value using scalar loads.
18629     // Find the largest scalar type that divides the total loaded size.
18630     MVT SclrLoadTy = MVT::i8;
18631     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18632          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18633       MVT Tp = (MVT::SimpleValueType)tp;
18634       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18635         SclrLoadTy = Tp;
18636       }
18637     }
18638
18639     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18640     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18641         (64 <= MemSz))
18642       SclrLoadTy = MVT::f64;
18643
18644     // Calculate the number of scalar loads that we need to perform
18645     // in order to load our vector from memory.
18646     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18647     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18648       return SDValue();
18649
18650     unsigned loadRegZize = RegSz;
18651     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18652       loadRegZize /= 2;
18653
18654     // Represent our vector as a sequence of elements which are the
18655     // largest scalar that we can load.
18656     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18657       loadRegZize/SclrLoadTy.getSizeInBits());
18658
18659     // Represent the data using the same element type that is stored in
18660     // memory. In practice, we ''widen'' MemVT.
18661     EVT WideVecVT =
18662           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18663                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18664
18665     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18666       "Invalid vector type");
18667
18668     // We can't shuffle using an illegal type.
18669     if (!TLI.isTypeLegal(WideVecVT))
18670       return SDValue();
18671
18672     SmallVector<SDValue, 8> Chains;
18673     SDValue Ptr = Ld->getBasePtr();
18674     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18675                                         TLI.getPointerTy());
18676     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18677
18678     for (unsigned i = 0; i < NumLoads; ++i) {
18679       // Perform a single load.
18680       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18681                                        Ptr, Ld->getPointerInfo(),
18682                                        Ld->isVolatile(), Ld->isNonTemporal(),
18683                                        Ld->isInvariant(), Ld->getAlignment());
18684       Chains.push_back(ScalarLoad.getValue(1));
18685       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18686       // another round of DAGCombining.
18687       if (i == 0)
18688         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18689       else
18690         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18691                           ScalarLoad, DAG.getIntPtrConstant(i));
18692
18693       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18694     }
18695
18696     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18697                                Chains.size());
18698
18699     // Bitcast the loaded value to a vector of the original element type, in
18700     // the size of the target vector type.
18701     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18702     unsigned SizeRatio = RegSz/MemSz;
18703
18704     if (Ext == ISD::SEXTLOAD) {
18705       // If we have SSE4.1 we can directly emit a VSEXT node.
18706       if (Subtarget->hasSSE41()) {
18707         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18708         return DCI.CombineTo(N, Sext, TF, true);
18709       }
18710
18711       // Otherwise we'll shuffle the small elements in the high bits of the
18712       // larger type and perform an arithmetic shift. If the shift is not legal
18713       // it's better to scalarize.
18714       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18715         return SDValue();
18716
18717       // Redistribute the loaded elements into the different locations.
18718       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18719       for (unsigned i = 0; i != NumElems; ++i)
18720         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18721
18722       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18723                                            DAG.getUNDEF(WideVecVT),
18724                                            &ShuffleVec[0]);
18725
18726       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18727
18728       // Build the arithmetic shift.
18729       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18730                      MemVT.getVectorElementType().getSizeInBits();
18731       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18732                           DAG.getConstant(Amt, RegVT));
18733
18734       return DCI.CombineTo(N, Shuff, TF, true);
18735     }
18736
18737     // Redistribute the loaded elements into the different locations.
18738     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18739     for (unsigned i = 0; i != NumElems; ++i)
18740       ShuffleVec[i*SizeRatio] = i;
18741
18742     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18743                                          DAG.getUNDEF(WideVecVT),
18744                                          &ShuffleVec[0]);
18745
18746     // Bitcast to the requested type.
18747     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18748     // Replace the original load with the new sequence
18749     // and return the new chain.
18750     return DCI.CombineTo(N, Shuff, TF, true);
18751   }
18752
18753   return SDValue();
18754 }
18755
18756 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18757 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18758                                    const X86Subtarget *Subtarget) {
18759   StoreSDNode *St = cast<StoreSDNode>(N);
18760   EVT VT = St->getValue().getValueType();
18761   EVT StVT = St->getMemoryVT();
18762   SDLoc dl(St);
18763   SDValue StoredVal = St->getOperand(1);
18764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18765
18766   // If we are saving a concatenation of two XMM registers, perform two stores.
18767   // On Sandy Bridge, 256-bit memory operations are executed by two
18768   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18769   // memory  operation.
18770   unsigned Alignment = St->getAlignment();
18771   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18772   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18773       StVT == VT && !IsAligned) {
18774     unsigned NumElems = VT.getVectorNumElements();
18775     if (NumElems < 2)
18776       return SDValue();
18777
18778     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18779     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18780
18781     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18782     SDValue Ptr0 = St->getBasePtr();
18783     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18784
18785     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18786                                 St->getPointerInfo(), St->isVolatile(),
18787                                 St->isNonTemporal(), Alignment);
18788     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18789                                 St->getPointerInfo(), St->isVolatile(),
18790                                 St->isNonTemporal(),
18791                                 std::min(16U, Alignment));
18792     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18793   }
18794
18795   // Optimize trunc store (of multiple scalars) to shuffle and store.
18796   // First, pack all of the elements in one place. Next, store to memory
18797   // in fewer chunks.
18798   if (St->isTruncatingStore() && VT.isVector()) {
18799     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18800     unsigned NumElems = VT.getVectorNumElements();
18801     assert(StVT != VT && "Cannot truncate to the same type");
18802     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18803     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18804
18805     // From, To sizes and ElemCount must be pow of two
18806     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18807     // We are going to use the original vector elt for storing.
18808     // Accumulated smaller vector elements must be a multiple of the store size.
18809     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18810
18811     unsigned SizeRatio  = FromSz / ToSz;
18812
18813     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18814
18815     // Create a type on which we perform the shuffle
18816     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18817             StVT.getScalarType(), NumElems*SizeRatio);
18818
18819     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18820
18821     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18822     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18823     for (unsigned i = 0; i != NumElems; ++i)
18824       ShuffleVec[i] = i * SizeRatio;
18825
18826     // Can't shuffle using an illegal type.
18827     if (!TLI.isTypeLegal(WideVecVT))
18828       return SDValue();
18829
18830     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18831                                          DAG.getUNDEF(WideVecVT),
18832                                          &ShuffleVec[0]);
18833     // At this point all of the data is stored at the bottom of the
18834     // register. We now need to save it to mem.
18835
18836     // Find the largest store unit
18837     MVT StoreType = MVT::i8;
18838     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18839          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18840       MVT Tp = (MVT::SimpleValueType)tp;
18841       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18842         StoreType = Tp;
18843     }
18844
18845     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18846     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18847         (64 <= NumElems * ToSz))
18848       StoreType = MVT::f64;
18849
18850     // Bitcast the original vector into a vector of store-size units
18851     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18852             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18853     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18854     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18855     SmallVector<SDValue, 8> Chains;
18856     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18857                                         TLI.getPointerTy());
18858     SDValue Ptr = St->getBasePtr();
18859
18860     // Perform one or more big stores into memory.
18861     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18862       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18863                                    StoreType, ShuffWide,
18864                                    DAG.getIntPtrConstant(i));
18865       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18866                                 St->getPointerInfo(), St->isVolatile(),
18867                                 St->isNonTemporal(), St->getAlignment());
18868       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18869       Chains.push_back(Ch);
18870     }
18871
18872     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18873                                Chains.size());
18874   }
18875
18876   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18877   // the FP state in cases where an emms may be missing.
18878   // A preferable solution to the general problem is to figure out the right
18879   // places to insert EMMS.  This qualifies as a quick hack.
18880
18881   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18882   if (VT.getSizeInBits() != 64)
18883     return SDValue();
18884
18885   const Function *F = DAG.getMachineFunction().getFunction();
18886   bool NoImplicitFloatOps = F->getAttributes().
18887     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18888   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18889                      && Subtarget->hasSSE2();
18890   if ((VT.isVector() ||
18891        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18892       isa<LoadSDNode>(St->getValue()) &&
18893       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18894       St->getChain().hasOneUse() && !St->isVolatile()) {
18895     SDNode* LdVal = St->getValue().getNode();
18896     LoadSDNode *Ld = 0;
18897     int TokenFactorIndex = -1;
18898     SmallVector<SDValue, 8> Ops;
18899     SDNode* ChainVal = St->getChain().getNode();
18900     // Must be a store of a load.  We currently handle two cases:  the load
18901     // is a direct child, and it's under an intervening TokenFactor.  It is
18902     // possible to dig deeper under nested TokenFactors.
18903     if (ChainVal == LdVal)
18904       Ld = cast<LoadSDNode>(St->getChain());
18905     else if (St->getValue().hasOneUse() &&
18906              ChainVal->getOpcode() == ISD::TokenFactor) {
18907       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18908         if (ChainVal->getOperand(i).getNode() == LdVal) {
18909           TokenFactorIndex = i;
18910           Ld = cast<LoadSDNode>(St->getValue());
18911         } else
18912           Ops.push_back(ChainVal->getOperand(i));
18913       }
18914     }
18915
18916     if (!Ld || !ISD::isNormalLoad(Ld))
18917       return SDValue();
18918
18919     // If this is not the MMX case, i.e. we are just turning i64 load/store
18920     // into f64 load/store, avoid the transformation if there are multiple
18921     // uses of the loaded value.
18922     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18923       return SDValue();
18924
18925     SDLoc LdDL(Ld);
18926     SDLoc StDL(N);
18927     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18928     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18929     // pair instead.
18930     if (Subtarget->is64Bit() || F64IsLegal) {
18931       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18932       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18933                                   Ld->getPointerInfo(), Ld->isVolatile(),
18934                                   Ld->isNonTemporal(), Ld->isInvariant(),
18935                                   Ld->getAlignment());
18936       SDValue NewChain = NewLd.getValue(1);
18937       if (TokenFactorIndex != -1) {
18938         Ops.push_back(NewChain);
18939         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18940                                Ops.size());
18941       }
18942       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18943                           St->getPointerInfo(),
18944                           St->isVolatile(), St->isNonTemporal(),
18945                           St->getAlignment());
18946     }
18947
18948     // Otherwise, lower to two pairs of 32-bit loads / stores.
18949     SDValue LoAddr = Ld->getBasePtr();
18950     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18951                                  DAG.getConstant(4, MVT::i32));
18952
18953     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18954                                Ld->getPointerInfo(),
18955                                Ld->isVolatile(), Ld->isNonTemporal(),
18956                                Ld->isInvariant(), Ld->getAlignment());
18957     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18958                                Ld->getPointerInfo().getWithOffset(4),
18959                                Ld->isVolatile(), Ld->isNonTemporal(),
18960                                Ld->isInvariant(),
18961                                MinAlign(Ld->getAlignment(), 4));
18962
18963     SDValue NewChain = LoLd.getValue(1);
18964     if (TokenFactorIndex != -1) {
18965       Ops.push_back(LoLd);
18966       Ops.push_back(HiLd);
18967       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18968                              Ops.size());
18969     }
18970
18971     LoAddr = St->getBasePtr();
18972     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18973                          DAG.getConstant(4, MVT::i32));
18974
18975     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18976                                 St->getPointerInfo(),
18977                                 St->isVolatile(), St->isNonTemporal(),
18978                                 St->getAlignment());
18979     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18980                                 St->getPointerInfo().getWithOffset(4),
18981                                 St->isVolatile(),
18982                                 St->isNonTemporal(),
18983                                 MinAlign(St->getAlignment(), 4));
18984     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18985   }
18986   return SDValue();
18987 }
18988
18989 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18990 /// and return the operands for the horizontal operation in LHS and RHS.  A
18991 /// horizontal operation performs the binary operation on successive elements
18992 /// of its first operand, then on successive elements of its second operand,
18993 /// returning the resulting values in a vector.  For example, if
18994 ///   A = < float a0, float a1, float a2, float a3 >
18995 /// and
18996 ///   B = < float b0, float b1, float b2, float b3 >
18997 /// then the result of doing a horizontal operation on A and B is
18998 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18999 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19000 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19001 /// set to A, RHS to B, and the routine returns 'true'.
19002 /// Note that the binary operation should have the property that if one of the
19003 /// operands is UNDEF then the result is UNDEF.
19004 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19005   // Look for the following pattern: if
19006   //   A = < float a0, float a1, float a2, float a3 >
19007   //   B = < float b0, float b1, float b2, float b3 >
19008   // and
19009   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19010   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19011   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19012   // which is A horizontal-op B.
19013
19014   // At least one of the operands should be a vector shuffle.
19015   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19016       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19017     return false;
19018
19019   MVT VT = LHS.getSimpleValueType();
19020
19021   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19022          "Unsupported vector type for horizontal add/sub");
19023
19024   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19025   // operate independently on 128-bit lanes.
19026   unsigned NumElts = VT.getVectorNumElements();
19027   unsigned NumLanes = VT.getSizeInBits()/128;
19028   unsigned NumLaneElts = NumElts / NumLanes;
19029   assert((NumLaneElts % 2 == 0) &&
19030          "Vector type should have an even number of elements in each lane");
19031   unsigned HalfLaneElts = NumLaneElts/2;
19032
19033   // View LHS in the form
19034   //   LHS = VECTOR_SHUFFLE A, B, LMask
19035   // If LHS is not a shuffle then pretend it is the shuffle
19036   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19037   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19038   // type VT.
19039   SDValue A, B;
19040   SmallVector<int, 16> LMask(NumElts);
19041   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19042     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19043       A = LHS.getOperand(0);
19044     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19045       B = LHS.getOperand(1);
19046     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19047     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19048   } else {
19049     if (LHS.getOpcode() != ISD::UNDEF)
19050       A = LHS;
19051     for (unsigned i = 0; i != NumElts; ++i)
19052       LMask[i] = i;
19053   }
19054
19055   // Likewise, view RHS in the form
19056   //   RHS = VECTOR_SHUFFLE C, D, RMask
19057   SDValue C, D;
19058   SmallVector<int, 16> RMask(NumElts);
19059   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19060     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19061       C = RHS.getOperand(0);
19062     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19063       D = RHS.getOperand(1);
19064     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19065     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19066   } else {
19067     if (RHS.getOpcode() != ISD::UNDEF)
19068       C = RHS;
19069     for (unsigned i = 0; i != NumElts; ++i)
19070       RMask[i] = i;
19071   }
19072
19073   // Check that the shuffles are both shuffling the same vectors.
19074   if (!(A == C && B == D) && !(A == D && B == C))
19075     return false;
19076
19077   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19078   if (!A.getNode() && !B.getNode())
19079     return false;
19080
19081   // If A and B occur in reverse order in RHS, then "swap" them (which means
19082   // rewriting the mask).
19083   if (A != C)
19084     CommuteVectorShuffleMask(RMask, NumElts);
19085
19086   // At this point LHS and RHS are equivalent to
19087   //   LHS = VECTOR_SHUFFLE A, B, LMask
19088   //   RHS = VECTOR_SHUFFLE A, B, RMask
19089   // Check that the masks correspond to performing a horizontal operation.
19090   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19091     for (unsigned i = 0; i != NumLaneElts; ++i) {
19092       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19093
19094       // Ignore any UNDEF components.
19095       if (LIdx < 0 || RIdx < 0 ||
19096           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19097           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19098         continue;
19099
19100       // Check that successive elements are being operated on.  If not, this is
19101       // not a horizontal operation.
19102       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19103       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19104       if (!(LIdx == Index && RIdx == Index + 1) &&
19105           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19106         return false;
19107     }
19108   }
19109
19110   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19111   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19112   return true;
19113 }
19114
19115 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19116 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19117                                   const X86Subtarget *Subtarget) {
19118   EVT VT = N->getValueType(0);
19119   SDValue LHS = N->getOperand(0);
19120   SDValue RHS = N->getOperand(1);
19121
19122   // Try to synthesize horizontal adds from adds of shuffles.
19123   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19124        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19125       isHorizontalBinOp(LHS, RHS, true))
19126     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19127   return SDValue();
19128 }
19129
19130 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19131 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19132                                   const X86Subtarget *Subtarget) {
19133   EVT VT = N->getValueType(0);
19134   SDValue LHS = N->getOperand(0);
19135   SDValue RHS = N->getOperand(1);
19136
19137   // Try to synthesize horizontal subs from subs of shuffles.
19138   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19139        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19140       isHorizontalBinOp(LHS, RHS, false))
19141     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19142   return SDValue();
19143 }
19144
19145 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19146 /// X86ISD::FXOR nodes.
19147 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19148   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19149   // F[X]OR(0.0, x) -> x
19150   // F[X]OR(x, 0.0) -> x
19151   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19152     if (C->getValueAPF().isPosZero())
19153       return N->getOperand(1);
19154   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19155     if (C->getValueAPF().isPosZero())
19156       return N->getOperand(0);
19157   return SDValue();
19158 }
19159
19160 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19161 /// X86ISD::FMAX nodes.
19162 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19163   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19164
19165   // Only perform optimizations if UnsafeMath is used.
19166   if (!DAG.getTarget().Options.UnsafeFPMath)
19167     return SDValue();
19168
19169   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19170   // into FMINC and FMAXC, which are Commutative operations.
19171   unsigned NewOp = 0;
19172   switch (N->getOpcode()) {
19173     default: llvm_unreachable("unknown opcode");
19174     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19175     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19176   }
19177
19178   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19179                      N->getOperand(0), N->getOperand(1));
19180 }
19181
19182 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19183 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19184   // FAND(0.0, x) -> 0.0
19185   // FAND(x, 0.0) -> 0.0
19186   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19187     if (C->getValueAPF().isPosZero())
19188       return N->getOperand(0);
19189   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19190     if (C->getValueAPF().isPosZero())
19191       return N->getOperand(1);
19192   return SDValue();
19193 }
19194
19195 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19196 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19197   // FANDN(x, 0.0) -> 0.0
19198   // FANDN(0.0, x) -> x
19199   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19200     if (C->getValueAPF().isPosZero())
19201       return N->getOperand(1);
19202   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19203     if (C->getValueAPF().isPosZero())
19204       return N->getOperand(1);
19205   return SDValue();
19206 }
19207
19208 static SDValue PerformBTCombine(SDNode *N,
19209                                 SelectionDAG &DAG,
19210                                 TargetLowering::DAGCombinerInfo &DCI) {
19211   // BT ignores high bits in the bit index operand.
19212   SDValue Op1 = N->getOperand(1);
19213   if (Op1.hasOneUse()) {
19214     unsigned BitWidth = Op1.getValueSizeInBits();
19215     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19216     APInt KnownZero, KnownOne;
19217     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19218                                           !DCI.isBeforeLegalizeOps());
19219     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19220     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19221         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19222       DCI.CommitTargetLoweringOpt(TLO);
19223   }
19224   return SDValue();
19225 }
19226
19227 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19228   SDValue Op = N->getOperand(0);
19229   if (Op.getOpcode() == ISD::BITCAST)
19230     Op = Op.getOperand(0);
19231   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19232   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19233       VT.getVectorElementType().getSizeInBits() ==
19234       OpVT.getVectorElementType().getSizeInBits()) {
19235     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19236   }
19237   return SDValue();
19238 }
19239
19240 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19241                                                const X86Subtarget *Subtarget) {
19242   EVT VT = N->getValueType(0);
19243   if (!VT.isVector())
19244     return SDValue();
19245
19246   SDValue N0 = N->getOperand(0);
19247   SDValue N1 = N->getOperand(1);
19248   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19249   SDLoc dl(N);
19250
19251   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19252   // both SSE and AVX2 since there is no sign-extended shift right
19253   // operation on a vector with 64-bit elements.
19254   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19255   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19256   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19257       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19258     SDValue N00 = N0.getOperand(0);
19259
19260     // EXTLOAD has a better solution on AVX2,
19261     // it may be replaced with X86ISD::VSEXT node.
19262     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19263       if (!ISD::isNormalLoad(N00.getNode()))
19264         return SDValue();
19265
19266     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19267         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19268                                   N00, N1);
19269       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19270     }
19271   }
19272   return SDValue();
19273 }
19274
19275 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19276                                   TargetLowering::DAGCombinerInfo &DCI,
19277                                   const X86Subtarget *Subtarget) {
19278   if (!DCI.isBeforeLegalizeOps())
19279     return SDValue();
19280
19281   if (!Subtarget->hasFp256())
19282     return SDValue();
19283
19284   EVT VT = N->getValueType(0);
19285   if (VT.isVector() && VT.getSizeInBits() == 256) {
19286     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19287     if (R.getNode())
19288       return R;
19289   }
19290
19291   return SDValue();
19292 }
19293
19294 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19295                                  const X86Subtarget* Subtarget) {
19296   SDLoc dl(N);
19297   EVT VT = N->getValueType(0);
19298
19299   // Let legalize expand this if it isn't a legal type yet.
19300   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19301     return SDValue();
19302
19303   EVT ScalarVT = VT.getScalarType();
19304   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19305       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19306     return SDValue();
19307
19308   SDValue A = N->getOperand(0);
19309   SDValue B = N->getOperand(1);
19310   SDValue C = N->getOperand(2);
19311
19312   bool NegA = (A.getOpcode() == ISD::FNEG);
19313   bool NegB = (B.getOpcode() == ISD::FNEG);
19314   bool NegC = (C.getOpcode() == ISD::FNEG);
19315
19316   // Negative multiplication when NegA xor NegB
19317   bool NegMul = (NegA != NegB);
19318   if (NegA)
19319     A = A.getOperand(0);
19320   if (NegB)
19321     B = B.getOperand(0);
19322   if (NegC)
19323     C = C.getOperand(0);
19324
19325   unsigned Opcode;
19326   if (!NegMul)
19327     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19328   else
19329     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19330
19331   return DAG.getNode(Opcode, dl, VT, A, B, C);
19332 }
19333
19334 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19335                                   TargetLowering::DAGCombinerInfo &DCI,
19336                                   const X86Subtarget *Subtarget) {
19337   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19338   //           (and (i32 x86isd::setcc_carry), 1)
19339   // This eliminates the zext. This transformation is necessary because
19340   // ISD::SETCC is always legalized to i8.
19341   SDLoc dl(N);
19342   SDValue N0 = N->getOperand(0);
19343   EVT VT = N->getValueType(0);
19344
19345   if (N0.getOpcode() == ISD::AND &&
19346       N0.hasOneUse() &&
19347       N0.getOperand(0).hasOneUse()) {
19348     SDValue N00 = N0.getOperand(0);
19349     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19350       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19351       if (!C || C->getZExtValue() != 1)
19352         return SDValue();
19353       return DAG.getNode(ISD::AND, dl, VT,
19354                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19355                                      N00.getOperand(0), N00.getOperand(1)),
19356                          DAG.getConstant(1, VT));
19357     }
19358   }
19359
19360   if (N0.getOpcode() == ISD::TRUNCATE &&
19361       N0.hasOneUse() &&
19362       N0.getOperand(0).hasOneUse()) {
19363     SDValue N00 = N0.getOperand(0);
19364     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19365       return DAG.getNode(ISD::AND, dl, VT,
19366                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19367                                      N00.getOperand(0), N00.getOperand(1)),
19368                          DAG.getConstant(1, VT));
19369     }
19370   }
19371   if (VT.is256BitVector()) {
19372     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19373     if (R.getNode())
19374       return R;
19375   }
19376
19377   return SDValue();
19378 }
19379
19380 // Optimize x == -y --> x+y == 0
19381 //          x != -y --> x+y != 0
19382 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19383                                       const X86Subtarget* Subtarget) {
19384   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19385   SDValue LHS = N->getOperand(0);
19386   SDValue RHS = N->getOperand(1);
19387   EVT VT = N->getValueType(0);
19388   SDLoc DL(N);
19389
19390   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19391     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19392       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19393         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19394                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19395         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19396                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19397       }
19398   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19399     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19400       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19401         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19402                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19403         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19404                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19405       }
19406
19407   if (VT.getScalarType() == MVT::i1) {
19408     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19409       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19410     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19411     if (!IsSEXT0 && !IsVZero0)
19412       return SDValue();
19413     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19414       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19415     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19416
19417     if (!IsSEXT1 && !IsVZero1)
19418       return SDValue();
19419
19420     if (IsSEXT0 && IsVZero1) {
19421       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19422       if (CC == ISD::SETEQ)
19423         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19424       return LHS.getOperand(0);
19425     }
19426     if (IsSEXT1 && IsVZero0) {
19427       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19428       if (CC == ISD::SETEQ)
19429         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19430       return RHS.getOperand(0);
19431     }
19432   }
19433
19434   return SDValue();
19435 }
19436
19437 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19438 // as "sbb reg,reg", since it can be extended without zext and produces
19439 // an all-ones bit which is more useful than 0/1 in some cases.
19440 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19441                                MVT VT) {
19442   if (VT == MVT::i8)
19443     return DAG.getNode(ISD::AND, DL, VT,
19444                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19445                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19446                        DAG.getConstant(1, VT));
19447   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19448   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19449                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19450                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19451 }
19452
19453 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19454 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19455                                    TargetLowering::DAGCombinerInfo &DCI,
19456                                    const X86Subtarget *Subtarget) {
19457   SDLoc DL(N);
19458   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19459   SDValue EFLAGS = N->getOperand(1);
19460
19461   if (CC == X86::COND_A) {
19462     // Try to convert COND_A into COND_B in an attempt to facilitate
19463     // materializing "setb reg".
19464     //
19465     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19466     // cannot take an immediate as its first operand.
19467     //
19468     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19469         EFLAGS.getValueType().isInteger() &&
19470         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19471       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19472                                    EFLAGS.getNode()->getVTList(),
19473                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19474       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19475       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19476     }
19477   }
19478
19479   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19480   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19481   // cases.
19482   if (CC == X86::COND_B)
19483     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19484
19485   SDValue Flags;
19486
19487   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19488   if (Flags.getNode()) {
19489     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19490     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19491   }
19492
19493   return SDValue();
19494 }
19495
19496 // Optimize branch condition evaluation.
19497 //
19498 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19499                                     TargetLowering::DAGCombinerInfo &DCI,
19500                                     const X86Subtarget *Subtarget) {
19501   SDLoc DL(N);
19502   SDValue Chain = N->getOperand(0);
19503   SDValue Dest = N->getOperand(1);
19504   SDValue EFLAGS = N->getOperand(3);
19505   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19506
19507   SDValue Flags;
19508
19509   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19510   if (Flags.getNode()) {
19511     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19512     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19513                        Flags);
19514   }
19515
19516   return SDValue();
19517 }
19518
19519 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19520                                         const X86TargetLowering *XTLI) {
19521   SDValue Op0 = N->getOperand(0);
19522   EVT InVT = Op0->getValueType(0);
19523
19524   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19525   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19526     SDLoc dl(N);
19527     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19528     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19529     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19530   }
19531
19532   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19533   // a 32-bit target where SSE doesn't support i64->FP operations.
19534   if (Op0.getOpcode() == ISD::LOAD) {
19535     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19536     EVT VT = Ld->getValueType(0);
19537     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19538         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19539         !XTLI->getSubtarget()->is64Bit() &&
19540         VT == MVT::i64) {
19541       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19542                                           Ld->getChain(), Op0, DAG);
19543       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19544       return FILDChain;
19545     }
19546   }
19547   return SDValue();
19548 }
19549
19550 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19551 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19552                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19553   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19554   // the result is either zero or one (depending on the input carry bit).
19555   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19556   if (X86::isZeroNode(N->getOperand(0)) &&
19557       X86::isZeroNode(N->getOperand(1)) &&
19558       // We don't have a good way to replace an EFLAGS use, so only do this when
19559       // dead right now.
19560       SDValue(N, 1).use_empty()) {
19561     SDLoc DL(N);
19562     EVT VT = N->getValueType(0);
19563     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19564     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19565                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19566                                            DAG.getConstant(X86::COND_B,MVT::i8),
19567                                            N->getOperand(2)),
19568                                DAG.getConstant(1, VT));
19569     return DCI.CombineTo(N, Res1, CarryOut);
19570   }
19571
19572   return SDValue();
19573 }
19574
19575 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19576 //      (add Y, (setne X, 0)) -> sbb -1, Y
19577 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19578 //      (sub (setne X, 0), Y) -> adc -1, Y
19579 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19580   SDLoc DL(N);
19581
19582   // Look through ZExts.
19583   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19584   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19585     return SDValue();
19586
19587   SDValue SetCC = Ext.getOperand(0);
19588   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19589     return SDValue();
19590
19591   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19592   if (CC != X86::COND_E && CC != X86::COND_NE)
19593     return SDValue();
19594
19595   SDValue Cmp = SetCC.getOperand(1);
19596   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19597       !X86::isZeroNode(Cmp.getOperand(1)) ||
19598       !Cmp.getOperand(0).getValueType().isInteger())
19599     return SDValue();
19600
19601   SDValue CmpOp0 = Cmp.getOperand(0);
19602   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19603                                DAG.getConstant(1, CmpOp0.getValueType()));
19604
19605   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19606   if (CC == X86::COND_NE)
19607     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19608                        DL, OtherVal.getValueType(), OtherVal,
19609                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19610   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19611                      DL, OtherVal.getValueType(), OtherVal,
19612                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19613 }
19614
19615 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19616 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19617                                  const X86Subtarget *Subtarget) {
19618   EVT VT = N->getValueType(0);
19619   SDValue Op0 = N->getOperand(0);
19620   SDValue Op1 = N->getOperand(1);
19621
19622   // Try to synthesize horizontal adds from adds of shuffles.
19623   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19624        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19625       isHorizontalBinOp(Op0, Op1, true))
19626     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19627
19628   return OptimizeConditionalInDecrement(N, DAG);
19629 }
19630
19631 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19632                                  const X86Subtarget *Subtarget) {
19633   SDValue Op0 = N->getOperand(0);
19634   SDValue Op1 = N->getOperand(1);
19635
19636   // X86 can't encode an immediate LHS of a sub. See if we can push the
19637   // negation into a preceding instruction.
19638   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19639     // If the RHS of the sub is a XOR with one use and a constant, invert the
19640     // immediate. Then add one to the LHS of the sub so we can turn
19641     // X-Y -> X+~Y+1, saving one register.
19642     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19643         isa<ConstantSDNode>(Op1.getOperand(1))) {
19644       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19645       EVT VT = Op0.getValueType();
19646       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19647                                    Op1.getOperand(0),
19648                                    DAG.getConstant(~XorC, VT));
19649       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19650                          DAG.getConstant(C->getAPIntValue()+1, VT));
19651     }
19652   }
19653
19654   // Try to synthesize horizontal adds from adds of shuffles.
19655   EVT VT = N->getValueType(0);
19656   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19657        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19658       isHorizontalBinOp(Op0, Op1, true))
19659     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19660
19661   return OptimizeConditionalInDecrement(N, DAG);
19662 }
19663
19664 /// performVZEXTCombine - Performs build vector combines
19665 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19666                                         TargetLowering::DAGCombinerInfo &DCI,
19667                                         const X86Subtarget *Subtarget) {
19668   // (vzext (bitcast (vzext (x)) -> (vzext x)
19669   SDValue In = N->getOperand(0);
19670   while (In.getOpcode() == ISD::BITCAST)
19671     In = In.getOperand(0);
19672
19673   if (In.getOpcode() != X86ISD::VZEXT)
19674     return SDValue();
19675
19676   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19677                      In.getOperand(0));
19678 }
19679
19680 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19681                                              DAGCombinerInfo &DCI) const {
19682   SelectionDAG &DAG = DCI.DAG;
19683   switch (N->getOpcode()) {
19684   default: break;
19685   case ISD::EXTRACT_VECTOR_ELT:
19686     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19687   case ISD::VSELECT:
19688   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19689   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19690   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19691   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19692   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19693   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19694   case ISD::SHL:
19695   case ISD::SRA:
19696   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19697   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19698   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19699   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19700   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19701   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19702   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19703   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19704   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19705   case X86ISD::FXOR:
19706   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19707   case X86ISD::FMIN:
19708   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19709   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19710   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19711   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19712   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19713   case ISD::ANY_EXTEND:
19714   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19715   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19716   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19717   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19718   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19719   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19720   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19721   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19722   case X86ISD::SHUFP:       // Handle all target specific shuffles
19723   case X86ISD::PALIGNR:
19724   case X86ISD::UNPCKH:
19725   case X86ISD::UNPCKL:
19726   case X86ISD::MOVHLPS:
19727   case X86ISD::MOVLHPS:
19728   case X86ISD::PSHUFD:
19729   case X86ISD::PSHUFHW:
19730   case X86ISD::PSHUFLW:
19731   case X86ISD::MOVSS:
19732   case X86ISD::MOVSD:
19733   case X86ISD::VPERMILP:
19734   case X86ISD::VPERM2X128:
19735   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19736   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19737   }
19738
19739   return SDValue();
19740 }
19741
19742 /// isTypeDesirableForOp - Return true if the target has native support for
19743 /// the specified value type and it is 'desirable' to use the type for the
19744 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19745 /// instruction encodings are longer and some i16 instructions are slow.
19746 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19747   if (!isTypeLegal(VT))
19748     return false;
19749   if (VT != MVT::i16)
19750     return true;
19751
19752   switch (Opc) {
19753   default:
19754     return true;
19755   case ISD::LOAD:
19756   case ISD::SIGN_EXTEND:
19757   case ISD::ZERO_EXTEND:
19758   case ISD::ANY_EXTEND:
19759   case ISD::SHL:
19760   case ISD::SRL:
19761   case ISD::SUB:
19762   case ISD::ADD:
19763   case ISD::MUL:
19764   case ISD::AND:
19765   case ISD::OR:
19766   case ISD::XOR:
19767     return false;
19768   }
19769 }
19770
19771 /// IsDesirableToPromoteOp - This method query the target whether it is
19772 /// beneficial for dag combiner to promote the specified node. If true, it
19773 /// should return the desired promotion type by reference.
19774 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19775   EVT VT = Op.getValueType();
19776   if (VT != MVT::i16)
19777     return false;
19778
19779   bool Promote = false;
19780   bool Commute = false;
19781   switch (Op.getOpcode()) {
19782   default: break;
19783   case ISD::LOAD: {
19784     LoadSDNode *LD = cast<LoadSDNode>(Op);
19785     // If the non-extending load has a single use and it's not live out, then it
19786     // might be folded.
19787     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19788                                                      Op.hasOneUse()*/) {
19789       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19790              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19791         // The only case where we'd want to promote LOAD (rather then it being
19792         // promoted as an operand is when it's only use is liveout.
19793         if (UI->getOpcode() != ISD::CopyToReg)
19794           return false;
19795       }
19796     }
19797     Promote = true;
19798     break;
19799   }
19800   case ISD::SIGN_EXTEND:
19801   case ISD::ZERO_EXTEND:
19802   case ISD::ANY_EXTEND:
19803     Promote = true;
19804     break;
19805   case ISD::SHL:
19806   case ISD::SRL: {
19807     SDValue N0 = Op.getOperand(0);
19808     // Look out for (store (shl (load), x)).
19809     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19810       return false;
19811     Promote = true;
19812     break;
19813   }
19814   case ISD::ADD:
19815   case ISD::MUL:
19816   case ISD::AND:
19817   case ISD::OR:
19818   case ISD::XOR:
19819     Commute = true;
19820     // fallthrough
19821   case ISD::SUB: {
19822     SDValue N0 = Op.getOperand(0);
19823     SDValue N1 = Op.getOperand(1);
19824     if (!Commute && MayFoldLoad(N1))
19825       return false;
19826     // Avoid disabling potential load folding opportunities.
19827     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19828       return false;
19829     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19830       return false;
19831     Promote = true;
19832   }
19833   }
19834
19835   PVT = MVT::i32;
19836   return Promote;
19837 }
19838
19839 //===----------------------------------------------------------------------===//
19840 //                           X86 Inline Assembly Support
19841 //===----------------------------------------------------------------------===//
19842
19843 namespace {
19844   // Helper to match a string separated by whitespace.
19845   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19846     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19847
19848     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19849       StringRef piece(*args[i]);
19850       if (!s.startswith(piece)) // Check if the piece matches.
19851         return false;
19852
19853       s = s.substr(piece.size());
19854       StringRef::size_type pos = s.find_first_not_of(" \t");
19855       if (pos == 0) // We matched a prefix.
19856         return false;
19857
19858       s = s.substr(pos);
19859     }
19860
19861     return s.empty();
19862   }
19863   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19864 }
19865
19866 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19867
19868   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19869     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19870         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19871         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19872
19873       if (AsmPieces.size() == 3)
19874         return true;
19875       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19876         return true;
19877     }
19878   }
19879   return false;
19880 }
19881
19882 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19883   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19884
19885   std::string AsmStr = IA->getAsmString();
19886
19887   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19888   if (!Ty || Ty->getBitWidth() % 16 != 0)
19889     return false;
19890
19891   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19892   SmallVector<StringRef, 4> AsmPieces;
19893   SplitString(AsmStr, AsmPieces, ";\n");
19894
19895   switch (AsmPieces.size()) {
19896   default: return false;
19897   case 1:
19898     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19899     // we will turn this bswap into something that will be lowered to logical
19900     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19901     // lower so don't worry about this.
19902     // bswap $0
19903     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19904         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19905         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19906         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19907         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19908         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19909       // No need to check constraints, nothing other than the equivalent of
19910       // "=r,0" would be valid here.
19911       return IntrinsicLowering::LowerToByteSwap(CI);
19912     }
19913
19914     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19915     if (CI->getType()->isIntegerTy(16) &&
19916         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19917         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19918          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19919       AsmPieces.clear();
19920       const std::string &ConstraintsStr = IA->getConstraintString();
19921       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19922       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19923       if (clobbersFlagRegisters(AsmPieces))
19924         return IntrinsicLowering::LowerToByteSwap(CI);
19925     }
19926     break;
19927   case 3:
19928     if (CI->getType()->isIntegerTy(32) &&
19929         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19930         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19931         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19932         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19933       AsmPieces.clear();
19934       const std::string &ConstraintsStr = IA->getConstraintString();
19935       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19936       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19937       if (clobbersFlagRegisters(AsmPieces))
19938         return IntrinsicLowering::LowerToByteSwap(CI);
19939     }
19940
19941     if (CI->getType()->isIntegerTy(64)) {
19942       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19943       if (Constraints.size() >= 2 &&
19944           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19945           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19946         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19947         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19948             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19949             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19950           return IntrinsicLowering::LowerToByteSwap(CI);
19951       }
19952     }
19953     break;
19954   }
19955   return false;
19956 }
19957
19958 /// getConstraintType - Given a constraint letter, return the type of
19959 /// constraint it is for this target.
19960 X86TargetLowering::ConstraintType
19961 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19962   if (Constraint.size() == 1) {
19963     switch (Constraint[0]) {
19964     case 'R':
19965     case 'q':
19966     case 'Q':
19967     case 'f':
19968     case 't':
19969     case 'u':
19970     case 'y':
19971     case 'x':
19972     case 'Y':
19973     case 'l':
19974       return C_RegisterClass;
19975     case 'a':
19976     case 'b':
19977     case 'c':
19978     case 'd':
19979     case 'S':
19980     case 'D':
19981     case 'A':
19982       return C_Register;
19983     case 'I':
19984     case 'J':
19985     case 'K':
19986     case 'L':
19987     case 'M':
19988     case 'N':
19989     case 'G':
19990     case 'C':
19991     case 'e':
19992     case 'Z':
19993       return C_Other;
19994     default:
19995       break;
19996     }
19997   }
19998   return TargetLowering::getConstraintType(Constraint);
19999 }
20000
20001 /// Examine constraint type and operand type and determine a weight value.
20002 /// This object must already have been set up with the operand type
20003 /// and the current alternative constraint selected.
20004 TargetLowering::ConstraintWeight
20005   X86TargetLowering::getSingleConstraintMatchWeight(
20006     AsmOperandInfo &info, const char *constraint) const {
20007   ConstraintWeight weight = CW_Invalid;
20008   Value *CallOperandVal = info.CallOperandVal;
20009     // If we don't have a value, we can't do a match,
20010     // but allow it at the lowest weight.
20011   if (CallOperandVal == NULL)
20012     return CW_Default;
20013   Type *type = CallOperandVal->getType();
20014   // Look at the constraint type.
20015   switch (*constraint) {
20016   default:
20017     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20018   case 'R':
20019   case 'q':
20020   case 'Q':
20021   case 'a':
20022   case 'b':
20023   case 'c':
20024   case 'd':
20025   case 'S':
20026   case 'D':
20027   case 'A':
20028     if (CallOperandVal->getType()->isIntegerTy())
20029       weight = CW_SpecificReg;
20030     break;
20031   case 'f':
20032   case 't':
20033   case 'u':
20034     if (type->isFloatingPointTy())
20035       weight = CW_SpecificReg;
20036     break;
20037   case 'y':
20038     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20039       weight = CW_SpecificReg;
20040     break;
20041   case 'x':
20042   case 'Y':
20043     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20044         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20045       weight = CW_Register;
20046     break;
20047   case 'I':
20048     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20049       if (C->getZExtValue() <= 31)
20050         weight = CW_Constant;
20051     }
20052     break;
20053   case 'J':
20054     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20055       if (C->getZExtValue() <= 63)
20056         weight = CW_Constant;
20057     }
20058     break;
20059   case 'K':
20060     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20061       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20062         weight = CW_Constant;
20063     }
20064     break;
20065   case 'L':
20066     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20067       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20068         weight = CW_Constant;
20069     }
20070     break;
20071   case 'M':
20072     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20073       if (C->getZExtValue() <= 3)
20074         weight = CW_Constant;
20075     }
20076     break;
20077   case 'N':
20078     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20079       if (C->getZExtValue() <= 0xff)
20080         weight = CW_Constant;
20081     }
20082     break;
20083   case 'G':
20084   case 'C':
20085     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20086       weight = CW_Constant;
20087     }
20088     break;
20089   case 'e':
20090     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20091       if ((C->getSExtValue() >= -0x80000000LL) &&
20092           (C->getSExtValue() <= 0x7fffffffLL))
20093         weight = CW_Constant;
20094     }
20095     break;
20096   case 'Z':
20097     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20098       if (C->getZExtValue() <= 0xffffffff)
20099         weight = CW_Constant;
20100     }
20101     break;
20102   }
20103   return weight;
20104 }
20105
20106 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20107 /// with another that has more specific requirements based on the type of the
20108 /// corresponding operand.
20109 const char *X86TargetLowering::
20110 LowerXConstraint(EVT ConstraintVT) const {
20111   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20112   // 'f' like normal targets.
20113   if (ConstraintVT.isFloatingPoint()) {
20114     if (Subtarget->hasSSE2())
20115       return "Y";
20116     if (Subtarget->hasSSE1())
20117       return "x";
20118   }
20119
20120   return TargetLowering::LowerXConstraint(ConstraintVT);
20121 }
20122
20123 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20124 /// vector.  If it is invalid, don't add anything to Ops.
20125 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20126                                                      std::string &Constraint,
20127                                                      std::vector<SDValue>&Ops,
20128                                                      SelectionDAG &DAG) const {
20129   SDValue Result(0, 0);
20130
20131   // Only support length 1 constraints for now.
20132   if (Constraint.length() > 1) return;
20133
20134   char ConstraintLetter = Constraint[0];
20135   switch (ConstraintLetter) {
20136   default: break;
20137   case 'I':
20138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20139       if (C->getZExtValue() <= 31) {
20140         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20141         break;
20142       }
20143     }
20144     return;
20145   case 'J':
20146     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20147       if (C->getZExtValue() <= 63) {
20148         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20149         break;
20150       }
20151     }
20152     return;
20153   case 'K':
20154     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20155       if (isInt<8>(C->getSExtValue())) {
20156         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20157         break;
20158       }
20159     }
20160     return;
20161   case 'N':
20162     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20163       if (C->getZExtValue() <= 255) {
20164         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20165         break;
20166       }
20167     }
20168     return;
20169   case 'e': {
20170     // 32-bit signed value
20171     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20172       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20173                                            C->getSExtValue())) {
20174         // Widen to 64 bits here to get it sign extended.
20175         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20176         break;
20177       }
20178     // FIXME gcc accepts some relocatable values here too, but only in certain
20179     // memory models; it's complicated.
20180     }
20181     return;
20182   }
20183   case 'Z': {
20184     // 32-bit unsigned value
20185     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20186       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20187                                            C->getZExtValue())) {
20188         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20189         break;
20190       }
20191     }
20192     // FIXME gcc accepts some relocatable values here too, but only in certain
20193     // memory models; it's complicated.
20194     return;
20195   }
20196   case 'i': {
20197     // Literal immediates are always ok.
20198     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20199       // Widen to 64 bits here to get it sign extended.
20200       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20201       break;
20202     }
20203
20204     // In any sort of PIC mode addresses need to be computed at runtime by
20205     // adding in a register or some sort of table lookup.  These can't
20206     // be used as immediates.
20207     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20208       return;
20209
20210     // If we are in non-pic codegen mode, we allow the address of a global (with
20211     // an optional displacement) to be used with 'i'.
20212     GlobalAddressSDNode *GA = 0;
20213     int64_t Offset = 0;
20214
20215     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20216     while (1) {
20217       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20218         Offset += GA->getOffset();
20219         break;
20220       } else if (Op.getOpcode() == ISD::ADD) {
20221         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20222           Offset += C->getZExtValue();
20223           Op = Op.getOperand(0);
20224           continue;
20225         }
20226       } else if (Op.getOpcode() == ISD::SUB) {
20227         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20228           Offset += -C->getZExtValue();
20229           Op = Op.getOperand(0);
20230           continue;
20231         }
20232       }
20233
20234       // Otherwise, this isn't something we can handle, reject it.
20235       return;
20236     }
20237
20238     const GlobalValue *GV = GA->getGlobal();
20239     // If we require an extra load to get this address, as in PIC mode, we
20240     // can't accept it.
20241     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20242                                                         getTargetMachine())))
20243       return;
20244
20245     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20246                                         GA->getValueType(0), Offset);
20247     break;
20248   }
20249   }
20250
20251   if (Result.getNode()) {
20252     Ops.push_back(Result);
20253     return;
20254   }
20255   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20256 }
20257
20258 std::pair<unsigned, const TargetRegisterClass*>
20259 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20260                                                 MVT VT) const {
20261   // First, see if this is a constraint that directly corresponds to an LLVM
20262   // register class.
20263   if (Constraint.size() == 1) {
20264     // GCC Constraint Letters
20265     switch (Constraint[0]) {
20266     default: break;
20267       // TODO: Slight differences here in allocation order and leaving
20268       // RIP in the class. Do they matter any more here than they do
20269       // in the normal allocation?
20270     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20271       if (Subtarget->is64Bit()) {
20272         if (VT == MVT::i32 || VT == MVT::f32)
20273           return std::make_pair(0U, &X86::GR32RegClass);
20274         if (VT == MVT::i16)
20275           return std::make_pair(0U, &X86::GR16RegClass);
20276         if (VT == MVT::i8 || VT == MVT::i1)
20277           return std::make_pair(0U, &X86::GR8RegClass);
20278         if (VT == MVT::i64 || VT == MVT::f64)
20279           return std::make_pair(0U, &X86::GR64RegClass);
20280         break;
20281       }
20282       // 32-bit fallthrough
20283     case 'Q':   // Q_REGS
20284       if (VT == MVT::i32 || VT == MVT::f32)
20285         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20286       if (VT == MVT::i16)
20287         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20288       if (VT == MVT::i8 || VT == MVT::i1)
20289         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20290       if (VT == MVT::i64)
20291         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20292       break;
20293     case 'r':   // GENERAL_REGS
20294     case 'l':   // INDEX_REGS
20295       if (VT == MVT::i8 || VT == MVT::i1)
20296         return std::make_pair(0U, &X86::GR8RegClass);
20297       if (VT == MVT::i16)
20298         return std::make_pair(0U, &X86::GR16RegClass);
20299       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20300         return std::make_pair(0U, &X86::GR32RegClass);
20301       return std::make_pair(0U, &X86::GR64RegClass);
20302     case 'R':   // LEGACY_REGS
20303       if (VT == MVT::i8 || VT == MVT::i1)
20304         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20305       if (VT == MVT::i16)
20306         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20307       if (VT == MVT::i32 || !Subtarget->is64Bit())
20308         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20309       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20310     case 'f':  // FP Stack registers.
20311       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20312       // value to the correct fpstack register class.
20313       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20314         return std::make_pair(0U, &X86::RFP32RegClass);
20315       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20316         return std::make_pair(0U, &X86::RFP64RegClass);
20317       return std::make_pair(0U, &X86::RFP80RegClass);
20318     case 'y':   // MMX_REGS if MMX allowed.
20319       if (!Subtarget->hasMMX()) break;
20320       return std::make_pair(0U, &X86::VR64RegClass);
20321     case 'Y':   // SSE_REGS if SSE2 allowed
20322       if (!Subtarget->hasSSE2()) break;
20323       // FALL THROUGH.
20324     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20325       if (!Subtarget->hasSSE1()) break;
20326
20327       switch (VT.SimpleTy) {
20328       default: break;
20329       // Scalar SSE types.
20330       case MVT::f32:
20331       case MVT::i32:
20332         return std::make_pair(0U, &X86::FR32RegClass);
20333       case MVT::f64:
20334       case MVT::i64:
20335         return std::make_pair(0U, &X86::FR64RegClass);
20336       // Vector types.
20337       case MVT::v16i8:
20338       case MVT::v8i16:
20339       case MVT::v4i32:
20340       case MVT::v2i64:
20341       case MVT::v4f32:
20342       case MVT::v2f64:
20343         return std::make_pair(0U, &X86::VR128RegClass);
20344       // AVX types.
20345       case MVT::v32i8:
20346       case MVT::v16i16:
20347       case MVT::v8i32:
20348       case MVT::v4i64:
20349       case MVT::v8f32:
20350       case MVT::v4f64:
20351         return std::make_pair(0U, &X86::VR256RegClass);
20352       case MVT::v8f64:
20353       case MVT::v16f32:
20354       case MVT::v16i32:
20355       case MVT::v8i64:
20356         return std::make_pair(0U, &X86::VR512RegClass);
20357       }
20358       break;
20359     }
20360   }
20361
20362   // Use the default implementation in TargetLowering to convert the register
20363   // constraint into a member of a register class.
20364   std::pair<unsigned, const TargetRegisterClass*> Res;
20365   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20366
20367   // Not found as a standard register?
20368   if (Res.second == 0) {
20369     // Map st(0) -> st(7) -> ST0
20370     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20371         tolower(Constraint[1]) == 's' &&
20372         tolower(Constraint[2]) == 't' &&
20373         Constraint[3] == '(' &&
20374         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20375         Constraint[5] == ')' &&
20376         Constraint[6] == '}') {
20377
20378       Res.first = X86::ST0+Constraint[4]-'0';
20379       Res.second = &X86::RFP80RegClass;
20380       return Res;
20381     }
20382
20383     // GCC allows "st(0)" to be called just plain "st".
20384     if (StringRef("{st}").equals_lower(Constraint)) {
20385       Res.first = X86::ST0;
20386       Res.second = &X86::RFP80RegClass;
20387       return Res;
20388     }
20389
20390     // flags -> EFLAGS
20391     if (StringRef("{flags}").equals_lower(Constraint)) {
20392       Res.first = X86::EFLAGS;
20393       Res.second = &X86::CCRRegClass;
20394       return Res;
20395     }
20396
20397     // 'A' means EAX + EDX.
20398     if (Constraint == "A") {
20399       Res.first = X86::EAX;
20400       Res.second = &X86::GR32_ADRegClass;
20401       return Res;
20402     }
20403     return Res;
20404   }
20405
20406   // Otherwise, check to see if this is a register class of the wrong value
20407   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20408   // turn into {ax},{dx}.
20409   if (Res.second->hasType(VT))
20410     return Res;   // Correct type already, nothing to do.
20411
20412   // All of the single-register GCC register classes map their values onto
20413   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20414   // really want an 8-bit or 32-bit register, map to the appropriate register
20415   // class and return the appropriate register.
20416   if (Res.second == &X86::GR16RegClass) {
20417     if (VT == MVT::i8 || VT == MVT::i1) {
20418       unsigned DestReg = 0;
20419       switch (Res.first) {
20420       default: break;
20421       case X86::AX: DestReg = X86::AL; break;
20422       case X86::DX: DestReg = X86::DL; break;
20423       case X86::CX: DestReg = X86::CL; break;
20424       case X86::BX: DestReg = X86::BL; break;
20425       }
20426       if (DestReg) {
20427         Res.first = DestReg;
20428         Res.second = &X86::GR8RegClass;
20429       }
20430     } else if (VT == MVT::i32 || VT == MVT::f32) {
20431       unsigned DestReg = 0;
20432       switch (Res.first) {
20433       default: break;
20434       case X86::AX: DestReg = X86::EAX; break;
20435       case X86::DX: DestReg = X86::EDX; break;
20436       case X86::CX: DestReg = X86::ECX; break;
20437       case X86::BX: DestReg = X86::EBX; break;
20438       case X86::SI: DestReg = X86::ESI; break;
20439       case X86::DI: DestReg = X86::EDI; break;
20440       case X86::BP: DestReg = X86::EBP; break;
20441       case X86::SP: DestReg = X86::ESP; break;
20442       }
20443       if (DestReg) {
20444         Res.first = DestReg;
20445         Res.second = &X86::GR32RegClass;
20446       }
20447     } else if (VT == MVT::i64 || VT == MVT::f64) {
20448       unsigned DestReg = 0;
20449       switch (Res.first) {
20450       default: break;
20451       case X86::AX: DestReg = X86::RAX; break;
20452       case X86::DX: DestReg = X86::RDX; break;
20453       case X86::CX: DestReg = X86::RCX; break;
20454       case X86::BX: DestReg = X86::RBX; break;
20455       case X86::SI: DestReg = X86::RSI; break;
20456       case X86::DI: DestReg = X86::RDI; break;
20457       case X86::BP: DestReg = X86::RBP; break;
20458       case X86::SP: DestReg = X86::RSP; break;
20459       }
20460       if (DestReg) {
20461         Res.first = DestReg;
20462         Res.second = &X86::GR64RegClass;
20463       }
20464     }
20465   } else if (Res.second == &X86::FR32RegClass ||
20466              Res.second == &X86::FR64RegClass ||
20467              Res.second == &X86::VR128RegClass ||
20468              Res.second == &X86::VR256RegClass ||
20469              Res.second == &X86::FR32XRegClass ||
20470              Res.second == &X86::FR64XRegClass ||
20471              Res.second == &X86::VR128XRegClass ||
20472              Res.second == &X86::VR256XRegClass ||
20473              Res.second == &X86::VR512RegClass) {
20474     // Handle references to XMM physical registers that got mapped into the
20475     // wrong class.  This can happen with constraints like {xmm0} where the
20476     // target independent register mapper will just pick the first match it can
20477     // find, ignoring the required type.
20478
20479     if (VT == MVT::f32 || VT == MVT::i32)
20480       Res.second = &X86::FR32RegClass;
20481     else if (VT == MVT::f64 || VT == MVT::i64)
20482       Res.second = &X86::FR64RegClass;
20483     else if (X86::VR128RegClass.hasType(VT))
20484       Res.second = &X86::VR128RegClass;
20485     else if (X86::VR256RegClass.hasType(VT))
20486       Res.second = &X86::VR256RegClass;
20487     else if (X86::VR512RegClass.hasType(VT))
20488       Res.second = &X86::VR512RegClass;
20489   }
20490
20491   return Res;
20492 }