e59560ed88bfde67d39db797a245e624ae6a6a4a
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <bitset>
51 #include <cctype>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "x86-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89
90   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
92                                VecIdx);
93
94   return Result;
95
96 }
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104                                    SelectionDAG &DAG, SDLoc dl) {
105   assert((Vec.getValueType().is256BitVector() ||
106           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
108 }
109
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112                                    SelectionDAG &DAG, SDLoc dl) {
113   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
115 }
116
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118                                unsigned IdxVal, SelectionDAG &DAG,
119                                SDLoc dl, unsigned vectorWidth) {
120   assert((vectorWidth == 128 || vectorWidth == 256) &&
121          "Unsupported vector width");
122   // Inserting UNDEF is Result
123   if (Vec.getOpcode() == ISD::UNDEF)
124     return Result;
125   EVT VT = Vec.getValueType();
126   EVT ElVT = VT.getVectorElementType();
127   EVT ResultVT = Result.getValueType();
128
129   // Insert the relevant vectorWidth bits.
130   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131
132   // This is the index of the first element of the vectorWidth-bit chunk
133   // we want.
134   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
135                                * ElemsPerChunk);
136
137   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
139                      VecIdx);
140 }
141 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference.  Idx is an index in the 128 bits
145 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148                                   unsigned IdxVal, SelectionDAG &DAG,
149                                   SDLoc dl) {
150   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
152 }
153
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155                                   unsigned IdxVal, SelectionDAG &DAG,
156                                   SDLoc dl) {
157   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
159 }
160
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166                                    unsigned NumElems, SelectionDAG &DAG,
167                                    SDLoc dl) {
168   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
170 }
171
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173                                    unsigned NumElems, SelectionDAG &DAG,
174                                    SDLoc dl) {
175   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
177 }
178
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181   bool is64Bit = Subtarget->is64Bit();
182
183   if (Subtarget->isTargetMacho()) {
184     if (is64Bit)
185       return new X86_64MachoTargetObjectFile();
186     return new TargetLoweringObjectFileMachO();
187   }
188
189   if (Subtarget->isTargetLinux())
190     return new X86LinuxTargetObjectFile();
191   if (Subtarget->isTargetELF())
192     return new TargetLoweringObjectFileELF();
193   if (Subtarget->isTargetKnownWindowsMSVC())
194     return new X86WindowsTargetObjectFile();
195   if (Subtarget->isTargetCOFF())
196     return new TargetLoweringObjectFileCOFF();
197   llvm_unreachable("unknown subtarget type");
198 }
199
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201   : TargetLowering(TM, createTLOF(TM)) {
202   Subtarget = &TM.getSubtarget<X86Subtarget>();
203   X86ScalarSSEf64 = Subtarget->hasSSE2();
204   X86ScalarSSEf32 = Subtarget->hasSSE1();
205   TD = getDataLayout();
206
207   resetOperationActions();
208 }
209
210 void X86TargetLowering::resetOperationActions() {
211   const TargetMachine &TM = getTargetMachine();
212   static bool FirstTimeThrough = true;
213
214   // If none of the target options have changed, then we don't need to reset the
215   // operation actions.
216   if (!FirstTimeThrough && TO == TM.Options) return;
217
218   if (!FirstTimeThrough) {
219     // Reinitialize the actions.
220     initActions();
221     FirstTimeThrough = false;
222   }
223
224   TO = TM.Options;
225
226   // Set up the TargetLowering object.
227   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228
229   // X86 is weird, it always uses i8 for shift amounts and setcc results.
230   setBooleanContents(ZeroOrOneBooleanContent);
231   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233
234   // For 64-bit since we have so many registers use the ILP scheduler, for
235   // 32-bit code use the register pressure specific scheduling.
236   // For Atom, always use ILP scheduling.
237   if (Subtarget->isAtom())
238     setSchedulingPreference(Sched::ILP);
239   else if (Subtarget->is64Bit())
240     setSchedulingPreference(Sched::ILP);
241   else
242     setSchedulingPreference(Sched::RegPressure);
243   const X86RegisterInfo *RegInfo =
244     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246
247   // Bypass expensive divides on Atom when compiling with O2
248   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249     addBypassSlowDiv(32, 8);
250     if (Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   // SETOEQ and SETUNE require checking two conditions.
306   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312
313   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314   // operation.
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
318
319   if (Subtarget->is64Bit()) {
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
322   } else if (!TM.Options.UseSoftFloat) {
323     // We have an algorithm for SSE2->double, and we turn this into a
324     // 64-bit FILD followed by conditional FADD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
326     // We have an algorithm for SSE2, and we turn this into a 64-bit
327     // FILD for other targets.
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
329   }
330
331   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332   // this operation.
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
335
336   if (!TM.Options.UseSoftFloat) {
337     // SSE has no i16 to fp conversion, only i32
338     if (X86ScalarSSEf32) {
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
340       // f32 and f64 cases are Legal, f80 case is not
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     } else {
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
345     }
346   } else {
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
349   }
350
351   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
352   // are Legal, f80 is custom lowered.
353   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
354   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
355
356   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357   // this operation.
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
360
361   if (X86ScalarSSEf32) {
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
363     // f32 and f64 cases are Legal, f80 case is not
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   } else {
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
368   }
369
370   // Handle FP_TO_UINT by promoting the destination to a larger signed
371   // conversion.
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
375
376   if (Subtarget->is64Bit()) {
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
379   } else if (!TM.Options.UseSoftFloat) {
380     // Since AVX is a superset of SSE3, only check for SSE here.
381     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382       // Expand FP_TO_UINT into a select.
383       // FIXME: We would like to use a Custom expander here eventually to do
384       // the optimal thing for SSE vs. the default expansion in the legalizer.
385       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
386     else
387       // With SSE3 we can use fisttpll to convert to a signed i64; without
388       // SSE, we're stuck with a fistpll.
389       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
390   }
391
392   if (isTargetFTOL()) {
393     // Use the _ftol2 runtime function, which has a pseudo-instruction
394     // to handle its weird calling convention.
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
396   }
397
398   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399   if (!X86ScalarSSEf64) {
400     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
401     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
402     if (Subtarget->is64Bit()) {
403       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
404       // Without SSE, i64->f64 goes through memory.
405       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
406     }
407   }
408
409   // Scalar integer divide and remainder are lowered to use operations that
410   // produce two results, to match the available instructions. This exposes
411   // the two-result form to trivial CSE, which is able to combine x/y and x%y
412   // into a single instruction.
413   //
414   // Scalar integer multiply-high is also lowered to use two-result
415   // operations, to match the available instructions. However, plain multiply
416   // (low) operations are left as Legal, as there are single-result
417   // instructions for this in x86. Using the two-result multiply instructions
418   // when both high and low results are needed must be arranged by dagcombine.
419   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420     MVT VT = IntVTs[i];
421     setOperationAction(ISD::MULHS, VT, Expand);
422     setOperationAction(ISD::MULHU, VT, Expand);
423     setOperationAction(ISD::SDIV, VT, Expand);
424     setOperationAction(ISD::UDIV, VT, Expand);
425     setOperationAction(ISD::SREM, VT, Expand);
426     setOperationAction(ISD::UREM, VT, Expand);
427
428     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429     setOperationAction(ISD::ADDC, VT, Custom);
430     setOperationAction(ISD::ADDE, VT, Custom);
431     setOperationAction(ISD::SUBC, VT, Custom);
432     setOperationAction(ISD::SUBE, VT, Custom);
433   }
434
435   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
436   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
437   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
444   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
445   if (Subtarget->is64Bit())
446     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
450   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
454   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
455
456   // Promote the i8 variants and force them on up to i32 which has a shorter
457   // encoding.
458   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
460   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
462   if (Subtarget->hasBMI()) {
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
469     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
470     if (Subtarget->is64Bit())
471       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasLZCNT()) {
475     // When promoting the i8 variants, force them to i32 for a shorter
476     // encoding.
477     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
482     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
483     if (Subtarget->is64Bit())
484       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485   } else {
486     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
492     if (Subtarget->is64Bit()) {
493       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
494       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495     }
496   }
497
498   if (Subtarget->hasPOPCNT()) {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
500   } else {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
503     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
506   }
507
508   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
509
510   if (!Subtarget->hasMOVBE())
511     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
512
513   // These should be promoted to a larger select which is supported.
514   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
515   // X86 wants to expand cmov itself.
516   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
528   if (Subtarget->is64Bit()) {
529     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
530     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
531   }
532   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
533   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535   // support continuation, user-level threading, and etc.. As a result, no
536   // other SjLj exception interfaces are implemented and please don't build
537   // your own exception handling based on them.
538   // LLVM/Clang supports zero-cost DWARF exception handling.
539   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
541
542   // Darwin ABI issue.
543   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
544   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
546   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
547   if (Subtarget->is64Bit())
548     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
550   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
551   if (Subtarget->is64Bit()) {
552     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
553     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
554     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
555     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
556     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
557   }
558   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
561   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
562   if (Subtarget->is64Bit()) {
563     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
565     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
566   }
567
568   if (Subtarget->hasSSE1())
569     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
570
571   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
572
573   // Expand certain atomics
574   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575     MVT VT = IntVTs[i];
576     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
579   }
580
581   if (!Subtarget->is64Bit()) {
582     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
594   }
595
596   if (Subtarget->hasCmpxchg16b()) {
597     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
598   }
599
600   // FIXME - use subtarget debug flags
601   if (!Subtarget->isTargetDarwin() &&
602       !Subtarget->isTargetELF() &&
603       !Subtarget->isTargetCygMing()) {
604     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605   }
606
607   if (Subtarget->is64Bit()) {
608     setExceptionPointerRegister(X86::RAX);
609     setExceptionSelectorRegister(X86::RDX);
610   } else {
611     setExceptionPointerRegister(X86::EAX);
612     setExceptionSelectorRegister(X86::EDX);
613   }
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616
617   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619
620   setOperationAction(ISD::TRAP, MVT::Other, Legal);
621   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622
623   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
625   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
626   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627     // TargetInfo::X86_64ABIBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
630   } else {
631     // TargetInfo::CharPtrBuiltinVaList
632     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
633     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
634   }
635
636   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
637   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
638
639   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                      MVT::i64 : MVT::i32, Custom);
641
642   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643     // f32 and f64 use SSE.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f32, &X86::FR32RegClass);
646     addRegisterClass(MVT::f64, &X86::FR64RegClass);
647
648     // Use ANDPD to simulate FABS.
649     setOperationAction(ISD::FABS , MVT::f64, Custom);
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f64, Custom);
654     setOperationAction(ISD::FNEG , MVT::f32, Custom);
655
656     // Use ANDPD and ORPD to simulate FCOPYSIGN.
657     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659
660     // Lower this to FGETSIGNx86 plus an AND.
661     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663
664     // We don't support sin/cos/fmod
665     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
666     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
667     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671
672     // Expand FP immediates into loads from the stack, except for the special
673     // cases we handle.
674     addLegalFPImmediate(APFloat(+0.0)); // xorpd
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677     // Use SSE for f32, x87 for f64.
678     // Set up the FP register classes.
679     addRegisterClass(MVT::f32, &X86::FR32RegClass);
680     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681
682     // Use ANDPS to simulate FABS.
683     setOperationAction(ISD::FABS , MVT::f32, Custom);
684
685     // Use XORP to simulate FNEG.
686     setOperationAction(ISD::FNEG , MVT::f32, Custom);
687
688     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
689
690     // Use ANDPS and ORPS to simulate FCOPYSIGN.
691     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693
694     // We don't support sin/cos/fmod
695     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
696     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
697     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698
699     // Special cases we handle for FP constants.
700     addLegalFPImmediate(APFloat(+0.0f)); // xorps
701     addLegalFPImmediate(APFloat(+0.0)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705
706     if (!TM.Options.UnsafeFPMath) {
707       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
708       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
709       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710     }
711   } else if (!TM.Options.UseSoftFloat) {
712     // f32 and f64 in x87.
713     // Set up the FP register classes.
714     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716
717     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
718     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721
722     if (!TM.Options.UnsafeFPMath) {
723       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
724       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729     }
730     addLegalFPImmediate(APFloat(+0.0)); // FLD0
731     addLegalFPImmediate(APFloat(+1.0)); // FLD1
732     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
738   }
739
740   // We don't support FMA.
741   setOperationAction(ISD::FMA, MVT::f64, Expand);
742   setOperationAction(ISD::FMA, MVT::f32, Expand);
743
744   // Long double always uses X87.
745   if (!TM.Options.UseSoftFloat) {
746     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
748     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749     {
750       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751       addLegalFPImmediate(TmpFlt);  // FLD0
752       TmpFlt.changeSign();
753       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
754
755       bool ignored;
756       APFloat TmpFlt2(+1.0);
757       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758                       &ignored);
759       addLegalFPImmediate(TmpFlt2);  // FLD1
760       TmpFlt2.changeSign();
761       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
762     }
763
764     if (!TM.Options.UnsafeFPMath) {
765       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
766       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
767       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
768     }
769
770     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
772     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
774     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775     setOperationAction(ISD::FMA, MVT::f80, Expand);
776   }
777
778   // Always use a library call for pow.
779   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
782
783   setOperationAction(ISD::FLOG, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788
789   // First set operation action for all vector types to either promote
790   // (for widening) or expand (for scalarization). Then we will selectively
791   // turn on ones that can be effectively codegen'd.
792   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794     MVT VT = (MVT::SimpleValueType)i;
795     setOperationAction(ISD::ADD , VT, Expand);
796     setOperationAction(ISD::SUB , VT, Expand);
797     setOperationAction(ISD::FADD, VT, Expand);
798     setOperationAction(ISD::FNEG, VT, Expand);
799     setOperationAction(ISD::FSUB, VT, Expand);
800     setOperationAction(ISD::MUL , VT, Expand);
801     setOperationAction(ISD::FMUL, VT, Expand);
802     setOperationAction(ISD::SDIV, VT, Expand);
803     setOperationAction(ISD::UDIV, VT, Expand);
804     setOperationAction(ISD::FDIV, VT, Expand);
805     setOperationAction(ISD::SREM, VT, Expand);
806     setOperationAction(ISD::UREM, VT, Expand);
807     setOperationAction(ISD::LOAD, VT, Expand);
808     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::FABS, VT, Expand);
814     setOperationAction(ISD::FSIN, VT, Expand);
815     setOperationAction(ISD::FSINCOS, VT, Expand);
816     setOperationAction(ISD::FCOS, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FREM, VT, Expand);
819     setOperationAction(ISD::FMA,  VT, Expand);
820     setOperationAction(ISD::FPOWI, VT, Expand);
821     setOperationAction(ISD::FSQRT, VT, Expand);
822     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823     setOperationAction(ISD::FFLOOR, VT, Expand);
824     setOperationAction(ISD::FCEIL, VT, Expand);
825     setOperationAction(ISD::FTRUNC, VT, Expand);
826     setOperationAction(ISD::FRINT, VT, Expand);
827     setOperationAction(ISD::FNEARBYINT, VT, Expand);
828     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::SDIVREM, VT, Expand);
831     setOperationAction(ISD::UDIVREM, VT, Expand);
832     setOperationAction(ISD::FPOW, VT, Expand);
833     setOperationAction(ISD::CTPOP, VT, Expand);
834     setOperationAction(ISD::CTTZ, VT, Expand);
835     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836     setOperationAction(ISD::CTLZ, VT, Expand);
837     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::SHL, VT, Expand);
839     setOperationAction(ISD::SRA, VT, Expand);
840     setOperationAction(ISD::SRL, VT, Expand);
841     setOperationAction(ISD::ROTL, VT, Expand);
842     setOperationAction(ISD::ROTR, VT, Expand);
843     setOperationAction(ISD::BSWAP, VT, Expand);
844     setOperationAction(ISD::SETCC, VT, Expand);
845     setOperationAction(ISD::FLOG, VT, Expand);
846     setOperationAction(ISD::FLOG2, VT, Expand);
847     setOperationAction(ISD::FLOG10, VT, Expand);
848     setOperationAction(ISD::FEXP, VT, Expand);
849     setOperationAction(ISD::FEXP2, VT, Expand);
850     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855     setOperationAction(ISD::TRUNCATE, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859     setOperationAction(ISD::VSELECT, VT, Expand);
860     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862       setTruncStoreAction(VT,
863                           (MVT::SimpleValueType)InnerVT, Expand);
864     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
867   }
868
869   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870   // with -msoft-float, disable use of MMX as well.
871   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873     // No operations on x86mmx supported, everything uses intrinsics.
874   }
875
876   // MMX-sized vectors (other than x86mmx) are expected to be expanded
877   // into smaller operations.
878   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
879   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
880   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
882   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
883   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
884   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
885   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
886   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
887   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
888   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
889   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
890   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
891   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
892   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
893   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
894   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
898   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
899   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
900   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
903   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
907
908   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
910
911     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
912     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
916     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
917     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
918     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
919     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
920     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
921     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
923   }
924
925   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
927
928     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929     // registers cannot be used even for integer operations.
930     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
934
935     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
936     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
937     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
938     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
939     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
940     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
941     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
942     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
943     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
944     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
945     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
946     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
947     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
951     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
952     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
953
954     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
955     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
958
959     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
960     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
964
965     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967       MVT VT = (MVT::SimpleValueType)i;
968       // Do not attempt to custom lower non-power-of-2 vectors
969       if (!isPowerOf2_32(VT.getVectorNumElements()))
970         continue;
971       // Do not attempt to custom lower non-128-bit vectors
972       if (!VT.is128BitVector())
973         continue;
974       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
975       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
976       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
977     }
978
979     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
980     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
981     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
982     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
985
986     if (Subtarget->is64Bit()) {
987       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
988       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
989     }
990
991     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993       MVT VT = (MVT::SimpleValueType)i;
994
995       // Do not attempt to promote non-128-bit vectors
996       if (!VT.is128BitVector())
997         continue;
998
999       setOperationAction(ISD::AND,    VT, Promote);
1000       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1001       setOperationAction(ISD::OR,     VT, Promote);
1002       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1003       setOperationAction(ISD::XOR,    VT, Promote);
1004       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1005       setOperationAction(ISD::LOAD,   VT, Promote);
1006       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1007       setOperationAction(ISD::SELECT, VT, Promote);
1008       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1009     }
1010
1011     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1012
1013     // Custom lower v2i64 and v2f64 selects.
1014     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1015     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1016     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1017     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1018
1019     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1020     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1021
1022     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1023     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1024     // As there is no 64-bit GPR available, we need build a special custom
1025     // sequence to convert from v2i32 to v2f32.
1026     if (!Subtarget->is64Bit())
1027       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1028
1029     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1030     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1031
1032     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1033   }
1034
1035   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1037     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1038     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1041     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1042     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1043     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1046
1047     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1057
1058     // FIXME: Do we need to handle scalar-to-vector here?
1059     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1060
1061     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1062     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1063     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1066
1067     // i8 and i16 vectors are custom , because the source register and source
1068     // source memory operand types are not the same width.  f32 vectors are
1069     // custom since the immediate controlling the insert encodes additional
1070     // information.
1071     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1072     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1075
1076     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1080
1081     // FIXME: these should be Legal but thats only for the case where
1082     // the index is constant.  For now custom expand to deal with that.
1083     if (Subtarget->is64Bit()) {
1084       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1085       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1086     }
1087   }
1088
1089   if (Subtarget->hasSSE2()) {
1090     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1091     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1092
1093     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1098
1099     // In the customized shift lowering, the legal cases in AVX2 will be
1100     // recognized.
1101     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1102     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1103
1104     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1110     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1111   }
1112
1113   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1115     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1120
1121     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1122     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1123     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1124
1125     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1127     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1130     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1131     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1135     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1136     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1137
1138     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1139     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1140     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1143     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1144     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1148     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1149     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1150
1151     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152     // even though v8i16 is a legal type.
1153     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1154     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1156
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1160
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1163
1164     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1165
1166     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1167     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1168
1169     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1176
1177     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1181
1182     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1185
1186     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1190
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1203
1204     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1211     }
1212
1213     if (Subtarget->hasInt256()) {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1227       // Don't lower v32i8 because there is no 128-bit byte mul
1228
1229       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1232     } else {
1233       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1237
1238       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1246       // Don't lower v32i8 because there is no 128-bit byte mul
1247     }
1248
1249     // In the customized shift lowering, the legal cases in AVX2 will be
1250     // recognized.
1251     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1255     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1256
1257     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1258
1259     // Custom lower several nodes for 256-bit types.
1260     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262       MVT VT = (MVT::SimpleValueType)i;
1263
1264       // Extract subvector is special because the value type
1265       // (result) is 128-bit but the source is 256-bit wide.
1266       if (VT.is128BitVector())
1267         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1268
1269       // Do not attempt to custom lower other non-256-bit vectors
1270       if (!VT.is256BitVector())
1271         continue;
1272
1273       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1274       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1275       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1276       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1278       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1279       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1280     }
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1314     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1315     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1316     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1317     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1318     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1324
1325     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1330     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1331
1332     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1337     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1338     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1339     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1340     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1341
1342     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1343     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1344     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1346     if (Subtarget->is64Bit()) {
1347       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1348       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1349       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1350       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1351     }
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1360     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1361     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1362
1363     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1369     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1370     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1373     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1376
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1383
1384     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1385     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1386
1387     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1388
1389     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1390     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1392     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1393     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1394     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1395     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1396     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1397     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1398
1399     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1400     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1403     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1404
1405     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1406
1407     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1408     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1409
1410     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1414     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1415
1416     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1417     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1418     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1420     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1421     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1422
1423     // Custom lower several nodes.
1424     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426       MVT VT = (MVT::SimpleValueType)i;
1427
1428       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429       // Extract subvector is special because the value type
1430       // (result) is 256/128-bit but the source is 512-bit wide.
1431       if (VT.is128BitVector() || VT.is256BitVector())
1432         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1433
1434       if (VT.getVectorElementType() == MVT::i1)
1435         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1436
1437       // Do not attempt to custom lower other non-512-bit vectors
1438       if (!VT.is512BitVector())
1439         continue;
1440
1441       if ( EltSize >= 32) {
1442         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1443         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1444         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1445         setOperationAction(ISD::VSELECT,             VT, Legal);
1446         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1447         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1448         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1449       }
1450     }
1451     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452       MVT VT = (MVT::SimpleValueType)i;
1453
1454       // Do not attempt to promote non-256-bit vectors
1455       if (!VT.is512BitVector())
1456         continue;
1457
1458       setOperationAction(ISD::SELECT, VT, Promote);
1459       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1460     }
1461   }// has  AVX-512
1462
1463   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464   // of this type with custom code.
1465   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1468                        Custom);
1469   }
1470
1471   // We want to custom lower some of our intrinsics.
1472   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475   if (!Subtarget->is64Bit())
1476     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, 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     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548       report_fatal_error("failed to perform tail call elimination on a call "
2549                          "site marked musttail");
2550
2551     // Sibcalls are automatically detected tailcalls which do not require
2552     // ABI changes.
2553     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2554       IsSibcall = true;
2555
2556     if (isTailCall)
2557       ++NumTailCalls;
2558   }
2559
2560   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561          "Var args not supported with calling convention fastcc, ghc or hipe");
2562
2563   // Analyze operands of the call, assigning locations to each operand.
2564   SmallVector<CCValAssign, 16> ArgLocs;
2565   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566                  ArgLocs, *DAG.getContext());
2567
2568   // Allocate shadow area for Win64
2569   if (IsWin64)
2570     CCInfo.AllocateStack(32, 8);
2571
2572   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573
2574   // Get a count of how many bytes are to be pushed on the stack.
2575   unsigned NumBytes = CCInfo.getNextStackOffset();
2576   if (IsSibcall)
2577     // This is a sibcall. The memory operands are available in caller's
2578     // own caller's stack.
2579     NumBytes = 0;
2580   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581            IsTailCallConvention(CallConv))
2582     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2583
2584   int FPDiff = 0;
2585   if (isTailCall && !IsSibcall) {
2586     // Lower arguments at fp - stackoffset + fpdiff.
2587     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2589
2590     FPDiff = NumBytesCallerPushed - NumBytes;
2591
2592     // Set the delta of movement of the returnaddr stackslot.
2593     // But only set if delta is greater than previous delta.
2594     if (FPDiff < X86Info->getTCReturnAddrDelta())
2595       X86Info->setTCReturnAddrDelta(FPDiff);
2596   }
2597
2598   unsigned NumBytesToPush = NumBytes;
2599   unsigned NumBytesToPop = NumBytes;
2600
2601   // If we have an inalloca argument, all stack space has already been allocated
2602   // for us and be right at the top of the stack.  We don't support multiple
2603   // arguments passed in memory when using inalloca.
2604   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2605     NumBytesToPush = 0;
2606     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607            "an inalloca argument must be the only memory argument");
2608   }
2609
2610   if (!IsSibcall)
2611     Chain = DAG.getCALLSEQ_START(
2612         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2613
2614   SDValue RetAddrFrIdx;
2615   // Load return address for tail calls.
2616   if (isTailCall && FPDiff)
2617     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618                                     Is64Bit, FPDiff, dl);
2619
2620   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621   SmallVector<SDValue, 8> MemOpChains;
2622   SDValue StackPtr;
2623
2624   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2625   // of tail call optimization arguments are handle later.
2626   const X86RegisterInfo *RegInfo =
2627     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629     // Skip inalloca arguments, they have already been written.
2630     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631     if (Flags.isInAlloca())
2632       continue;
2633
2634     CCValAssign &VA = ArgLocs[i];
2635     EVT RegVT = VA.getLocVT();
2636     SDValue Arg = OutVals[i];
2637     bool isByVal = Flags.isByVal();
2638
2639     // Promote the value if needed.
2640     switch (VA.getLocInfo()) {
2641     default: llvm_unreachable("Unknown loc info!");
2642     case CCValAssign::Full: break;
2643     case CCValAssign::SExt:
2644       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2645       break;
2646     case CCValAssign::ZExt:
2647       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2648       break;
2649     case CCValAssign::AExt:
2650       if (RegVT.is128BitVector()) {
2651         // Special case: passing MMX values in XMM registers.
2652         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2655       } else
2656         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2657       break;
2658     case CCValAssign::BCvt:
2659       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::Indirect: {
2662       // Store the argument.
2663       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666                            MachinePointerInfo::getFixedStack(FI),
2667                            false, false, 0);
2668       Arg = SpillSlot;
2669       break;
2670     }
2671     }
2672
2673     if (VA.isRegLoc()) {
2674       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675       if (isVarArg && IsWin64) {
2676         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677         // shadow reg if callee is a varargs function.
2678         unsigned ShadowReg = 0;
2679         switch (VA.getLocReg()) {
2680         case X86::XMM0: ShadowReg = X86::RCX; break;
2681         case X86::XMM1: ShadowReg = X86::RDX; break;
2682         case X86::XMM2: ShadowReg = X86::R8; break;
2683         case X86::XMM3: ShadowReg = X86::R9; break;
2684         }
2685         if (ShadowReg)
2686           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2687       }
2688     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689       assert(VA.isMemLoc());
2690       if (StackPtr.getNode() == 0)
2691         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2692                                       getPointerTy());
2693       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694                                              dl, DAG, VA, Flags));
2695     }
2696   }
2697
2698   if (!MemOpChains.empty())
2699     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2700                         &MemOpChains[0], MemOpChains.size());
2701
2702   if (Subtarget->isPICStyleGOT()) {
2703     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2704     // GOT pointer.
2705     if (!isTailCall) {
2706       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2707                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2708     } else {
2709       // If we are tail calling and generating PIC/GOT style code load the
2710       // address of the callee into ECX. The value in ecx is used as target of
2711       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2712       // for tail calls on PIC/GOT architectures. Normally we would just put the
2713       // address of GOT into ebx and then call target@PLT. But for tail calls
2714       // ebx would be restored (since ebx is callee saved) before jumping to the
2715       // target@PLT.
2716
2717       // Note: The actual moving to ECX is done further down.
2718       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2719       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2720           !G->getGlobal()->hasProtectedVisibility())
2721         Callee = LowerGlobalAddress(Callee, DAG);
2722       else if (isa<ExternalSymbolSDNode>(Callee))
2723         Callee = LowerExternalSymbol(Callee, DAG);
2724     }
2725   }
2726
2727   if (Is64Bit && isVarArg && !IsWin64) {
2728     // From AMD64 ABI document:
2729     // For calls that may call functions that use varargs or stdargs
2730     // (prototype-less calls or calls to functions containing ellipsis (...) in
2731     // the declaration) %al is used as hidden argument to specify the number
2732     // of SSE registers used. The contents of %al do not need to match exactly
2733     // the number of registers, but must be an ubound on the number of SSE
2734     // registers used and is in the range 0 - 8 inclusive.
2735
2736     // Count the number of XMM registers allocated.
2737     static const MCPhysReg XMMArgRegs[] = {
2738       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2739       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2740     };
2741     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2742     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2743            && "SSE registers cannot be used when SSE is disabled");
2744
2745     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2746                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2747   }
2748
2749   // For tail calls lower the arguments to the 'real' stack slot.
2750   if (isTailCall) {
2751     // Force all the incoming stack arguments to be loaded from the stack
2752     // before any new outgoing arguments are stored to the stack, because the
2753     // outgoing stack slots may alias the incoming argument stack slots, and
2754     // the alias isn't otherwise explicit. This is slightly more conservative
2755     // than necessary, because it means that each store effectively depends
2756     // on every argument instead of just those arguments it would clobber.
2757     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2758
2759     SmallVector<SDValue, 8> MemOpChains2;
2760     SDValue FIN;
2761     int FI = 0;
2762     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2763       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2764         CCValAssign &VA = ArgLocs[i];
2765         if (VA.isRegLoc())
2766           continue;
2767         assert(VA.isMemLoc());
2768         SDValue Arg = OutVals[i];
2769         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2770         // Create frame index.
2771         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2772         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2773         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2774         FIN = DAG.getFrameIndex(FI, getPointerTy());
2775
2776         if (Flags.isByVal()) {
2777           // Copy relative to framepointer.
2778           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2779           if (StackPtr.getNode() == 0)
2780             StackPtr = DAG.getCopyFromReg(Chain, dl,
2781                                           RegInfo->getStackRegister(),
2782                                           getPointerTy());
2783           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2784
2785           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2786                                                            ArgChain,
2787                                                            Flags, DAG, dl));
2788         } else {
2789           // Store relative to framepointer.
2790           MemOpChains2.push_back(
2791             DAG.getStore(ArgChain, dl, Arg, FIN,
2792                          MachinePointerInfo::getFixedStack(FI),
2793                          false, false, 0));
2794         }
2795       }
2796     }
2797
2798     if (!MemOpChains2.empty())
2799       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2800                           &MemOpChains2[0], MemOpChains2.size());
2801
2802     // Store the return address to the appropriate stack slot.
2803     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2804                                      getPointerTy(), RegInfo->getSlotSize(),
2805                                      FPDiff, dl);
2806   }
2807
2808   // Build a sequence of copy-to-reg nodes chained together with token chain
2809   // and flag operands which copy the outgoing args into registers.
2810   SDValue InFlag;
2811   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2812     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2813                              RegsToPass[i].second, InFlag);
2814     InFlag = Chain.getValue(1);
2815   }
2816
2817   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2818     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2819     // In the 64-bit large code model, we have to make all calls
2820     // through a register, since the call instruction's 32-bit
2821     // pc-relative offset may not be large enough to hold the whole
2822     // address.
2823   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2824     // If the callee is a GlobalAddress node (quite common, every direct call
2825     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2826     // it.
2827
2828     // We should use extra load for direct calls to dllimported functions in
2829     // non-JIT mode.
2830     const GlobalValue *GV = G->getGlobal();
2831     if (!GV->hasDLLImportStorageClass()) {
2832       unsigned char OpFlags = 0;
2833       bool ExtraLoad = false;
2834       unsigned WrapperKind = ISD::DELETED_NODE;
2835
2836       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2837       // external symbols most go through the PLT in PIC mode.  If the symbol
2838       // has hidden or protected visibility, or if it is static or local, then
2839       // we don't need to use the PLT - we can directly call it.
2840       if (Subtarget->isTargetELF() &&
2841           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2842           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2843         OpFlags = X86II::MO_PLT;
2844       } else if (Subtarget->isPICStyleStubAny() &&
2845                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2846                  (!Subtarget->getTargetTriple().isMacOSX() ||
2847                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2848         // PC-relative references to external symbols should go through $stub,
2849         // unless we're building with the leopard linker or later, which
2850         // automatically synthesizes these stubs.
2851         OpFlags = X86II::MO_DARWIN_STUB;
2852       } else if (Subtarget->isPICStyleRIPRel() &&
2853                  isa<Function>(GV) &&
2854                  cast<Function>(GV)->getAttributes().
2855                    hasAttribute(AttributeSet::FunctionIndex,
2856                                 Attribute::NonLazyBind)) {
2857         // If the function is marked as non-lazy, generate an indirect call
2858         // which loads from the GOT directly. This avoids runtime overhead
2859         // at the cost of eager binding (and one extra byte of encoding).
2860         OpFlags = X86II::MO_GOTPCREL;
2861         WrapperKind = X86ISD::WrapperRIP;
2862         ExtraLoad = true;
2863       }
2864
2865       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2866                                           G->getOffset(), OpFlags);
2867
2868       // Add a wrapper if needed.
2869       if (WrapperKind != ISD::DELETED_NODE)
2870         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2871       // Add extra indirection if needed.
2872       if (ExtraLoad)
2873         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2874                              MachinePointerInfo::getGOT(),
2875                              false, false, false, 0);
2876     }
2877   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2878     unsigned char OpFlags = 0;
2879
2880     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2881     // external symbols should go through the PLT.
2882     if (Subtarget->isTargetELF() &&
2883         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2884       OpFlags = X86II::MO_PLT;
2885     } else if (Subtarget->isPICStyleStubAny() &&
2886                (!Subtarget->getTargetTriple().isMacOSX() ||
2887                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2888       // PC-relative references to external symbols should go through $stub,
2889       // unless we're building with the leopard linker or later, which
2890       // automatically synthesizes these stubs.
2891       OpFlags = X86II::MO_DARWIN_STUB;
2892     }
2893
2894     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2895                                          OpFlags);
2896   }
2897
2898   // Returns a chain & a flag for retval copy to use.
2899   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2900   SmallVector<SDValue, 8> Ops;
2901
2902   if (!IsSibcall && isTailCall) {
2903     Chain = DAG.getCALLSEQ_END(Chain,
2904                                DAG.getIntPtrConstant(NumBytesToPop, true),
2905                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2906     InFlag = Chain.getValue(1);
2907   }
2908
2909   Ops.push_back(Chain);
2910   Ops.push_back(Callee);
2911
2912   if (isTailCall)
2913     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2914
2915   // Add argument registers to the end of the list so that they are known live
2916   // into the call.
2917   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2918     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2919                                   RegsToPass[i].second.getValueType()));
2920
2921   // Add a register mask operand representing the call-preserved registers.
2922   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2923   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2924   assert(Mask && "Missing call preserved mask for calling convention");
2925   Ops.push_back(DAG.getRegisterMask(Mask));
2926
2927   if (InFlag.getNode())
2928     Ops.push_back(InFlag);
2929
2930   if (isTailCall) {
2931     // We used to do:
2932     //// If this is the first return lowered for this function, add the regs
2933     //// to the liveout set for the function.
2934     // This isn't right, although it's probably harmless on x86; liveouts
2935     // should be computed from returns not tail calls.  Consider a void
2936     // function making a tail call to a function returning int.
2937     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2938   }
2939
2940   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2941   InFlag = Chain.getValue(1);
2942
2943   // Create the CALLSEQ_END node.
2944   unsigned NumBytesForCalleeToPop;
2945   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2946                        getTargetMachine().Options.GuaranteedTailCallOpt))
2947     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2948   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2949            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950            SR == StackStructReturn)
2951     // If this is a call to a struct-return function, the callee
2952     // pops the hidden struct pointer, so we have to push it back.
2953     // This is common for Darwin/X86, Linux & Mingw32 targets.
2954     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2955     NumBytesForCalleeToPop = 4;
2956   else
2957     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2958
2959   // Returns a flag for retval copy to use.
2960   if (!IsSibcall) {
2961     Chain = DAG.getCALLSEQ_END(Chain,
2962                                DAG.getIntPtrConstant(NumBytesToPop, true),
2963                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2964                                                      true),
2965                                InFlag, dl);
2966     InFlag = Chain.getValue(1);
2967   }
2968
2969   // Handle result values, copying them out of physregs into vregs that we
2970   // return.
2971   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2972                          Ins, dl, DAG, InVals);
2973 }
2974
2975 //===----------------------------------------------------------------------===//
2976 //                Fast Calling Convention (tail call) implementation
2977 //===----------------------------------------------------------------------===//
2978
2979 //  Like std call, callee cleans arguments, convention except that ECX is
2980 //  reserved for storing the tail called function address. Only 2 registers are
2981 //  free for argument passing (inreg). Tail call optimization is performed
2982 //  provided:
2983 //                * tailcallopt is enabled
2984 //                * caller/callee are fastcc
2985 //  On X86_64 architecture with GOT-style position independent code only local
2986 //  (within module) calls are supported at the moment.
2987 //  To keep the stack aligned according to platform abi the function
2988 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2989 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2990 //  If a tail called function callee has more arguments than the caller the
2991 //  caller needs to make sure that there is room to move the RETADDR to. This is
2992 //  achieved by reserving an area the size of the argument delta right after the
2993 //  original REtADDR, but before the saved framepointer or the spilled registers
2994 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2995 //  stack layout:
2996 //    arg1
2997 //    arg2
2998 //    RETADDR
2999 //    [ new RETADDR
3000 //      move area ]
3001 //    (possible EBP)
3002 //    ESI
3003 //    EDI
3004 //    local1 ..
3005
3006 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3007 /// for a 16 byte align requirement.
3008 unsigned
3009 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3010                                                SelectionDAG& DAG) const {
3011   MachineFunction &MF = DAG.getMachineFunction();
3012   const TargetMachine &TM = MF.getTarget();
3013   const X86RegisterInfo *RegInfo =
3014     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3015   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3016   unsigned StackAlignment = TFI.getStackAlignment();
3017   uint64_t AlignMask = StackAlignment - 1;
3018   int64_t Offset = StackSize;
3019   unsigned SlotSize = RegInfo->getSlotSize();
3020   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3021     // Number smaller than 12 so just add the difference.
3022     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3023   } else {
3024     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3025     Offset = ((~AlignMask) & Offset) + StackAlignment +
3026       (StackAlignment-SlotSize);
3027   }
3028   return Offset;
3029 }
3030
3031 /// MatchingStackOffset - Return true if the given stack call argument is
3032 /// already available in the same position (relatively) of the caller's
3033 /// incoming argument stack.
3034 static
3035 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3036                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3037                          const X86InstrInfo *TII) {
3038   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3039   int FI = INT_MAX;
3040   if (Arg.getOpcode() == ISD::CopyFromReg) {
3041     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3042     if (!TargetRegisterInfo::isVirtualRegister(VR))
3043       return false;
3044     MachineInstr *Def = MRI->getVRegDef(VR);
3045     if (!Def)
3046       return false;
3047     if (!Flags.isByVal()) {
3048       if (!TII->isLoadFromStackSlot(Def, FI))
3049         return false;
3050     } else {
3051       unsigned Opcode = Def->getOpcode();
3052       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3053           Def->getOperand(1).isFI()) {
3054         FI = Def->getOperand(1).getIndex();
3055         Bytes = Flags.getByValSize();
3056       } else
3057         return false;
3058     }
3059   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3060     if (Flags.isByVal())
3061       // ByVal argument is passed in as a pointer but it's now being
3062       // dereferenced. e.g.
3063       // define @foo(%struct.X* %A) {
3064       //   tail call @bar(%struct.X* byval %A)
3065       // }
3066       return false;
3067     SDValue Ptr = Ld->getBasePtr();
3068     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3069     if (!FINode)
3070       return false;
3071     FI = FINode->getIndex();
3072   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3073     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3074     FI = FINode->getIndex();
3075     Bytes = Flags.getByValSize();
3076   } else
3077     return false;
3078
3079   assert(FI != INT_MAX);
3080   if (!MFI->isFixedObjectIndex(FI))
3081     return false;
3082   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3083 }
3084
3085 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3086 /// for tail call optimization. Targets which want to do tail call
3087 /// optimization should implement this function.
3088 bool
3089 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3090                                                      CallingConv::ID CalleeCC,
3091                                                      bool isVarArg,
3092                                                      bool isCalleeStructRet,
3093                                                      bool isCallerStructRet,
3094                                                      Type *RetTy,
3095                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3096                                     const SmallVectorImpl<SDValue> &OutVals,
3097                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3098                                                      SelectionDAG &DAG) const {
3099   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3100     return false;
3101
3102   // If -tailcallopt is specified, make fastcc functions tail-callable.
3103   const MachineFunction &MF = DAG.getMachineFunction();
3104   const Function *CallerF = MF.getFunction();
3105
3106   // If the function return type is x86_fp80 and the callee return type is not,
3107   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3108   // perform a tailcall optimization here.
3109   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3110     return false;
3111
3112   CallingConv::ID CallerCC = CallerF->getCallingConv();
3113   bool CCMatch = CallerCC == CalleeCC;
3114   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3115   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3116
3117   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3118     if (IsTailCallConvention(CalleeCC) && CCMatch)
3119       return true;
3120     return false;
3121   }
3122
3123   // Look for obvious safe cases to perform tail call optimization that do not
3124   // require ABI changes. This is what gcc calls sibcall.
3125
3126   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3127   // emit a special epilogue.
3128   const X86RegisterInfo *RegInfo =
3129     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3130   if (RegInfo->needsStackRealignment(MF))
3131     return false;
3132
3133   // Also avoid sibcall optimization if either caller or callee uses struct
3134   // return semantics.
3135   if (isCalleeStructRet || isCallerStructRet)
3136     return false;
3137
3138   // An stdcall/thiscall caller is expected to clean up its arguments; the
3139   // callee isn't going to do that.
3140   // FIXME: this is more restrictive than needed. We could produce a tailcall
3141   // when the stack adjustment matches. For example, with a thiscall that takes
3142   // only one argument.
3143   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3144                    CallerCC == CallingConv::X86_ThisCall))
3145     return false;
3146
3147   // Do not sibcall optimize vararg calls unless all arguments are passed via
3148   // registers.
3149   if (isVarArg && !Outs.empty()) {
3150
3151     // Optimizing for varargs on Win64 is unlikely to be safe without
3152     // additional testing.
3153     if (IsCalleeWin64 || IsCallerWin64)
3154       return false;
3155
3156     SmallVector<CCValAssign, 16> ArgLocs;
3157     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3158                    getTargetMachine(), ArgLocs, *DAG.getContext());
3159
3160     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3161     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3162       if (!ArgLocs[i].isRegLoc())
3163         return false;
3164   }
3165
3166   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3167   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3168   // this into a sibcall.
3169   bool Unused = false;
3170   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3171     if (!Ins[i].Used) {
3172       Unused = true;
3173       break;
3174     }
3175   }
3176   if (Unused) {
3177     SmallVector<CCValAssign, 16> RVLocs;
3178     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3179                    getTargetMachine(), RVLocs, *DAG.getContext());
3180     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3181     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3182       CCValAssign &VA = RVLocs[i];
3183       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3184         return false;
3185     }
3186   }
3187
3188   // If the calling conventions do not match, then we'd better make sure the
3189   // results are returned in the same way as what the caller expects.
3190   if (!CCMatch) {
3191     SmallVector<CCValAssign, 16> RVLocs1;
3192     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3193                     getTargetMachine(), RVLocs1, *DAG.getContext());
3194     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3195
3196     SmallVector<CCValAssign, 16> RVLocs2;
3197     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3198                     getTargetMachine(), RVLocs2, *DAG.getContext());
3199     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3200
3201     if (RVLocs1.size() != RVLocs2.size())
3202       return false;
3203     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3204       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3205         return false;
3206       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3207         return false;
3208       if (RVLocs1[i].isRegLoc()) {
3209         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3210           return false;
3211       } else {
3212         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3213           return false;
3214       }
3215     }
3216   }
3217
3218   // If the callee takes no arguments then go on to check the results of the
3219   // call.
3220   if (!Outs.empty()) {
3221     // Check if stack adjustment is needed. For now, do not do this if any
3222     // argument is passed on the stack.
3223     SmallVector<CCValAssign, 16> ArgLocs;
3224     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3225                    getTargetMachine(), ArgLocs, *DAG.getContext());
3226
3227     // Allocate shadow area for Win64
3228     if (IsCalleeWin64)
3229       CCInfo.AllocateStack(32, 8);
3230
3231     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3232     if (CCInfo.getNextStackOffset()) {
3233       MachineFunction &MF = DAG.getMachineFunction();
3234       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3235         return false;
3236
3237       // Check if the arguments are already laid out in the right way as
3238       // the caller's fixed stack objects.
3239       MachineFrameInfo *MFI = MF.getFrameInfo();
3240       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3241       const X86InstrInfo *TII =
3242         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3243       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3244         CCValAssign &VA = ArgLocs[i];
3245         SDValue Arg = OutVals[i];
3246         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3247         if (VA.getLocInfo() == CCValAssign::Indirect)
3248           return false;
3249         if (!VA.isRegLoc()) {
3250           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3251                                    MFI, MRI, TII))
3252             return false;
3253         }
3254       }
3255     }
3256
3257     // If the tailcall address may be in a register, then make sure it's
3258     // possible to register allocate for it. In 32-bit, the call address can
3259     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3260     // callee-saved registers are restored. These happen to be the same
3261     // registers used to pass 'inreg' arguments so watch out for those.
3262     if (!Subtarget->is64Bit() &&
3263         ((!isa<GlobalAddressSDNode>(Callee) &&
3264           !isa<ExternalSymbolSDNode>(Callee)) ||
3265          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3266       unsigned NumInRegs = 0;
3267       // In PIC we need an extra register to formulate the address computation
3268       // for the callee.
3269       unsigned MaxInRegs =
3270           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3271
3272       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3273         CCValAssign &VA = ArgLocs[i];
3274         if (!VA.isRegLoc())
3275           continue;
3276         unsigned Reg = VA.getLocReg();
3277         switch (Reg) {
3278         default: break;
3279         case X86::EAX: case X86::EDX: case X86::ECX:
3280           if (++NumInRegs == MaxInRegs)
3281             return false;
3282           break;
3283         }
3284       }
3285     }
3286   }
3287
3288   return true;
3289 }
3290
3291 FastISel *
3292 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3293                                   const TargetLibraryInfo *libInfo) const {
3294   return X86::createFastISel(funcInfo, libInfo);
3295 }
3296
3297 //===----------------------------------------------------------------------===//
3298 //                           Other Lowering Hooks
3299 //===----------------------------------------------------------------------===//
3300
3301 static bool MayFoldLoad(SDValue Op) {
3302   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3303 }
3304
3305 static bool MayFoldIntoStore(SDValue Op) {
3306   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3307 }
3308
3309 static bool isTargetShuffle(unsigned Opcode) {
3310   switch(Opcode) {
3311   default: return false;
3312   case X86ISD::PSHUFD:
3313   case X86ISD::PSHUFHW:
3314   case X86ISD::PSHUFLW:
3315   case X86ISD::SHUFP:
3316   case X86ISD::PALIGNR:
3317   case X86ISD::MOVLHPS:
3318   case X86ISD::MOVLHPD:
3319   case X86ISD::MOVHLPS:
3320   case X86ISD::MOVLPS:
3321   case X86ISD::MOVLPD:
3322   case X86ISD::MOVSHDUP:
3323   case X86ISD::MOVSLDUP:
3324   case X86ISD::MOVDDUP:
3325   case X86ISD::MOVSS:
3326   case X86ISD::MOVSD:
3327   case X86ISD::UNPCKL:
3328   case X86ISD::UNPCKH:
3329   case X86ISD::VPERMILP:
3330   case X86ISD::VPERM2X128:
3331   case X86ISD::VPERMI:
3332     return true;
3333   }
3334 }
3335
3336 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3337                                     SDValue V1, SelectionDAG &DAG) {
3338   switch(Opc) {
3339   default: llvm_unreachable("Unknown x86 shuffle node");
3340   case X86ISD::MOVSHDUP:
3341   case X86ISD::MOVSLDUP:
3342   case X86ISD::MOVDDUP:
3343     return DAG.getNode(Opc, dl, VT, V1);
3344   }
3345 }
3346
3347 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3348                                     SDValue V1, unsigned TargetMask,
3349                                     SelectionDAG &DAG) {
3350   switch(Opc) {
3351   default: llvm_unreachable("Unknown x86 shuffle node");
3352   case X86ISD::PSHUFD:
3353   case X86ISD::PSHUFHW:
3354   case X86ISD::PSHUFLW:
3355   case X86ISD::VPERMILP:
3356   case X86ISD::VPERMI:
3357     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3358   }
3359 }
3360
3361 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3362                                     SDValue V1, SDValue V2, unsigned TargetMask,
3363                                     SelectionDAG &DAG) {
3364   switch(Opc) {
3365   default: llvm_unreachable("Unknown x86 shuffle node");
3366   case X86ISD::PALIGNR:
3367   case X86ISD::SHUFP:
3368   case X86ISD::VPERM2X128:
3369     return DAG.getNode(Opc, dl, VT, V1, V2,
3370                        DAG.getConstant(TargetMask, MVT::i8));
3371   }
3372 }
3373
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3376   switch(Opc) {
3377   default: llvm_unreachable("Unknown x86 shuffle node");
3378   case X86ISD::MOVLHPS:
3379   case X86ISD::MOVLHPD:
3380   case X86ISD::MOVHLPS:
3381   case X86ISD::MOVLPS:
3382   case X86ISD::MOVLPD:
3383   case X86ISD::MOVSS:
3384   case X86ISD::MOVSD:
3385   case X86ISD::UNPCKL:
3386   case X86ISD::UNPCKH:
3387     return DAG.getNode(Opc, dl, VT, V1, V2);
3388   }
3389 }
3390
3391 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3392   MachineFunction &MF = DAG.getMachineFunction();
3393   const X86RegisterInfo *RegInfo =
3394     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3395   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3396   int ReturnAddrIndex = FuncInfo->getRAIndex();
3397
3398   if (ReturnAddrIndex == 0) {
3399     // Set up a frame object for the return address.
3400     unsigned SlotSize = RegInfo->getSlotSize();
3401     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3402                                                            -(int64_t)SlotSize,
3403                                                            false);
3404     FuncInfo->setRAIndex(ReturnAddrIndex);
3405   }
3406
3407   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3408 }
3409
3410 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3411                                        bool hasSymbolicDisplacement) {
3412   // Offset should fit into 32 bit immediate field.
3413   if (!isInt<32>(Offset))
3414     return false;
3415
3416   // If we don't have a symbolic displacement - we don't have any extra
3417   // restrictions.
3418   if (!hasSymbolicDisplacement)
3419     return true;
3420
3421   // FIXME: Some tweaks might be needed for medium code model.
3422   if (M != CodeModel::Small && M != CodeModel::Kernel)
3423     return false;
3424
3425   // For small code model we assume that latest object is 16MB before end of 31
3426   // bits boundary. We may also accept pretty large negative constants knowing
3427   // that all objects are in the positive half of address space.
3428   if (M == CodeModel::Small && Offset < 16*1024*1024)
3429     return true;
3430
3431   // For kernel code model we know that all object resist in the negative half
3432   // of 32bits address space. We may not accept negative offsets, since they may
3433   // be just off and we may accept pretty large positive ones.
3434   if (M == CodeModel::Kernel && Offset > 0)
3435     return true;
3436
3437   return false;
3438 }
3439
3440 /// isCalleePop - Determines whether the callee is required to pop its
3441 /// own arguments. Callee pop is necessary to support tail calls.
3442 bool X86::isCalleePop(CallingConv::ID CallingConv,
3443                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3444   if (IsVarArg)
3445     return false;
3446
3447   switch (CallingConv) {
3448   default:
3449     return false;
3450   case CallingConv::X86_StdCall:
3451     return !is64Bit;
3452   case CallingConv::X86_FastCall:
3453     return !is64Bit;
3454   case CallingConv::X86_ThisCall:
3455     return !is64Bit;
3456   case CallingConv::Fast:
3457     return TailCallOpt;
3458   case CallingConv::GHC:
3459     return TailCallOpt;
3460   case CallingConv::HiPE:
3461     return TailCallOpt;
3462   }
3463 }
3464
3465 /// \brief Return true if the condition is an unsigned comparison operation.
3466 static bool isX86CCUnsigned(unsigned X86CC) {
3467   switch (X86CC) {
3468   default: llvm_unreachable("Invalid integer condition!");
3469   case X86::COND_E:     return true;
3470   case X86::COND_G:     return false;
3471   case X86::COND_GE:    return false;
3472   case X86::COND_L:     return false;
3473   case X86::COND_LE:    return false;
3474   case X86::COND_NE:    return true;
3475   case X86::COND_B:     return true;
3476   case X86::COND_A:     return true;
3477   case X86::COND_BE:    return true;
3478   case X86::COND_AE:    return true;
3479   }
3480   llvm_unreachable("covered switch fell through?!");
3481 }
3482
3483 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3484 /// specific condition code, returning the condition code and the LHS/RHS of the
3485 /// comparison to make.
3486 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3487                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3488   if (!isFP) {
3489     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3490       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3491         // X > -1   -> X == 0, jump !sign.
3492         RHS = DAG.getConstant(0, RHS.getValueType());
3493         return X86::COND_NS;
3494       }
3495       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3496         // X < 0   -> X == 0, jump on sign.
3497         return X86::COND_S;
3498       }
3499       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3500         // X < 1   -> X <= 0
3501         RHS = DAG.getConstant(0, RHS.getValueType());
3502         return X86::COND_LE;
3503       }
3504     }
3505
3506     switch (SetCCOpcode) {
3507     default: llvm_unreachable("Invalid integer condition!");
3508     case ISD::SETEQ:  return X86::COND_E;
3509     case ISD::SETGT:  return X86::COND_G;
3510     case ISD::SETGE:  return X86::COND_GE;
3511     case ISD::SETLT:  return X86::COND_L;
3512     case ISD::SETLE:  return X86::COND_LE;
3513     case ISD::SETNE:  return X86::COND_NE;
3514     case ISD::SETULT: return X86::COND_B;
3515     case ISD::SETUGT: return X86::COND_A;
3516     case ISD::SETULE: return X86::COND_BE;
3517     case ISD::SETUGE: return X86::COND_AE;
3518     }
3519   }
3520
3521   // First determine if it is required or is profitable to flip the operands.
3522
3523   // If LHS is a foldable load, but RHS is not, flip the condition.
3524   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3525       !ISD::isNON_EXTLoad(RHS.getNode())) {
3526     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3527     std::swap(LHS, RHS);
3528   }
3529
3530   switch (SetCCOpcode) {
3531   default: break;
3532   case ISD::SETOLT:
3533   case ISD::SETOLE:
3534   case ISD::SETUGT:
3535   case ISD::SETUGE:
3536     std::swap(LHS, RHS);
3537     break;
3538   }
3539
3540   // On a floating point condition, the flags are set as follows:
3541   // ZF  PF  CF   op
3542   //  0 | 0 | 0 | X > Y
3543   //  0 | 0 | 1 | X < Y
3544   //  1 | 0 | 0 | X == Y
3545   //  1 | 1 | 1 | unordered
3546   switch (SetCCOpcode) {
3547   default: llvm_unreachable("Condcode should be pre-legalized away");
3548   case ISD::SETUEQ:
3549   case ISD::SETEQ:   return X86::COND_E;
3550   case ISD::SETOLT:              // flipped
3551   case ISD::SETOGT:
3552   case ISD::SETGT:   return X86::COND_A;
3553   case ISD::SETOLE:              // flipped
3554   case ISD::SETOGE:
3555   case ISD::SETGE:   return X86::COND_AE;
3556   case ISD::SETUGT:              // flipped
3557   case ISD::SETULT:
3558   case ISD::SETLT:   return X86::COND_B;
3559   case ISD::SETUGE:              // flipped
3560   case ISD::SETULE:
3561   case ISD::SETLE:   return X86::COND_BE;
3562   case ISD::SETONE:
3563   case ISD::SETNE:   return X86::COND_NE;
3564   case ISD::SETUO:   return X86::COND_P;
3565   case ISD::SETO:    return X86::COND_NP;
3566   case ISD::SETOEQ:
3567   case ISD::SETUNE:  return X86::COND_INVALID;
3568   }
3569 }
3570
3571 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3572 /// code. Current x86 isa includes the following FP cmov instructions:
3573 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3574 static bool hasFPCMov(unsigned X86CC) {
3575   switch (X86CC) {
3576   default:
3577     return false;
3578   case X86::COND_B:
3579   case X86::COND_BE:
3580   case X86::COND_E:
3581   case X86::COND_P:
3582   case X86::COND_A:
3583   case X86::COND_AE:
3584   case X86::COND_NE:
3585   case X86::COND_NP:
3586     return true;
3587   }
3588 }
3589
3590 /// isFPImmLegal - Returns true if the target can instruction select the
3591 /// specified FP immediate natively. If false, the legalizer will
3592 /// materialize the FP immediate as a load from a constant pool.
3593 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3594   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3595     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3596       return true;
3597   }
3598   return false;
3599 }
3600
3601 /// \brief Returns true if it is beneficial to convert a load of a constant
3602 /// to just the constant itself.
3603 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3604                                                           Type *Ty) const {
3605   assert(Ty->isIntegerTy());
3606
3607   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3608   if (BitSize == 0 || BitSize > 64)
3609     return false;
3610   return true;
3611 }
3612
3613 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3614 /// the specified range (L, H].
3615 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3616   return (Val < 0) || (Val >= Low && Val < Hi);
3617 }
3618
3619 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3620 /// specified value.
3621 static bool isUndefOrEqual(int Val, int CmpVal) {
3622   return (Val < 0 || Val == CmpVal);
3623 }
3624
3625 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3626 /// from position Pos and ending in Pos+Size, falls within the specified
3627 /// sequential range (L, L+Pos]. or is undef.
3628 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3629                                        unsigned Pos, unsigned Size, int Low) {
3630   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3631     if (!isUndefOrEqual(Mask[i], Low))
3632       return false;
3633   return true;
3634 }
3635
3636 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3637 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3638 /// the second operand.
3639 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3640   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3641     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3642   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3643     return (Mask[0] < 2 && Mask[1] < 2);
3644   return false;
3645 }
3646
3647 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3648 /// is suitable for input to PSHUFHW.
3649 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3650   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3651     return false;
3652
3653   // Lower quadword copied in order or undef.
3654   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3655     return false;
3656
3657   // Upper quadword shuffled.
3658   for (unsigned i = 4; i != 8; ++i)
3659     if (!isUndefOrInRange(Mask[i], 4, 8))
3660       return false;
3661
3662   if (VT == MVT::v16i16) {
3663     // Lower quadword copied in order or undef.
3664     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3665       return false;
3666
3667     // Upper quadword shuffled.
3668     for (unsigned i = 12; i != 16; ++i)
3669       if (!isUndefOrInRange(Mask[i], 12, 16))
3670         return false;
3671   }
3672
3673   return true;
3674 }
3675
3676 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3677 /// is suitable for input to PSHUFLW.
3678 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3679   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3680     return false;
3681
3682   // Upper quadword copied in order.
3683   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3684     return false;
3685
3686   // Lower quadword shuffled.
3687   for (unsigned i = 0; i != 4; ++i)
3688     if (!isUndefOrInRange(Mask[i], 0, 4))
3689       return false;
3690
3691   if (VT == MVT::v16i16) {
3692     // Upper quadword copied in order.
3693     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3694       return false;
3695
3696     // Lower quadword shuffled.
3697     for (unsigned i = 8; i != 12; ++i)
3698       if (!isUndefOrInRange(Mask[i], 8, 12))
3699         return false;
3700   }
3701
3702   return true;
3703 }
3704
3705 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PALIGNR.
3707 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3708                           const X86Subtarget *Subtarget) {
3709   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3710       (VT.is256BitVector() && !Subtarget->hasInt256()))
3711     return false;
3712
3713   unsigned NumElts = VT.getVectorNumElements();
3714   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3715   unsigned NumLaneElts = NumElts/NumLanes;
3716
3717   // Do not handle 64-bit element shuffles with palignr.
3718   if (NumLaneElts == 2)
3719     return false;
3720
3721   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3722     unsigned i;
3723     for (i = 0; i != NumLaneElts; ++i) {
3724       if (Mask[i+l] >= 0)
3725         break;
3726     }
3727
3728     // Lane is all undef, go to next lane
3729     if (i == NumLaneElts)
3730       continue;
3731
3732     int Start = Mask[i+l];
3733
3734     // Make sure its in this lane in one of the sources
3735     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3736         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3737       return false;
3738
3739     // If not lane 0, then we must match lane 0
3740     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3741       return false;
3742
3743     // Correct second source to be contiguous with first source
3744     if (Start >= (int)NumElts)
3745       Start -= NumElts - NumLaneElts;
3746
3747     // Make sure we're shifting in the right direction.
3748     if (Start <= (int)(i+l))
3749       return false;
3750
3751     Start -= i;
3752
3753     // Check the rest of the elements to see if they are consecutive.
3754     for (++i; i != NumLaneElts; ++i) {
3755       int Idx = Mask[i+l];
3756
3757       // Make sure its in this lane
3758       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3759           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3760         return false;
3761
3762       // If not lane 0, then we must match lane 0
3763       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3764         return false;
3765
3766       if (Idx >= (int)NumElts)
3767         Idx -= NumElts - NumLaneElts;
3768
3769       if (!isUndefOrEqual(Idx, Start+i))
3770         return false;
3771
3772     }
3773   }
3774
3775   return true;
3776 }
3777
3778 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3779 /// the two vector operands have swapped position.
3780 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3781                                      unsigned NumElems) {
3782   for (unsigned i = 0; i != NumElems; ++i) {
3783     int idx = Mask[i];
3784     if (idx < 0)
3785       continue;
3786     else if (idx < (int)NumElems)
3787       Mask[i] = idx + NumElems;
3788     else
3789       Mask[i] = idx - NumElems;
3790   }
3791 }
3792
3793 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3794 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3795 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3796 /// reverse of what x86 shuffles want.
3797 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3798
3799   unsigned NumElems = VT.getVectorNumElements();
3800   unsigned NumLanes = VT.getSizeInBits()/128;
3801   unsigned NumLaneElems = NumElems/NumLanes;
3802
3803   if (NumLaneElems != 2 && NumLaneElems != 4)
3804     return false;
3805
3806   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3807   bool symetricMaskRequired =
3808     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3809
3810   // VSHUFPSY divides the resulting vector into 4 chunks.
3811   // The sources are also splitted into 4 chunks, and each destination
3812   // chunk must come from a different source chunk.
3813   //
3814   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3815   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3816   //
3817   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3818   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3819   //
3820   // VSHUFPDY divides the resulting vector into 4 chunks.
3821   // The sources are also splitted into 4 chunks, and each destination
3822   // chunk must come from a different source chunk.
3823   //
3824   //  SRC1 =>      X3       X2       X1       X0
3825   //  SRC2 =>      Y3       Y2       Y1       Y0
3826   //
3827   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3828   //
3829   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3830   unsigned HalfLaneElems = NumLaneElems/2;
3831   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3832     for (unsigned i = 0; i != NumLaneElems; ++i) {
3833       int Idx = Mask[i+l];
3834       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3835       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3836         return false;
3837       // For VSHUFPSY, the mask of the second half must be the same as the
3838       // first but with the appropriate offsets. This works in the same way as
3839       // VPERMILPS works with masks.
3840       if (!symetricMaskRequired || Idx < 0)
3841         continue;
3842       if (MaskVal[i] < 0) {
3843         MaskVal[i] = Idx - l;
3844         continue;
3845       }
3846       if ((signed)(Idx - l) != MaskVal[i])
3847         return false;
3848     }
3849   }
3850
3851   return true;
3852 }
3853
3854 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3856 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3857   if (!VT.is128BitVector())
3858     return false;
3859
3860   unsigned NumElems = VT.getVectorNumElements();
3861
3862   if (NumElems != 4)
3863     return false;
3864
3865   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3866   return isUndefOrEqual(Mask[0], 6) &&
3867          isUndefOrEqual(Mask[1], 7) &&
3868          isUndefOrEqual(Mask[2], 2) &&
3869          isUndefOrEqual(Mask[3], 3);
3870 }
3871
3872 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3873 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3874 /// <2, 3, 2, 3>
3875 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3876   if (!VT.is128BitVector())
3877     return false;
3878
3879   unsigned NumElems = VT.getVectorNumElements();
3880
3881   if (NumElems != 4)
3882     return false;
3883
3884   return isUndefOrEqual(Mask[0], 2) &&
3885          isUndefOrEqual(Mask[1], 3) &&
3886          isUndefOrEqual(Mask[2], 2) &&
3887          isUndefOrEqual(Mask[3], 3);
3888 }
3889
3890 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3891 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3892 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3893   if (!VT.is128BitVector())
3894     return false;
3895
3896   unsigned NumElems = VT.getVectorNumElements();
3897
3898   if (NumElems != 2 && NumElems != 4)
3899     return false;
3900
3901   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3902     if (!isUndefOrEqual(Mask[i], i + NumElems))
3903       return false;
3904
3905   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3906     if (!isUndefOrEqual(Mask[i], i))
3907       return false;
3908
3909   return true;
3910 }
3911
3912 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3914 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3915   if (!VT.is128BitVector())
3916     return false;
3917
3918   unsigned NumElems = VT.getVectorNumElements();
3919
3920   if (NumElems != 2 && NumElems != 4)
3921     return false;
3922
3923   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924     if (!isUndefOrEqual(Mask[i], i))
3925       return false;
3926
3927   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3929       return false;
3930
3931   return true;
3932 }
3933
3934 //
3935 // Some special combinations that can be optimized.
3936 //
3937 static
3938 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3939                                SelectionDAG &DAG) {
3940   MVT VT = SVOp->getSimpleValueType(0);
3941   SDLoc dl(SVOp);
3942
3943   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3944     return SDValue();
3945
3946   ArrayRef<int> Mask = SVOp->getMask();
3947
3948   // These are the special masks that may be optimized.
3949   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3950   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3951   bool MatchEvenMask = true;
3952   bool MatchOddMask  = true;
3953   for (int i=0; i<8; ++i) {
3954     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3955       MatchEvenMask = false;
3956     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3957       MatchOddMask = false;
3958   }
3959
3960   if (!MatchEvenMask && !MatchOddMask)
3961     return SDValue();
3962
3963   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3964
3965   SDValue Op0 = SVOp->getOperand(0);
3966   SDValue Op1 = SVOp->getOperand(1);
3967
3968   if (MatchEvenMask) {
3969     // Shift the second operand right to 32 bits.
3970     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3971     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3972   } else {
3973     // Shift the first operand left to 32 bits.
3974     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3975     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3976   }
3977   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3978   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3979 }
3980
3981 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3983 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3984                          bool HasInt256, bool V2IsSplat = false) {
3985
3986   assert(VT.getSizeInBits() >= 128 &&
3987          "Unsupported vector type for unpckl");
3988
3989   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3990   unsigned NumLanes;
3991   unsigned NumOf256BitLanes;
3992   unsigned NumElts = VT.getVectorNumElements();
3993   if (VT.is256BitVector()) {
3994     if (NumElts != 4 && NumElts != 8 &&
3995         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3996     return false;
3997     NumLanes = 2;
3998     NumOf256BitLanes = 1;
3999   } else if (VT.is512BitVector()) {
4000     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4001            "Unsupported vector type for unpckh");
4002     NumLanes = 2;
4003     NumOf256BitLanes = 2;
4004   } else {
4005     NumLanes = 1;
4006     NumOf256BitLanes = 1;
4007   }
4008
4009   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4010   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4011
4012   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4013     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4014       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4015         int BitI  = Mask[l256*NumEltsInStride+l+i];
4016         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4017         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4018           return false;
4019         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4020           return false;
4021         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4022           return false;
4023       }
4024     }
4025   }
4026   return true;
4027 }
4028
4029 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4030 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4031 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4032                          bool HasInt256, bool V2IsSplat = false) {
4033   assert(VT.getSizeInBits() >= 128 &&
4034          "Unsupported vector type for unpckh");
4035
4036   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4037   unsigned NumLanes;
4038   unsigned NumOf256BitLanes;
4039   unsigned NumElts = VT.getVectorNumElements();
4040   if (VT.is256BitVector()) {
4041     if (NumElts != 4 && NumElts != 8 &&
4042         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4043     return false;
4044     NumLanes = 2;
4045     NumOf256BitLanes = 1;
4046   } else if (VT.is512BitVector()) {
4047     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4048            "Unsupported vector type for unpckh");
4049     NumLanes = 2;
4050     NumOf256BitLanes = 2;
4051   } else {
4052     NumLanes = 1;
4053     NumOf256BitLanes = 1;
4054   }
4055
4056   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4057   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4058
4059   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4060     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4061       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4062         int BitI  = Mask[l256*NumEltsInStride+l+i];
4063         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4064         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4065           return false;
4066         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4067           return false;
4068         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4069           return false;
4070       }
4071     }
4072   }
4073   return true;
4074 }
4075
4076 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4077 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4078 /// <0, 0, 1, 1>
4079 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4080   unsigned NumElts = VT.getVectorNumElements();
4081   bool Is256BitVec = VT.is256BitVector();
4082
4083   if (VT.is512BitVector())
4084     return false;
4085   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4086          "Unsupported vector type for unpckh");
4087
4088   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4089       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4090     return false;
4091
4092   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4093   // FIXME: Need a better way to get rid of this, there's no latency difference
4094   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4095   // the former later. We should also remove the "_undef" special mask.
4096   if (NumElts == 4 && Is256BitVec)
4097     return false;
4098
4099   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4100   // independently on 128-bit lanes.
4101   unsigned NumLanes = VT.getSizeInBits()/128;
4102   unsigned NumLaneElts = NumElts/NumLanes;
4103
4104   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4105     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4106       int BitI  = Mask[l+i];
4107       int BitI1 = Mask[l+i+1];
4108
4109       if (!isUndefOrEqual(BitI, j))
4110         return false;
4111       if (!isUndefOrEqual(BitI1, j))
4112         return false;
4113     }
4114   }
4115
4116   return true;
4117 }
4118
4119 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4120 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4121 /// <2, 2, 3, 3>
4122 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4123   unsigned NumElts = VT.getVectorNumElements();
4124
4125   if (VT.is512BitVector())
4126     return false;
4127
4128   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4129          "Unsupported vector type for unpckh");
4130
4131   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4132       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4133     return false;
4134
4135   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4136   // independently on 128-bit lanes.
4137   unsigned NumLanes = VT.getSizeInBits()/128;
4138   unsigned NumLaneElts = NumElts/NumLanes;
4139
4140   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4141     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4142       int BitI  = Mask[l+i];
4143       int BitI1 = Mask[l+i+1];
4144       if (!isUndefOrEqual(BitI, j))
4145         return false;
4146       if (!isUndefOrEqual(BitI1, j))
4147         return false;
4148     }
4149   }
4150   return true;
4151 }
4152
4153 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4154 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4155 /// MOVSD, and MOVD, i.e. setting the lowest element.
4156 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4157   if (VT.getVectorElementType().getSizeInBits() < 32)
4158     return false;
4159   if (!VT.is128BitVector())
4160     return false;
4161
4162   unsigned NumElts = VT.getVectorNumElements();
4163
4164   if (!isUndefOrEqual(Mask[0], NumElts))
4165     return false;
4166
4167   for (unsigned i = 1; i != NumElts; ++i)
4168     if (!isUndefOrEqual(Mask[i], i))
4169       return false;
4170
4171   return true;
4172 }
4173
4174 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4175 /// as permutations between 128-bit chunks or halves. As an example: this
4176 /// shuffle bellow:
4177 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4178 /// The first half comes from the second half of V1 and the second half from the
4179 /// the second half of V2.
4180 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4181   if (!HasFp256 || !VT.is256BitVector())
4182     return false;
4183
4184   // The shuffle result is divided into half A and half B. In total the two
4185   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4186   // B must come from C, D, E or F.
4187   unsigned HalfSize = VT.getVectorNumElements()/2;
4188   bool MatchA = false, MatchB = false;
4189
4190   // Check if A comes from one of C, D, E, F.
4191   for (unsigned Half = 0; Half != 4; ++Half) {
4192     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4193       MatchA = true;
4194       break;
4195     }
4196   }
4197
4198   // Check if B comes from one of C, D, E, F.
4199   for (unsigned Half = 0; Half != 4; ++Half) {
4200     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4201       MatchB = true;
4202       break;
4203     }
4204   }
4205
4206   return MatchA && MatchB;
4207 }
4208
4209 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4210 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4211 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4212   MVT VT = SVOp->getSimpleValueType(0);
4213
4214   unsigned HalfSize = VT.getVectorNumElements()/2;
4215
4216   unsigned FstHalf = 0, SndHalf = 0;
4217   for (unsigned i = 0; i < HalfSize; ++i) {
4218     if (SVOp->getMaskElt(i) > 0) {
4219       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4220       break;
4221     }
4222   }
4223   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4224     if (SVOp->getMaskElt(i) > 0) {
4225       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4226       break;
4227     }
4228   }
4229
4230   return (FstHalf | (SndHalf << 4));
4231 }
4232
4233 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4234 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4235   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4236   if (EltSize < 32)
4237     return false;
4238
4239   unsigned NumElts = VT.getVectorNumElements();
4240   Imm8 = 0;
4241   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4242     for (unsigned i = 0; i != NumElts; ++i) {
4243       if (Mask[i] < 0)
4244         continue;
4245       Imm8 |= Mask[i] << (i*2);
4246     }
4247     return true;
4248   }
4249
4250   unsigned LaneSize = 4;
4251   SmallVector<int, 4> MaskVal(LaneSize, -1);
4252
4253   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4254     for (unsigned i = 0; i != LaneSize; ++i) {
4255       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4256         return false;
4257       if (Mask[i+l] < 0)
4258         continue;
4259       if (MaskVal[i] < 0) {
4260         MaskVal[i] = Mask[i+l] - l;
4261         Imm8 |= MaskVal[i] << (i*2);
4262         continue;
4263       }
4264       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4265         return false;
4266     }
4267   }
4268   return true;
4269 }
4270
4271 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4272 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4273 /// Note that VPERMIL mask matching is different depending whether theunderlying
4274 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4275 /// to the same elements of the low, but to the higher half of the source.
4276 /// In VPERMILPD the two lanes could be shuffled independently of each other
4277 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4278 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4279   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4280   if (VT.getSizeInBits() < 256 || EltSize < 32)
4281     return false;
4282   bool symetricMaskRequired = (EltSize == 32);
4283   unsigned NumElts = VT.getVectorNumElements();
4284
4285   unsigned NumLanes = VT.getSizeInBits()/128;
4286   unsigned LaneSize = NumElts/NumLanes;
4287   // 2 or 4 elements in one lane
4288
4289   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4290   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4291     for (unsigned i = 0; i != LaneSize; ++i) {
4292       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4293         return false;
4294       if (symetricMaskRequired) {
4295         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4296           ExpectedMaskVal[i] = Mask[i+l] - l;
4297           continue;
4298         }
4299         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4300           return false;
4301       }
4302     }
4303   }
4304   return true;
4305 }
4306
4307 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4308 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4309 /// element of vector 2 and the other elements to come from vector 1 in order.
4310 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4311                                bool V2IsSplat = false, bool V2IsUndef = false) {
4312   if (!VT.is128BitVector())
4313     return false;
4314
4315   unsigned NumOps = VT.getVectorNumElements();
4316   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4317     return false;
4318
4319   if (!isUndefOrEqual(Mask[0], 0))
4320     return false;
4321
4322   for (unsigned i = 1; i != NumOps; ++i)
4323     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4324           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4325           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4326       return false;
4327
4328   return true;
4329 }
4330
4331 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4332 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4333 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4334 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4335                            const X86Subtarget *Subtarget) {
4336   if (!Subtarget->hasSSE3())
4337     return false;
4338
4339   unsigned NumElems = VT.getVectorNumElements();
4340
4341   if ((VT.is128BitVector() && NumElems != 4) ||
4342       (VT.is256BitVector() && NumElems != 8) ||
4343       (VT.is512BitVector() && NumElems != 16))
4344     return false;
4345
4346   // "i+1" is the value the indexed mask element must have
4347   for (unsigned i = 0; i != NumElems; i += 2)
4348     if (!isUndefOrEqual(Mask[i], i+1) ||
4349         !isUndefOrEqual(Mask[i+1], i+1))
4350       return false;
4351
4352   return true;
4353 }
4354
4355 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4356 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4357 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4358 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4359                            const X86Subtarget *Subtarget) {
4360   if (!Subtarget->hasSSE3())
4361     return false;
4362
4363   unsigned NumElems = VT.getVectorNumElements();
4364
4365   if ((VT.is128BitVector() && NumElems != 4) ||
4366       (VT.is256BitVector() && NumElems != 8) ||
4367       (VT.is512BitVector() && NumElems != 16))
4368     return false;
4369
4370   // "i" is the value the indexed mask element must have
4371   for (unsigned i = 0; i != NumElems; i += 2)
4372     if (!isUndefOrEqual(Mask[i], i) ||
4373         !isUndefOrEqual(Mask[i+1], i))
4374       return false;
4375
4376   return true;
4377 }
4378
4379 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4380 /// specifies a shuffle of elements that is suitable for input to 256-bit
4381 /// version of MOVDDUP.
4382 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4383   if (!HasFp256 || !VT.is256BitVector())
4384     return false;
4385
4386   unsigned NumElts = VT.getVectorNumElements();
4387   if (NumElts != 4)
4388     return false;
4389
4390   for (unsigned i = 0; i != NumElts/2; ++i)
4391     if (!isUndefOrEqual(Mask[i], 0))
4392       return false;
4393   for (unsigned i = NumElts/2; i != NumElts; ++i)
4394     if (!isUndefOrEqual(Mask[i], NumElts/2))
4395       return false;
4396   return true;
4397 }
4398
4399 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4400 /// specifies a shuffle of elements that is suitable for input to 128-bit
4401 /// version of MOVDDUP.
4402 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4403   if (!VT.is128BitVector())
4404     return false;
4405
4406   unsigned e = VT.getVectorNumElements() / 2;
4407   for (unsigned i = 0; i != e; ++i)
4408     if (!isUndefOrEqual(Mask[i], i))
4409       return false;
4410   for (unsigned i = 0; i != e; ++i)
4411     if (!isUndefOrEqual(Mask[e+i], i))
4412       return false;
4413   return true;
4414 }
4415
4416 /// isVEXTRACTIndex - Return true if the specified
4417 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4418 /// suitable for instruction that extract 128 or 256 bit vectors
4419 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4420   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4421   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4422     return false;
4423
4424   // The index should be aligned on a vecWidth-bit boundary.
4425   uint64_t Index =
4426     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4427
4428   MVT VT = N->getSimpleValueType(0);
4429   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4430   bool Result = (Index * ElSize) % vecWidth == 0;
4431
4432   return Result;
4433 }
4434
4435 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4436 /// operand specifies a subvector insert that is suitable for input to
4437 /// insertion of 128 or 256-bit subvectors
4438 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4439   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4440   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4441     return false;
4442   // The index should be aligned on a vecWidth-bit boundary.
4443   uint64_t Index =
4444     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4445
4446   MVT VT = N->getSimpleValueType(0);
4447   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4448   bool Result = (Index * ElSize) % vecWidth == 0;
4449
4450   return Result;
4451 }
4452
4453 bool X86::isVINSERT128Index(SDNode *N) {
4454   return isVINSERTIndex(N, 128);
4455 }
4456
4457 bool X86::isVINSERT256Index(SDNode *N) {
4458   return isVINSERTIndex(N, 256);
4459 }
4460
4461 bool X86::isVEXTRACT128Index(SDNode *N) {
4462   return isVEXTRACTIndex(N, 128);
4463 }
4464
4465 bool X86::isVEXTRACT256Index(SDNode *N) {
4466   return isVEXTRACTIndex(N, 256);
4467 }
4468
4469 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4470 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4471 /// Handles 128-bit and 256-bit.
4472 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4473   MVT VT = N->getSimpleValueType(0);
4474
4475   assert((VT.getSizeInBits() >= 128) &&
4476          "Unsupported vector type for PSHUF/SHUFP");
4477
4478   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4479   // independently on 128-bit lanes.
4480   unsigned NumElts = VT.getVectorNumElements();
4481   unsigned NumLanes = VT.getSizeInBits()/128;
4482   unsigned NumLaneElts = NumElts/NumLanes;
4483
4484   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4485          "Only supports 2, 4 or 8 elements per lane");
4486
4487   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4488   unsigned Mask = 0;
4489   for (unsigned i = 0; i != NumElts; ++i) {
4490     int Elt = N->getMaskElt(i);
4491     if (Elt < 0) continue;
4492     Elt &= NumLaneElts - 1;
4493     unsigned ShAmt = (i << Shift) % 8;
4494     Mask |= Elt << ShAmt;
4495   }
4496
4497   return Mask;
4498 }
4499
4500 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4501 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4502 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4503   MVT VT = N->getSimpleValueType(0);
4504
4505   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4506          "Unsupported vector type for PSHUFHW");
4507
4508   unsigned NumElts = VT.getVectorNumElements();
4509
4510   unsigned Mask = 0;
4511   for (unsigned l = 0; l != NumElts; l += 8) {
4512     // 8 nodes per lane, but we only care about the last 4.
4513     for (unsigned i = 0; i < 4; ++i) {
4514       int Elt = N->getMaskElt(l+i+4);
4515       if (Elt < 0) continue;
4516       Elt &= 0x3; // only 2-bits.
4517       Mask |= Elt << (i * 2);
4518     }
4519   }
4520
4521   return Mask;
4522 }
4523
4524 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4525 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4526 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4527   MVT VT = N->getSimpleValueType(0);
4528
4529   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4530          "Unsupported vector type for PSHUFHW");
4531
4532   unsigned NumElts = VT.getVectorNumElements();
4533
4534   unsigned Mask = 0;
4535   for (unsigned l = 0; l != NumElts; l += 8) {
4536     // 8 nodes per lane, but we only care about the first 4.
4537     for (unsigned i = 0; i < 4; ++i) {
4538       int Elt = N->getMaskElt(l+i);
4539       if (Elt < 0) continue;
4540       Elt &= 0x3; // only 2-bits
4541       Mask |= Elt << (i * 2);
4542     }
4543   }
4544
4545   return Mask;
4546 }
4547
4548 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4549 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4550 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4551   MVT VT = SVOp->getSimpleValueType(0);
4552   unsigned EltSize = VT.is512BitVector() ? 1 :
4553     VT.getVectorElementType().getSizeInBits() >> 3;
4554
4555   unsigned NumElts = VT.getVectorNumElements();
4556   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4557   unsigned NumLaneElts = NumElts/NumLanes;
4558
4559   int Val = 0;
4560   unsigned i;
4561   for (i = 0; i != NumElts; ++i) {
4562     Val = SVOp->getMaskElt(i);
4563     if (Val >= 0)
4564       break;
4565   }
4566   if (Val >= (int)NumElts)
4567     Val -= NumElts - NumLaneElts;
4568
4569   assert(Val - i > 0 && "PALIGNR imm should be positive");
4570   return (Val - i) * EltSize;
4571 }
4572
4573 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4574   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4575   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4576     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4577
4578   uint64_t Index =
4579     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4580
4581   MVT VecVT = N->getOperand(0).getSimpleValueType();
4582   MVT ElVT = VecVT.getVectorElementType();
4583
4584   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4585   return Index / NumElemsPerChunk;
4586 }
4587
4588 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4589   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4590   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4591     llvm_unreachable("Illegal insert subvector for VINSERT");
4592
4593   uint64_t Index =
4594     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4595
4596   MVT VecVT = N->getSimpleValueType(0);
4597   MVT ElVT = VecVT.getVectorElementType();
4598
4599   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4600   return Index / NumElemsPerChunk;
4601 }
4602
4603 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4604 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4605 /// and VINSERTI128 instructions.
4606 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4607   return getExtractVEXTRACTImmediate(N, 128);
4608 }
4609
4610 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4611 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4612 /// and VINSERTI64x4 instructions.
4613 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4614   return getExtractVEXTRACTImmediate(N, 256);
4615 }
4616
4617 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4618 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4619 /// and VINSERTI128 instructions.
4620 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4621   return getInsertVINSERTImmediate(N, 128);
4622 }
4623
4624 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4625 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4626 /// and VINSERTI64x4 instructions.
4627 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4628   return getInsertVINSERTImmediate(N, 256);
4629 }
4630
4631 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4632 /// constant +0.0.
4633 bool X86::isZeroNode(SDValue Elt) {
4634   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4635     return CN->isNullValue();
4636   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4637     return CFP->getValueAPF().isPosZero();
4638   return false;
4639 }
4640
4641 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4642 /// their permute mask.
4643 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4644                                     SelectionDAG &DAG) {
4645   MVT VT = SVOp->getSimpleValueType(0);
4646   unsigned NumElems = VT.getVectorNumElements();
4647   SmallVector<int, 8> MaskVec;
4648
4649   for (unsigned i = 0; i != NumElems; ++i) {
4650     int Idx = SVOp->getMaskElt(i);
4651     if (Idx >= 0) {
4652       if (Idx < (int)NumElems)
4653         Idx += NumElems;
4654       else
4655         Idx -= NumElems;
4656     }
4657     MaskVec.push_back(Idx);
4658   }
4659   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4660                               SVOp->getOperand(0), &MaskVec[0]);
4661 }
4662
4663 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4664 /// match movhlps. The lower half elements should come from upper half of
4665 /// V1 (and in order), and the upper half elements should come from the upper
4666 /// half of V2 (and in order).
4667 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4668   if (!VT.is128BitVector())
4669     return false;
4670   if (VT.getVectorNumElements() != 4)
4671     return false;
4672   for (unsigned i = 0, e = 2; i != e; ++i)
4673     if (!isUndefOrEqual(Mask[i], i+2))
4674       return false;
4675   for (unsigned i = 2; i != 4; ++i)
4676     if (!isUndefOrEqual(Mask[i], i+4))
4677       return false;
4678   return true;
4679 }
4680
4681 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4682 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4683 /// required.
4684 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4685   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4686     return false;
4687   N = N->getOperand(0).getNode();
4688   if (!ISD::isNON_EXTLoad(N))
4689     return false;
4690   if (LD)
4691     *LD = cast<LoadSDNode>(N);
4692   return true;
4693 }
4694
4695 // Test whether the given value is a vector value which will be legalized
4696 // into a load.
4697 static bool WillBeConstantPoolLoad(SDNode *N) {
4698   if (N->getOpcode() != ISD::BUILD_VECTOR)
4699     return false;
4700
4701   // Check for any non-constant elements.
4702   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4703     switch (N->getOperand(i).getNode()->getOpcode()) {
4704     case ISD::UNDEF:
4705     case ISD::ConstantFP:
4706     case ISD::Constant:
4707       break;
4708     default:
4709       return false;
4710     }
4711
4712   // Vectors of all-zeros and all-ones are materialized with special
4713   // instructions rather than being loaded.
4714   return !ISD::isBuildVectorAllZeros(N) &&
4715          !ISD::isBuildVectorAllOnes(N);
4716 }
4717
4718 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4719 /// match movlp{s|d}. The lower half elements should come from lower half of
4720 /// V1 (and in order), and the upper half elements should come from the upper
4721 /// half of V2 (and in order). And since V1 will become the source of the
4722 /// MOVLP, it must be either a vector load or a scalar load to vector.
4723 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4724                                ArrayRef<int> Mask, MVT VT) {
4725   if (!VT.is128BitVector())
4726     return false;
4727
4728   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4729     return false;
4730   // Is V2 is a vector load, don't do this transformation. We will try to use
4731   // load folding shufps op.
4732   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4733     return false;
4734
4735   unsigned NumElems = VT.getVectorNumElements();
4736
4737   if (NumElems != 2 && NumElems != 4)
4738     return false;
4739   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4740     if (!isUndefOrEqual(Mask[i], i))
4741       return false;
4742   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4743     if (!isUndefOrEqual(Mask[i], i+NumElems))
4744       return false;
4745   return true;
4746 }
4747
4748 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4749 /// all the same.
4750 static bool isSplatVector(SDNode *N) {
4751   if (N->getOpcode() != ISD::BUILD_VECTOR)
4752     return false;
4753
4754   SDValue SplatValue = N->getOperand(0);
4755   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4756     if (N->getOperand(i) != SplatValue)
4757       return false;
4758   return true;
4759 }
4760
4761 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4762 /// to an zero vector.
4763 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4764 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4765   SDValue V1 = N->getOperand(0);
4766   SDValue V2 = N->getOperand(1);
4767   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4768   for (unsigned i = 0; i != NumElems; ++i) {
4769     int Idx = N->getMaskElt(i);
4770     if (Idx >= (int)NumElems) {
4771       unsigned Opc = V2.getOpcode();
4772       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4773         continue;
4774       if (Opc != ISD::BUILD_VECTOR ||
4775           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4776         return false;
4777     } else if (Idx >= 0) {
4778       unsigned Opc = V1.getOpcode();
4779       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4780         continue;
4781       if (Opc != ISD::BUILD_VECTOR ||
4782           !X86::isZeroNode(V1.getOperand(Idx)))
4783         return false;
4784     }
4785   }
4786   return true;
4787 }
4788
4789 /// getZeroVector - Returns a vector of specified type with all zero elements.
4790 ///
4791 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4792                              SelectionDAG &DAG, SDLoc dl) {
4793   assert(VT.isVector() && "Expected a vector type");
4794
4795   // Always build SSE zero vectors as <4 x i32> bitcasted
4796   // to their dest type. This ensures they get CSE'd.
4797   SDValue Vec;
4798   if (VT.is128BitVector()) {  // SSE
4799     if (Subtarget->hasSSE2()) {  // SSE2
4800       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4801       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4802     } else { // SSE1
4803       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4804       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4805     }
4806   } else if (VT.is256BitVector()) { // AVX
4807     if (Subtarget->hasInt256()) { // AVX2
4808       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4809       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4810       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4811                         array_lengthof(Ops));
4812     } else {
4813       // 256-bit logic and arithmetic instructions in AVX are all
4814       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4815       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4816       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4817       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4818                         array_lengthof(Ops));
4819     }
4820   } else if (VT.is512BitVector()) { // AVX-512
4821       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4822       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4823                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4824       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4825   } else if (VT.getScalarType() == MVT::i1) {
4826     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4827     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4828     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4829                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4830     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4831                        Ops, VT.getVectorNumElements());
4832   } else
4833     llvm_unreachable("Unexpected vector type");
4834
4835   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4836 }
4837
4838 /// getOnesVector - Returns a vector of specified type with all bits set.
4839 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4840 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4841 /// Then bitcast to their original type, ensuring they get CSE'd.
4842 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4843                              SDLoc dl) {
4844   assert(VT.isVector() && "Expected a vector type");
4845
4846   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4847   SDValue Vec;
4848   if (VT.is256BitVector()) {
4849     if (HasInt256) { // AVX2
4850       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4851       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4852                         array_lengthof(Ops));
4853     } else { // AVX
4854       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4855       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4856     }
4857   } else if (VT.is128BitVector()) {
4858     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4859   } else
4860     llvm_unreachable("Unexpected vector type");
4861
4862   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4863 }
4864
4865 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4866 /// that point to V2 points to its first element.
4867 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4868   for (unsigned i = 0; i != NumElems; ++i) {
4869     if (Mask[i] > (int)NumElems) {
4870       Mask[i] = NumElems;
4871     }
4872   }
4873 }
4874
4875 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4876 /// operation of specified width.
4877 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4878                        SDValue V2) {
4879   unsigned NumElems = VT.getVectorNumElements();
4880   SmallVector<int, 8> Mask;
4881   Mask.push_back(NumElems);
4882   for (unsigned i = 1; i != NumElems; ++i)
4883     Mask.push_back(i);
4884   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4885 }
4886
4887 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4888 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4889                           SDValue V2) {
4890   unsigned NumElems = VT.getVectorNumElements();
4891   SmallVector<int, 8> Mask;
4892   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4893     Mask.push_back(i);
4894     Mask.push_back(i + NumElems);
4895   }
4896   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4897 }
4898
4899 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4900 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4901                           SDValue V2) {
4902   unsigned NumElems = VT.getVectorNumElements();
4903   SmallVector<int, 8> Mask;
4904   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4905     Mask.push_back(i + Half);
4906     Mask.push_back(i + NumElems + Half);
4907   }
4908   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4909 }
4910
4911 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4912 // a generic shuffle instruction because the target has no such instructions.
4913 // Generate shuffles which repeat i16 and i8 several times until they can be
4914 // represented by v4f32 and then be manipulated by target suported shuffles.
4915 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4916   MVT VT = V.getSimpleValueType();
4917   int NumElems = VT.getVectorNumElements();
4918   SDLoc dl(V);
4919
4920   while (NumElems > 4) {
4921     if (EltNo < NumElems/2) {
4922       V = getUnpackl(DAG, dl, VT, V, V);
4923     } else {
4924       V = getUnpackh(DAG, dl, VT, V, V);
4925       EltNo -= NumElems/2;
4926     }
4927     NumElems >>= 1;
4928   }
4929   return V;
4930 }
4931
4932 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4933 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4934   MVT VT = V.getSimpleValueType();
4935   SDLoc dl(V);
4936
4937   if (VT.is128BitVector()) {
4938     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4939     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4940     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4941                              &SplatMask[0]);
4942   } else if (VT.is256BitVector()) {
4943     // To use VPERMILPS to splat scalars, the second half of indicies must
4944     // refer to the higher part, which is a duplication of the lower one,
4945     // because VPERMILPS can only handle in-lane permutations.
4946     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4947                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4948
4949     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4950     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4951                              &SplatMask[0]);
4952   } else
4953     llvm_unreachable("Vector size not supported");
4954
4955   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4956 }
4957
4958 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4959 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4960   MVT SrcVT = SV->getSimpleValueType(0);
4961   SDValue V1 = SV->getOperand(0);
4962   SDLoc dl(SV);
4963
4964   int EltNo = SV->getSplatIndex();
4965   int NumElems = SrcVT.getVectorNumElements();
4966   bool Is256BitVec = SrcVT.is256BitVector();
4967
4968   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4969          "Unknown how to promote splat for type");
4970
4971   // Extract the 128-bit part containing the splat element and update
4972   // the splat element index when it refers to the higher register.
4973   if (Is256BitVec) {
4974     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4975     if (EltNo >= NumElems/2)
4976       EltNo -= NumElems/2;
4977   }
4978
4979   // All i16 and i8 vector types can't be used directly by a generic shuffle
4980   // instruction because the target has no such instruction. Generate shuffles
4981   // which repeat i16 and i8 several times until they fit in i32, and then can
4982   // be manipulated by target suported shuffles.
4983   MVT EltVT = SrcVT.getVectorElementType();
4984   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4985     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4986
4987   // Recreate the 256-bit vector and place the same 128-bit vector
4988   // into the low and high part. This is necessary because we want
4989   // to use VPERM* to shuffle the vectors
4990   if (Is256BitVec) {
4991     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4992   }
4993
4994   return getLegalSplat(DAG, V1, EltNo);
4995 }
4996
4997 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4998 /// vector of zero or undef vector.  This produces a shuffle where the low
4999 /// element of V2 is swizzled into the zero/undef vector, landing at element
5000 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5001 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5002                                            bool IsZero,
5003                                            const X86Subtarget *Subtarget,
5004                                            SelectionDAG &DAG) {
5005   MVT VT = V2.getSimpleValueType();
5006   SDValue V1 = IsZero
5007     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5008   unsigned NumElems = VT.getVectorNumElements();
5009   SmallVector<int, 16> MaskVec;
5010   for (unsigned i = 0; i != NumElems; ++i)
5011     // If this is the insertion idx, put the low elt of V2 here.
5012     MaskVec.push_back(i == Idx ? NumElems : i);
5013   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5014 }
5015
5016 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5017 /// target specific opcode. Returns true if the Mask could be calculated.
5018 /// Sets IsUnary to true if only uses one source.
5019 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5020                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5021   unsigned NumElems = VT.getVectorNumElements();
5022   SDValue ImmN;
5023
5024   IsUnary = false;
5025   switch(N->getOpcode()) {
5026   case X86ISD::SHUFP:
5027     ImmN = N->getOperand(N->getNumOperands()-1);
5028     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5029     break;
5030   case X86ISD::UNPCKH:
5031     DecodeUNPCKHMask(VT, Mask);
5032     break;
5033   case X86ISD::UNPCKL:
5034     DecodeUNPCKLMask(VT, Mask);
5035     break;
5036   case X86ISD::MOVHLPS:
5037     DecodeMOVHLPSMask(NumElems, Mask);
5038     break;
5039   case X86ISD::MOVLHPS:
5040     DecodeMOVLHPSMask(NumElems, Mask);
5041     break;
5042   case X86ISD::PALIGNR:
5043     ImmN = N->getOperand(N->getNumOperands()-1);
5044     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5045     break;
5046   case X86ISD::PSHUFD:
5047   case X86ISD::VPERMILP:
5048     ImmN = N->getOperand(N->getNumOperands()-1);
5049     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5050     IsUnary = true;
5051     break;
5052   case X86ISD::PSHUFHW:
5053     ImmN = N->getOperand(N->getNumOperands()-1);
5054     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5055     IsUnary = true;
5056     break;
5057   case X86ISD::PSHUFLW:
5058     ImmN = N->getOperand(N->getNumOperands()-1);
5059     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5060     IsUnary = true;
5061     break;
5062   case X86ISD::VPERMI:
5063     ImmN = N->getOperand(N->getNumOperands()-1);
5064     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5065     IsUnary = true;
5066     break;
5067   case X86ISD::MOVSS:
5068   case X86ISD::MOVSD: {
5069     // The index 0 always comes from the first element of the second source,
5070     // this is why MOVSS and MOVSD are used in the first place. The other
5071     // elements come from the other positions of the first source vector
5072     Mask.push_back(NumElems);
5073     for (unsigned i = 1; i != NumElems; ++i) {
5074       Mask.push_back(i);
5075     }
5076     break;
5077   }
5078   case X86ISD::VPERM2X128:
5079     ImmN = N->getOperand(N->getNumOperands()-1);
5080     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081     if (Mask.empty()) return false;
5082     break;
5083   case X86ISD::MOVDDUP:
5084   case X86ISD::MOVLHPD:
5085   case X86ISD::MOVLPD:
5086   case X86ISD::MOVLPS:
5087   case X86ISD::MOVSHDUP:
5088   case X86ISD::MOVSLDUP:
5089     // Not yet implemented
5090     return false;
5091   default: llvm_unreachable("unknown target shuffle node");
5092   }
5093
5094   return true;
5095 }
5096
5097 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5098 /// element of the result of the vector shuffle.
5099 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5100                                    unsigned Depth) {
5101   if (Depth == 6)
5102     return SDValue();  // Limit search depth.
5103
5104   SDValue V = SDValue(N, 0);
5105   EVT VT = V.getValueType();
5106   unsigned Opcode = V.getOpcode();
5107
5108   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5109   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5110     int Elt = SV->getMaskElt(Index);
5111
5112     if (Elt < 0)
5113       return DAG.getUNDEF(VT.getVectorElementType());
5114
5115     unsigned NumElems = VT.getVectorNumElements();
5116     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5117                                          : SV->getOperand(1);
5118     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5119   }
5120
5121   // Recurse into target specific vector shuffles to find scalars.
5122   if (isTargetShuffle(Opcode)) {
5123     MVT ShufVT = V.getSimpleValueType();
5124     unsigned NumElems = ShufVT.getVectorNumElements();
5125     SmallVector<int, 16> ShuffleMask;
5126     bool IsUnary;
5127
5128     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5129       return SDValue();
5130
5131     int Elt = ShuffleMask[Index];
5132     if (Elt < 0)
5133       return DAG.getUNDEF(ShufVT.getVectorElementType());
5134
5135     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5136                                          : N->getOperand(1);
5137     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5138                                Depth+1);
5139   }
5140
5141   // Actual nodes that may contain scalar elements
5142   if (Opcode == ISD::BITCAST) {
5143     V = V.getOperand(0);
5144     EVT SrcVT = V.getValueType();
5145     unsigned NumElems = VT.getVectorNumElements();
5146
5147     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5148       return SDValue();
5149   }
5150
5151   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5152     return (Index == 0) ? V.getOperand(0)
5153                         : DAG.getUNDEF(VT.getVectorElementType());
5154
5155   if (V.getOpcode() == ISD::BUILD_VECTOR)
5156     return V.getOperand(Index);
5157
5158   return SDValue();
5159 }
5160
5161 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5162 /// shuffle operation which come from a consecutively from a zero. The
5163 /// search can start in two different directions, from left or right.
5164 /// We count undefs as zeros until PreferredNum is reached.
5165 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5166                                          unsigned NumElems, bool ZerosFromLeft,
5167                                          SelectionDAG &DAG,
5168                                          unsigned PreferredNum = -1U) {
5169   unsigned NumZeros = 0;
5170   for (unsigned i = 0; i != NumElems; ++i) {
5171     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5172     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5173     if (!Elt.getNode())
5174       break;
5175
5176     if (X86::isZeroNode(Elt))
5177       ++NumZeros;
5178     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5179       NumZeros = std::min(NumZeros + 1, PreferredNum);
5180     else
5181       break;
5182   }
5183
5184   return NumZeros;
5185 }
5186
5187 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5188 /// correspond consecutively to elements from one of the vector operands,
5189 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5190 static
5191 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5192                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5193                               unsigned NumElems, unsigned &OpNum) {
5194   bool SeenV1 = false;
5195   bool SeenV2 = false;
5196
5197   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5198     int Idx = SVOp->getMaskElt(i);
5199     // Ignore undef indicies
5200     if (Idx < 0)
5201       continue;
5202
5203     if (Idx < (int)NumElems)
5204       SeenV1 = true;
5205     else
5206       SeenV2 = true;
5207
5208     // Only accept consecutive elements from the same vector
5209     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5210       return false;
5211   }
5212
5213   OpNum = SeenV1 ? 0 : 1;
5214   return true;
5215 }
5216
5217 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5218 /// logical left shift of a vector.
5219 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5220                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5221   unsigned NumElems =
5222     SVOp->getSimpleValueType(0).getVectorNumElements();
5223   unsigned NumZeros = getNumOfConsecutiveZeros(
5224       SVOp, NumElems, false /* check zeros from right */, DAG,
5225       SVOp->getMaskElt(0));
5226   unsigned OpSrc;
5227
5228   if (!NumZeros)
5229     return false;
5230
5231   // Considering the elements in the mask that are not consecutive zeros,
5232   // check if they consecutively come from only one of the source vectors.
5233   //
5234   //               V1 = {X, A, B, C}     0
5235   //                         \  \  \    /
5236   //   vector_shuffle V1, V2 <1, 2, 3, X>
5237   //
5238   if (!isShuffleMaskConsecutive(SVOp,
5239             0,                   // Mask Start Index
5240             NumElems-NumZeros,   // Mask End Index(exclusive)
5241             NumZeros,            // Where to start looking in the src vector
5242             NumElems,            // Number of elements in vector
5243             OpSrc))              // Which source operand ?
5244     return false;
5245
5246   isLeft = false;
5247   ShAmt = NumZeros;
5248   ShVal = SVOp->getOperand(OpSrc);
5249   return true;
5250 }
5251
5252 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5253 /// logical left shift of a vector.
5254 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5255                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5256   unsigned NumElems =
5257     SVOp->getSimpleValueType(0).getVectorNumElements();
5258   unsigned NumZeros = getNumOfConsecutiveZeros(
5259       SVOp, NumElems, true /* check zeros from left */, DAG,
5260       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5261   unsigned OpSrc;
5262
5263   if (!NumZeros)
5264     return false;
5265
5266   // Considering the elements in the mask that are not consecutive zeros,
5267   // check if they consecutively come from only one of the source vectors.
5268   //
5269   //                           0    { A, B, X, X } = V2
5270   //                          / \    /  /
5271   //   vector_shuffle V1, V2 <X, X, 4, 5>
5272   //
5273   if (!isShuffleMaskConsecutive(SVOp,
5274             NumZeros,     // Mask Start Index
5275             NumElems,     // Mask End Index(exclusive)
5276             0,            // Where to start looking in the src vector
5277             NumElems,     // Number of elements in vector
5278             OpSrc))       // Which source operand ?
5279     return false;
5280
5281   isLeft = true;
5282   ShAmt = NumZeros;
5283   ShVal = SVOp->getOperand(OpSrc);
5284   return true;
5285 }
5286
5287 /// isVectorShift - Returns true if the shuffle can be implemented as a
5288 /// logical left or right shift of a vector.
5289 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5290                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5291   // Although the logic below support any bitwidth size, there are no
5292   // shift instructions which handle more than 128-bit vectors.
5293   if (!SVOp->getSimpleValueType(0).is128BitVector())
5294     return false;
5295
5296   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5297       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5298     return true;
5299
5300   return false;
5301 }
5302
5303 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5304 ///
5305 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5306                                        unsigned NumNonZero, unsigned NumZero,
5307                                        SelectionDAG &DAG,
5308                                        const X86Subtarget* Subtarget,
5309                                        const TargetLowering &TLI) {
5310   if (NumNonZero > 8)
5311     return SDValue();
5312
5313   SDLoc dl(Op);
5314   SDValue V(0, 0);
5315   bool First = true;
5316   for (unsigned i = 0; i < 16; ++i) {
5317     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5318     if (ThisIsNonZero && First) {
5319       if (NumZero)
5320         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5321       else
5322         V = DAG.getUNDEF(MVT::v8i16);
5323       First = false;
5324     }
5325
5326     if ((i & 1) != 0) {
5327       SDValue ThisElt(0, 0), LastElt(0, 0);
5328       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5329       if (LastIsNonZero) {
5330         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5331                               MVT::i16, Op.getOperand(i-1));
5332       }
5333       if (ThisIsNonZero) {
5334         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5335         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5336                               ThisElt, DAG.getConstant(8, MVT::i8));
5337         if (LastIsNonZero)
5338           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5339       } else
5340         ThisElt = LastElt;
5341
5342       if (ThisElt.getNode())
5343         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5344                         DAG.getIntPtrConstant(i/2));
5345     }
5346   }
5347
5348   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5349 }
5350
5351 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5352 ///
5353 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5354                                      unsigned NumNonZero, unsigned NumZero,
5355                                      SelectionDAG &DAG,
5356                                      const X86Subtarget* Subtarget,
5357                                      const TargetLowering &TLI) {
5358   if (NumNonZero > 4)
5359     return SDValue();
5360
5361   SDLoc dl(Op);
5362   SDValue V(0, 0);
5363   bool First = true;
5364   for (unsigned i = 0; i < 8; ++i) {
5365     bool isNonZero = (NonZeros & (1 << i)) != 0;
5366     if (isNonZero) {
5367       if (First) {
5368         if (NumZero)
5369           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5370         else
5371           V = DAG.getUNDEF(MVT::v8i16);
5372         First = false;
5373       }
5374       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5375                       MVT::v8i16, V, Op.getOperand(i),
5376                       DAG.getIntPtrConstant(i));
5377     }
5378   }
5379
5380   return V;
5381 }
5382
5383 /// getVShift - Return a vector logical shift node.
5384 ///
5385 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5386                          unsigned NumBits, SelectionDAG &DAG,
5387                          const TargetLowering &TLI, SDLoc dl) {
5388   assert(VT.is128BitVector() && "Unknown type for VShift");
5389   EVT ShVT = MVT::v2i64;
5390   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5391   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5392   return DAG.getNode(ISD::BITCAST, dl, VT,
5393                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5394                              DAG.getConstant(NumBits,
5395                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5396 }
5397
5398 static SDValue
5399 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5400
5401   // Check if the scalar load can be widened into a vector load. And if
5402   // the address is "base + cst" see if the cst can be "absorbed" into
5403   // the shuffle mask.
5404   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5405     SDValue Ptr = LD->getBasePtr();
5406     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5407       return SDValue();
5408     EVT PVT = LD->getValueType(0);
5409     if (PVT != MVT::i32 && PVT != MVT::f32)
5410       return SDValue();
5411
5412     int FI = -1;
5413     int64_t Offset = 0;
5414     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5415       FI = FINode->getIndex();
5416       Offset = 0;
5417     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5418                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5419       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5420       Offset = Ptr.getConstantOperandVal(1);
5421       Ptr = Ptr.getOperand(0);
5422     } else {
5423       return SDValue();
5424     }
5425
5426     // FIXME: 256-bit vector instructions don't require a strict alignment,
5427     // improve this code to support it better.
5428     unsigned RequiredAlign = VT.getSizeInBits()/8;
5429     SDValue Chain = LD->getChain();
5430     // Make sure the stack object alignment is at least 16 or 32.
5431     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5432     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5433       if (MFI->isFixedObjectIndex(FI)) {
5434         // Can't change the alignment. FIXME: It's possible to compute
5435         // the exact stack offset and reference FI + adjust offset instead.
5436         // If someone *really* cares about this. That's the way to implement it.
5437         return SDValue();
5438       } else {
5439         MFI->setObjectAlignment(FI, RequiredAlign);
5440       }
5441     }
5442
5443     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5444     // Ptr + (Offset & ~15).
5445     if (Offset < 0)
5446       return SDValue();
5447     if ((Offset % RequiredAlign) & 3)
5448       return SDValue();
5449     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5450     if (StartOffset)
5451       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5452                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5453
5454     int EltNo = (Offset - StartOffset) >> 2;
5455     unsigned NumElems = VT.getVectorNumElements();
5456
5457     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5458     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5459                              LD->getPointerInfo().getWithOffset(StartOffset),
5460                              false, false, false, 0);
5461
5462     SmallVector<int, 8> Mask;
5463     for (unsigned i = 0; i != NumElems; ++i)
5464       Mask.push_back(EltNo);
5465
5466     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5467   }
5468
5469   return SDValue();
5470 }
5471
5472 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5473 /// vector of type 'VT', see if the elements can be replaced by a single large
5474 /// load which has the same value as a build_vector whose operands are 'elts'.
5475 ///
5476 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5477 ///
5478 /// FIXME: we'd also like to handle the case where the last elements are zero
5479 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5480 /// There's even a handy isZeroNode for that purpose.
5481 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5482                                         SDLoc &DL, SelectionDAG &DAG,
5483                                         bool isAfterLegalize) {
5484   EVT EltVT = VT.getVectorElementType();
5485   unsigned NumElems = Elts.size();
5486
5487   LoadSDNode *LDBase = NULL;
5488   unsigned LastLoadedElt = -1U;
5489
5490   // For each element in the initializer, see if we've found a load or an undef.
5491   // If we don't find an initial load element, or later load elements are
5492   // non-consecutive, bail out.
5493   for (unsigned i = 0; i < NumElems; ++i) {
5494     SDValue Elt = Elts[i];
5495
5496     if (!Elt.getNode() ||
5497         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5498       return SDValue();
5499     if (!LDBase) {
5500       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5501         return SDValue();
5502       LDBase = cast<LoadSDNode>(Elt.getNode());
5503       LastLoadedElt = i;
5504       continue;
5505     }
5506     if (Elt.getOpcode() == ISD::UNDEF)
5507       continue;
5508
5509     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5510     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5511       return SDValue();
5512     LastLoadedElt = i;
5513   }
5514
5515   // If we have found an entire vector of loads and undefs, then return a large
5516   // load of the entire vector width starting at the base pointer.  If we found
5517   // consecutive loads for the low half, generate a vzext_load node.
5518   if (LastLoadedElt == NumElems - 1) {
5519
5520     if (isAfterLegalize &&
5521         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5522       return SDValue();
5523
5524     SDValue NewLd = SDValue();
5525
5526     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5527       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528                           LDBase->getPointerInfo(),
5529                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5530                           LDBase->isInvariant(), 0);
5531     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5532                         LDBase->getPointerInfo(),
5533                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5534                         LDBase->isInvariant(), LDBase->getAlignment());
5535
5536     if (LDBase->hasAnyUseOfValue(1)) {
5537       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5538                                      SDValue(LDBase, 1),
5539                                      SDValue(NewLd.getNode(), 1));
5540       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5541       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5542                              SDValue(NewLd.getNode(), 1));
5543     }
5544
5545     return NewLd;
5546   }
5547   if (NumElems == 4 && LastLoadedElt == 1 &&
5548       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5549     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5550     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5551     SDValue ResNode =
5552         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5553                                 array_lengthof(Ops), MVT::i64,
5554                                 LDBase->getPointerInfo(),
5555                                 LDBase->getAlignment(),
5556                                 false/*isVolatile*/, true/*ReadMem*/,
5557                                 false/*WriteMem*/);
5558
5559     // Make sure the newly-created LOAD is in the same position as LDBase in
5560     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5561     // update uses of LDBase's output chain to use the TokenFactor.
5562     if (LDBase->hasAnyUseOfValue(1)) {
5563       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5564                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5565       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5566       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5567                              SDValue(ResNode.getNode(), 1));
5568     }
5569
5570     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5571   }
5572   return SDValue();
5573 }
5574
5575 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5576 /// to generate a splat value for the following cases:
5577 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5578 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5579 /// a scalar load, or a constant.
5580 /// The VBROADCAST node is returned when a pattern is found,
5581 /// or SDValue() otherwise.
5582 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5583                                     SelectionDAG &DAG) {
5584   if (!Subtarget->hasFp256())
5585     return SDValue();
5586
5587   MVT VT = Op.getSimpleValueType();
5588   SDLoc dl(Op);
5589
5590   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5591          "Unsupported vector type for broadcast.");
5592
5593   SDValue Ld;
5594   bool ConstSplatVal;
5595
5596   switch (Op.getOpcode()) {
5597     default:
5598       // Unknown pattern found.
5599       return SDValue();
5600
5601     case ISD::BUILD_VECTOR: {
5602       // The BUILD_VECTOR node must be a splat.
5603       if (!isSplatVector(Op.getNode()))
5604         return SDValue();
5605
5606       Ld = Op.getOperand(0);
5607       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5608                      Ld.getOpcode() == ISD::ConstantFP);
5609
5610       // The suspected load node has several users. Make sure that all
5611       // of its users are from the BUILD_VECTOR node.
5612       // Constants may have multiple users.
5613       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5614         return SDValue();
5615       break;
5616     }
5617
5618     case ISD::VECTOR_SHUFFLE: {
5619       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5620
5621       // Shuffles must have a splat mask where the first element is
5622       // broadcasted.
5623       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5624         return SDValue();
5625
5626       SDValue Sc = Op.getOperand(0);
5627       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5628           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5629
5630         if (!Subtarget->hasInt256())
5631           return SDValue();
5632
5633         // Use the register form of the broadcast instruction available on AVX2.
5634         if (VT.getSizeInBits() >= 256)
5635           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5636         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5637       }
5638
5639       Ld = Sc.getOperand(0);
5640       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5641                        Ld.getOpcode() == ISD::ConstantFP);
5642
5643       // The scalar_to_vector node and the suspected
5644       // load node must have exactly one user.
5645       // Constants may have multiple users.
5646
5647       // AVX-512 has register version of the broadcast
5648       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5649         Ld.getValueType().getSizeInBits() >= 32;
5650       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5651           !hasRegVer))
5652         return SDValue();
5653       break;
5654     }
5655   }
5656
5657   bool IsGE256 = (VT.getSizeInBits() >= 256);
5658
5659   // Handle the broadcasting a single constant scalar from the constant pool
5660   // into a vector. On Sandybridge it is still better to load a constant vector
5661   // from the constant pool and not to broadcast it from a scalar.
5662   if (ConstSplatVal && Subtarget->hasInt256()) {
5663     EVT CVT = Ld.getValueType();
5664     assert(!CVT.isVector() && "Must not broadcast a vector type");
5665     unsigned ScalarSize = CVT.getSizeInBits();
5666
5667     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5668       const Constant *C = 0;
5669       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5670         C = CI->getConstantIntValue();
5671       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5672         C = CF->getConstantFPValue();
5673
5674       assert(C && "Invalid constant type");
5675
5676       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5677       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5678       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5679       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5680                        MachinePointerInfo::getConstantPool(),
5681                        false, false, false, Alignment);
5682
5683       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5684     }
5685   }
5686
5687   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5688   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5689
5690   // Handle AVX2 in-register broadcasts.
5691   if (!IsLoad && Subtarget->hasInt256() &&
5692       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5693     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5694
5695   // The scalar source must be a normal load.
5696   if (!IsLoad)
5697     return SDValue();
5698
5699   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5700     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5701
5702   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5703   // double since there is no vbroadcastsd xmm
5704   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5705     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5706       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5707   }
5708
5709   // Unsupported broadcast.
5710   return SDValue();
5711 }
5712
5713 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5714 /// underlying vector and index.
5715 ///
5716 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5717 /// index.
5718 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5719                                          SDValue ExtIdx) {
5720   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5721   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5722     return Idx;
5723
5724   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5725   // lowered this:
5726   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5727   // to:
5728   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5729   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5730   //                           undef)
5731   //                       Constant<0>)
5732   // In this case the vector is the extract_subvector expression and the index
5733   // is 2, as specified by the shuffle.
5734   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5735   SDValue ShuffleVec = SVOp->getOperand(0);
5736   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5737   assert(ShuffleVecVT.getVectorElementType() ==
5738          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5739
5740   int ShuffleIdx = SVOp->getMaskElt(Idx);
5741   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5742     ExtractedFromVec = ShuffleVec;
5743     return ShuffleIdx;
5744   }
5745   return Idx;
5746 }
5747
5748 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5749   MVT VT = Op.getSimpleValueType();
5750
5751   // Skip if insert_vec_elt is not supported.
5752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5753   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5754     return SDValue();
5755
5756   SDLoc DL(Op);
5757   unsigned NumElems = Op.getNumOperands();
5758
5759   SDValue VecIn1;
5760   SDValue VecIn2;
5761   SmallVector<unsigned, 4> InsertIndices;
5762   SmallVector<int, 8> Mask(NumElems, -1);
5763
5764   for (unsigned i = 0; i != NumElems; ++i) {
5765     unsigned Opc = Op.getOperand(i).getOpcode();
5766
5767     if (Opc == ISD::UNDEF)
5768       continue;
5769
5770     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5771       // Quit if more than 1 elements need inserting.
5772       if (InsertIndices.size() > 1)
5773         return SDValue();
5774
5775       InsertIndices.push_back(i);
5776       continue;
5777     }
5778
5779     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5780     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5781     // Quit if non-constant index.
5782     if (!isa<ConstantSDNode>(ExtIdx))
5783       return SDValue();
5784     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5785
5786     // Quit if extracted from vector of different type.
5787     if (ExtractedFromVec.getValueType() != VT)
5788       return SDValue();
5789
5790     if (VecIn1.getNode() == 0)
5791       VecIn1 = ExtractedFromVec;
5792     else if (VecIn1 != ExtractedFromVec) {
5793       if (VecIn2.getNode() == 0)
5794         VecIn2 = ExtractedFromVec;
5795       else if (VecIn2 != ExtractedFromVec)
5796         // Quit if more than 2 vectors to shuffle
5797         return SDValue();
5798     }
5799
5800     if (ExtractedFromVec == VecIn1)
5801       Mask[i] = Idx;
5802     else if (ExtractedFromVec == VecIn2)
5803       Mask[i] = Idx + NumElems;
5804   }
5805
5806   if (VecIn1.getNode() == 0)
5807     return SDValue();
5808
5809   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5810   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5811   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5812     unsigned Idx = InsertIndices[i];
5813     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5814                      DAG.getIntPtrConstant(Idx));
5815   }
5816
5817   return NV;
5818 }
5819
5820 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5821 SDValue
5822 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5823
5824   MVT VT = Op.getSimpleValueType();
5825   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5826          "Unexpected type in LowerBUILD_VECTORvXi1!");
5827
5828   SDLoc dl(Op);
5829   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5830     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5831     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5832                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5833     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5834                        Ops, VT.getVectorNumElements());
5835   }
5836
5837   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5838     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5839     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5840                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5841     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5842                        Ops, VT.getVectorNumElements());
5843   }
5844
5845   bool AllContants = true;
5846   uint64_t Immediate = 0;
5847   int NonConstIdx = -1;
5848   bool IsSplat = true;
5849   unsigned NumNonConsts = 0;
5850   unsigned NumConsts = 0;
5851   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5852     SDValue In = Op.getOperand(idx);
5853     if (In.getOpcode() == ISD::UNDEF)
5854       continue;
5855     if (!isa<ConstantSDNode>(In)) {
5856       AllContants = false;
5857       NonConstIdx = idx;
5858       NumNonConsts++;
5859     }
5860     else {
5861       NumConsts++;
5862       if (cast<ConstantSDNode>(In)->getZExtValue())
5863       Immediate |= (1ULL << idx);
5864     }
5865     if (In != Op.getOperand(0))
5866       IsSplat = false;
5867   }
5868
5869   if (AllContants) {
5870     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5871       DAG.getConstant(Immediate, MVT::i16));
5872     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5873                        DAG.getIntPtrConstant(0));
5874   }
5875
5876   if (NumNonConsts == 1 && NonConstIdx != 0) {
5877     SDValue DstVec;
5878     if (NumConsts) {
5879       SDValue VecAsImm = DAG.getConstant(Immediate,
5880                                          MVT::getIntegerVT(VT.getSizeInBits()));
5881       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5882     }
5883     else 
5884       DstVec = DAG.getUNDEF(VT);
5885     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5886                        Op.getOperand(NonConstIdx),
5887                        DAG.getIntPtrConstant(NonConstIdx));
5888   }
5889   if (!IsSplat && (NonConstIdx != 0))
5890     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5891   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5892   SDValue Select;
5893   if (IsSplat)
5894     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5895                           DAG.getConstant(-1, SelectVT),
5896                           DAG.getConstant(0, SelectVT));
5897   else
5898     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5899                          DAG.getConstant((Immediate | 1), SelectVT),
5900                          DAG.getConstant(Immediate, SelectVT));
5901   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5902 }
5903
5904 SDValue
5905 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5906   SDLoc dl(Op);
5907
5908   MVT VT = Op.getSimpleValueType();
5909   MVT ExtVT = VT.getVectorElementType();
5910   unsigned NumElems = Op.getNumOperands();
5911
5912   // Generate vectors for predicate vectors.
5913   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5914     return LowerBUILD_VECTORvXi1(Op, DAG);
5915
5916   // Vectors containing all zeros can be matched by pxor and xorps later
5917   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5918     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5919     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5920     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5921       return Op;
5922
5923     return getZeroVector(VT, Subtarget, DAG, dl);
5924   }
5925
5926   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5927   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5928   // vpcmpeqd on 256-bit vectors.
5929   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5930     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5931       return Op;
5932
5933     if (!VT.is512BitVector())
5934       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5935   }
5936
5937   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5938   if (Broadcast.getNode())
5939     return Broadcast;
5940
5941   unsigned EVTBits = ExtVT.getSizeInBits();
5942
5943   unsigned NumZero  = 0;
5944   unsigned NumNonZero = 0;
5945   unsigned NonZeros = 0;
5946   bool IsAllConstants = true;
5947   SmallSet<SDValue, 8> Values;
5948   for (unsigned i = 0; i < NumElems; ++i) {
5949     SDValue Elt = Op.getOperand(i);
5950     if (Elt.getOpcode() == ISD::UNDEF)
5951       continue;
5952     Values.insert(Elt);
5953     if (Elt.getOpcode() != ISD::Constant &&
5954         Elt.getOpcode() != ISD::ConstantFP)
5955       IsAllConstants = false;
5956     if (X86::isZeroNode(Elt))
5957       NumZero++;
5958     else {
5959       NonZeros |= (1 << i);
5960       NumNonZero++;
5961     }
5962   }
5963
5964   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5965   if (NumNonZero == 0)
5966     return DAG.getUNDEF(VT);
5967
5968   // Special case for single non-zero, non-undef, element.
5969   if (NumNonZero == 1) {
5970     unsigned Idx = countTrailingZeros(NonZeros);
5971     SDValue Item = Op.getOperand(Idx);
5972
5973     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5974     // the value are obviously zero, truncate the value to i32 and do the
5975     // insertion that way.  Only do this if the value is non-constant or if the
5976     // value is a constant being inserted into element 0.  It is cheaper to do
5977     // a constant pool load than it is to do a movd + shuffle.
5978     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5979         (!IsAllConstants || Idx == 0)) {
5980       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5981         // Handle SSE only.
5982         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5983         EVT VecVT = MVT::v4i32;
5984         unsigned VecElts = 4;
5985
5986         // Truncate the value (which may itself be a constant) to i32, and
5987         // convert it to a vector with movd (S2V+shuffle to zero extend).
5988         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5989         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5990         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5991
5992         // Now we have our 32-bit value zero extended in the low element of
5993         // a vector.  If Idx != 0, swizzle it into place.
5994         if (Idx != 0) {
5995           SmallVector<int, 4> Mask;
5996           Mask.push_back(Idx);
5997           for (unsigned i = 1; i != VecElts; ++i)
5998             Mask.push_back(i);
5999           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6000                                       &Mask[0]);
6001         }
6002         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6003       }
6004     }
6005
6006     // If we have a constant or non-constant insertion into the low element of
6007     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6008     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6009     // depending on what the source datatype is.
6010     if (Idx == 0) {
6011       if (NumZero == 0)
6012         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6013
6014       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6015           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6016         if (VT.is256BitVector() || VT.is512BitVector()) {
6017           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6018           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6019                              Item, DAG.getIntPtrConstant(0));
6020         }
6021         assert(VT.is128BitVector() && "Expected an SSE value type!");
6022         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6023         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6024         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6025       }
6026
6027       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6028         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6029         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6030         if (VT.is256BitVector()) {
6031           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6032           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6033         } else {
6034           assert(VT.is128BitVector() && "Expected an SSE value type!");
6035           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6036         }
6037         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6038       }
6039     }
6040
6041     // Is it a vector logical left shift?
6042     if (NumElems == 2 && Idx == 1 &&
6043         X86::isZeroNode(Op.getOperand(0)) &&
6044         !X86::isZeroNode(Op.getOperand(1))) {
6045       unsigned NumBits = VT.getSizeInBits();
6046       return getVShift(true, VT,
6047                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6048                                    VT, Op.getOperand(1)),
6049                        NumBits/2, DAG, *this, dl);
6050     }
6051
6052     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6053       return SDValue();
6054
6055     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6056     // is a non-constant being inserted into an element other than the low one,
6057     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6058     // movd/movss) to move this into the low element, then shuffle it into
6059     // place.
6060     if (EVTBits == 32) {
6061       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6062
6063       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6064       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6065       SmallVector<int, 8> MaskVec;
6066       for (unsigned i = 0; i != NumElems; ++i)
6067         MaskVec.push_back(i == Idx ? 0 : 1);
6068       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6069     }
6070   }
6071
6072   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6073   if (Values.size() == 1) {
6074     if (EVTBits == 32) {
6075       // Instead of a shuffle like this:
6076       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6077       // Check if it's possible to issue this instead.
6078       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6079       unsigned Idx = countTrailingZeros(NonZeros);
6080       SDValue Item = Op.getOperand(Idx);
6081       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6082         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6083     }
6084     return SDValue();
6085   }
6086
6087   // A vector full of immediates; various special cases are already
6088   // handled, so this is best done with a single constant-pool load.
6089   if (IsAllConstants)
6090     return SDValue();
6091
6092   // For AVX-length vectors, build the individual 128-bit pieces and use
6093   // shuffles to put them in place.
6094   if (VT.is256BitVector() || VT.is512BitVector()) {
6095     SmallVector<SDValue, 64> V;
6096     for (unsigned i = 0; i != NumElems; ++i)
6097       V.push_back(Op.getOperand(i));
6098
6099     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6100
6101     // Build both the lower and upper subvector.
6102     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6103     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6104                                 NumElems/2);
6105
6106     // Recreate the wider vector with the lower and upper part.
6107     if (VT.is256BitVector())
6108       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6109     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6110   }
6111
6112   // Let legalizer expand 2-wide build_vectors.
6113   if (EVTBits == 64) {
6114     if (NumNonZero == 1) {
6115       // One half is zero or undef.
6116       unsigned Idx = countTrailingZeros(NonZeros);
6117       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6118                                  Op.getOperand(Idx));
6119       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6120     }
6121     return SDValue();
6122   }
6123
6124   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6125   if (EVTBits == 8 && NumElems == 16) {
6126     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6127                                         Subtarget, *this);
6128     if (V.getNode()) return V;
6129   }
6130
6131   if (EVTBits == 16 && NumElems == 8) {
6132     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6133                                       Subtarget, *this);
6134     if (V.getNode()) return V;
6135   }
6136
6137   // If element VT is == 32 bits, turn it into a number of shuffles.
6138   SmallVector<SDValue, 8> V(NumElems);
6139   if (NumElems == 4 && NumZero > 0) {
6140     for (unsigned i = 0; i < 4; ++i) {
6141       bool isZero = !(NonZeros & (1 << i));
6142       if (isZero)
6143         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6144       else
6145         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6146     }
6147
6148     for (unsigned i = 0; i < 2; ++i) {
6149       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6150         default: break;
6151         case 0:
6152           V[i] = V[i*2];  // Must be a zero vector.
6153           break;
6154         case 1:
6155           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6156           break;
6157         case 2:
6158           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6159           break;
6160         case 3:
6161           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6162           break;
6163       }
6164     }
6165
6166     bool Reverse1 = (NonZeros & 0x3) == 2;
6167     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6168     int MaskVec[] = {
6169       Reverse1 ? 1 : 0,
6170       Reverse1 ? 0 : 1,
6171       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6172       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6173     };
6174     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6175   }
6176
6177   if (Values.size() > 1 && VT.is128BitVector()) {
6178     // Check for a build vector of consecutive loads.
6179     for (unsigned i = 0; i < NumElems; ++i)
6180       V[i] = Op.getOperand(i);
6181
6182     // Check for elements which are consecutive loads.
6183     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6184     if (LD.getNode())
6185       return LD;
6186
6187     // Check for a build vector from mostly shuffle plus few inserting.
6188     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6189     if (Sh.getNode())
6190       return Sh;
6191
6192     // For SSE 4.1, use insertps to put the high elements into the low element.
6193     if (getSubtarget()->hasSSE41()) {
6194       SDValue Result;
6195       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6196         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6197       else
6198         Result = DAG.getUNDEF(VT);
6199
6200       for (unsigned i = 1; i < NumElems; ++i) {
6201         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6202         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6203                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6204       }
6205       return Result;
6206     }
6207
6208     // Otherwise, expand into a number of unpckl*, start by extending each of
6209     // our (non-undef) elements to the full vector width with the element in the
6210     // bottom slot of the vector (which generates no code for SSE).
6211     for (unsigned i = 0; i < NumElems; ++i) {
6212       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6213         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6214       else
6215         V[i] = DAG.getUNDEF(VT);
6216     }
6217
6218     // Next, we iteratively mix elements, e.g. for v4f32:
6219     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6220     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6221     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6222     unsigned EltStride = NumElems >> 1;
6223     while (EltStride != 0) {
6224       for (unsigned i = 0; i < EltStride; ++i) {
6225         // If V[i+EltStride] is undef and this is the first round of mixing,
6226         // then it is safe to just drop this shuffle: V[i] is already in the
6227         // right place, the one element (since it's the first round) being
6228         // inserted as undef can be dropped.  This isn't safe for successive
6229         // rounds because they will permute elements within both vectors.
6230         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6231             EltStride == NumElems/2)
6232           continue;
6233
6234         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6235       }
6236       EltStride >>= 1;
6237     }
6238     return V[0];
6239   }
6240   return SDValue();
6241 }
6242
6243 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6244 // to create 256-bit vectors from two other 128-bit ones.
6245 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6246   SDLoc dl(Op);
6247   MVT ResVT = Op.getSimpleValueType();
6248
6249   assert((ResVT.is256BitVector() ||
6250           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6251
6252   SDValue V1 = Op.getOperand(0);
6253   SDValue V2 = Op.getOperand(1);
6254   unsigned NumElems = ResVT.getVectorNumElements();
6255   if(ResVT.is256BitVector())
6256     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6257
6258   if (Op.getNumOperands() == 4) {
6259     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6260                                 ResVT.getVectorNumElements()/2);
6261     SDValue V3 = Op.getOperand(2);
6262     SDValue V4 = Op.getOperand(3);
6263     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6264       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6265   }
6266   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6267 }
6268
6269 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6270   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6271   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6272          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6273           Op.getNumOperands() == 4)));
6274
6275   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6276   // from two other 128-bit ones.
6277
6278   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6279   return LowerAVXCONCAT_VECTORS(Op, DAG);
6280 }
6281
6282 // Try to lower a shuffle node into a simple blend instruction.
6283 static SDValue
6284 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6285                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6286   SDValue V1 = SVOp->getOperand(0);
6287   SDValue V2 = SVOp->getOperand(1);
6288   SDLoc dl(SVOp);
6289   MVT VT = SVOp->getSimpleValueType(0);
6290   MVT EltVT = VT.getVectorElementType();
6291   unsigned NumElems = VT.getVectorNumElements();
6292
6293   // There is no blend with immediate in AVX-512.
6294   if (VT.is512BitVector())
6295     return SDValue();
6296
6297   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6298     return SDValue();
6299   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6300     return SDValue();
6301
6302   // Check the mask for BLEND and build the value.
6303   unsigned MaskValue = 0;
6304   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6305   unsigned NumLanes = (NumElems-1)/8 + 1;
6306   unsigned NumElemsInLane = NumElems / NumLanes;
6307
6308   // Blend for v16i16 should be symetric for the both lanes.
6309   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6310
6311     int SndLaneEltIdx = (NumLanes == 2) ?
6312       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6313     int EltIdx = SVOp->getMaskElt(i);
6314
6315     if ((EltIdx < 0 || EltIdx == (int)i) &&
6316         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6317       continue;
6318
6319     if (((unsigned)EltIdx == (i + NumElems)) &&
6320         (SndLaneEltIdx < 0 ||
6321          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6322       MaskValue |= (1<<i);
6323     else
6324       return SDValue();
6325   }
6326
6327   // Convert i32 vectors to floating point if it is not AVX2.
6328   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6329   MVT BlendVT = VT;
6330   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6331     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6332                                NumElems);
6333     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6334     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6335   }
6336
6337   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6338                             DAG.getConstant(MaskValue, MVT::i32));
6339   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6340 }
6341
6342 /// In vector type \p VT, return true if the element at index \p InputIdx
6343 /// falls on a different 128-bit lane than \p OutputIdx.
6344 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6345                                      unsigned OutputIdx) {
6346   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6347   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6348 }
6349
6350 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6351 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6352 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6353 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6354 /// zero.
6355 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6356                          SelectionDAG &DAG) {
6357   MVT VT = V1.getSimpleValueType();
6358   assert(VT.is128BitVector() || VT.is256BitVector());
6359
6360   MVT EltVT = VT.getVectorElementType();
6361   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6362   unsigned NumElts = VT.getVectorNumElements();
6363
6364   SmallVector<SDValue, 32> PshufbMask;
6365   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6366     int InputIdx = MaskVals[OutputIdx];
6367     unsigned InputByteIdx;
6368
6369     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6370       InputByteIdx = 0x80;
6371     else {
6372       // Cross lane is not allowed.
6373       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6374         return SDValue();
6375       InputByteIdx = InputIdx * EltSizeInBytes;
6376       // Index is an byte offset within the 128-bit lane.
6377       InputByteIdx &= 0xf;
6378     }
6379
6380     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6381       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6382       if (InputByteIdx != 0x80)
6383         ++InputByteIdx;
6384     }
6385   }
6386
6387   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6388   if (ShufVT != VT)
6389     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6390   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6391                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6392                                  PshufbMask.data(), PshufbMask.size()));
6393 }
6394
6395 // v8i16 shuffles - Prefer shuffles in the following order:
6396 // 1. [all]   pshuflw, pshufhw, optional move
6397 // 2. [ssse3] 1 x pshufb
6398 // 3. [ssse3] 2 x pshufb + 1 x por
6399 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6400 static SDValue
6401 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6402                          SelectionDAG &DAG) {
6403   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6404   SDValue V1 = SVOp->getOperand(0);
6405   SDValue V2 = SVOp->getOperand(1);
6406   SDLoc dl(SVOp);
6407   SmallVector<int, 8> MaskVals;
6408
6409   // Determine if more than 1 of the words in each of the low and high quadwords
6410   // of the result come from the same quadword of one of the two inputs.  Undef
6411   // mask values count as coming from any quadword, for better codegen.
6412   //
6413   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6414   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6415   unsigned LoQuad[] = { 0, 0, 0, 0 };
6416   unsigned HiQuad[] = { 0, 0, 0, 0 };
6417   // Indices of quads used.
6418   std::bitset<4> InputQuads;
6419   for (unsigned i = 0; i < 8; ++i) {
6420     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6421     int EltIdx = SVOp->getMaskElt(i);
6422     MaskVals.push_back(EltIdx);
6423     if (EltIdx < 0) {
6424       ++Quad[0];
6425       ++Quad[1];
6426       ++Quad[2];
6427       ++Quad[3];
6428       continue;
6429     }
6430     ++Quad[EltIdx / 4];
6431     InputQuads.set(EltIdx / 4);
6432   }
6433
6434   int BestLoQuad = -1;
6435   unsigned MaxQuad = 1;
6436   for (unsigned i = 0; i < 4; ++i) {
6437     if (LoQuad[i] > MaxQuad) {
6438       BestLoQuad = i;
6439       MaxQuad = LoQuad[i];
6440     }
6441   }
6442
6443   int BestHiQuad = -1;
6444   MaxQuad = 1;
6445   for (unsigned i = 0; i < 4; ++i) {
6446     if (HiQuad[i] > MaxQuad) {
6447       BestHiQuad = i;
6448       MaxQuad = HiQuad[i];
6449     }
6450   }
6451
6452   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6453   // of the two input vectors, shuffle them into one input vector so only a
6454   // single pshufb instruction is necessary. If there are more than 2 input
6455   // quads, disable the next transformation since it does not help SSSE3.
6456   bool V1Used = InputQuads[0] || InputQuads[1];
6457   bool V2Used = InputQuads[2] || InputQuads[3];
6458   if (Subtarget->hasSSSE3()) {
6459     if (InputQuads.count() == 2 && V1Used && V2Used) {
6460       BestLoQuad = InputQuads[0] ? 0 : 1;
6461       BestHiQuad = InputQuads[2] ? 2 : 3;
6462     }
6463     if (InputQuads.count() > 2) {
6464       BestLoQuad = -1;
6465       BestHiQuad = -1;
6466     }
6467   }
6468
6469   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6470   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6471   // words from all 4 input quadwords.
6472   SDValue NewV;
6473   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6474     int MaskV[] = {
6475       BestLoQuad < 0 ? 0 : BestLoQuad,
6476       BestHiQuad < 0 ? 1 : BestHiQuad
6477     };
6478     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6479                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6480                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6481     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6482
6483     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6484     // source words for the shuffle, to aid later transformations.
6485     bool AllWordsInNewV = true;
6486     bool InOrder[2] = { true, true };
6487     for (unsigned i = 0; i != 8; ++i) {
6488       int idx = MaskVals[i];
6489       if (idx != (int)i)
6490         InOrder[i/4] = false;
6491       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6492         continue;
6493       AllWordsInNewV = false;
6494       break;
6495     }
6496
6497     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6498     if (AllWordsInNewV) {
6499       for (int i = 0; i != 8; ++i) {
6500         int idx = MaskVals[i];
6501         if (idx < 0)
6502           continue;
6503         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6504         if ((idx != i) && idx < 4)
6505           pshufhw = false;
6506         if ((idx != i) && idx > 3)
6507           pshuflw = false;
6508       }
6509       V1 = NewV;
6510       V2Used = false;
6511       BestLoQuad = 0;
6512       BestHiQuad = 1;
6513     }
6514
6515     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6516     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6517     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6518       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6519       unsigned TargetMask = 0;
6520       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6521                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6522       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6523       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6524                              getShufflePSHUFLWImmediate(SVOp);
6525       V1 = NewV.getOperand(0);
6526       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6527     }
6528   }
6529
6530   // Promote splats to a larger type which usually leads to more efficient code.
6531   // FIXME: Is this true if pshufb is available?
6532   if (SVOp->isSplat())
6533     return PromoteSplat(SVOp, DAG);
6534
6535   // If we have SSSE3, and all words of the result are from 1 input vector,
6536   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6537   // is present, fall back to case 4.
6538   if (Subtarget->hasSSSE3()) {
6539     SmallVector<SDValue,16> pshufbMask;
6540
6541     // If we have elements from both input vectors, set the high bit of the
6542     // shuffle mask element to zero out elements that come from V2 in the V1
6543     // mask, and elements that come from V1 in the V2 mask, so that the two
6544     // results can be OR'd together.
6545     bool TwoInputs = V1Used && V2Used;
6546     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6547     if (!TwoInputs)
6548       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6549
6550     // Calculate the shuffle mask for the second input, shuffle it, and
6551     // OR it with the first shuffled input.
6552     CommuteVectorShuffleMask(MaskVals, 8);
6553     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6554     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6555     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6556   }
6557
6558   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6559   // and update MaskVals with new element order.
6560   std::bitset<8> InOrder;
6561   if (BestLoQuad >= 0) {
6562     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6563     for (int i = 0; i != 4; ++i) {
6564       int idx = MaskVals[i];
6565       if (idx < 0) {
6566         InOrder.set(i);
6567       } else if ((idx / 4) == BestLoQuad) {
6568         MaskV[i] = idx & 3;
6569         InOrder.set(i);
6570       }
6571     }
6572     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6573                                 &MaskV[0]);
6574
6575     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6576       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6577       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6578                                   NewV.getOperand(0),
6579                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6580     }
6581   }
6582
6583   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6584   // and update MaskVals with the new element order.
6585   if (BestHiQuad >= 0) {
6586     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6587     for (unsigned i = 4; i != 8; ++i) {
6588       int idx = MaskVals[i];
6589       if (idx < 0) {
6590         InOrder.set(i);
6591       } else if ((idx / 4) == BestHiQuad) {
6592         MaskV[i] = (idx & 3) + 4;
6593         InOrder.set(i);
6594       }
6595     }
6596     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6597                                 &MaskV[0]);
6598
6599     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6600       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6601       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6602                                   NewV.getOperand(0),
6603                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6604     }
6605   }
6606
6607   // In case BestHi & BestLo were both -1, which means each quadword has a word
6608   // from each of the four input quadwords, calculate the InOrder bitvector now
6609   // before falling through to the insert/extract cleanup.
6610   if (BestLoQuad == -1 && BestHiQuad == -1) {
6611     NewV = V1;
6612     for (int i = 0; i != 8; ++i)
6613       if (MaskVals[i] < 0 || MaskVals[i] == i)
6614         InOrder.set(i);
6615   }
6616
6617   // The other elements are put in the right place using pextrw and pinsrw.
6618   for (unsigned i = 0; i != 8; ++i) {
6619     if (InOrder[i])
6620       continue;
6621     int EltIdx = MaskVals[i];
6622     if (EltIdx < 0)
6623       continue;
6624     SDValue ExtOp = (EltIdx < 8) ?
6625       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6626                   DAG.getIntPtrConstant(EltIdx)) :
6627       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6628                   DAG.getIntPtrConstant(EltIdx - 8));
6629     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6630                        DAG.getIntPtrConstant(i));
6631   }
6632   return NewV;
6633 }
6634
6635 /// \brief v16i16 shuffles
6636 ///
6637 /// FIXME: We only support generation of a single pshufb currently.  We can
6638 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6639 /// well (e.g 2 x pshufb + 1 x por).
6640 static SDValue
6641 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6642   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6643   SDValue V1 = SVOp->getOperand(0);
6644   SDValue V2 = SVOp->getOperand(1);
6645   SDLoc dl(SVOp);
6646
6647   if (V2.getOpcode() != ISD::UNDEF)
6648     return SDValue();
6649
6650   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6651   return getPSHUFB(MaskVals, V1, dl, DAG);
6652 }
6653
6654 // v16i8 shuffles - Prefer shuffles in the following order:
6655 // 1. [ssse3] 1 x pshufb
6656 // 2. [ssse3] 2 x pshufb + 1 x por
6657 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6658 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6659                                         const X86Subtarget* Subtarget,
6660                                         SelectionDAG &DAG) {
6661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6662   SDValue V1 = SVOp->getOperand(0);
6663   SDValue V2 = SVOp->getOperand(1);
6664   SDLoc dl(SVOp);
6665   ArrayRef<int> MaskVals = SVOp->getMask();
6666
6667   // Promote splats to a larger type which usually leads to more efficient code.
6668   // FIXME: Is this true if pshufb is available?
6669   if (SVOp->isSplat())
6670     return PromoteSplat(SVOp, DAG);
6671
6672   // If we have SSSE3, case 1 is generated when all result bytes come from
6673   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6674   // present, fall back to case 3.
6675
6676   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6677   if (Subtarget->hasSSSE3()) {
6678     SmallVector<SDValue,16> pshufbMask;
6679
6680     // If all result elements are from one input vector, then only translate
6681     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6682     //
6683     // Otherwise, we have elements from both input vectors, and must zero out
6684     // elements that come from V2 in the first mask, and V1 in the second mask
6685     // so that we can OR them together.
6686     for (unsigned i = 0; i != 16; ++i) {
6687       int EltIdx = MaskVals[i];
6688       if (EltIdx < 0 || EltIdx >= 16)
6689         EltIdx = 0x80;
6690       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6691     }
6692     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6693                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6694                                  MVT::v16i8, &pshufbMask[0], 16));
6695
6696     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6697     // the 2nd operand if it's undefined or zero.
6698     if (V2.getOpcode() == ISD::UNDEF ||
6699         ISD::isBuildVectorAllZeros(V2.getNode()))
6700       return V1;
6701
6702     // Calculate the shuffle mask for the second input, shuffle it, and
6703     // OR it with the first shuffled input.
6704     pshufbMask.clear();
6705     for (unsigned i = 0; i != 16; ++i) {
6706       int EltIdx = MaskVals[i];
6707       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6708       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6709     }
6710     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6711                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6712                                  MVT::v16i8, &pshufbMask[0], 16));
6713     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6714   }
6715
6716   // No SSSE3 - Calculate in place words and then fix all out of place words
6717   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6718   // the 16 different words that comprise the two doublequadword input vectors.
6719   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6720   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6721   SDValue NewV = V1;
6722   for (int i = 0; i != 8; ++i) {
6723     int Elt0 = MaskVals[i*2];
6724     int Elt1 = MaskVals[i*2+1];
6725
6726     // This word of the result is all undef, skip it.
6727     if (Elt0 < 0 && Elt1 < 0)
6728       continue;
6729
6730     // This word of the result is already in the correct place, skip it.
6731     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6732       continue;
6733
6734     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6735     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6736     SDValue InsElt;
6737
6738     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6739     // using a single extract together, load it and store it.
6740     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6741       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6742                            DAG.getIntPtrConstant(Elt1 / 2));
6743       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6744                         DAG.getIntPtrConstant(i));
6745       continue;
6746     }
6747
6748     // If Elt1 is defined, extract it from the appropriate source.  If the
6749     // source byte is not also odd, shift the extracted word left 8 bits
6750     // otherwise clear the bottom 8 bits if we need to do an or.
6751     if (Elt1 >= 0) {
6752       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6753                            DAG.getIntPtrConstant(Elt1 / 2));
6754       if ((Elt1 & 1) == 0)
6755         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6756                              DAG.getConstant(8,
6757                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6758       else if (Elt0 >= 0)
6759         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6760                              DAG.getConstant(0xFF00, MVT::i16));
6761     }
6762     // If Elt0 is defined, extract it from the appropriate source.  If the
6763     // source byte is not also even, shift the extracted word right 8 bits. If
6764     // Elt1 was also defined, OR the extracted values together before
6765     // inserting them in the result.
6766     if (Elt0 >= 0) {
6767       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6768                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6769       if ((Elt0 & 1) != 0)
6770         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6771                               DAG.getConstant(8,
6772                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6773       else if (Elt1 >= 0)
6774         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6775                              DAG.getConstant(0x00FF, MVT::i16));
6776       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6777                          : InsElt0;
6778     }
6779     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6780                        DAG.getIntPtrConstant(i));
6781   }
6782   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6783 }
6784
6785 // v32i8 shuffles - Translate to VPSHUFB if possible.
6786 static
6787 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6788                                  const X86Subtarget *Subtarget,
6789                                  SelectionDAG &DAG) {
6790   MVT VT = SVOp->getSimpleValueType(0);
6791   SDValue V1 = SVOp->getOperand(0);
6792   SDValue V2 = SVOp->getOperand(1);
6793   SDLoc dl(SVOp);
6794   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6795
6796   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6797   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6798   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6799
6800   // VPSHUFB may be generated if
6801   // (1) one of input vector is undefined or zeroinitializer.
6802   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6803   // And (2) the mask indexes don't cross the 128-bit lane.
6804   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6805       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6806     return SDValue();
6807
6808   if (V1IsAllZero && !V2IsAllZero) {
6809     CommuteVectorShuffleMask(MaskVals, 32);
6810     V1 = V2;
6811   }
6812   return getPSHUFB(MaskVals, V1, dl, DAG);
6813 }
6814
6815 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6816 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6817 /// done when every pair / quad of shuffle mask elements point to elements in
6818 /// the right sequence. e.g.
6819 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6820 static
6821 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6822                                  SelectionDAG &DAG) {
6823   MVT VT = SVOp->getSimpleValueType(0);
6824   SDLoc dl(SVOp);
6825   unsigned NumElems = VT.getVectorNumElements();
6826   MVT NewVT;
6827   unsigned Scale;
6828   switch (VT.SimpleTy) {
6829   default: llvm_unreachable("Unexpected!");
6830   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6831   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6832   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6833   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6834   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6835   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6836   }
6837
6838   SmallVector<int, 8> MaskVec;
6839   for (unsigned i = 0; i != NumElems; i += Scale) {
6840     int StartIdx = -1;
6841     for (unsigned j = 0; j != Scale; ++j) {
6842       int EltIdx = SVOp->getMaskElt(i+j);
6843       if (EltIdx < 0)
6844         continue;
6845       if (StartIdx < 0)
6846         StartIdx = (EltIdx / Scale);
6847       if (EltIdx != (int)(StartIdx*Scale + j))
6848         return SDValue();
6849     }
6850     MaskVec.push_back(StartIdx);
6851   }
6852
6853   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6854   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6855   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6856 }
6857
6858 /// getVZextMovL - Return a zero-extending vector move low node.
6859 ///
6860 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6861                             SDValue SrcOp, SelectionDAG &DAG,
6862                             const X86Subtarget *Subtarget, SDLoc dl) {
6863   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6864     LoadSDNode *LD = NULL;
6865     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6866       LD = dyn_cast<LoadSDNode>(SrcOp);
6867     if (!LD) {
6868       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6869       // instead.
6870       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6871       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6872           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6873           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6874           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6875         // PR2108
6876         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6877         return DAG.getNode(ISD::BITCAST, dl, VT,
6878                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6879                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6880                                                    OpVT,
6881                                                    SrcOp.getOperand(0)
6882                                                           .getOperand(0))));
6883       }
6884     }
6885   }
6886
6887   return DAG.getNode(ISD::BITCAST, dl, VT,
6888                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6889                                  DAG.getNode(ISD::BITCAST, dl,
6890                                              OpVT, SrcOp)));
6891 }
6892
6893 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6894 /// which could not be matched by any known target speficic shuffle
6895 static SDValue
6896 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6897
6898   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6899   if (NewOp.getNode())
6900     return NewOp;
6901
6902   MVT VT = SVOp->getSimpleValueType(0);
6903
6904   unsigned NumElems = VT.getVectorNumElements();
6905   unsigned NumLaneElems = NumElems / 2;
6906
6907   SDLoc dl(SVOp);
6908   MVT EltVT = VT.getVectorElementType();
6909   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6910   SDValue Output[2];
6911
6912   SmallVector<int, 16> Mask;
6913   for (unsigned l = 0; l < 2; ++l) {
6914     // Build a shuffle mask for the output, discovering on the fly which
6915     // input vectors to use as shuffle operands (recorded in InputUsed).
6916     // If building a suitable shuffle vector proves too hard, then bail
6917     // out with UseBuildVector set.
6918     bool UseBuildVector = false;
6919     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6920     unsigned LaneStart = l * NumLaneElems;
6921     for (unsigned i = 0; i != NumLaneElems; ++i) {
6922       // The mask element.  This indexes into the input.
6923       int Idx = SVOp->getMaskElt(i+LaneStart);
6924       if (Idx < 0) {
6925         // the mask element does not index into any input vector.
6926         Mask.push_back(-1);
6927         continue;
6928       }
6929
6930       // The input vector this mask element indexes into.
6931       int Input = Idx / NumLaneElems;
6932
6933       // Turn the index into an offset from the start of the input vector.
6934       Idx -= Input * NumLaneElems;
6935
6936       // Find or create a shuffle vector operand to hold this input.
6937       unsigned OpNo;
6938       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6939         if (InputUsed[OpNo] == Input)
6940           // This input vector is already an operand.
6941           break;
6942         if (InputUsed[OpNo] < 0) {
6943           // Create a new operand for this input vector.
6944           InputUsed[OpNo] = Input;
6945           break;
6946         }
6947       }
6948
6949       if (OpNo >= array_lengthof(InputUsed)) {
6950         // More than two input vectors used!  Give up on trying to create a
6951         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6952         UseBuildVector = true;
6953         break;
6954       }
6955
6956       // Add the mask index for the new shuffle vector.
6957       Mask.push_back(Idx + OpNo * NumLaneElems);
6958     }
6959
6960     if (UseBuildVector) {
6961       SmallVector<SDValue, 16> SVOps;
6962       for (unsigned i = 0; i != NumLaneElems; ++i) {
6963         // The mask element.  This indexes into the input.
6964         int Idx = SVOp->getMaskElt(i+LaneStart);
6965         if (Idx < 0) {
6966           SVOps.push_back(DAG.getUNDEF(EltVT));
6967           continue;
6968         }
6969
6970         // The input vector this mask element indexes into.
6971         int Input = Idx / NumElems;
6972
6973         // Turn the index into an offset from the start of the input vector.
6974         Idx -= Input * NumElems;
6975
6976         // Extract the vector element by hand.
6977         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6978                                     SVOp->getOperand(Input),
6979                                     DAG.getIntPtrConstant(Idx)));
6980       }
6981
6982       // Construct the output using a BUILD_VECTOR.
6983       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6984                               SVOps.size());
6985     } else if (InputUsed[0] < 0) {
6986       // No input vectors were used! The result is undefined.
6987       Output[l] = DAG.getUNDEF(NVT);
6988     } else {
6989       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6990                                         (InputUsed[0] % 2) * NumLaneElems,
6991                                         DAG, dl);
6992       // If only one input was used, use an undefined vector for the other.
6993       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6994         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6995                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6996       // At least one input vector was used. Create a new shuffle vector.
6997       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6998     }
6999
7000     Mask.clear();
7001   }
7002
7003   // Concatenate the result back
7004   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7005 }
7006
7007 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7008 /// 4 elements, and match them with several different shuffle types.
7009 static SDValue
7010 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7011   SDValue V1 = SVOp->getOperand(0);
7012   SDValue V2 = SVOp->getOperand(1);
7013   SDLoc dl(SVOp);
7014   MVT VT = SVOp->getSimpleValueType(0);
7015
7016   assert(VT.is128BitVector() && "Unsupported vector size");
7017
7018   std::pair<int, int> Locs[4];
7019   int Mask1[] = { -1, -1, -1, -1 };
7020   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7021
7022   unsigned NumHi = 0;
7023   unsigned NumLo = 0;
7024   for (unsigned i = 0; i != 4; ++i) {
7025     int Idx = PermMask[i];
7026     if (Idx < 0) {
7027       Locs[i] = std::make_pair(-1, -1);
7028     } else {
7029       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7030       if (Idx < 4) {
7031         Locs[i] = std::make_pair(0, NumLo);
7032         Mask1[NumLo] = Idx;
7033         NumLo++;
7034       } else {
7035         Locs[i] = std::make_pair(1, NumHi);
7036         if (2+NumHi < 4)
7037           Mask1[2+NumHi] = Idx;
7038         NumHi++;
7039       }
7040     }
7041   }
7042
7043   if (NumLo <= 2 && NumHi <= 2) {
7044     // If no more than two elements come from either vector. This can be
7045     // implemented with two shuffles. First shuffle gather the elements.
7046     // The second shuffle, which takes the first shuffle as both of its
7047     // vector operands, put the elements into the right order.
7048     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7049
7050     int Mask2[] = { -1, -1, -1, -1 };
7051
7052     for (unsigned i = 0; i != 4; ++i)
7053       if (Locs[i].first != -1) {
7054         unsigned Idx = (i < 2) ? 0 : 4;
7055         Idx += Locs[i].first * 2 + Locs[i].second;
7056         Mask2[i] = Idx;
7057       }
7058
7059     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7060   }
7061
7062   if (NumLo == 3 || NumHi == 3) {
7063     // Otherwise, we must have three elements from one vector, call it X, and
7064     // one element from the other, call it Y.  First, use a shufps to build an
7065     // intermediate vector with the one element from Y and the element from X
7066     // that will be in the same half in the final destination (the indexes don't
7067     // matter). Then, use a shufps to build the final vector, taking the half
7068     // containing the element from Y from the intermediate, and the other half
7069     // from X.
7070     if (NumHi == 3) {
7071       // Normalize it so the 3 elements come from V1.
7072       CommuteVectorShuffleMask(PermMask, 4);
7073       std::swap(V1, V2);
7074     }
7075
7076     // Find the element from V2.
7077     unsigned HiIndex;
7078     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7079       int Val = PermMask[HiIndex];
7080       if (Val < 0)
7081         continue;
7082       if (Val >= 4)
7083         break;
7084     }
7085
7086     Mask1[0] = PermMask[HiIndex];
7087     Mask1[1] = -1;
7088     Mask1[2] = PermMask[HiIndex^1];
7089     Mask1[3] = -1;
7090     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7091
7092     if (HiIndex >= 2) {
7093       Mask1[0] = PermMask[0];
7094       Mask1[1] = PermMask[1];
7095       Mask1[2] = HiIndex & 1 ? 6 : 4;
7096       Mask1[3] = HiIndex & 1 ? 4 : 6;
7097       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7098     }
7099
7100     Mask1[0] = HiIndex & 1 ? 2 : 0;
7101     Mask1[1] = HiIndex & 1 ? 0 : 2;
7102     Mask1[2] = PermMask[2];
7103     Mask1[3] = PermMask[3];
7104     if (Mask1[2] >= 0)
7105       Mask1[2] += 4;
7106     if (Mask1[3] >= 0)
7107       Mask1[3] += 4;
7108     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7109   }
7110
7111   // Break it into (shuffle shuffle_hi, shuffle_lo).
7112   int LoMask[] = { -1, -1, -1, -1 };
7113   int HiMask[] = { -1, -1, -1, -1 };
7114
7115   int *MaskPtr = LoMask;
7116   unsigned MaskIdx = 0;
7117   unsigned LoIdx = 0;
7118   unsigned HiIdx = 2;
7119   for (unsigned i = 0; i != 4; ++i) {
7120     if (i == 2) {
7121       MaskPtr = HiMask;
7122       MaskIdx = 1;
7123       LoIdx = 0;
7124       HiIdx = 2;
7125     }
7126     int Idx = PermMask[i];
7127     if (Idx < 0) {
7128       Locs[i] = std::make_pair(-1, -1);
7129     } else if (Idx < 4) {
7130       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7131       MaskPtr[LoIdx] = Idx;
7132       LoIdx++;
7133     } else {
7134       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7135       MaskPtr[HiIdx] = Idx;
7136       HiIdx++;
7137     }
7138   }
7139
7140   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7141   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7142   int MaskOps[] = { -1, -1, -1, -1 };
7143   for (unsigned i = 0; i != 4; ++i)
7144     if (Locs[i].first != -1)
7145       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7146   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7147 }
7148
7149 static bool MayFoldVectorLoad(SDValue V) {
7150   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7151     V = V.getOperand(0);
7152
7153   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7154     V = V.getOperand(0);
7155   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7156       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7157     // BUILD_VECTOR (load), undef
7158     V = V.getOperand(0);
7159
7160   return MayFoldLoad(V);
7161 }
7162
7163 static
7164 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7165   MVT VT = Op.getSimpleValueType();
7166
7167   // Canonizalize to v2f64.
7168   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7169   return DAG.getNode(ISD::BITCAST, dl, VT,
7170                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7171                                           V1, DAG));
7172 }
7173
7174 static
7175 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7176                         bool HasSSE2) {
7177   SDValue V1 = Op.getOperand(0);
7178   SDValue V2 = Op.getOperand(1);
7179   MVT VT = Op.getSimpleValueType();
7180
7181   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7182
7183   if (HasSSE2 && VT == MVT::v2f64)
7184     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7185
7186   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7187   return DAG.getNode(ISD::BITCAST, dl, VT,
7188                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7189                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7190                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7191 }
7192
7193 static
7194 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7195   SDValue V1 = Op.getOperand(0);
7196   SDValue V2 = Op.getOperand(1);
7197   MVT VT = Op.getSimpleValueType();
7198
7199   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7200          "unsupported shuffle type");
7201
7202   if (V2.getOpcode() == ISD::UNDEF)
7203     V2 = V1;
7204
7205   // v4i32 or v4f32
7206   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7207 }
7208
7209 static
7210 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7211   SDValue V1 = Op.getOperand(0);
7212   SDValue V2 = Op.getOperand(1);
7213   MVT VT = Op.getSimpleValueType();
7214   unsigned NumElems = VT.getVectorNumElements();
7215
7216   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7217   // operand of these instructions is only memory, so check if there's a
7218   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7219   // same masks.
7220   bool CanFoldLoad = false;
7221
7222   // Trivial case, when V2 comes from a load.
7223   if (MayFoldVectorLoad(V2))
7224     CanFoldLoad = true;
7225
7226   // When V1 is a load, it can be folded later into a store in isel, example:
7227   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7228   //    turns into:
7229   //  (MOVLPSmr addr:$src1, VR128:$src2)
7230   // So, recognize this potential and also use MOVLPS or MOVLPD
7231   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7232     CanFoldLoad = true;
7233
7234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7235   if (CanFoldLoad) {
7236     if (HasSSE2 && NumElems == 2)
7237       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7238
7239     if (NumElems == 4)
7240       // If we don't care about the second element, proceed to use movss.
7241       if (SVOp->getMaskElt(1) != -1)
7242         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7243   }
7244
7245   // movl and movlp will both match v2i64, but v2i64 is never matched by
7246   // movl earlier because we make it strict to avoid messing with the movlp load
7247   // folding logic (see the code above getMOVLP call). Match it here then,
7248   // this is horrible, but will stay like this until we move all shuffle
7249   // matching to x86 specific nodes. Note that for the 1st condition all
7250   // types are matched with movsd.
7251   if (HasSSE2) {
7252     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7253     // as to remove this logic from here, as much as possible
7254     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7255       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7256     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7257   }
7258
7259   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7260
7261   // Invert the operand order and use SHUFPS to match it.
7262   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7263                               getShuffleSHUFImmediate(SVOp), DAG);
7264 }
7265
7266 // Reduce a vector shuffle to zext.
7267 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7268                                     SelectionDAG &DAG) {
7269   // PMOVZX is only available from SSE41.
7270   if (!Subtarget->hasSSE41())
7271     return SDValue();
7272
7273   MVT VT = Op.getSimpleValueType();
7274
7275   // Only AVX2 support 256-bit vector integer extending.
7276   if (!Subtarget->hasInt256() && VT.is256BitVector())
7277     return SDValue();
7278
7279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7280   SDLoc DL(Op);
7281   SDValue V1 = Op.getOperand(0);
7282   SDValue V2 = Op.getOperand(1);
7283   unsigned NumElems = VT.getVectorNumElements();
7284
7285   // Extending is an unary operation and the element type of the source vector
7286   // won't be equal to or larger than i64.
7287   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7288       VT.getVectorElementType() == MVT::i64)
7289     return SDValue();
7290
7291   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7292   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7293   while ((1U << Shift) < NumElems) {
7294     if (SVOp->getMaskElt(1U << Shift) == 1)
7295       break;
7296     Shift += 1;
7297     // The maximal ratio is 8, i.e. from i8 to i64.
7298     if (Shift > 3)
7299       return SDValue();
7300   }
7301
7302   // Check the shuffle mask.
7303   unsigned Mask = (1U << Shift) - 1;
7304   for (unsigned i = 0; i != NumElems; ++i) {
7305     int EltIdx = SVOp->getMaskElt(i);
7306     if ((i & Mask) != 0 && EltIdx != -1)
7307       return SDValue();
7308     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7309       return SDValue();
7310   }
7311
7312   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7313   MVT NeVT = MVT::getIntegerVT(NBits);
7314   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7315
7316   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7317     return SDValue();
7318
7319   // Simplify the operand as it's prepared to be fed into shuffle.
7320   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7321   if (V1.getOpcode() == ISD::BITCAST &&
7322       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7323       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7324       V1.getOperand(0).getOperand(0)
7325         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7326     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7327     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7328     ConstantSDNode *CIdx =
7329       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7330     // If it's foldable, i.e. normal load with single use, we will let code
7331     // selection to fold it. Otherwise, we will short the conversion sequence.
7332     if (CIdx && CIdx->getZExtValue() == 0 &&
7333         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7334       MVT FullVT = V.getSimpleValueType();
7335       MVT V1VT = V1.getSimpleValueType();
7336       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7337         // The "ext_vec_elt" node is wider than the result node.
7338         // In this case we should extract subvector from V.
7339         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7340         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7341         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7342                                         FullVT.getVectorNumElements()/Ratio);
7343         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7344                         DAG.getIntPtrConstant(0));
7345       }
7346       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7347     }
7348   }
7349
7350   return DAG.getNode(ISD::BITCAST, DL, VT,
7351                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7352 }
7353
7354 static SDValue
7355 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7356                        SelectionDAG &DAG) {
7357   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7358   MVT VT = Op.getSimpleValueType();
7359   SDLoc dl(Op);
7360   SDValue V1 = Op.getOperand(0);
7361   SDValue V2 = Op.getOperand(1);
7362
7363   if (isZeroShuffle(SVOp))
7364     return getZeroVector(VT, Subtarget, DAG, dl);
7365
7366   // Handle splat operations
7367   if (SVOp->isSplat()) {
7368     // Use vbroadcast whenever the splat comes from a foldable load
7369     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7370     if (Broadcast.getNode())
7371       return Broadcast;
7372   }
7373
7374   // Check integer expanding shuffles.
7375   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7376   if (NewOp.getNode())
7377     return NewOp;
7378
7379   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7380   // do it!
7381   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7382       VT == MVT::v16i16 || VT == MVT::v32i8) {
7383     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7384     if (NewOp.getNode())
7385       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7386   } else if ((VT == MVT::v4i32 ||
7387              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7388     // FIXME: Figure out a cleaner way to do this.
7389     // Try to make use of movq to zero out the top part.
7390     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7391       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7392       if (NewOp.getNode()) {
7393         MVT NewVT = NewOp.getSimpleValueType();
7394         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7395                                NewVT, true, false))
7396           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7397                               DAG, Subtarget, dl);
7398       }
7399     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7400       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7401       if (NewOp.getNode()) {
7402         MVT NewVT = NewOp.getSimpleValueType();
7403         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7404           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7405                               DAG, Subtarget, dl);
7406       }
7407     }
7408   }
7409   return SDValue();
7410 }
7411
7412 SDValue
7413 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7414   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7415   SDValue V1 = Op.getOperand(0);
7416   SDValue V2 = Op.getOperand(1);
7417   MVT VT = Op.getSimpleValueType();
7418   SDLoc dl(Op);
7419   unsigned NumElems = VT.getVectorNumElements();
7420   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7421   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7422   bool V1IsSplat = false;
7423   bool V2IsSplat = false;
7424   bool HasSSE2 = Subtarget->hasSSE2();
7425   bool HasFp256    = Subtarget->hasFp256();
7426   bool HasInt256   = Subtarget->hasInt256();
7427   MachineFunction &MF = DAG.getMachineFunction();
7428   bool OptForSize = MF.getFunction()->getAttributes().
7429     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7430
7431   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7432
7433   if (V1IsUndef && V2IsUndef)
7434     return DAG.getUNDEF(VT);
7435
7436   // When we create a shuffle node we put the UNDEF node to second operand,
7437   // but in some cases the first operand may be transformed to UNDEF.
7438   // In this case we should just commute the node.
7439   if (V1IsUndef)
7440     return CommuteVectorShuffle(SVOp, DAG);
7441
7442   // Vector shuffle lowering takes 3 steps:
7443   //
7444   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7445   //    narrowing and commutation of operands should be handled.
7446   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7447   //    shuffle nodes.
7448   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7449   //    so the shuffle can be broken into other shuffles and the legalizer can
7450   //    try the lowering again.
7451   //
7452   // The general idea is that no vector_shuffle operation should be left to
7453   // be matched during isel, all of them must be converted to a target specific
7454   // node here.
7455
7456   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7457   // narrowing and commutation of operands should be handled. The actual code
7458   // doesn't include all of those, work in progress...
7459   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7460   if (NewOp.getNode())
7461     return NewOp;
7462
7463   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7464
7465   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7466   // unpckh_undef). Only use pshufd if speed is more important than size.
7467   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7468     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7469   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7470     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7471
7472   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7473       V2IsUndef && MayFoldVectorLoad(V1))
7474     return getMOVDDup(Op, dl, V1, DAG);
7475
7476   if (isMOVHLPS_v_undef_Mask(M, VT))
7477     return getMOVHighToLow(Op, dl, DAG);
7478
7479   // Use to match splats
7480   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7481       (VT == MVT::v2f64 || VT == MVT::v2i64))
7482     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7483
7484   if (isPSHUFDMask(M, VT)) {
7485     // The actual implementation will match the mask in the if above and then
7486     // during isel it can match several different instructions, not only pshufd
7487     // as its name says, sad but true, emulate the behavior for now...
7488     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7489       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7490
7491     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7492
7493     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7494       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7495
7496     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7497       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7498                                   DAG);
7499
7500     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7501                                 TargetMask, DAG);
7502   }
7503
7504   if (isPALIGNRMask(M, VT, Subtarget))
7505     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7506                                 getShufflePALIGNRImmediate(SVOp),
7507                                 DAG);
7508
7509   // Check if this can be converted into a logical shift.
7510   bool isLeft = false;
7511   unsigned ShAmt = 0;
7512   SDValue ShVal;
7513   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7514   if (isShift && ShVal.hasOneUse()) {
7515     // If the shifted value has multiple uses, it may be cheaper to use
7516     // v_set0 + movlhps or movhlps, etc.
7517     MVT EltVT = VT.getVectorElementType();
7518     ShAmt *= EltVT.getSizeInBits();
7519     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7520   }
7521
7522   if (isMOVLMask(M, VT)) {
7523     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7524       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7525     if (!isMOVLPMask(M, VT)) {
7526       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7527         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7528
7529       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7530         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7531     }
7532   }
7533
7534   // FIXME: fold these into legal mask.
7535   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7536     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7537
7538   if (isMOVHLPSMask(M, VT))
7539     return getMOVHighToLow(Op, dl, DAG);
7540
7541   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7542     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7543
7544   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7545     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7546
7547   if (isMOVLPMask(M, VT))
7548     return getMOVLP(Op, dl, DAG, HasSSE2);
7549
7550   if (ShouldXformToMOVHLPS(M, VT) ||
7551       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7552     return CommuteVectorShuffle(SVOp, DAG);
7553
7554   if (isShift) {
7555     // No better options. Use a vshldq / vsrldq.
7556     MVT EltVT = VT.getVectorElementType();
7557     ShAmt *= EltVT.getSizeInBits();
7558     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7559   }
7560
7561   bool Commuted = false;
7562   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7563   // 1,1,1,1 -> v8i16 though.
7564   V1IsSplat = isSplatVector(V1.getNode());
7565   V2IsSplat = isSplatVector(V2.getNode());
7566
7567   // Canonicalize the splat or undef, if present, to be on the RHS.
7568   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7569     CommuteVectorShuffleMask(M, NumElems);
7570     std::swap(V1, V2);
7571     std::swap(V1IsSplat, V2IsSplat);
7572     Commuted = true;
7573   }
7574
7575   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7576     // Shuffling low element of v1 into undef, just return v1.
7577     if (V2IsUndef)
7578       return V1;
7579     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7580     // the instruction selector will not match, so get a canonical MOVL with
7581     // swapped operands to undo the commute.
7582     return getMOVL(DAG, dl, VT, V2, V1);
7583   }
7584
7585   if (isUNPCKLMask(M, VT, HasInt256))
7586     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7587
7588   if (isUNPCKHMask(M, VT, HasInt256))
7589     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7590
7591   if (V2IsSplat) {
7592     // Normalize mask so all entries that point to V2 points to its first
7593     // element then try to match unpck{h|l} again. If match, return a
7594     // new vector_shuffle with the corrected mask.p
7595     SmallVector<int, 8> NewMask(M.begin(), M.end());
7596     NormalizeMask(NewMask, NumElems);
7597     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7598       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7599     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7600       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7601   }
7602
7603   if (Commuted) {
7604     // Commute is back and try unpck* again.
7605     // FIXME: this seems wrong.
7606     CommuteVectorShuffleMask(M, NumElems);
7607     std::swap(V1, V2);
7608     std::swap(V1IsSplat, V2IsSplat);
7609
7610     if (isUNPCKLMask(M, VT, HasInt256))
7611       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7612
7613     if (isUNPCKHMask(M, VT, HasInt256))
7614       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7615   }
7616
7617   // Normalize the node to match x86 shuffle ops if needed
7618   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7619     return CommuteVectorShuffle(SVOp, DAG);
7620
7621   // The checks below are all present in isShuffleMaskLegal, but they are
7622   // inlined here right now to enable us to directly emit target specific
7623   // nodes, and remove one by one until they don't return Op anymore.
7624
7625   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7626       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7627     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7628       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7629   }
7630
7631   if (isPSHUFHWMask(M, VT, HasInt256))
7632     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7633                                 getShufflePSHUFHWImmediate(SVOp),
7634                                 DAG);
7635
7636   if (isPSHUFLWMask(M, VT, HasInt256))
7637     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7638                                 getShufflePSHUFLWImmediate(SVOp),
7639                                 DAG);
7640
7641   if (isSHUFPMask(M, VT))
7642     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7643                                 getShuffleSHUFImmediate(SVOp), DAG);
7644
7645   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7646     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7647   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7648     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7649
7650   //===--------------------------------------------------------------------===//
7651   // Generate target specific nodes for 128 or 256-bit shuffles only
7652   // supported in the AVX instruction set.
7653   //
7654
7655   // Handle VMOVDDUPY permutations
7656   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7657     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7658
7659   // Handle VPERMILPS/D* permutations
7660   if (isVPERMILPMask(M, VT)) {
7661     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7662       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7663                                   getShuffleSHUFImmediate(SVOp), DAG);
7664     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7665                                 getShuffleSHUFImmediate(SVOp), DAG);
7666   }
7667
7668   // Handle VPERM2F128/VPERM2I128 permutations
7669   if (isVPERM2X128Mask(M, VT, HasFp256))
7670     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7671                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7672
7673   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7674   if (BlendOp.getNode())
7675     return BlendOp;
7676
7677   unsigned Imm8;
7678   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7679     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7680
7681   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7682       VT.is512BitVector()) {
7683     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7684     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7685     SmallVector<SDValue, 16> permclMask;
7686     for (unsigned i = 0; i != NumElems; ++i) {
7687       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7688     }
7689
7690     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7691                                 &permclMask[0], NumElems);
7692     if (V2IsUndef)
7693       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7694       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7695                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7696     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7697                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7698   }
7699
7700   //===--------------------------------------------------------------------===//
7701   // Since no target specific shuffle was selected for this generic one,
7702   // lower it into other known shuffles. FIXME: this isn't true yet, but
7703   // this is the plan.
7704   //
7705
7706   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7707   if (VT == MVT::v8i16) {
7708     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7709     if (NewOp.getNode())
7710       return NewOp;
7711   }
7712
7713   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7714     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7715     if (NewOp.getNode())
7716       return NewOp;
7717   }
7718
7719   if (VT == MVT::v16i8) {
7720     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7721     if (NewOp.getNode())
7722       return NewOp;
7723   }
7724
7725   if (VT == MVT::v32i8) {
7726     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7727     if (NewOp.getNode())
7728       return NewOp;
7729   }
7730
7731   // Handle all 128-bit wide vectors with 4 elements, and match them with
7732   // several different shuffle types.
7733   if (NumElems == 4 && VT.is128BitVector())
7734     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7735
7736   // Handle general 256-bit shuffles
7737   if (VT.is256BitVector())
7738     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7739
7740   return SDValue();
7741 }
7742
7743 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7744   MVT VT = Op.getSimpleValueType();
7745   SDLoc dl(Op);
7746
7747   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7748     return SDValue();
7749
7750   if (VT.getSizeInBits() == 8) {
7751     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7752                                   Op.getOperand(0), Op.getOperand(1));
7753     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7754                                   DAG.getValueType(VT));
7755     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7756   }
7757
7758   if (VT.getSizeInBits() == 16) {
7759     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7760     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7761     if (Idx == 0)
7762       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7763                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7764                                      DAG.getNode(ISD::BITCAST, dl,
7765                                                  MVT::v4i32,
7766                                                  Op.getOperand(0)),
7767                                      Op.getOperand(1)));
7768     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7769                                   Op.getOperand(0), Op.getOperand(1));
7770     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7771                                   DAG.getValueType(VT));
7772     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7773   }
7774
7775   if (VT == MVT::f32) {
7776     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7777     // the result back to FR32 register. It's only worth matching if the
7778     // result has a single use which is a store or a bitcast to i32.  And in
7779     // the case of a store, it's not worth it if the index is a constant 0,
7780     // because a MOVSSmr can be used instead, which is smaller and faster.
7781     if (!Op.hasOneUse())
7782       return SDValue();
7783     SDNode *User = *Op.getNode()->use_begin();
7784     if ((User->getOpcode() != ISD::STORE ||
7785          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7786           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7787         (User->getOpcode() != ISD::BITCAST ||
7788          User->getValueType(0) != MVT::i32))
7789       return SDValue();
7790     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7791                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7792                                               Op.getOperand(0)),
7793                                               Op.getOperand(1));
7794     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7795   }
7796
7797   if (VT == MVT::i32 || VT == MVT::i64) {
7798     // ExtractPS/pextrq works with constant index.
7799     if (isa<ConstantSDNode>(Op.getOperand(1)))
7800       return Op;
7801   }
7802   return SDValue();
7803 }
7804
7805 /// Extract one bit from mask vector, like v16i1 or v8i1.
7806 /// AVX-512 feature.
7807 SDValue
7808 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7809   SDValue Vec = Op.getOperand(0);
7810   SDLoc dl(Vec);
7811   MVT VecVT = Vec.getSimpleValueType();
7812   SDValue Idx = Op.getOperand(1);
7813   MVT EltVT = Op.getSimpleValueType();
7814
7815   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7816
7817   // variable index can't be handled in mask registers,
7818   // extend vector to VR512
7819   if (!isa<ConstantSDNode>(Idx)) {
7820     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7821     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7822     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7823                               ExtVT.getVectorElementType(), Ext, Idx);
7824     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7825   }
7826
7827   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7828   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7829   unsigned MaxSift = rc->getSize()*8 - 1;
7830   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7831                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7832   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7833                     DAG.getConstant(MaxSift, MVT::i8));
7834   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7835                        DAG.getIntPtrConstant(0));
7836 }
7837
7838 SDValue
7839 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7840                                            SelectionDAG &DAG) const {
7841   SDLoc dl(Op);
7842   SDValue Vec = Op.getOperand(0);
7843   MVT VecVT = Vec.getSimpleValueType();
7844   SDValue Idx = Op.getOperand(1);
7845
7846   if (Op.getSimpleValueType() == MVT::i1)
7847     return ExtractBitFromMaskVector(Op, DAG);
7848
7849   if (!isa<ConstantSDNode>(Idx)) {
7850     if (VecVT.is512BitVector() ||
7851         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7852          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7853
7854       MVT MaskEltVT =
7855         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7856       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7857                                     MaskEltVT.getSizeInBits());
7858
7859       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7860       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7861                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7862                                 Idx, DAG.getConstant(0, getPointerTy()));
7863       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7864       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7865                         Perm, DAG.getConstant(0, getPointerTy()));
7866     }
7867     return SDValue();
7868   }
7869
7870   // If this is a 256-bit vector result, first extract the 128-bit vector and
7871   // then extract the element from the 128-bit vector.
7872   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7873
7874     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7875     // Get the 128-bit vector.
7876     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7877     MVT EltVT = VecVT.getVectorElementType();
7878
7879     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7880
7881     //if (IdxVal >= NumElems/2)
7882     //  IdxVal -= NumElems/2;
7883     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7884     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7885                        DAG.getConstant(IdxVal, MVT::i32));
7886   }
7887
7888   assert(VecVT.is128BitVector() && "Unexpected vector length");
7889
7890   if (Subtarget->hasSSE41()) {
7891     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7892     if (Res.getNode())
7893       return Res;
7894   }
7895
7896   MVT VT = Op.getSimpleValueType();
7897   // TODO: handle v16i8.
7898   if (VT.getSizeInBits() == 16) {
7899     SDValue Vec = Op.getOperand(0);
7900     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7901     if (Idx == 0)
7902       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7903                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7904                                      DAG.getNode(ISD::BITCAST, dl,
7905                                                  MVT::v4i32, Vec),
7906                                      Op.getOperand(1)));
7907     // Transform it so it match pextrw which produces a 32-bit result.
7908     MVT EltVT = MVT::i32;
7909     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7910                                   Op.getOperand(0), Op.getOperand(1));
7911     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7912                                   DAG.getValueType(VT));
7913     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7914   }
7915
7916   if (VT.getSizeInBits() == 32) {
7917     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7918     if (Idx == 0)
7919       return Op;
7920
7921     // SHUFPS the element to the lowest double word, then movss.
7922     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7923     MVT VVT = Op.getOperand(0).getSimpleValueType();
7924     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7925                                        DAG.getUNDEF(VVT), Mask);
7926     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7927                        DAG.getIntPtrConstant(0));
7928   }
7929
7930   if (VT.getSizeInBits() == 64) {
7931     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7932     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7933     //        to match extract_elt for f64.
7934     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7935     if (Idx == 0)
7936       return Op;
7937
7938     // UNPCKHPD the element to the lowest double word, then movsd.
7939     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7940     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7941     int Mask[2] = { 1, -1 };
7942     MVT VVT = Op.getOperand(0).getSimpleValueType();
7943     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7944                                        DAG.getUNDEF(VVT), Mask);
7945     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7946                        DAG.getIntPtrConstant(0));
7947   }
7948
7949   return SDValue();
7950 }
7951
7952 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7953   MVT VT = Op.getSimpleValueType();
7954   MVT EltVT = VT.getVectorElementType();
7955   SDLoc dl(Op);
7956
7957   SDValue N0 = Op.getOperand(0);
7958   SDValue N1 = Op.getOperand(1);
7959   SDValue N2 = Op.getOperand(2);
7960
7961   if (!VT.is128BitVector())
7962     return SDValue();
7963
7964   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7965       isa<ConstantSDNode>(N2)) {
7966     unsigned Opc;
7967     if (VT == MVT::v8i16)
7968       Opc = X86ISD::PINSRW;
7969     else if (VT == MVT::v16i8)
7970       Opc = X86ISD::PINSRB;
7971     else
7972       Opc = X86ISD::PINSRB;
7973
7974     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7975     // argument.
7976     if (N1.getValueType() != MVT::i32)
7977       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7978     if (N2.getValueType() != MVT::i32)
7979       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7980     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7981   }
7982
7983   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7984     // Bits [7:6] of the constant are the source select.  This will always be
7985     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7986     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7987     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7988     // Bits [5:4] of the constant are the destination select.  This is the
7989     //  value of the incoming immediate.
7990     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7991     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7992     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7993     // Create this as a scalar to vector..
7994     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7995     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7996   }
7997
7998   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7999     // PINSR* works with constant index.
8000     return Op;
8001   }
8002   return SDValue();
8003 }
8004
8005 /// Insert one bit to mask vector, like v16i1 or v8i1.
8006 /// AVX-512 feature.
8007 SDValue 
8008 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8009   SDLoc dl(Op);
8010   SDValue Vec = Op.getOperand(0);
8011   SDValue Elt = Op.getOperand(1);
8012   SDValue Idx = Op.getOperand(2);
8013   MVT VecVT = Vec.getSimpleValueType();
8014
8015   if (!isa<ConstantSDNode>(Idx)) {
8016     // Non constant index. Extend source and destination,
8017     // insert element and then truncate the result.
8018     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8019     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8020     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8021       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8022       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8023     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8024   }
8025
8026   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8027   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8028   if (Vec.getOpcode() == ISD::UNDEF)
8029     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8030                        DAG.getConstant(IdxVal, MVT::i8));
8031   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8032   unsigned MaxSift = rc->getSize()*8 - 1;
8033   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8034                     DAG.getConstant(MaxSift, MVT::i8));
8035   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8036                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8037   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8038 }
8039 SDValue
8040 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8041   MVT VT = Op.getSimpleValueType();
8042   MVT EltVT = VT.getVectorElementType();
8043   
8044   if (EltVT == MVT::i1)
8045     return InsertBitToMaskVector(Op, DAG);
8046
8047   SDLoc dl(Op);
8048   SDValue N0 = Op.getOperand(0);
8049   SDValue N1 = Op.getOperand(1);
8050   SDValue N2 = Op.getOperand(2);
8051
8052   // If this is a 256-bit vector result, first extract the 128-bit vector,
8053   // insert the element into the extracted half and then place it back.
8054   if (VT.is256BitVector() || VT.is512BitVector()) {
8055     if (!isa<ConstantSDNode>(N2))
8056       return SDValue();
8057
8058     // Get the desired 128-bit vector half.
8059     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8060     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8061
8062     // Insert the element into the desired half.
8063     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8064     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8065
8066     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8067                     DAG.getConstant(IdxIn128, MVT::i32));
8068
8069     // Insert the changed part back to the 256-bit vector
8070     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8071   }
8072
8073   if (Subtarget->hasSSE41())
8074     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8075
8076   if (EltVT == MVT::i8)
8077     return SDValue();
8078
8079   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8080     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8081     // as its second argument.
8082     if (N1.getValueType() != MVT::i32)
8083       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8084     if (N2.getValueType() != MVT::i32)
8085       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8086     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8087   }
8088   return SDValue();
8089 }
8090
8091 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8092   SDLoc dl(Op);
8093   MVT OpVT = Op.getSimpleValueType();
8094
8095   // If this is a 256-bit vector result, first insert into a 128-bit
8096   // vector and then insert into the 256-bit vector.
8097   if (!OpVT.is128BitVector()) {
8098     // Insert into a 128-bit vector.
8099     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8100     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8101                                  OpVT.getVectorNumElements() / SizeFactor);
8102
8103     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8104
8105     // Insert the 128-bit vector.
8106     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8107   }
8108
8109   if (OpVT == MVT::v1i64 &&
8110       Op.getOperand(0).getValueType() == MVT::i64)
8111     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8112
8113   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8114   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8115   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8116                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8117 }
8118
8119 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8120 // a simple subregister reference or explicit instructions to grab
8121 // upper bits of a vector.
8122 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8123                                       SelectionDAG &DAG) {
8124   SDLoc dl(Op);
8125   SDValue In =  Op.getOperand(0);
8126   SDValue Idx = Op.getOperand(1);
8127   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8128   MVT ResVT   = Op.getSimpleValueType();
8129   MVT InVT    = In.getSimpleValueType();
8130
8131   if (Subtarget->hasFp256()) {
8132     if (ResVT.is128BitVector() &&
8133         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8134         isa<ConstantSDNode>(Idx)) {
8135       return Extract128BitVector(In, IdxVal, DAG, dl);
8136     }
8137     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8138         isa<ConstantSDNode>(Idx)) {
8139       return Extract256BitVector(In, IdxVal, DAG, dl);
8140     }
8141   }
8142   return SDValue();
8143 }
8144
8145 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8146 // simple superregister reference or explicit instructions to insert
8147 // the upper bits of a vector.
8148 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8149                                      SelectionDAG &DAG) {
8150   if (Subtarget->hasFp256()) {
8151     SDLoc dl(Op.getNode());
8152     SDValue Vec = Op.getNode()->getOperand(0);
8153     SDValue SubVec = Op.getNode()->getOperand(1);
8154     SDValue Idx = Op.getNode()->getOperand(2);
8155
8156     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8157          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8158         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8159         isa<ConstantSDNode>(Idx)) {
8160       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8161       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8162     }
8163
8164     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8165         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8166         isa<ConstantSDNode>(Idx)) {
8167       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8168       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8169     }
8170   }
8171   return SDValue();
8172 }
8173
8174 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8175 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8176 // one of the above mentioned nodes. It has to be wrapped because otherwise
8177 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8178 // be used to form addressing mode. These wrapped nodes will be selected
8179 // into MOV32ri.
8180 SDValue
8181 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8182   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8183
8184   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8185   // global base reg.
8186   unsigned char OpFlag = 0;
8187   unsigned WrapperKind = X86ISD::Wrapper;
8188   CodeModel::Model M = getTargetMachine().getCodeModel();
8189
8190   if (Subtarget->isPICStyleRIPRel() &&
8191       (M == CodeModel::Small || M == CodeModel::Kernel))
8192     WrapperKind = X86ISD::WrapperRIP;
8193   else if (Subtarget->isPICStyleGOT())
8194     OpFlag = X86II::MO_GOTOFF;
8195   else if (Subtarget->isPICStyleStubPIC())
8196     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8197
8198   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8199                                              CP->getAlignment(),
8200                                              CP->getOffset(), OpFlag);
8201   SDLoc DL(CP);
8202   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8203   // With PIC, the address is actually $g + Offset.
8204   if (OpFlag) {
8205     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8206                          DAG.getNode(X86ISD::GlobalBaseReg,
8207                                      SDLoc(), getPointerTy()),
8208                          Result);
8209   }
8210
8211   return Result;
8212 }
8213
8214 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8215   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8216
8217   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8218   // global base reg.
8219   unsigned char OpFlag = 0;
8220   unsigned WrapperKind = X86ISD::Wrapper;
8221   CodeModel::Model M = getTargetMachine().getCodeModel();
8222
8223   if (Subtarget->isPICStyleRIPRel() &&
8224       (M == CodeModel::Small || M == CodeModel::Kernel))
8225     WrapperKind = X86ISD::WrapperRIP;
8226   else if (Subtarget->isPICStyleGOT())
8227     OpFlag = X86II::MO_GOTOFF;
8228   else if (Subtarget->isPICStyleStubPIC())
8229     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8230
8231   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8232                                           OpFlag);
8233   SDLoc DL(JT);
8234   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8235
8236   // With PIC, the address is actually $g + Offset.
8237   if (OpFlag)
8238     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8239                          DAG.getNode(X86ISD::GlobalBaseReg,
8240                                      SDLoc(), getPointerTy()),
8241                          Result);
8242
8243   return Result;
8244 }
8245
8246 SDValue
8247 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8248   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8249
8250   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8251   // global base reg.
8252   unsigned char OpFlag = 0;
8253   unsigned WrapperKind = X86ISD::Wrapper;
8254   CodeModel::Model M = getTargetMachine().getCodeModel();
8255
8256   if (Subtarget->isPICStyleRIPRel() &&
8257       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8258     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8259       OpFlag = X86II::MO_GOTPCREL;
8260     WrapperKind = X86ISD::WrapperRIP;
8261   } else if (Subtarget->isPICStyleGOT()) {
8262     OpFlag = X86II::MO_GOT;
8263   } else if (Subtarget->isPICStyleStubPIC()) {
8264     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8265   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8266     OpFlag = X86II::MO_DARWIN_NONLAZY;
8267   }
8268
8269   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8270
8271   SDLoc DL(Op);
8272   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8273
8274   // With PIC, the address is actually $g + Offset.
8275   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8276       !Subtarget->is64Bit()) {
8277     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8278                          DAG.getNode(X86ISD::GlobalBaseReg,
8279                                      SDLoc(), getPointerTy()),
8280                          Result);
8281   }
8282
8283   // For symbols that require a load from a stub to get the address, emit the
8284   // load.
8285   if (isGlobalStubReference(OpFlag))
8286     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8287                          MachinePointerInfo::getGOT(), false, false, false, 0);
8288
8289   return Result;
8290 }
8291
8292 SDValue
8293 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8294   // Create the TargetBlockAddressAddress node.
8295   unsigned char OpFlags =
8296     Subtarget->ClassifyBlockAddressReference();
8297   CodeModel::Model M = getTargetMachine().getCodeModel();
8298   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8299   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8300   SDLoc dl(Op);
8301   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8302                                              OpFlags);
8303
8304   if (Subtarget->isPICStyleRIPRel() &&
8305       (M == CodeModel::Small || M == CodeModel::Kernel))
8306     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8307   else
8308     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8309
8310   // With PIC, the address is actually $g + Offset.
8311   if (isGlobalRelativeToPICBase(OpFlags)) {
8312     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8313                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8314                          Result);
8315   }
8316
8317   return Result;
8318 }
8319
8320 SDValue
8321 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8322                                       int64_t Offset, SelectionDAG &DAG) const {
8323   // Create the TargetGlobalAddress node, folding in the constant
8324   // offset if it is legal.
8325   unsigned char OpFlags =
8326     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8327   CodeModel::Model M = getTargetMachine().getCodeModel();
8328   SDValue Result;
8329   if (OpFlags == X86II::MO_NO_FLAG &&
8330       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8331     // A direct static reference to a global.
8332     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8333     Offset = 0;
8334   } else {
8335     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8336   }
8337
8338   if (Subtarget->isPICStyleRIPRel() &&
8339       (M == CodeModel::Small || M == CodeModel::Kernel))
8340     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8341   else
8342     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8343
8344   // With PIC, the address is actually $g + Offset.
8345   if (isGlobalRelativeToPICBase(OpFlags)) {
8346     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8347                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8348                          Result);
8349   }
8350
8351   // For globals that require a load from a stub to get the address, emit the
8352   // load.
8353   if (isGlobalStubReference(OpFlags))
8354     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8355                          MachinePointerInfo::getGOT(), false, false, false, 0);
8356
8357   // If there was a non-zero offset that we didn't fold, create an explicit
8358   // addition for it.
8359   if (Offset != 0)
8360     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8361                          DAG.getConstant(Offset, getPointerTy()));
8362
8363   return Result;
8364 }
8365
8366 SDValue
8367 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8368   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8369   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8370   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8371 }
8372
8373 static SDValue
8374 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8375            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8376            unsigned char OperandFlags, bool LocalDynamic = false) {
8377   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8378   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8379   SDLoc dl(GA);
8380   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8381                                            GA->getValueType(0),
8382                                            GA->getOffset(),
8383                                            OperandFlags);
8384
8385   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8386                                            : X86ISD::TLSADDR;
8387
8388   if (InFlag) {
8389     SDValue Ops[] = { Chain,  TGA, *InFlag };
8390     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8391   } else {
8392     SDValue Ops[]  = { Chain, TGA };
8393     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8394   }
8395
8396   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8397   MFI->setAdjustsStack(true);
8398
8399   SDValue Flag = Chain.getValue(1);
8400   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8401 }
8402
8403 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8404 static SDValue
8405 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8406                                 const EVT PtrVT) {
8407   SDValue InFlag;
8408   SDLoc dl(GA);  // ? function entry point might be better
8409   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8410                                    DAG.getNode(X86ISD::GlobalBaseReg,
8411                                                SDLoc(), PtrVT), InFlag);
8412   InFlag = Chain.getValue(1);
8413
8414   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8415 }
8416
8417 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8418 static SDValue
8419 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8420                                 const EVT PtrVT) {
8421   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8422                     X86::RAX, X86II::MO_TLSGD);
8423 }
8424
8425 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8426                                            SelectionDAG &DAG,
8427                                            const EVT PtrVT,
8428                                            bool is64Bit) {
8429   SDLoc dl(GA);
8430
8431   // Get the start address of the TLS block for this module.
8432   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8433       .getInfo<X86MachineFunctionInfo>();
8434   MFI->incNumLocalDynamicTLSAccesses();
8435
8436   SDValue Base;
8437   if (is64Bit) {
8438     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8439                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8440   } else {
8441     SDValue InFlag;
8442     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8443         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8444     InFlag = Chain.getValue(1);
8445     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8446                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8447   }
8448
8449   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8450   // of Base.
8451
8452   // Build x@dtpoff.
8453   unsigned char OperandFlags = X86II::MO_DTPOFF;
8454   unsigned WrapperKind = X86ISD::Wrapper;
8455   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8456                                            GA->getValueType(0),
8457                                            GA->getOffset(), OperandFlags);
8458   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8459
8460   // Add x@dtpoff with the base.
8461   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8462 }
8463
8464 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8465 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8466                                    const EVT PtrVT, TLSModel::Model model,
8467                                    bool is64Bit, bool isPIC) {
8468   SDLoc dl(GA);
8469
8470   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8471   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8472                                                          is64Bit ? 257 : 256));
8473
8474   SDValue ThreadPointer =
8475       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8476                   MachinePointerInfo(Ptr), false, false, false, 0);
8477
8478   unsigned char OperandFlags = 0;
8479   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8480   // initialexec.
8481   unsigned WrapperKind = X86ISD::Wrapper;
8482   if (model == TLSModel::LocalExec) {
8483     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8484   } else if (model == TLSModel::InitialExec) {
8485     if (is64Bit) {
8486       OperandFlags = X86II::MO_GOTTPOFF;
8487       WrapperKind = X86ISD::WrapperRIP;
8488     } else {
8489       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8490     }
8491   } else {
8492     llvm_unreachable("Unexpected model");
8493   }
8494
8495   // emit "addl x@ntpoff,%eax" (local exec)
8496   // or "addl x@indntpoff,%eax" (initial exec)
8497   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8498   SDValue TGA =
8499       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8500                                  GA->getOffset(), OperandFlags);
8501   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8502
8503   if (model == TLSModel::InitialExec) {
8504     if (isPIC && !is64Bit) {
8505       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8506                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8507                            Offset);
8508     }
8509
8510     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8511                          MachinePointerInfo::getGOT(), false, false, false, 0);
8512   }
8513
8514   // The address of the thread local variable is the add of the thread
8515   // pointer with the offset of the variable.
8516   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8517 }
8518
8519 SDValue
8520 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8521
8522   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8523   const GlobalValue *GV = GA->getGlobal();
8524
8525   if (Subtarget->isTargetELF()) {
8526     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8527
8528     switch (model) {
8529       case TLSModel::GeneralDynamic:
8530         if (Subtarget->is64Bit())
8531           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8532         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8533       case TLSModel::LocalDynamic:
8534         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8535                                            Subtarget->is64Bit());
8536       case TLSModel::InitialExec:
8537       case TLSModel::LocalExec:
8538         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8539                                    Subtarget->is64Bit(),
8540                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8541     }
8542     llvm_unreachable("Unknown TLS model.");
8543   }
8544
8545   if (Subtarget->isTargetDarwin()) {
8546     // Darwin only has one model of TLS.  Lower to that.
8547     unsigned char OpFlag = 0;
8548     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8549                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8550
8551     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8552     // global base reg.
8553     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8554                   !Subtarget->is64Bit();
8555     if (PIC32)
8556       OpFlag = X86II::MO_TLVP_PIC_BASE;
8557     else
8558       OpFlag = X86II::MO_TLVP;
8559     SDLoc DL(Op);
8560     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8561                                                 GA->getValueType(0),
8562                                                 GA->getOffset(), OpFlag);
8563     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8564
8565     // With PIC32, the address is actually $g + Offset.
8566     if (PIC32)
8567       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8568                            DAG.getNode(X86ISD::GlobalBaseReg,
8569                                        SDLoc(), getPointerTy()),
8570                            Offset);
8571
8572     // Lowering the machine isd will make sure everything is in the right
8573     // location.
8574     SDValue Chain = DAG.getEntryNode();
8575     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8576     SDValue Args[] = { Chain, Offset };
8577     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8578
8579     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8580     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8581     MFI->setAdjustsStack(true);
8582
8583     // And our return value (tls address) is in the standard call return value
8584     // location.
8585     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8586     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8587                               Chain.getValue(1));
8588   }
8589
8590   if (Subtarget->isTargetKnownWindowsMSVC() ||
8591       Subtarget->isTargetWindowsGNU()) {
8592     // Just use the implicit TLS architecture
8593     // Need to generate someting similar to:
8594     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8595     //                                  ; from TEB
8596     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8597     //   mov     rcx, qword [rdx+rcx*8]
8598     //   mov     eax, .tls$:tlsvar
8599     //   [rax+rcx] contains the address
8600     // Windows 64bit: gs:0x58
8601     // Windows 32bit: fs:__tls_array
8602
8603     // If GV is an alias then use the aliasee for determining
8604     // thread-localness.
8605     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8606       GV = GA->getAliasedGlobal();
8607     SDLoc dl(GA);
8608     SDValue Chain = DAG.getEntryNode();
8609
8610     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8611     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8612     // use its literal value of 0x2C.
8613     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8614                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8615                                                              256)
8616                                         : Type::getInt32PtrTy(*DAG.getContext(),
8617                                                               257));
8618
8619     SDValue TlsArray =
8620         Subtarget->is64Bit()
8621             ? DAG.getIntPtrConstant(0x58)
8622             : (Subtarget->isTargetWindowsGNU()
8623                    ? DAG.getIntPtrConstant(0x2C)
8624                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8625
8626     SDValue ThreadPointer =
8627         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8628                     MachinePointerInfo(Ptr), false, false, false, 0);
8629
8630     // Load the _tls_index variable
8631     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8632     if (Subtarget->is64Bit())
8633       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8634                            IDX, MachinePointerInfo(), MVT::i32,
8635                            false, false, 0);
8636     else
8637       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8638                         false, false, false, 0);
8639
8640     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8641                                     getPointerTy());
8642     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8643
8644     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8645     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8646                       false, false, false, 0);
8647
8648     // Get the offset of start of .tls section
8649     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8650                                              GA->getValueType(0),
8651                                              GA->getOffset(), X86II::MO_SECREL);
8652     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8653
8654     // The address of the thread local variable is the add of the thread
8655     // pointer with the offset of the variable.
8656     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8657   }
8658
8659   llvm_unreachable("TLS not implemented for this target.");
8660 }
8661
8662 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8663 /// and take a 2 x i32 value to shift plus a shift amount.
8664 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8665   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8666   MVT VT = Op.getSimpleValueType();
8667   unsigned VTBits = VT.getSizeInBits();
8668   SDLoc dl(Op);
8669   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8670   SDValue ShOpLo = Op.getOperand(0);
8671   SDValue ShOpHi = Op.getOperand(1);
8672   SDValue ShAmt  = Op.getOperand(2);
8673   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8674   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8675   // during isel.
8676   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8677                                   DAG.getConstant(VTBits - 1, MVT::i8));
8678   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8679                                      DAG.getConstant(VTBits - 1, MVT::i8))
8680                        : DAG.getConstant(0, VT);
8681
8682   SDValue Tmp2, Tmp3;
8683   if (Op.getOpcode() == ISD::SHL_PARTS) {
8684     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8685     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8686   } else {
8687     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8688     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8689   }
8690
8691   // If the shift amount is larger or equal than the width of a part we can't
8692   // rely on the results of shld/shrd. Insert a test and select the appropriate
8693   // values for large shift amounts.
8694   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8695                                 DAG.getConstant(VTBits, MVT::i8));
8696   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8697                              AndNode, DAG.getConstant(0, MVT::i8));
8698
8699   SDValue Hi, Lo;
8700   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8701   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8702   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8703
8704   if (Op.getOpcode() == ISD::SHL_PARTS) {
8705     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8706     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8707   } else {
8708     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8709     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8710   }
8711
8712   SDValue Ops[2] = { Lo, Hi };
8713   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8714 }
8715
8716 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8717                                            SelectionDAG &DAG) const {
8718   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8719
8720   if (SrcVT.isVector())
8721     return SDValue();
8722
8723   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8724          "Unknown SINT_TO_FP to lower!");
8725
8726   // These are really Legal; return the operand so the caller accepts it as
8727   // Legal.
8728   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8729     return Op;
8730   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8731       Subtarget->is64Bit()) {
8732     return Op;
8733   }
8734
8735   SDLoc dl(Op);
8736   unsigned Size = SrcVT.getSizeInBits()/8;
8737   MachineFunction &MF = DAG.getMachineFunction();
8738   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8739   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8740   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8741                                StackSlot,
8742                                MachinePointerInfo::getFixedStack(SSFI),
8743                                false, false, 0);
8744   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8745 }
8746
8747 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8748                                      SDValue StackSlot,
8749                                      SelectionDAG &DAG) const {
8750   // Build the FILD
8751   SDLoc DL(Op);
8752   SDVTList Tys;
8753   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8754   if (useSSE)
8755     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8756   else
8757     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8758
8759   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8760
8761   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8762   MachineMemOperand *MMO;
8763   if (FI) {
8764     int SSFI = FI->getIndex();
8765     MMO =
8766       DAG.getMachineFunction()
8767       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8768                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8769   } else {
8770     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8771     StackSlot = StackSlot.getOperand(1);
8772   }
8773   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8774   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8775                                            X86ISD::FILD, DL,
8776                                            Tys, Ops, array_lengthof(Ops),
8777                                            SrcVT, MMO);
8778
8779   if (useSSE) {
8780     Chain = Result.getValue(1);
8781     SDValue InFlag = Result.getValue(2);
8782
8783     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8784     // shouldn't be necessary except that RFP cannot be live across
8785     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8786     MachineFunction &MF = DAG.getMachineFunction();
8787     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8788     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8789     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8790     Tys = DAG.getVTList(MVT::Other);
8791     SDValue Ops[] = {
8792       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8793     };
8794     MachineMemOperand *MMO =
8795       DAG.getMachineFunction()
8796       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8797                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8798
8799     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8800                                     Ops, array_lengthof(Ops),
8801                                     Op.getValueType(), MMO);
8802     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8803                          MachinePointerInfo::getFixedStack(SSFI),
8804                          false, false, false, 0);
8805   }
8806
8807   return Result;
8808 }
8809
8810 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8811 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8812                                                SelectionDAG &DAG) const {
8813   // This algorithm is not obvious. Here it is what we're trying to output:
8814   /*
8815      movq       %rax,  %xmm0
8816      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8817      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8818      #ifdef __SSE3__
8819        haddpd   %xmm0, %xmm0
8820      #else
8821        pshufd   $0x4e, %xmm0, %xmm1
8822        addpd    %xmm1, %xmm0
8823      #endif
8824   */
8825
8826   SDLoc dl(Op);
8827   LLVMContext *Context = DAG.getContext();
8828
8829   // Build some magic constants.
8830   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8831   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8832   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8833
8834   SmallVector<Constant*,2> CV1;
8835   CV1.push_back(
8836     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8837                                       APInt(64, 0x4330000000000000ULL))));
8838   CV1.push_back(
8839     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8840                                       APInt(64, 0x4530000000000000ULL))));
8841   Constant *C1 = ConstantVector::get(CV1);
8842   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8843
8844   // Load the 64-bit value into an XMM register.
8845   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8846                             Op.getOperand(0));
8847   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8848                               MachinePointerInfo::getConstantPool(),
8849                               false, false, false, 16);
8850   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8851                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8852                               CLod0);
8853
8854   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8855                               MachinePointerInfo::getConstantPool(),
8856                               false, false, false, 16);
8857   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8858   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8859   SDValue Result;
8860
8861   if (Subtarget->hasSSE3()) {
8862     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8863     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8864   } else {
8865     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8866     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8867                                            S2F, 0x4E, DAG);
8868     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8869                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8870                          Sub);
8871   }
8872
8873   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8874                      DAG.getIntPtrConstant(0));
8875 }
8876
8877 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8878 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8879                                                SelectionDAG &DAG) const {
8880   SDLoc dl(Op);
8881   // FP constant to bias correct the final result.
8882   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8883                                    MVT::f64);
8884
8885   // Load the 32-bit value into an XMM register.
8886   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8887                              Op.getOperand(0));
8888
8889   // Zero out the upper parts of the register.
8890   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8891
8892   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8893                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8894                      DAG.getIntPtrConstant(0));
8895
8896   // Or the load with the bias.
8897   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8898                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8899                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8900                                                    MVT::v2f64, Load)),
8901                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8902                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8903                                                    MVT::v2f64, Bias)));
8904   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8905                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8906                    DAG.getIntPtrConstant(0));
8907
8908   // Subtract the bias.
8909   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8910
8911   // Handle final rounding.
8912   EVT DestVT = Op.getValueType();
8913
8914   if (DestVT.bitsLT(MVT::f64))
8915     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8916                        DAG.getIntPtrConstant(0));
8917   if (DestVT.bitsGT(MVT::f64))
8918     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8919
8920   // Handle final rounding.
8921   return Sub;
8922 }
8923
8924 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8925                                                SelectionDAG &DAG) const {
8926   SDValue N0 = Op.getOperand(0);
8927   MVT SVT = N0.getSimpleValueType();
8928   SDLoc dl(Op);
8929
8930   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8931           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8932          "Custom UINT_TO_FP is not supported!");
8933
8934   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8935   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8936                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8937 }
8938
8939 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8940                                            SelectionDAG &DAG) const {
8941   SDValue N0 = Op.getOperand(0);
8942   SDLoc dl(Op);
8943
8944   if (Op.getValueType().isVector())
8945     return lowerUINT_TO_FP_vec(Op, DAG);
8946
8947   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8948   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8949   // the optimization here.
8950   if (DAG.SignBitIsZero(N0))
8951     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8952
8953   MVT SrcVT = N0.getSimpleValueType();
8954   MVT DstVT = Op.getSimpleValueType();
8955   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8956     return LowerUINT_TO_FP_i64(Op, DAG);
8957   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8958     return LowerUINT_TO_FP_i32(Op, DAG);
8959   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8960     return SDValue();
8961
8962   // Make a 64-bit buffer, and use it to build an FILD.
8963   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8964   if (SrcVT == MVT::i32) {
8965     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8966     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8967                                      getPointerTy(), StackSlot, WordOff);
8968     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8969                                   StackSlot, MachinePointerInfo(),
8970                                   false, false, 0);
8971     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8972                                   OffsetSlot, MachinePointerInfo(),
8973                                   false, false, 0);
8974     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8975     return Fild;
8976   }
8977
8978   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8979   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8980                                StackSlot, MachinePointerInfo(),
8981                                false, false, 0);
8982   // For i64 source, we need to add the appropriate power of 2 if the input
8983   // was negative.  This is the same as the optimization in
8984   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8985   // we must be careful to do the computation in x87 extended precision, not
8986   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8987   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8988   MachineMemOperand *MMO =
8989     DAG.getMachineFunction()
8990     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8991                           MachineMemOperand::MOLoad, 8, 8);
8992
8993   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8994   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8995   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8996                                          array_lengthof(Ops), MVT::i64, MMO);
8997
8998   APInt FF(32, 0x5F800000ULL);
8999
9000   // Check whether the sign bit is set.
9001   SDValue SignSet = DAG.getSetCC(dl,
9002                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9003                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9004                                  ISD::SETLT);
9005
9006   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9007   SDValue FudgePtr = DAG.getConstantPool(
9008                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9009                                          getPointerTy());
9010
9011   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9012   SDValue Zero = DAG.getIntPtrConstant(0);
9013   SDValue Four = DAG.getIntPtrConstant(4);
9014   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9015                                Zero, Four);
9016   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9017
9018   // Load the value out, extending it from f32 to f80.
9019   // FIXME: Avoid the extend by constructing the right constant pool?
9020   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9021                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9022                                  MVT::f32, false, false, 4);
9023   // Extend everything to 80 bits to force it to be done on x87.
9024   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9025   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9026 }
9027
9028 std::pair<SDValue,SDValue>
9029 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9030                                     bool IsSigned, bool IsReplace) const {
9031   SDLoc DL(Op);
9032
9033   EVT DstTy = Op.getValueType();
9034
9035   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9036     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9037     DstTy = MVT::i64;
9038   }
9039
9040   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9041          DstTy.getSimpleVT() >= MVT::i16 &&
9042          "Unknown FP_TO_INT to lower!");
9043
9044   // These are really Legal.
9045   if (DstTy == MVT::i32 &&
9046       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9047     return std::make_pair(SDValue(), SDValue());
9048   if (Subtarget->is64Bit() &&
9049       DstTy == MVT::i64 &&
9050       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9051     return std::make_pair(SDValue(), SDValue());
9052
9053   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9054   // stack slot, or into the FTOL runtime function.
9055   MachineFunction &MF = DAG.getMachineFunction();
9056   unsigned MemSize = DstTy.getSizeInBits()/8;
9057   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9058   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9059
9060   unsigned Opc;
9061   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9062     Opc = X86ISD::WIN_FTOL;
9063   else
9064     switch (DstTy.getSimpleVT().SimpleTy) {
9065     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9066     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9067     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9068     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9069     }
9070
9071   SDValue Chain = DAG.getEntryNode();
9072   SDValue Value = Op.getOperand(0);
9073   EVT TheVT = Op.getOperand(0).getValueType();
9074   // FIXME This causes a redundant load/store if the SSE-class value is already
9075   // in memory, such as if it is on the callstack.
9076   if (isScalarFPTypeInSSEReg(TheVT)) {
9077     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9078     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9079                          MachinePointerInfo::getFixedStack(SSFI),
9080                          false, false, 0);
9081     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9082     SDValue Ops[] = {
9083       Chain, StackSlot, DAG.getValueType(TheVT)
9084     };
9085
9086     MachineMemOperand *MMO =
9087       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9088                               MachineMemOperand::MOLoad, MemSize, MemSize);
9089     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9090                                     array_lengthof(Ops), DstTy, MMO);
9091     Chain = Value.getValue(1);
9092     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9093     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9094   }
9095
9096   MachineMemOperand *MMO =
9097     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9098                             MachineMemOperand::MOStore, MemSize, MemSize);
9099
9100   if (Opc != X86ISD::WIN_FTOL) {
9101     // Build the FP_TO_INT*_IN_MEM
9102     SDValue Ops[] = { Chain, Value, StackSlot };
9103     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9104                                            Ops, array_lengthof(Ops), DstTy,
9105                                            MMO);
9106     return std::make_pair(FIST, StackSlot);
9107   } else {
9108     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9109       DAG.getVTList(MVT::Other, MVT::Glue),
9110       Chain, Value);
9111     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9112       MVT::i32, ftol.getValue(1));
9113     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9114       MVT::i32, eax.getValue(2));
9115     SDValue Ops[] = { eax, edx };
9116     SDValue pair = IsReplace
9117       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9118       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9119     return std::make_pair(pair, SDValue());
9120   }
9121 }
9122
9123 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9124                               const X86Subtarget *Subtarget) {
9125   MVT VT = Op->getSimpleValueType(0);
9126   SDValue In = Op->getOperand(0);
9127   MVT InVT = In.getSimpleValueType();
9128   SDLoc dl(Op);
9129
9130   // Optimize vectors in AVX mode:
9131   //
9132   //   v8i16 -> v8i32
9133   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9134   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9135   //   Concat upper and lower parts.
9136   //
9137   //   v4i32 -> v4i64
9138   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9139   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9140   //   Concat upper and lower parts.
9141   //
9142
9143   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9144       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9145       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9146     return SDValue();
9147
9148   if (Subtarget->hasInt256())
9149     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9150
9151   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9152   SDValue Undef = DAG.getUNDEF(InVT);
9153   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9154   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9155   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9156
9157   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9158                              VT.getVectorNumElements()/2);
9159
9160   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9161   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9162
9163   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9164 }
9165
9166 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9167                                         SelectionDAG &DAG) {
9168   MVT VT = Op->getSimpleValueType(0);
9169   SDValue In = Op->getOperand(0);
9170   MVT InVT = In.getSimpleValueType();
9171   SDLoc DL(Op);
9172   unsigned int NumElts = VT.getVectorNumElements();
9173   if (NumElts != 8 && NumElts != 16)
9174     return SDValue();
9175
9176   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9177     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9178
9179   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9181   // Now we have only mask extension
9182   assert(InVT.getVectorElementType() == MVT::i1);
9183   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9184   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9185   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9186   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9187   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9188                            MachinePointerInfo::getConstantPool(),
9189                            false, false, false, Alignment);
9190
9191   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9192   if (VT.is512BitVector())
9193     return Brcst;
9194   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9195 }
9196
9197 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9198                                SelectionDAG &DAG) {
9199   if (Subtarget->hasFp256()) {
9200     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9201     if (Res.getNode())
9202       return Res;
9203   }
9204
9205   return SDValue();
9206 }
9207
9208 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9209                                 SelectionDAG &DAG) {
9210   SDLoc DL(Op);
9211   MVT VT = Op.getSimpleValueType();
9212   SDValue In = Op.getOperand(0);
9213   MVT SVT = In.getSimpleValueType();
9214
9215   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9216     return LowerZERO_EXTEND_AVX512(Op, DAG);
9217
9218   if (Subtarget->hasFp256()) {
9219     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9220     if (Res.getNode())
9221       return Res;
9222   }
9223
9224   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9225          VT.getVectorNumElements() != SVT.getVectorNumElements());
9226   return SDValue();
9227 }
9228
9229 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9230   SDLoc DL(Op);
9231   MVT VT = Op.getSimpleValueType();
9232   SDValue In = Op.getOperand(0);
9233   MVT InVT = In.getSimpleValueType();
9234
9235   if (VT == MVT::i1) {
9236     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9237            "Invalid scalar TRUNCATE operation");
9238     if (InVT == MVT::i32)
9239       return SDValue();
9240     if (InVT.getSizeInBits() == 64)
9241       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9242     else if (InVT.getSizeInBits() < 32)
9243       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9244     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9245   }
9246   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9247          "Invalid TRUNCATE operation");
9248
9249   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9250     if (VT.getVectorElementType().getSizeInBits() >=8)
9251       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9252
9253     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9254     unsigned NumElts = InVT.getVectorNumElements();
9255     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9256     if (InVT.getSizeInBits() < 512) {
9257       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9258       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9259       InVT = ExtVT;
9260     }
9261     
9262     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9263     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9264     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9265     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9266     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9267                            MachinePointerInfo::getConstantPool(),
9268                            false, false, false, Alignment);
9269     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9270     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9271     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9272   }
9273
9274   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9275     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9276     if (Subtarget->hasInt256()) {
9277       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9278       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9279       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9280                                 ShufMask);
9281       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9282                          DAG.getIntPtrConstant(0));
9283     }
9284
9285     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9286                                DAG.getIntPtrConstant(0));
9287     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9288                                DAG.getIntPtrConstant(2));
9289     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9290     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9291     static const int ShufMask[] = {0, 2, 4, 6};
9292     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9293   }
9294
9295   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9296     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9297     if (Subtarget->hasInt256()) {
9298       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9299
9300       SmallVector<SDValue,32> pshufbMask;
9301       for (unsigned i = 0; i < 2; ++i) {
9302         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9303         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9304         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9305         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9306         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9307         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9308         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9309         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9310         for (unsigned j = 0; j < 8; ++j)
9311           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9312       }
9313       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9314                                &pshufbMask[0], 32);
9315       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9316       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9317
9318       static const int ShufMask[] = {0,  2,  -1,  -1};
9319       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9320                                 &ShufMask[0]);
9321       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9322                        DAG.getIntPtrConstant(0));
9323       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9324     }
9325
9326     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9327                                DAG.getIntPtrConstant(0));
9328
9329     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9330                                DAG.getIntPtrConstant(4));
9331
9332     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9333     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9334
9335     // The PSHUFB mask:
9336     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9337                                    -1, -1, -1, -1, -1, -1, -1, -1};
9338
9339     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9340     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9341     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9342
9343     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9344     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9345
9346     // The MOVLHPS Mask:
9347     static const int ShufMask2[] = {0, 1, 4, 5};
9348     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9349     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9350   }
9351
9352   // Handle truncation of V256 to V128 using shuffles.
9353   if (!VT.is128BitVector() || !InVT.is256BitVector())
9354     return SDValue();
9355
9356   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9357
9358   unsigned NumElems = VT.getVectorNumElements();
9359   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9360
9361   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9362   // Prepare truncation shuffle mask
9363   for (unsigned i = 0; i != NumElems; ++i)
9364     MaskVec[i] = i * 2;
9365   SDValue V = DAG.getVectorShuffle(NVT, DL,
9366                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9367                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9368   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9369                      DAG.getIntPtrConstant(0));
9370 }
9371
9372 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9373                                            SelectionDAG &DAG) const {
9374   assert(!Op.getSimpleValueType().isVector());
9375
9376   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9377     /*IsSigned=*/ true, /*IsReplace=*/ false);
9378   SDValue FIST = Vals.first, StackSlot = Vals.second;
9379   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9380   if (FIST.getNode() == 0) return Op;
9381
9382   if (StackSlot.getNode())
9383     // Load the result.
9384     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9385                        FIST, StackSlot, MachinePointerInfo(),
9386                        false, false, false, 0);
9387
9388   // The node is the result.
9389   return FIST;
9390 }
9391
9392 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9393                                            SelectionDAG &DAG) const {
9394   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9395     /*IsSigned=*/ false, /*IsReplace=*/ false);
9396   SDValue FIST = Vals.first, StackSlot = Vals.second;
9397   assert(FIST.getNode() && "Unexpected failure");
9398
9399   if (StackSlot.getNode())
9400     // Load the result.
9401     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9402                        FIST, StackSlot, MachinePointerInfo(),
9403                        false, false, false, 0);
9404
9405   // The node is the result.
9406   return FIST;
9407 }
9408
9409 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9410   SDLoc DL(Op);
9411   MVT VT = Op.getSimpleValueType();
9412   SDValue In = Op.getOperand(0);
9413   MVT SVT = In.getSimpleValueType();
9414
9415   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9416
9417   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9418                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9419                                  In, DAG.getUNDEF(SVT)));
9420 }
9421
9422 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9423   LLVMContext *Context = DAG.getContext();
9424   SDLoc dl(Op);
9425   MVT VT = Op.getSimpleValueType();
9426   MVT EltVT = VT;
9427   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9428   if (VT.isVector()) {
9429     EltVT = VT.getVectorElementType();
9430     NumElts = VT.getVectorNumElements();
9431   }
9432   Constant *C;
9433   if (EltVT == MVT::f64)
9434     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9435                                           APInt(64, ~(1ULL << 63))));
9436   else
9437     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9438                                           APInt(32, ~(1U << 31))));
9439   C = ConstantVector::getSplat(NumElts, C);
9440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9441   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9442   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9443   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9444                              MachinePointerInfo::getConstantPool(),
9445                              false, false, false, Alignment);
9446   if (VT.isVector()) {
9447     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9448     return DAG.getNode(ISD::BITCAST, dl, VT,
9449                        DAG.getNode(ISD::AND, dl, ANDVT,
9450                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9451                                                Op.getOperand(0)),
9452                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9453   }
9454   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9455 }
9456
9457 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9458   LLVMContext *Context = DAG.getContext();
9459   SDLoc dl(Op);
9460   MVT VT = Op.getSimpleValueType();
9461   MVT EltVT = VT;
9462   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9463   if (VT.isVector()) {
9464     EltVT = VT.getVectorElementType();
9465     NumElts = VT.getVectorNumElements();
9466   }
9467   Constant *C;
9468   if (EltVT == MVT::f64)
9469     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9470                                           APInt(64, 1ULL << 63)));
9471   else
9472     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9473                                           APInt(32, 1U << 31)));
9474   C = ConstantVector::getSplat(NumElts, C);
9475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9476   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9477   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9478   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9479                              MachinePointerInfo::getConstantPool(),
9480                              false, false, false, Alignment);
9481   if (VT.isVector()) {
9482     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9483     return DAG.getNode(ISD::BITCAST, dl, VT,
9484                        DAG.getNode(ISD::XOR, dl, XORVT,
9485                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9486                                                Op.getOperand(0)),
9487                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9488   }
9489
9490   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9491 }
9492
9493 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9495   LLVMContext *Context = DAG.getContext();
9496   SDValue Op0 = Op.getOperand(0);
9497   SDValue Op1 = Op.getOperand(1);
9498   SDLoc dl(Op);
9499   MVT VT = Op.getSimpleValueType();
9500   MVT SrcVT = Op1.getSimpleValueType();
9501
9502   // If second operand is smaller, extend it first.
9503   if (SrcVT.bitsLT(VT)) {
9504     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9505     SrcVT = VT;
9506   }
9507   // And if it is bigger, shrink it first.
9508   if (SrcVT.bitsGT(VT)) {
9509     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9510     SrcVT = VT;
9511   }
9512
9513   // At this point the operands and the result should have the same
9514   // type, and that won't be f80 since that is not custom lowered.
9515
9516   // First get the sign bit of second operand.
9517   SmallVector<Constant*,4> CV;
9518   if (SrcVT == MVT::f64) {
9519     const fltSemantics &Sem = APFloat::IEEEdouble;
9520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9521     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9522   } else {
9523     const fltSemantics &Sem = APFloat::IEEEsingle;
9524     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9525     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9526     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9527     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9528   }
9529   Constant *C = ConstantVector::get(CV);
9530   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9531   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9532                               MachinePointerInfo::getConstantPool(),
9533                               false, false, false, 16);
9534   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9535
9536   // Shift sign bit right or left if the two operands have different types.
9537   if (SrcVT.bitsGT(VT)) {
9538     // Op0 is MVT::f32, Op1 is MVT::f64.
9539     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9540     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9541                           DAG.getConstant(32, MVT::i32));
9542     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9543     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9544                           DAG.getIntPtrConstant(0));
9545   }
9546
9547   // Clear first operand sign bit.
9548   CV.clear();
9549   if (VT == MVT::f64) {
9550     const fltSemantics &Sem = APFloat::IEEEdouble;
9551     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9552                                                    APInt(64, ~(1ULL << 63)))));
9553     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9554   } else {
9555     const fltSemantics &Sem = APFloat::IEEEsingle;
9556     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9557                                                    APInt(32, ~(1U << 31)))));
9558     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9559     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9560     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9561   }
9562   C = ConstantVector::get(CV);
9563   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9564   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9565                               MachinePointerInfo::getConstantPool(),
9566                               false, false, false, 16);
9567   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9568
9569   // Or the value with the sign bit.
9570   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9571 }
9572
9573 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9574   SDValue N0 = Op.getOperand(0);
9575   SDLoc dl(Op);
9576   MVT VT = Op.getSimpleValueType();
9577
9578   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9579   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9580                                   DAG.getConstant(1, VT));
9581   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9582 }
9583
9584 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9585 //
9586 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9587                                       SelectionDAG &DAG) {
9588   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9589
9590   if (!Subtarget->hasSSE41())
9591     return SDValue();
9592
9593   if (!Op->hasOneUse())
9594     return SDValue();
9595
9596   SDNode *N = Op.getNode();
9597   SDLoc DL(N);
9598
9599   SmallVector<SDValue, 8> Opnds;
9600   DenseMap<SDValue, unsigned> VecInMap;
9601   SmallVector<SDValue, 8> VecIns;
9602   EVT VT = MVT::Other;
9603
9604   // Recognize a special case where a vector is casted into wide integer to
9605   // test all 0s.
9606   Opnds.push_back(N->getOperand(0));
9607   Opnds.push_back(N->getOperand(1));
9608
9609   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9610     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9611     // BFS traverse all OR'd operands.
9612     if (I->getOpcode() == ISD::OR) {
9613       Opnds.push_back(I->getOperand(0));
9614       Opnds.push_back(I->getOperand(1));
9615       // Re-evaluate the number of nodes to be traversed.
9616       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9617       continue;
9618     }
9619
9620     // Quit if a non-EXTRACT_VECTOR_ELT
9621     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9622       return SDValue();
9623
9624     // Quit if without a constant index.
9625     SDValue Idx = I->getOperand(1);
9626     if (!isa<ConstantSDNode>(Idx))
9627       return SDValue();
9628
9629     SDValue ExtractedFromVec = I->getOperand(0);
9630     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9631     if (M == VecInMap.end()) {
9632       VT = ExtractedFromVec.getValueType();
9633       // Quit if not 128/256-bit vector.
9634       if (!VT.is128BitVector() && !VT.is256BitVector())
9635         return SDValue();
9636       // Quit if not the same type.
9637       if (VecInMap.begin() != VecInMap.end() &&
9638           VT != VecInMap.begin()->first.getValueType())
9639         return SDValue();
9640       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9641       VecIns.push_back(ExtractedFromVec);
9642     }
9643     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9644   }
9645
9646   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9647          "Not extracted from 128-/256-bit vector.");
9648
9649   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9650
9651   for (DenseMap<SDValue, unsigned>::const_iterator
9652         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9653     // Quit if not all elements are used.
9654     if (I->second != FullMask)
9655       return SDValue();
9656   }
9657
9658   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9659
9660   // Cast all vectors into TestVT for PTEST.
9661   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9662     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9663
9664   // If more than one full vectors are evaluated, OR them first before PTEST.
9665   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9666     // Each iteration will OR 2 nodes and append the result until there is only
9667     // 1 node left, i.e. the final OR'd value of all vectors.
9668     SDValue LHS = VecIns[Slot];
9669     SDValue RHS = VecIns[Slot + 1];
9670     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9671   }
9672
9673   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9674                      VecIns.back(), VecIns.back());
9675 }
9676
9677 /// \brief return true if \c Op has a use that doesn't just read flags.
9678 static bool hasNonFlagsUse(SDValue Op) {
9679   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9680        ++UI) {
9681     SDNode *User = *UI;
9682     unsigned UOpNo = UI.getOperandNo();
9683     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9684       // Look pass truncate.
9685       UOpNo = User->use_begin().getOperandNo();
9686       User = *User->use_begin();
9687     }
9688
9689     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9690         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9691       return true;
9692   }
9693   return false;
9694 }
9695
9696 /// Emit nodes that will be selected as "test Op0,Op0", or something
9697 /// equivalent.
9698 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9699                                     SelectionDAG &DAG) const {
9700   if (Op.getValueType() == MVT::i1)
9701     // KORTEST instruction should be selected
9702     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9703                        DAG.getConstant(0, Op.getValueType()));
9704
9705   // CF and OF aren't always set the way we want. Determine which
9706   // of these we need.
9707   bool NeedCF = false;
9708   bool NeedOF = false;
9709   switch (X86CC) {
9710   default: break;
9711   case X86::COND_A: case X86::COND_AE:
9712   case X86::COND_B: case X86::COND_BE:
9713     NeedCF = true;
9714     break;
9715   case X86::COND_G: case X86::COND_GE:
9716   case X86::COND_L: case X86::COND_LE:
9717   case X86::COND_O: case X86::COND_NO:
9718     NeedOF = true;
9719     break;
9720   }
9721   // See if we can use the EFLAGS value from the operand instead of
9722   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9723   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9724   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9725     // Emit a CMP with 0, which is the TEST pattern.
9726     //if (Op.getValueType() == MVT::i1)
9727     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9728     //                     DAG.getConstant(0, MVT::i1));
9729     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9730                        DAG.getConstant(0, Op.getValueType()));
9731   }
9732   unsigned Opcode = 0;
9733   unsigned NumOperands = 0;
9734
9735   // Truncate operations may prevent the merge of the SETCC instruction
9736   // and the arithmetic instruction before it. Attempt to truncate the operands
9737   // of the arithmetic instruction and use a reduced bit-width instruction.
9738   bool NeedTruncation = false;
9739   SDValue ArithOp = Op;
9740   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9741     SDValue Arith = Op->getOperand(0);
9742     // Both the trunc and the arithmetic op need to have one user each.
9743     if (Arith->hasOneUse())
9744       switch (Arith.getOpcode()) {
9745         default: break;
9746         case ISD::ADD:
9747         case ISD::SUB:
9748         case ISD::AND:
9749         case ISD::OR:
9750         case ISD::XOR: {
9751           NeedTruncation = true;
9752           ArithOp = Arith;
9753         }
9754       }
9755   }
9756
9757   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9758   // which may be the result of a CAST.  We use the variable 'Op', which is the
9759   // non-casted variable when we check for possible users.
9760   switch (ArithOp.getOpcode()) {
9761   case ISD::ADD:
9762     // Due to an isel shortcoming, be conservative if this add is likely to be
9763     // selected as part of a load-modify-store instruction. When the root node
9764     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9765     // uses of other nodes in the match, such as the ADD in this case. This
9766     // leads to the ADD being left around and reselected, with the result being
9767     // two adds in the output.  Alas, even if none our users are stores, that
9768     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9769     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9770     // climbing the DAG back to the root, and it doesn't seem to be worth the
9771     // effort.
9772     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9773          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9774       if (UI->getOpcode() != ISD::CopyToReg &&
9775           UI->getOpcode() != ISD::SETCC &&
9776           UI->getOpcode() != ISD::STORE)
9777         goto default_case;
9778
9779     if (ConstantSDNode *C =
9780         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9781       // An add of one will be selected as an INC.
9782       if (C->getAPIntValue() == 1) {
9783         Opcode = X86ISD::INC;
9784         NumOperands = 1;
9785         break;
9786       }
9787
9788       // An add of negative one (subtract of one) will be selected as a DEC.
9789       if (C->getAPIntValue().isAllOnesValue()) {
9790         Opcode = X86ISD::DEC;
9791         NumOperands = 1;
9792         break;
9793       }
9794     }
9795
9796     // Otherwise use a regular EFLAGS-setting add.
9797     Opcode = X86ISD::ADD;
9798     NumOperands = 2;
9799     break;
9800   case ISD::SHL:
9801   case ISD::SRL:
9802     // If we have a constant logical shift that's only used in a comparison
9803     // against zero turn it into an equivalent AND. This allows turning it into
9804     // a TEST instruction later.
9805     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9806         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9807       EVT VT = Op.getValueType();
9808       unsigned BitWidth = VT.getSizeInBits();
9809       unsigned ShAmt = Op->getConstantOperandVal(1);
9810       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9811         break;
9812       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9813                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9814                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9815       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9816         break;
9817       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9818                                 DAG.getConstant(Mask, VT));
9819       DAG.ReplaceAllUsesWith(Op, New);
9820       Op = New;
9821     }
9822     break;
9823
9824   case ISD::AND:
9825     // If the primary and result isn't used, don't bother using X86ISD::AND,
9826     // because a TEST instruction will be better.
9827     if (!hasNonFlagsUse(Op))
9828       break;
9829     // FALL THROUGH
9830   case ISD::SUB:
9831   case ISD::OR:
9832   case ISD::XOR:
9833     // Due to the ISEL shortcoming noted above, be conservative if this op is
9834     // likely to be selected as part of a load-modify-store instruction.
9835     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9836            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9837       if (UI->getOpcode() == ISD::STORE)
9838         goto default_case;
9839
9840     // Otherwise use a regular EFLAGS-setting instruction.
9841     switch (ArithOp.getOpcode()) {
9842     default: llvm_unreachable("unexpected operator!");
9843     case ISD::SUB: Opcode = X86ISD::SUB; break;
9844     case ISD::XOR: Opcode = X86ISD::XOR; break;
9845     case ISD::AND: Opcode = X86ISD::AND; break;
9846     case ISD::OR: {
9847       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9848         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9849         if (EFLAGS.getNode())
9850           return EFLAGS;
9851       }
9852       Opcode = X86ISD::OR;
9853       break;
9854     }
9855     }
9856
9857     NumOperands = 2;
9858     break;
9859   case X86ISD::ADD:
9860   case X86ISD::SUB:
9861   case X86ISD::INC:
9862   case X86ISD::DEC:
9863   case X86ISD::OR:
9864   case X86ISD::XOR:
9865   case X86ISD::AND:
9866     return SDValue(Op.getNode(), 1);
9867   default:
9868   default_case:
9869     break;
9870   }
9871
9872   // If we found that truncation is beneficial, perform the truncation and
9873   // update 'Op'.
9874   if (NeedTruncation) {
9875     EVT VT = Op.getValueType();
9876     SDValue WideVal = Op->getOperand(0);
9877     EVT WideVT = WideVal.getValueType();
9878     unsigned ConvertedOp = 0;
9879     // Use a target machine opcode to prevent further DAGCombine
9880     // optimizations that may separate the arithmetic operations
9881     // from the setcc node.
9882     switch (WideVal.getOpcode()) {
9883       default: break;
9884       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9885       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9886       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9887       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9888       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9889     }
9890
9891     if (ConvertedOp) {
9892       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9893       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9894         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9895         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9896         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9897       }
9898     }
9899   }
9900
9901   if (Opcode == 0)
9902     // Emit a CMP with 0, which is the TEST pattern.
9903     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9904                        DAG.getConstant(0, Op.getValueType()));
9905
9906   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9907   SmallVector<SDValue, 4> Ops;
9908   for (unsigned i = 0; i != NumOperands; ++i)
9909     Ops.push_back(Op.getOperand(i));
9910
9911   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9912   DAG.ReplaceAllUsesWith(Op, New);
9913   return SDValue(New.getNode(), 1);
9914 }
9915
9916 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9917 /// equivalent.
9918 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9919                                    SDLoc dl, SelectionDAG &DAG) const {
9920   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9921     if (C->getAPIntValue() == 0)
9922       return EmitTest(Op0, X86CC, dl, DAG);
9923
9924      if (Op0.getValueType() == MVT::i1)
9925        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9926   }
9927  
9928   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9929        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9930     // Do the comparison at i32 if it's smaller, besides the Atom case. 
9931     // This avoids subregister aliasing issues. Keep the smaller reference 
9932     // if we're optimizing for size, however, as that'll allow better folding 
9933     // of memory operations.
9934     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9935         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9936              AttributeSet::FunctionIndex, Attribute::MinSize) &&
9937         !Subtarget->isAtom()) {
9938       unsigned ExtendOp =
9939           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9940       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9941       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9942     }
9943     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9944     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9945     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9946                               Op0, Op1);
9947     return SDValue(Sub.getNode(), 1);
9948   }
9949   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9950 }
9951
9952 /// Convert a comparison if required by the subtarget.
9953 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9954                                                  SelectionDAG &DAG) const {
9955   // If the subtarget does not support the FUCOMI instruction, floating-point
9956   // comparisons have to be converted.
9957   if (Subtarget->hasCMov() ||
9958       Cmp.getOpcode() != X86ISD::CMP ||
9959       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9960       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9961     return Cmp;
9962
9963   // The instruction selector will select an FUCOM instruction instead of
9964   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9965   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9966   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9967   SDLoc dl(Cmp);
9968   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9969   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9970   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9971                             DAG.getConstant(8, MVT::i8));
9972   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9973   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9974 }
9975
9976 static bool isAllOnes(SDValue V) {
9977   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9978   return C && C->isAllOnesValue();
9979 }
9980
9981 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9982 /// if it's possible.
9983 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9984                                      SDLoc dl, SelectionDAG &DAG) const {
9985   SDValue Op0 = And.getOperand(0);
9986   SDValue Op1 = And.getOperand(1);
9987   if (Op0.getOpcode() == ISD::TRUNCATE)
9988     Op0 = Op0.getOperand(0);
9989   if (Op1.getOpcode() == ISD::TRUNCATE)
9990     Op1 = Op1.getOperand(0);
9991
9992   SDValue LHS, RHS;
9993   if (Op1.getOpcode() == ISD::SHL)
9994     std::swap(Op0, Op1);
9995   if (Op0.getOpcode() == ISD::SHL) {
9996     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9997       if (And00C->getZExtValue() == 1) {
9998         // If we looked past a truncate, check that it's only truncating away
9999         // known zeros.
10000         unsigned BitWidth = Op0.getValueSizeInBits();
10001         unsigned AndBitWidth = And.getValueSizeInBits();
10002         if (BitWidth > AndBitWidth) {
10003           APInt Zeros, Ones;
10004           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10005           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10006             return SDValue();
10007         }
10008         LHS = Op1;
10009         RHS = Op0.getOperand(1);
10010       }
10011   } else if (Op1.getOpcode() == ISD::Constant) {
10012     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10013     uint64_t AndRHSVal = AndRHS->getZExtValue();
10014     SDValue AndLHS = Op0;
10015
10016     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10017       LHS = AndLHS.getOperand(0);
10018       RHS = AndLHS.getOperand(1);
10019     }
10020
10021     // Use BT if the immediate can't be encoded in a TEST instruction.
10022     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10023       LHS = AndLHS;
10024       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10025     }
10026   }
10027
10028   if (LHS.getNode()) {
10029     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10030     // instruction.  Since the shift amount is in-range-or-undefined, we know
10031     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10032     // the encoding for the i16 version is larger than the i32 version.
10033     // Also promote i16 to i32 for performance / code size reason.
10034     if (LHS.getValueType() == MVT::i8 ||
10035         LHS.getValueType() == MVT::i16)
10036       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10037
10038     // If the operand types disagree, extend the shift amount to match.  Since
10039     // BT ignores high bits (like shifts) we can use anyextend.
10040     if (LHS.getValueType() != RHS.getValueType())
10041       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10042
10043     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10044     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10045     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10046                        DAG.getConstant(Cond, MVT::i8), BT);
10047   }
10048
10049   return SDValue();
10050 }
10051
10052 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10053 /// mask CMPs.
10054 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10055                               SDValue &Op1) {
10056   unsigned SSECC;
10057   bool Swap = false;
10058
10059   // SSE Condition code mapping:
10060   //  0 - EQ
10061   //  1 - LT
10062   //  2 - LE
10063   //  3 - UNORD
10064   //  4 - NEQ
10065   //  5 - NLT
10066   //  6 - NLE
10067   //  7 - ORD
10068   switch (SetCCOpcode) {
10069   default: llvm_unreachable("Unexpected SETCC condition");
10070   case ISD::SETOEQ:
10071   case ISD::SETEQ:  SSECC = 0; break;
10072   case ISD::SETOGT:
10073   case ISD::SETGT:  Swap = true; // Fallthrough
10074   case ISD::SETLT:
10075   case ISD::SETOLT: SSECC = 1; break;
10076   case ISD::SETOGE:
10077   case ISD::SETGE:  Swap = true; // Fallthrough
10078   case ISD::SETLE:
10079   case ISD::SETOLE: SSECC = 2; break;
10080   case ISD::SETUO:  SSECC = 3; break;
10081   case ISD::SETUNE:
10082   case ISD::SETNE:  SSECC = 4; break;
10083   case ISD::SETULE: Swap = true; // Fallthrough
10084   case ISD::SETUGE: SSECC = 5; break;
10085   case ISD::SETULT: Swap = true; // Fallthrough
10086   case ISD::SETUGT: SSECC = 6; break;
10087   case ISD::SETO:   SSECC = 7; break;
10088   case ISD::SETUEQ:
10089   case ISD::SETONE: SSECC = 8; break;
10090   }
10091   if (Swap)
10092     std::swap(Op0, Op1);
10093
10094   return SSECC;
10095 }
10096
10097 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10098 // ones, and then concatenate the result back.
10099 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10100   MVT VT = Op.getSimpleValueType();
10101
10102   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10103          "Unsupported value type for operation");
10104
10105   unsigned NumElems = VT.getVectorNumElements();
10106   SDLoc dl(Op);
10107   SDValue CC = Op.getOperand(2);
10108
10109   // Extract the LHS vectors
10110   SDValue LHS = Op.getOperand(0);
10111   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10112   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10113
10114   // Extract the RHS vectors
10115   SDValue RHS = Op.getOperand(1);
10116   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10117   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10118
10119   // Issue the operation on the smaller types and concatenate the result back
10120   MVT EltVT = VT.getVectorElementType();
10121   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10122   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10123                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10124                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10125 }
10126
10127 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10128                                      const X86Subtarget *Subtarget) {
10129   SDValue Op0 = Op.getOperand(0);
10130   SDValue Op1 = Op.getOperand(1);
10131   SDValue CC = Op.getOperand(2);
10132   MVT VT = Op.getSimpleValueType();
10133   SDLoc dl(Op);
10134
10135   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10136          Op.getValueType().getScalarType() == MVT::i1 &&
10137          "Cannot set masked compare for this operation");
10138
10139   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10140   unsigned  Opc = 0;
10141   bool Unsigned = false;
10142   bool Swap = false;
10143   unsigned SSECC;
10144   switch (SetCCOpcode) {
10145   default: llvm_unreachable("Unexpected SETCC condition");
10146   case ISD::SETNE:  SSECC = 4; break;
10147   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10148   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10149   case ISD::SETLT:  Swap = true; //fall-through
10150   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10151   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10152   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10153   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10154   case ISD::SETULE: Unsigned = true; //fall-through
10155   case ISD::SETLE:  SSECC = 2; break;
10156   }
10157
10158   if (Swap)
10159     std::swap(Op0, Op1);
10160   if (Opc)
10161     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10162   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10163   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10164                      DAG.getConstant(SSECC, MVT::i8));
10165 }
10166
10167 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10168 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10169 /// return an empty value.
10170 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10171 {
10172   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10173   if (!BV)
10174     return SDValue();
10175
10176   MVT VT = Op1.getSimpleValueType();
10177   MVT EVT = VT.getVectorElementType();
10178   unsigned n = VT.getVectorNumElements();
10179   SmallVector<SDValue, 8> ULTOp1;
10180
10181   for (unsigned i = 0; i < n; ++i) {
10182     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10183     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10184       return SDValue();
10185
10186     // Avoid underflow.
10187     APInt Val = Elt->getAPIntValue();
10188     if (Val == 0)
10189       return SDValue();
10190
10191     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10192   }
10193
10194   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10195 }
10196
10197 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10198                            SelectionDAG &DAG) {
10199   SDValue Op0 = Op.getOperand(0);
10200   SDValue Op1 = Op.getOperand(1);
10201   SDValue CC = Op.getOperand(2);
10202   MVT VT = Op.getSimpleValueType();
10203   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10204   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10205   SDLoc dl(Op);
10206
10207   if (isFP) {
10208 #ifndef NDEBUG
10209     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10210     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10211 #endif
10212
10213     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10214     unsigned Opc = X86ISD::CMPP;
10215     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10216       assert(VT.getVectorNumElements() <= 16);
10217       Opc = X86ISD::CMPM;
10218     }
10219     // In the two special cases we can't handle, emit two comparisons.
10220     if (SSECC == 8) {
10221       unsigned CC0, CC1;
10222       unsigned CombineOpc;
10223       if (SetCCOpcode == ISD::SETUEQ) {
10224         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10225       } else {
10226         assert(SetCCOpcode == ISD::SETONE);
10227         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10228       }
10229
10230       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10231                                  DAG.getConstant(CC0, MVT::i8));
10232       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10233                                  DAG.getConstant(CC1, MVT::i8));
10234       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10235     }
10236     // Handle all other FP comparisons here.
10237     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10238                        DAG.getConstant(SSECC, MVT::i8));
10239   }
10240
10241   // Break 256-bit integer vector compare into smaller ones.
10242   if (VT.is256BitVector() && !Subtarget->hasInt256())
10243     return Lower256IntVSETCC(Op, DAG);
10244
10245   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10246   EVT OpVT = Op1.getValueType();
10247   if (Subtarget->hasAVX512()) {
10248     if (Op1.getValueType().is512BitVector() ||
10249         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10250       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10251
10252     // In AVX-512 architecture setcc returns mask with i1 elements,
10253     // But there is no compare instruction for i8 and i16 elements.
10254     // We are not talking about 512-bit operands in this case, these
10255     // types are illegal.
10256     if (MaskResult &&
10257         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10258          OpVT.getVectorElementType().getSizeInBits() >= 8))
10259       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10260                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10261   }
10262
10263   // We are handling one of the integer comparisons here.  Since SSE only has
10264   // GT and EQ comparisons for integer, swapping operands and multiple
10265   // operations may be required for some comparisons.
10266   unsigned Opc;
10267   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10268   bool Subus = false;
10269
10270   switch (SetCCOpcode) {
10271   default: llvm_unreachable("Unexpected SETCC condition");
10272   case ISD::SETNE:  Invert = true;
10273   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10274   case ISD::SETLT:  Swap = true;
10275   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10276   case ISD::SETGE:  Swap = true;
10277   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10278                     Invert = true; break;
10279   case ISD::SETULT: Swap = true;
10280   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10281                     FlipSigns = true; break;
10282   case ISD::SETUGE: Swap = true;
10283   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10284                     FlipSigns = true; Invert = true; break;
10285   }
10286
10287   // Special case: Use min/max operations for SETULE/SETUGE
10288   MVT VET = VT.getVectorElementType();
10289   bool hasMinMax =
10290        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10291     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10292
10293   if (hasMinMax) {
10294     switch (SetCCOpcode) {
10295     default: break;
10296     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10297     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10298     }
10299
10300     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10301   }
10302
10303   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10304   if (!MinMax && hasSubus) {
10305     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10306     // Op0 u<= Op1:
10307     //   t = psubus Op0, Op1
10308     //   pcmpeq t, <0..0>
10309     switch (SetCCOpcode) {
10310     default: break;
10311     case ISD::SETULT: {
10312       // If the comparison is against a constant we can turn this into a
10313       // setule.  With psubus, setule does not require a swap.  This is
10314       // beneficial because the constant in the register is no longer
10315       // destructed as the destination so it can be hoisted out of a loop.
10316       // Only do this pre-AVX since vpcmp* is no longer destructive.
10317       if (Subtarget->hasAVX())
10318         break;
10319       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10320       if (ULEOp1.getNode()) {
10321         Op1 = ULEOp1;
10322         Subus = true; Invert = false; Swap = false;
10323       }
10324       break;
10325     }
10326     // Psubus is better than flip-sign because it requires no inversion.
10327     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10328     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10329     }
10330
10331     if (Subus) {
10332       Opc = X86ISD::SUBUS;
10333       FlipSigns = false;
10334     }
10335   }
10336
10337   if (Swap)
10338     std::swap(Op0, Op1);
10339
10340   // Check that the operation in question is available (most are plain SSE2,
10341   // but PCMPGTQ and PCMPEQQ have different requirements).
10342   if (VT == MVT::v2i64) {
10343     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10344       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10345
10346       // First cast everything to the right type.
10347       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10348       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10349
10350       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10351       // bits of the inputs before performing those operations. The lower
10352       // compare is always unsigned.
10353       SDValue SB;
10354       if (FlipSigns) {
10355         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10356       } else {
10357         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10358         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10359         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10360                          Sign, Zero, Sign, Zero);
10361       }
10362       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10363       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10364
10365       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10366       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10367       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10368
10369       // Create masks for only the low parts/high parts of the 64 bit integers.
10370       static const int MaskHi[] = { 1, 1, 3, 3 };
10371       static const int MaskLo[] = { 0, 0, 2, 2 };
10372       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10373       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10374       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10375
10376       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10377       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10378
10379       if (Invert)
10380         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10381
10382       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10383     }
10384
10385     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10386       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10387       // pcmpeqd + pshufd + pand.
10388       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10389
10390       // First cast everything to the right type.
10391       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10392       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10393
10394       // Do the compare.
10395       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10396
10397       // Make sure the lower and upper halves are both all-ones.
10398       static const int Mask[] = { 1, 0, 3, 2 };
10399       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10400       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10401
10402       if (Invert)
10403         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10404
10405       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10406     }
10407   }
10408
10409   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10410   // bits of the inputs before performing those operations.
10411   if (FlipSigns) {
10412     EVT EltVT = VT.getVectorElementType();
10413     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10414     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10415     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10416   }
10417
10418   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10419
10420   // If the logical-not of the result is required, perform that now.
10421   if (Invert)
10422     Result = DAG.getNOT(dl, Result, VT);
10423
10424   if (MinMax)
10425     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10426
10427   if (Subus)
10428     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10429                          getZeroVector(VT, Subtarget, DAG, dl));
10430
10431   return Result;
10432 }
10433
10434 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10435
10436   MVT VT = Op.getSimpleValueType();
10437
10438   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10439
10440   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10441          && "SetCC type must be 8-bit or 1-bit integer");
10442   SDValue Op0 = Op.getOperand(0);
10443   SDValue Op1 = Op.getOperand(1);
10444   SDLoc dl(Op);
10445   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10446
10447   // Optimize to BT if possible.
10448   // Lower (X & (1 << N)) == 0 to BT(X, N).
10449   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10450   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10451   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10452       Op1.getOpcode() == ISD::Constant &&
10453       cast<ConstantSDNode>(Op1)->isNullValue() &&
10454       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10455     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10456     if (NewSetCC.getNode())
10457       return NewSetCC;
10458   }
10459
10460   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10461   // these.
10462   if (Op1.getOpcode() == ISD::Constant &&
10463       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10464        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10465       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10466
10467     // If the input is a setcc, then reuse the input setcc or use a new one with
10468     // the inverted condition.
10469     if (Op0.getOpcode() == X86ISD::SETCC) {
10470       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10471       bool Invert = (CC == ISD::SETNE) ^
10472         cast<ConstantSDNode>(Op1)->isNullValue();
10473       if (!Invert)
10474         return Op0;
10475
10476       CCode = X86::GetOppositeBranchCondition(CCode);
10477       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10478                                   DAG.getConstant(CCode, MVT::i8),
10479                                   Op0.getOperand(1));
10480       if (VT == MVT::i1)
10481         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10482       return SetCC;
10483     }
10484   }
10485   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10486       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10487       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10488
10489     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10490     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10491   }
10492
10493   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10494   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10495   if (X86CC == X86::COND_INVALID)
10496     return SDValue();
10497
10498   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10499   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10500   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10501                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10502   if (VT == MVT::i1)
10503     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10504   return SetCC;
10505 }
10506
10507 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10508 static bool isX86LogicalCmp(SDValue Op) {
10509   unsigned Opc = Op.getNode()->getOpcode();
10510   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10511       Opc == X86ISD::SAHF)
10512     return true;
10513   if (Op.getResNo() == 1 &&
10514       (Opc == X86ISD::ADD ||
10515        Opc == X86ISD::SUB ||
10516        Opc == X86ISD::ADC ||
10517        Opc == X86ISD::SBB ||
10518        Opc == X86ISD::SMUL ||
10519        Opc == X86ISD::UMUL ||
10520        Opc == X86ISD::INC ||
10521        Opc == X86ISD::DEC ||
10522        Opc == X86ISD::OR ||
10523        Opc == X86ISD::XOR ||
10524        Opc == X86ISD::AND))
10525     return true;
10526
10527   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10528     return true;
10529
10530   return false;
10531 }
10532
10533 static bool isZero(SDValue V) {
10534   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10535   return C && C->isNullValue();
10536 }
10537
10538 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10539   if (V.getOpcode() != ISD::TRUNCATE)
10540     return false;
10541
10542   SDValue VOp0 = V.getOperand(0);
10543   unsigned InBits = VOp0.getValueSizeInBits();
10544   unsigned Bits = V.getValueSizeInBits();
10545   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10546 }
10547
10548 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10549   bool addTest = true;
10550   SDValue Cond  = Op.getOperand(0);
10551   SDValue Op1 = Op.getOperand(1);
10552   SDValue Op2 = Op.getOperand(2);
10553   SDLoc DL(Op);
10554   EVT VT = Op1.getValueType();
10555   SDValue CC;
10556
10557   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10558   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10559   // sequence later on.
10560   if (Cond.getOpcode() == ISD::SETCC &&
10561       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10562        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10563       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10564     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10565     int SSECC = translateX86FSETCC(
10566         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10567
10568     if (SSECC != 8) {
10569       if (Subtarget->hasAVX512()) {
10570         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10571                                   DAG.getConstant(SSECC, MVT::i8));
10572         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10573       }
10574       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10575                                 DAG.getConstant(SSECC, MVT::i8));
10576       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10577       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10578       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10579     }
10580   }
10581
10582   if (Cond.getOpcode() == ISD::SETCC) {
10583     SDValue NewCond = LowerSETCC(Cond, DAG);
10584     if (NewCond.getNode())
10585       Cond = NewCond;
10586   }
10587
10588   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10589   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10590   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10591   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10592   if (Cond.getOpcode() == X86ISD::SETCC &&
10593       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10594       isZero(Cond.getOperand(1).getOperand(1))) {
10595     SDValue Cmp = Cond.getOperand(1);
10596
10597     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10598
10599     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10600         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10601       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10602
10603       SDValue CmpOp0 = Cmp.getOperand(0);
10604       // Apply further optimizations for special cases
10605       // (select (x != 0), -1, 0) -> neg & sbb
10606       // (select (x == 0), 0, -1) -> neg & sbb
10607       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10608         if (YC->isNullValue() &&
10609             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10610           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10611           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10612                                     DAG.getConstant(0, CmpOp0.getValueType()),
10613                                     CmpOp0);
10614           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10615                                     DAG.getConstant(X86::COND_B, MVT::i8),
10616                                     SDValue(Neg.getNode(), 1));
10617           return Res;
10618         }
10619
10620       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10621                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10622       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10623
10624       SDValue Res =   // Res = 0 or -1.
10625         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10626                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10627
10628       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10629         Res = DAG.getNOT(DL, Res, Res.getValueType());
10630
10631       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10632       if (N2C == 0 || !N2C->isNullValue())
10633         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10634       return Res;
10635     }
10636   }
10637
10638   // Look past (and (setcc_carry (cmp ...)), 1).
10639   if (Cond.getOpcode() == ISD::AND &&
10640       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10641     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10642     if (C && C->getAPIntValue() == 1)
10643       Cond = Cond.getOperand(0);
10644   }
10645
10646   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10647   // setting operand in place of the X86ISD::SETCC.
10648   unsigned CondOpcode = Cond.getOpcode();
10649   if (CondOpcode == X86ISD::SETCC ||
10650       CondOpcode == X86ISD::SETCC_CARRY) {
10651     CC = Cond.getOperand(0);
10652
10653     SDValue Cmp = Cond.getOperand(1);
10654     unsigned Opc = Cmp.getOpcode();
10655     MVT VT = Op.getSimpleValueType();
10656
10657     bool IllegalFPCMov = false;
10658     if (VT.isFloatingPoint() && !VT.isVector() &&
10659         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10660       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10661
10662     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10663         Opc == X86ISD::BT) { // FIXME
10664       Cond = Cmp;
10665       addTest = false;
10666     }
10667   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10668              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10669              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10670               Cond.getOperand(0).getValueType() != MVT::i8)) {
10671     SDValue LHS = Cond.getOperand(0);
10672     SDValue RHS = Cond.getOperand(1);
10673     unsigned X86Opcode;
10674     unsigned X86Cond;
10675     SDVTList VTs;
10676     switch (CondOpcode) {
10677     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10678     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10679     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10680     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10681     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10682     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10683     default: llvm_unreachable("unexpected overflowing operator");
10684     }
10685     if (CondOpcode == ISD::UMULO)
10686       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10687                           MVT::i32);
10688     else
10689       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10690
10691     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10692
10693     if (CondOpcode == ISD::UMULO)
10694       Cond = X86Op.getValue(2);
10695     else
10696       Cond = X86Op.getValue(1);
10697
10698     CC = DAG.getConstant(X86Cond, MVT::i8);
10699     addTest = false;
10700   }
10701
10702   if (addTest) {
10703     // Look pass the truncate if the high bits are known zero.
10704     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10705         Cond = Cond.getOperand(0);
10706
10707     // We know the result of AND is compared against zero. Try to match
10708     // it to BT.
10709     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10710       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10711       if (NewSetCC.getNode()) {
10712         CC = NewSetCC.getOperand(0);
10713         Cond = NewSetCC.getOperand(1);
10714         addTest = false;
10715       }
10716     }
10717   }
10718
10719   if (addTest) {
10720     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10721     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10722   }
10723
10724   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10725   // a <  b ?  0 : -1 -> RES = setcc_carry
10726   // a >= b ? -1 :  0 -> RES = setcc_carry
10727   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10728   if (Cond.getOpcode() == X86ISD::SUB) {
10729     Cond = ConvertCmpIfNecessary(Cond, DAG);
10730     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10731
10732     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10733         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10734       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10735                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10736       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10737         return DAG.getNOT(DL, Res, Res.getValueType());
10738       return Res;
10739     }
10740   }
10741
10742   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10743   // widen the cmov and push the truncate through. This avoids introducing a new
10744   // branch during isel and doesn't add any extensions.
10745   if (Op.getValueType() == MVT::i8 &&
10746       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10747     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10748     if (T1.getValueType() == T2.getValueType() &&
10749         // Blacklist CopyFromReg to avoid partial register stalls.
10750         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10751       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10752       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10753       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10754     }
10755   }
10756
10757   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10758   // condition is true.
10759   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10760   SDValue Ops[] = { Op2, Op1, CC, Cond };
10761   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10762 }
10763
10764 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10765   MVT VT = Op->getSimpleValueType(0);
10766   SDValue In = Op->getOperand(0);
10767   MVT InVT = In.getSimpleValueType();
10768   SDLoc dl(Op);
10769
10770   unsigned int NumElts = VT.getVectorNumElements();
10771   if (NumElts != 8 && NumElts != 16)
10772     return SDValue();
10773
10774   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10775     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10776
10777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10778   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10779
10780   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10781   Constant *C = ConstantInt::get(*DAG.getContext(),
10782     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10783
10784   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10785   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10786   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10787                           MachinePointerInfo::getConstantPool(),
10788                           false, false, false, Alignment);
10789   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10790   if (VT.is512BitVector())
10791     return Brcst;
10792   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10793 }
10794
10795 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10796                                 SelectionDAG &DAG) {
10797   MVT VT = Op->getSimpleValueType(0);
10798   SDValue In = Op->getOperand(0);
10799   MVT InVT = In.getSimpleValueType();
10800   SDLoc dl(Op);
10801
10802   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10803     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10804
10805   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10806       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10807       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10808     return SDValue();
10809
10810   if (Subtarget->hasInt256())
10811     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10812
10813   // Optimize vectors in AVX mode
10814   // Sign extend  v8i16 to v8i32 and
10815   //              v4i32 to v4i64
10816   //
10817   // Divide input vector into two parts
10818   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10819   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10820   // concat the vectors to original VT
10821
10822   unsigned NumElems = InVT.getVectorNumElements();
10823   SDValue Undef = DAG.getUNDEF(InVT);
10824
10825   SmallVector<int,8> ShufMask1(NumElems, -1);
10826   for (unsigned i = 0; i != NumElems/2; ++i)
10827     ShufMask1[i] = i;
10828
10829   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10830
10831   SmallVector<int,8> ShufMask2(NumElems, -1);
10832   for (unsigned i = 0; i != NumElems/2; ++i)
10833     ShufMask2[i] = i + NumElems/2;
10834
10835   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10836
10837   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10838                                 VT.getVectorNumElements()/2);
10839
10840   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10841   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10842
10843   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10844 }
10845
10846 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10847 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10848 // from the AND / OR.
10849 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10850   Opc = Op.getOpcode();
10851   if (Opc != ISD::OR && Opc != ISD::AND)
10852     return false;
10853   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10854           Op.getOperand(0).hasOneUse() &&
10855           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10856           Op.getOperand(1).hasOneUse());
10857 }
10858
10859 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10860 // 1 and that the SETCC node has a single use.
10861 static bool isXor1OfSetCC(SDValue Op) {
10862   if (Op.getOpcode() != ISD::XOR)
10863     return false;
10864   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10865   if (N1C && N1C->getAPIntValue() == 1) {
10866     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10867       Op.getOperand(0).hasOneUse();
10868   }
10869   return false;
10870 }
10871
10872 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10873   bool addTest = true;
10874   SDValue Chain = Op.getOperand(0);
10875   SDValue Cond  = Op.getOperand(1);
10876   SDValue Dest  = Op.getOperand(2);
10877   SDLoc dl(Op);
10878   SDValue CC;
10879   bool Inverted = false;
10880
10881   if (Cond.getOpcode() == ISD::SETCC) {
10882     // Check for setcc([su]{add,sub,mul}o == 0).
10883     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10884         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10885         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10886         Cond.getOperand(0).getResNo() == 1 &&
10887         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10888          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10889          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10890          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10891          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10892          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10893       Inverted = true;
10894       Cond = Cond.getOperand(0);
10895     } else {
10896       SDValue NewCond = LowerSETCC(Cond, DAG);
10897       if (NewCond.getNode())
10898         Cond = NewCond;
10899     }
10900   }
10901 #if 0
10902   // FIXME: LowerXALUO doesn't handle these!!
10903   else if (Cond.getOpcode() == X86ISD::ADD  ||
10904            Cond.getOpcode() == X86ISD::SUB  ||
10905            Cond.getOpcode() == X86ISD::SMUL ||
10906            Cond.getOpcode() == X86ISD::UMUL)
10907     Cond = LowerXALUO(Cond, DAG);
10908 #endif
10909
10910   // Look pass (and (setcc_carry (cmp ...)), 1).
10911   if (Cond.getOpcode() == ISD::AND &&
10912       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10913     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10914     if (C && C->getAPIntValue() == 1)
10915       Cond = Cond.getOperand(0);
10916   }
10917
10918   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10919   // setting operand in place of the X86ISD::SETCC.
10920   unsigned CondOpcode = Cond.getOpcode();
10921   if (CondOpcode == X86ISD::SETCC ||
10922       CondOpcode == X86ISD::SETCC_CARRY) {
10923     CC = Cond.getOperand(0);
10924
10925     SDValue Cmp = Cond.getOperand(1);
10926     unsigned Opc = Cmp.getOpcode();
10927     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10928     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10929       Cond = Cmp;
10930       addTest = false;
10931     } else {
10932       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10933       default: break;
10934       case X86::COND_O:
10935       case X86::COND_B:
10936         // These can only come from an arithmetic instruction with overflow,
10937         // e.g. SADDO, UADDO.
10938         Cond = Cond.getNode()->getOperand(1);
10939         addTest = false;
10940         break;
10941       }
10942     }
10943   }
10944   CondOpcode = Cond.getOpcode();
10945   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10946       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10947       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10948        Cond.getOperand(0).getValueType() != MVT::i8)) {
10949     SDValue LHS = Cond.getOperand(0);
10950     SDValue RHS = Cond.getOperand(1);
10951     unsigned X86Opcode;
10952     unsigned X86Cond;
10953     SDVTList VTs;
10954     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10955     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10956     // X86ISD::INC).
10957     switch (CondOpcode) {
10958     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10959     case ISD::SADDO:
10960       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10961         if (C->isOne()) {
10962           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10963           break;
10964         }
10965       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10966     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10967     case ISD::SSUBO:
10968       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10969         if (C->isOne()) {
10970           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10971           break;
10972         }
10973       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10974     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10975     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10976     default: llvm_unreachable("unexpected overflowing operator");
10977     }
10978     if (Inverted)
10979       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10980     if (CondOpcode == ISD::UMULO)
10981       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10982                           MVT::i32);
10983     else
10984       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10985
10986     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10987
10988     if (CondOpcode == ISD::UMULO)
10989       Cond = X86Op.getValue(2);
10990     else
10991       Cond = X86Op.getValue(1);
10992
10993     CC = DAG.getConstant(X86Cond, MVT::i8);
10994     addTest = false;
10995   } else {
10996     unsigned CondOpc;
10997     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10998       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10999       if (CondOpc == ISD::OR) {
11000         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11001         // two branches instead of an explicit OR instruction with a
11002         // separate test.
11003         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11004             isX86LogicalCmp(Cmp)) {
11005           CC = Cond.getOperand(0).getOperand(0);
11006           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11007                               Chain, Dest, CC, Cmp);
11008           CC = Cond.getOperand(1).getOperand(0);
11009           Cond = Cmp;
11010           addTest = false;
11011         }
11012       } else { // ISD::AND
11013         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11014         // two branches instead of an explicit AND instruction with a
11015         // separate test. However, we only do this if this block doesn't
11016         // have a fall-through edge, because this requires an explicit
11017         // jmp when the condition is false.
11018         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11019             isX86LogicalCmp(Cmp) &&
11020             Op.getNode()->hasOneUse()) {
11021           X86::CondCode CCode =
11022             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11023           CCode = X86::GetOppositeBranchCondition(CCode);
11024           CC = DAG.getConstant(CCode, MVT::i8);
11025           SDNode *User = *Op.getNode()->use_begin();
11026           // Look for an unconditional branch following this conditional branch.
11027           // We need this because we need to reverse the successors in order
11028           // to implement FCMP_OEQ.
11029           if (User->getOpcode() == ISD::BR) {
11030             SDValue FalseBB = User->getOperand(1);
11031             SDNode *NewBR =
11032               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11033             assert(NewBR == User);
11034             (void)NewBR;
11035             Dest = FalseBB;
11036
11037             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11038                                 Chain, Dest, CC, Cmp);
11039             X86::CondCode CCode =
11040               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11041             CCode = X86::GetOppositeBranchCondition(CCode);
11042             CC = DAG.getConstant(CCode, MVT::i8);
11043             Cond = Cmp;
11044             addTest = false;
11045           }
11046         }
11047       }
11048     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11049       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11050       // It should be transformed during dag combiner except when the condition
11051       // is set by a arithmetics with overflow node.
11052       X86::CondCode CCode =
11053         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11054       CCode = X86::GetOppositeBranchCondition(CCode);
11055       CC = DAG.getConstant(CCode, MVT::i8);
11056       Cond = Cond.getOperand(0).getOperand(1);
11057       addTest = false;
11058     } else if (Cond.getOpcode() == ISD::SETCC &&
11059                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11060       // For FCMP_OEQ, we can emit
11061       // two branches instead of an explicit AND instruction with a
11062       // separate test. However, we only do this if this block doesn't
11063       // have a fall-through edge, because this requires an explicit
11064       // jmp when the condition is false.
11065       if (Op.getNode()->hasOneUse()) {
11066         SDNode *User = *Op.getNode()->use_begin();
11067         // Look for an unconditional branch following this conditional branch.
11068         // We need this because we need to reverse the successors in order
11069         // to implement FCMP_OEQ.
11070         if (User->getOpcode() == ISD::BR) {
11071           SDValue FalseBB = User->getOperand(1);
11072           SDNode *NewBR =
11073             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11074           assert(NewBR == User);
11075           (void)NewBR;
11076           Dest = FalseBB;
11077
11078           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11079                                     Cond.getOperand(0), Cond.getOperand(1));
11080           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11081           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11082           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11083                               Chain, Dest, CC, Cmp);
11084           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11085           Cond = Cmp;
11086           addTest = false;
11087         }
11088       }
11089     } else if (Cond.getOpcode() == ISD::SETCC &&
11090                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11091       // For FCMP_UNE, we can emit
11092       // two branches instead of an explicit AND instruction with a
11093       // separate test. However, we only do this if this block doesn't
11094       // have a fall-through edge, because this requires an explicit
11095       // jmp when the condition is false.
11096       if (Op.getNode()->hasOneUse()) {
11097         SDNode *User = *Op.getNode()->use_begin();
11098         // Look for an unconditional branch following this conditional branch.
11099         // We need this because we need to reverse the successors in order
11100         // to implement FCMP_UNE.
11101         if (User->getOpcode() == ISD::BR) {
11102           SDValue FalseBB = User->getOperand(1);
11103           SDNode *NewBR =
11104             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11105           assert(NewBR == User);
11106           (void)NewBR;
11107
11108           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11109                                     Cond.getOperand(0), Cond.getOperand(1));
11110           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11111           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11112           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11113                               Chain, Dest, CC, Cmp);
11114           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11115           Cond = Cmp;
11116           addTest = false;
11117           Dest = FalseBB;
11118         }
11119       }
11120     }
11121   }
11122
11123   if (addTest) {
11124     // Look pass the truncate if the high bits are known zero.
11125     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11126         Cond = Cond.getOperand(0);
11127
11128     // We know the result of AND is compared against zero. Try to match
11129     // it to BT.
11130     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11131       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11132       if (NewSetCC.getNode()) {
11133         CC = NewSetCC.getOperand(0);
11134         Cond = NewSetCC.getOperand(1);
11135         addTest = false;
11136       }
11137     }
11138   }
11139
11140   if (addTest) {
11141     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11142     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11143   }
11144   Cond = ConvertCmpIfNecessary(Cond, DAG);
11145   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11146                      Chain, Dest, CC, Cond);
11147 }
11148
11149 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11150 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11151 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11152 // that the guard pages used by the OS virtual memory manager are allocated in
11153 // correct sequence.
11154 SDValue
11155 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11156                                            SelectionDAG &DAG) const {
11157   MachineFunction &MF = DAG.getMachineFunction();
11158   bool SplitStack = MF.shouldSplitStack();
11159   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11160                SplitStack;
11161   SDLoc dl(Op);
11162
11163   if (!Lower) {
11164     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11165     SDNode* Node = Op.getNode();
11166
11167     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11168     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11169         " not tell us which reg is the stack pointer!");
11170     EVT VT = Node->getValueType(0);
11171     SDValue Tmp1 = SDValue(Node, 0);
11172     SDValue Tmp2 = SDValue(Node, 1);
11173     SDValue Tmp3 = Node->getOperand(2);
11174     SDValue Chain = Tmp1.getOperand(0);
11175
11176     // Chain the dynamic stack allocation so that it doesn't modify the stack
11177     // pointer when other instructions are using the stack.
11178     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11179         SDLoc(Node));
11180
11181     SDValue Size = Tmp2.getOperand(1);
11182     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11183     Chain = SP.getValue(1);
11184     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11185     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11186     unsigned StackAlign = TFI.getStackAlignment();
11187     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11188     if (Align > StackAlign)
11189       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11190           DAG.getConstant(-(uint64_t)Align, VT));
11191     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11192
11193     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11194         DAG.getIntPtrConstant(0, true), SDValue(),
11195         SDLoc(Node));
11196
11197     SDValue Ops[2] = { Tmp1, Tmp2 };
11198     return DAG.getMergeValues(Ops, 2, dl);
11199   }
11200
11201   // Get the inputs.
11202   SDValue Chain = Op.getOperand(0);
11203   SDValue Size  = Op.getOperand(1);
11204   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11205   EVT VT = Op.getNode()->getValueType(0);
11206
11207   bool Is64Bit = Subtarget->is64Bit();
11208   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11209
11210   if (SplitStack) {
11211     MachineRegisterInfo &MRI = MF.getRegInfo();
11212
11213     if (Is64Bit) {
11214       // The 64 bit implementation of segmented stacks needs to clobber both r10
11215       // r11. This makes it impossible to use it along with nested parameters.
11216       const Function *F = MF.getFunction();
11217
11218       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11219            I != E; ++I)
11220         if (I->hasNestAttr())
11221           report_fatal_error("Cannot use segmented stacks with functions that "
11222                              "have nested arguments.");
11223     }
11224
11225     const TargetRegisterClass *AddrRegClass =
11226       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11227     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11228     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11229     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11230                                 DAG.getRegister(Vreg, SPTy));
11231     SDValue Ops1[2] = { Value, Chain };
11232     return DAG.getMergeValues(Ops1, 2, dl);
11233   } else {
11234     SDValue Flag;
11235     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11236
11237     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11238     Flag = Chain.getValue(1);
11239     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11240
11241     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11242
11243     const X86RegisterInfo *RegInfo =
11244       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11245     unsigned SPReg = RegInfo->getStackRegister();
11246     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11247     Chain = SP.getValue(1);
11248
11249     if (Align) {
11250       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11251                        DAG.getConstant(-(uint64_t)Align, VT));
11252       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11253     }
11254
11255     SDValue Ops1[2] = { SP, Chain };
11256     return DAG.getMergeValues(Ops1, 2, dl);
11257   }
11258 }
11259
11260 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11261   MachineFunction &MF = DAG.getMachineFunction();
11262   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11263
11264   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11265   SDLoc DL(Op);
11266
11267   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11268     // vastart just stores the address of the VarArgsFrameIndex slot into the
11269     // memory location argument.
11270     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11271                                    getPointerTy());
11272     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11273                         MachinePointerInfo(SV), false, false, 0);
11274   }
11275
11276   // __va_list_tag:
11277   //   gp_offset         (0 - 6 * 8)
11278   //   fp_offset         (48 - 48 + 8 * 16)
11279   //   overflow_arg_area (point to parameters coming in memory).
11280   //   reg_save_area
11281   SmallVector<SDValue, 8> MemOps;
11282   SDValue FIN = Op.getOperand(1);
11283   // Store gp_offset
11284   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11285                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11286                                                MVT::i32),
11287                                FIN, MachinePointerInfo(SV), false, false, 0);
11288   MemOps.push_back(Store);
11289
11290   // Store fp_offset
11291   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11292                     FIN, DAG.getIntPtrConstant(4));
11293   Store = DAG.getStore(Op.getOperand(0), DL,
11294                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11295                                        MVT::i32),
11296                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11297   MemOps.push_back(Store);
11298
11299   // Store ptr to overflow_arg_area
11300   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11301                     FIN, DAG.getIntPtrConstant(4));
11302   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11303                                     getPointerTy());
11304   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11305                        MachinePointerInfo(SV, 8),
11306                        false, false, 0);
11307   MemOps.push_back(Store);
11308
11309   // Store ptr to reg_save_area.
11310   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11311                     FIN, DAG.getIntPtrConstant(8));
11312   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11313                                     getPointerTy());
11314   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11315                        MachinePointerInfo(SV, 16), false, false, 0);
11316   MemOps.push_back(Store);
11317   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11318                      &MemOps[0], MemOps.size());
11319 }
11320
11321 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11322   assert(Subtarget->is64Bit() &&
11323          "LowerVAARG only handles 64-bit va_arg!");
11324   assert((Subtarget->isTargetLinux() ||
11325           Subtarget->isTargetDarwin()) &&
11326           "Unhandled target in LowerVAARG");
11327   assert(Op.getNode()->getNumOperands() == 4);
11328   SDValue Chain = Op.getOperand(0);
11329   SDValue SrcPtr = Op.getOperand(1);
11330   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11331   unsigned Align = Op.getConstantOperandVal(3);
11332   SDLoc dl(Op);
11333
11334   EVT ArgVT = Op.getNode()->getValueType(0);
11335   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11336   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11337   uint8_t ArgMode;
11338
11339   // Decide which area this value should be read from.
11340   // TODO: Implement the AMD64 ABI in its entirety. This simple
11341   // selection mechanism works only for the basic types.
11342   if (ArgVT == MVT::f80) {
11343     llvm_unreachable("va_arg for f80 not yet implemented");
11344   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11345     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11346   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11347     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11348   } else {
11349     llvm_unreachable("Unhandled argument type in LowerVAARG");
11350   }
11351
11352   if (ArgMode == 2) {
11353     // Sanity Check: Make sure using fp_offset makes sense.
11354     assert(!getTargetMachine().Options.UseSoftFloat &&
11355            !(DAG.getMachineFunction()
11356                 .getFunction()->getAttributes()
11357                 .hasAttribute(AttributeSet::FunctionIndex,
11358                               Attribute::NoImplicitFloat)) &&
11359            Subtarget->hasSSE1());
11360   }
11361
11362   // Insert VAARG_64 node into the DAG
11363   // VAARG_64 returns two values: Variable Argument Address, Chain
11364   SmallVector<SDValue, 11> InstOps;
11365   InstOps.push_back(Chain);
11366   InstOps.push_back(SrcPtr);
11367   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11368   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11369   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11370   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11371   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11372                                           VTs, &InstOps[0], InstOps.size(),
11373                                           MVT::i64,
11374                                           MachinePointerInfo(SV),
11375                                           /*Align=*/0,
11376                                           /*Volatile=*/false,
11377                                           /*ReadMem=*/true,
11378                                           /*WriteMem=*/true);
11379   Chain = VAARG.getValue(1);
11380
11381   // Load the next argument and return it
11382   return DAG.getLoad(ArgVT, dl,
11383                      Chain,
11384                      VAARG,
11385                      MachinePointerInfo(),
11386                      false, false, false, 0);
11387 }
11388
11389 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11390                            SelectionDAG &DAG) {
11391   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11392   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11393   SDValue Chain = Op.getOperand(0);
11394   SDValue DstPtr = Op.getOperand(1);
11395   SDValue SrcPtr = Op.getOperand(2);
11396   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11397   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11398   SDLoc DL(Op);
11399
11400   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11401                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11402                        false,
11403                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11404 }
11405
11406 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11407 // amount is a constant. Takes immediate version of shift as input.
11408 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11409                                           SDValue SrcOp, uint64_t ShiftAmt,
11410                                           SelectionDAG &DAG) {
11411   MVT ElementType = VT.getVectorElementType();
11412
11413   // Check for ShiftAmt >= element width
11414   if (ShiftAmt >= ElementType.getSizeInBits()) {
11415     if (Opc == X86ISD::VSRAI)
11416       ShiftAmt = ElementType.getSizeInBits() - 1;
11417     else
11418       return DAG.getConstant(0, VT);
11419   }
11420
11421   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11422          && "Unknown target vector shift-by-constant node");
11423
11424   // Fold this packed vector shift into a build vector if SrcOp is a
11425   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11426   if (VT == SrcOp.getSimpleValueType() &&
11427       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11428     SmallVector<SDValue, 8> Elts;
11429     unsigned NumElts = SrcOp->getNumOperands();
11430     ConstantSDNode *ND;
11431
11432     switch(Opc) {
11433     default: llvm_unreachable(0);
11434     case X86ISD::VSHLI:
11435       for (unsigned i=0; i!=NumElts; ++i) {
11436         SDValue CurrentOp = SrcOp->getOperand(i);
11437         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11438           Elts.push_back(CurrentOp);
11439           continue;
11440         }
11441         ND = cast<ConstantSDNode>(CurrentOp);
11442         const APInt &C = ND->getAPIntValue();
11443         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11444       }
11445       break;
11446     case X86ISD::VSRLI:
11447       for (unsigned i=0; i!=NumElts; ++i) {
11448         SDValue CurrentOp = SrcOp->getOperand(i);
11449         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11450           Elts.push_back(CurrentOp);
11451           continue;
11452         }
11453         ND = cast<ConstantSDNode>(CurrentOp);
11454         const APInt &C = ND->getAPIntValue();
11455         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11456       }
11457       break;
11458     case X86ISD::VSRAI:
11459       for (unsigned i=0; i!=NumElts; ++i) {
11460         SDValue CurrentOp = SrcOp->getOperand(i);
11461         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11462           Elts.push_back(CurrentOp);
11463           continue;
11464         }
11465         ND = cast<ConstantSDNode>(CurrentOp);
11466         const APInt &C = ND->getAPIntValue();
11467         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11468       }
11469       break;
11470     }
11471
11472     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11473   }
11474
11475   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11476 }
11477
11478 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11479 // may or may not be a constant. Takes immediate version of shift as input.
11480 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11481                                    SDValue SrcOp, SDValue ShAmt,
11482                                    SelectionDAG &DAG) {
11483   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11484
11485   // Catch shift-by-constant.
11486   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11487     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11488                                       CShAmt->getZExtValue(), DAG);
11489
11490   // Change opcode to non-immediate version
11491   switch (Opc) {
11492     default: llvm_unreachable("Unknown target vector shift node");
11493     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11494     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11495     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11496   }
11497
11498   // Need to build a vector containing shift amount
11499   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11500   SDValue ShOps[4];
11501   ShOps[0] = ShAmt;
11502   ShOps[1] = DAG.getConstant(0, MVT::i32);
11503   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11504   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11505
11506   // The return type has to be a 128-bit type with the same element
11507   // type as the input type.
11508   MVT EltVT = VT.getVectorElementType();
11509   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11510
11511   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11512   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11513 }
11514
11515 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11516   SDLoc dl(Op);
11517   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11518   switch (IntNo) {
11519   default: return SDValue();    // Don't custom lower most intrinsics.
11520   // Comparison intrinsics.
11521   case Intrinsic::x86_sse_comieq_ss:
11522   case Intrinsic::x86_sse_comilt_ss:
11523   case Intrinsic::x86_sse_comile_ss:
11524   case Intrinsic::x86_sse_comigt_ss:
11525   case Intrinsic::x86_sse_comige_ss:
11526   case Intrinsic::x86_sse_comineq_ss:
11527   case Intrinsic::x86_sse_ucomieq_ss:
11528   case Intrinsic::x86_sse_ucomilt_ss:
11529   case Intrinsic::x86_sse_ucomile_ss:
11530   case Intrinsic::x86_sse_ucomigt_ss:
11531   case Intrinsic::x86_sse_ucomige_ss:
11532   case Intrinsic::x86_sse_ucomineq_ss:
11533   case Intrinsic::x86_sse2_comieq_sd:
11534   case Intrinsic::x86_sse2_comilt_sd:
11535   case Intrinsic::x86_sse2_comile_sd:
11536   case Intrinsic::x86_sse2_comigt_sd:
11537   case Intrinsic::x86_sse2_comige_sd:
11538   case Intrinsic::x86_sse2_comineq_sd:
11539   case Intrinsic::x86_sse2_ucomieq_sd:
11540   case Intrinsic::x86_sse2_ucomilt_sd:
11541   case Intrinsic::x86_sse2_ucomile_sd:
11542   case Intrinsic::x86_sse2_ucomigt_sd:
11543   case Intrinsic::x86_sse2_ucomige_sd:
11544   case Intrinsic::x86_sse2_ucomineq_sd: {
11545     unsigned Opc;
11546     ISD::CondCode CC;
11547     switch (IntNo) {
11548     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11549     case Intrinsic::x86_sse_comieq_ss:
11550     case Intrinsic::x86_sse2_comieq_sd:
11551       Opc = X86ISD::COMI;
11552       CC = ISD::SETEQ;
11553       break;
11554     case Intrinsic::x86_sse_comilt_ss:
11555     case Intrinsic::x86_sse2_comilt_sd:
11556       Opc = X86ISD::COMI;
11557       CC = ISD::SETLT;
11558       break;
11559     case Intrinsic::x86_sse_comile_ss:
11560     case Intrinsic::x86_sse2_comile_sd:
11561       Opc = X86ISD::COMI;
11562       CC = ISD::SETLE;
11563       break;
11564     case Intrinsic::x86_sse_comigt_ss:
11565     case Intrinsic::x86_sse2_comigt_sd:
11566       Opc = X86ISD::COMI;
11567       CC = ISD::SETGT;
11568       break;
11569     case Intrinsic::x86_sse_comige_ss:
11570     case Intrinsic::x86_sse2_comige_sd:
11571       Opc = X86ISD::COMI;
11572       CC = ISD::SETGE;
11573       break;
11574     case Intrinsic::x86_sse_comineq_ss:
11575     case Intrinsic::x86_sse2_comineq_sd:
11576       Opc = X86ISD::COMI;
11577       CC = ISD::SETNE;
11578       break;
11579     case Intrinsic::x86_sse_ucomieq_ss:
11580     case Intrinsic::x86_sse2_ucomieq_sd:
11581       Opc = X86ISD::UCOMI;
11582       CC = ISD::SETEQ;
11583       break;
11584     case Intrinsic::x86_sse_ucomilt_ss:
11585     case Intrinsic::x86_sse2_ucomilt_sd:
11586       Opc = X86ISD::UCOMI;
11587       CC = ISD::SETLT;
11588       break;
11589     case Intrinsic::x86_sse_ucomile_ss:
11590     case Intrinsic::x86_sse2_ucomile_sd:
11591       Opc = X86ISD::UCOMI;
11592       CC = ISD::SETLE;
11593       break;
11594     case Intrinsic::x86_sse_ucomigt_ss:
11595     case Intrinsic::x86_sse2_ucomigt_sd:
11596       Opc = X86ISD::UCOMI;
11597       CC = ISD::SETGT;
11598       break;
11599     case Intrinsic::x86_sse_ucomige_ss:
11600     case Intrinsic::x86_sse2_ucomige_sd:
11601       Opc = X86ISD::UCOMI;
11602       CC = ISD::SETGE;
11603       break;
11604     case Intrinsic::x86_sse_ucomineq_ss:
11605     case Intrinsic::x86_sse2_ucomineq_sd:
11606       Opc = X86ISD::UCOMI;
11607       CC = ISD::SETNE;
11608       break;
11609     }
11610
11611     SDValue LHS = Op.getOperand(1);
11612     SDValue RHS = Op.getOperand(2);
11613     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11614     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11615     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11616     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11617                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11618     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11619   }
11620
11621   // Arithmetic intrinsics.
11622   case Intrinsic::x86_sse2_pmulu_dq:
11623   case Intrinsic::x86_avx2_pmulu_dq:
11624     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11625                        Op.getOperand(1), Op.getOperand(2));
11626
11627   // SSE2/AVX2 sub with unsigned saturation intrinsics
11628   case Intrinsic::x86_sse2_psubus_b:
11629   case Intrinsic::x86_sse2_psubus_w:
11630   case Intrinsic::x86_avx2_psubus_b:
11631   case Intrinsic::x86_avx2_psubus_w:
11632     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11633                        Op.getOperand(1), Op.getOperand(2));
11634
11635   // SSE3/AVX horizontal add/sub intrinsics
11636   case Intrinsic::x86_sse3_hadd_ps:
11637   case Intrinsic::x86_sse3_hadd_pd:
11638   case Intrinsic::x86_avx_hadd_ps_256:
11639   case Intrinsic::x86_avx_hadd_pd_256:
11640   case Intrinsic::x86_sse3_hsub_ps:
11641   case Intrinsic::x86_sse3_hsub_pd:
11642   case Intrinsic::x86_avx_hsub_ps_256:
11643   case Intrinsic::x86_avx_hsub_pd_256:
11644   case Intrinsic::x86_ssse3_phadd_w_128:
11645   case Intrinsic::x86_ssse3_phadd_d_128:
11646   case Intrinsic::x86_avx2_phadd_w:
11647   case Intrinsic::x86_avx2_phadd_d:
11648   case Intrinsic::x86_ssse3_phsub_w_128:
11649   case Intrinsic::x86_ssse3_phsub_d_128:
11650   case Intrinsic::x86_avx2_phsub_w:
11651   case Intrinsic::x86_avx2_phsub_d: {
11652     unsigned Opcode;
11653     switch (IntNo) {
11654     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11655     case Intrinsic::x86_sse3_hadd_ps:
11656     case Intrinsic::x86_sse3_hadd_pd:
11657     case Intrinsic::x86_avx_hadd_ps_256:
11658     case Intrinsic::x86_avx_hadd_pd_256:
11659       Opcode = X86ISD::FHADD;
11660       break;
11661     case Intrinsic::x86_sse3_hsub_ps:
11662     case Intrinsic::x86_sse3_hsub_pd:
11663     case Intrinsic::x86_avx_hsub_ps_256:
11664     case Intrinsic::x86_avx_hsub_pd_256:
11665       Opcode = X86ISD::FHSUB;
11666       break;
11667     case Intrinsic::x86_ssse3_phadd_w_128:
11668     case Intrinsic::x86_ssse3_phadd_d_128:
11669     case Intrinsic::x86_avx2_phadd_w:
11670     case Intrinsic::x86_avx2_phadd_d:
11671       Opcode = X86ISD::HADD;
11672       break;
11673     case Intrinsic::x86_ssse3_phsub_w_128:
11674     case Intrinsic::x86_ssse3_phsub_d_128:
11675     case Intrinsic::x86_avx2_phsub_w:
11676     case Intrinsic::x86_avx2_phsub_d:
11677       Opcode = X86ISD::HSUB;
11678       break;
11679     }
11680     return DAG.getNode(Opcode, dl, Op.getValueType(),
11681                        Op.getOperand(1), Op.getOperand(2));
11682   }
11683
11684   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11685   case Intrinsic::x86_sse2_pmaxu_b:
11686   case Intrinsic::x86_sse41_pmaxuw:
11687   case Intrinsic::x86_sse41_pmaxud:
11688   case Intrinsic::x86_avx2_pmaxu_b:
11689   case Intrinsic::x86_avx2_pmaxu_w:
11690   case Intrinsic::x86_avx2_pmaxu_d:
11691   case Intrinsic::x86_sse2_pminu_b:
11692   case Intrinsic::x86_sse41_pminuw:
11693   case Intrinsic::x86_sse41_pminud:
11694   case Intrinsic::x86_avx2_pminu_b:
11695   case Intrinsic::x86_avx2_pminu_w:
11696   case Intrinsic::x86_avx2_pminu_d:
11697   case Intrinsic::x86_sse41_pmaxsb:
11698   case Intrinsic::x86_sse2_pmaxs_w:
11699   case Intrinsic::x86_sse41_pmaxsd:
11700   case Intrinsic::x86_avx2_pmaxs_b:
11701   case Intrinsic::x86_avx2_pmaxs_w:
11702   case Intrinsic::x86_avx2_pmaxs_d:
11703   case Intrinsic::x86_sse41_pminsb:
11704   case Intrinsic::x86_sse2_pmins_w:
11705   case Intrinsic::x86_sse41_pminsd:
11706   case Intrinsic::x86_avx2_pmins_b:
11707   case Intrinsic::x86_avx2_pmins_w:
11708   case Intrinsic::x86_avx2_pmins_d: {
11709     unsigned Opcode;
11710     switch (IntNo) {
11711     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11712     case Intrinsic::x86_sse2_pmaxu_b:
11713     case Intrinsic::x86_sse41_pmaxuw:
11714     case Intrinsic::x86_sse41_pmaxud:
11715     case Intrinsic::x86_avx2_pmaxu_b:
11716     case Intrinsic::x86_avx2_pmaxu_w:
11717     case Intrinsic::x86_avx2_pmaxu_d:
11718       Opcode = X86ISD::UMAX;
11719       break;
11720     case Intrinsic::x86_sse2_pminu_b:
11721     case Intrinsic::x86_sse41_pminuw:
11722     case Intrinsic::x86_sse41_pminud:
11723     case Intrinsic::x86_avx2_pminu_b:
11724     case Intrinsic::x86_avx2_pminu_w:
11725     case Intrinsic::x86_avx2_pminu_d:
11726       Opcode = X86ISD::UMIN;
11727       break;
11728     case Intrinsic::x86_sse41_pmaxsb:
11729     case Intrinsic::x86_sse2_pmaxs_w:
11730     case Intrinsic::x86_sse41_pmaxsd:
11731     case Intrinsic::x86_avx2_pmaxs_b:
11732     case Intrinsic::x86_avx2_pmaxs_w:
11733     case Intrinsic::x86_avx2_pmaxs_d:
11734       Opcode = X86ISD::SMAX;
11735       break;
11736     case Intrinsic::x86_sse41_pminsb:
11737     case Intrinsic::x86_sse2_pmins_w:
11738     case Intrinsic::x86_sse41_pminsd:
11739     case Intrinsic::x86_avx2_pmins_b:
11740     case Intrinsic::x86_avx2_pmins_w:
11741     case Intrinsic::x86_avx2_pmins_d:
11742       Opcode = X86ISD::SMIN;
11743       break;
11744     }
11745     return DAG.getNode(Opcode, dl, Op.getValueType(),
11746                        Op.getOperand(1), Op.getOperand(2));
11747   }
11748
11749   // SSE/SSE2/AVX floating point max/min intrinsics.
11750   case Intrinsic::x86_sse_max_ps:
11751   case Intrinsic::x86_sse2_max_pd:
11752   case Intrinsic::x86_avx_max_ps_256:
11753   case Intrinsic::x86_avx_max_pd_256:
11754   case Intrinsic::x86_sse_min_ps:
11755   case Intrinsic::x86_sse2_min_pd:
11756   case Intrinsic::x86_avx_min_ps_256:
11757   case Intrinsic::x86_avx_min_pd_256: {
11758     unsigned Opcode;
11759     switch (IntNo) {
11760     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11761     case Intrinsic::x86_sse_max_ps:
11762     case Intrinsic::x86_sse2_max_pd:
11763     case Intrinsic::x86_avx_max_ps_256:
11764     case Intrinsic::x86_avx_max_pd_256:
11765       Opcode = X86ISD::FMAX;
11766       break;
11767     case Intrinsic::x86_sse_min_ps:
11768     case Intrinsic::x86_sse2_min_pd:
11769     case Intrinsic::x86_avx_min_ps_256:
11770     case Intrinsic::x86_avx_min_pd_256:
11771       Opcode = X86ISD::FMIN;
11772       break;
11773     }
11774     return DAG.getNode(Opcode, dl, Op.getValueType(),
11775                        Op.getOperand(1), Op.getOperand(2));
11776   }
11777
11778   // AVX2 variable shift intrinsics
11779   case Intrinsic::x86_avx2_psllv_d:
11780   case Intrinsic::x86_avx2_psllv_q:
11781   case Intrinsic::x86_avx2_psllv_d_256:
11782   case Intrinsic::x86_avx2_psllv_q_256:
11783   case Intrinsic::x86_avx2_psrlv_d:
11784   case Intrinsic::x86_avx2_psrlv_q:
11785   case Intrinsic::x86_avx2_psrlv_d_256:
11786   case Intrinsic::x86_avx2_psrlv_q_256:
11787   case Intrinsic::x86_avx2_psrav_d:
11788   case Intrinsic::x86_avx2_psrav_d_256: {
11789     unsigned Opcode;
11790     switch (IntNo) {
11791     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11792     case Intrinsic::x86_avx2_psllv_d:
11793     case Intrinsic::x86_avx2_psllv_q:
11794     case Intrinsic::x86_avx2_psllv_d_256:
11795     case Intrinsic::x86_avx2_psllv_q_256:
11796       Opcode = ISD::SHL;
11797       break;
11798     case Intrinsic::x86_avx2_psrlv_d:
11799     case Intrinsic::x86_avx2_psrlv_q:
11800     case Intrinsic::x86_avx2_psrlv_d_256:
11801     case Intrinsic::x86_avx2_psrlv_q_256:
11802       Opcode = ISD::SRL;
11803       break;
11804     case Intrinsic::x86_avx2_psrav_d:
11805     case Intrinsic::x86_avx2_psrav_d_256:
11806       Opcode = ISD::SRA;
11807       break;
11808     }
11809     return DAG.getNode(Opcode, dl, Op.getValueType(),
11810                        Op.getOperand(1), Op.getOperand(2));
11811   }
11812
11813   case Intrinsic::x86_ssse3_pshuf_b_128:
11814   case Intrinsic::x86_avx2_pshuf_b:
11815     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11816                        Op.getOperand(1), Op.getOperand(2));
11817
11818   case Intrinsic::x86_ssse3_psign_b_128:
11819   case Intrinsic::x86_ssse3_psign_w_128:
11820   case Intrinsic::x86_ssse3_psign_d_128:
11821   case Intrinsic::x86_avx2_psign_b:
11822   case Intrinsic::x86_avx2_psign_w:
11823   case Intrinsic::x86_avx2_psign_d:
11824     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11825                        Op.getOperand(1), Op.getOperand(2));
11826
11827   case Intrinsic::x86_sse41_insertps:
11828     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11829                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11830
11831   case Intrinsic::x86_avx_vperm2f128_ps_256:
11832   case Intrinsic::x86_avx_vperm2f128_pd_256:
11833   case Intrinsic::x86_avx_vperm2f128_si_256:
11834   case Intrinsic::x86_avx2_vperm2i128:
11835     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11836                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11837
11838   case Intrinsic::x86_avx2_permd:
11839   case Intrinsic::x86_avx2_permps:
11840     // Operands intentionally swapped. Mask is last operand to intrinsic,
11841     // but second operand for node/instruction.
11842     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11843                        Op.getOperand(2), Op.getOperand(1));
11844
11845   case Intrinsic::x86_sse_sqrt_ps:
11846   case Intrinsic::x86_sse2_sqrt_pd:
11847   case Intrinsic::x86_avx_sqrt_ps_256:
11848   case Intrinsic::x86_avx_sqrt_pd_256:
11849     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11850
11851   // ptest and testp intrinsics. The intrinsic these come from are designed to
11852   // return an integer value, not just an instruction so lower it to the ptest
11853   // or testp pattern and a setcc for the result.
11854   case Intrinsic::x86_sse41_ptestz:
11855   case Intrinsic::x86_sse41_ptestc:
11856   case Intrinsic::x86_sse41_ptestnzc:
11857   case Intrinsic::x86_avx_ptestz_256:
11858   case Intrinsic::x86_avx_ptestc_256:
11859   case Intrinsic::x86_avx_ptestnzc_256:
11860   case Intrinsic::x86_avx_vtestz_ps:
11861   case Intrinsic::x86_avx_vtestc_ps:
11862   case Intrinsic::x86_avx_vtestnzc_ps:
11863   case Intrinsic::x86_avx_vtestz_pd:
11864   case Intrinsic::x86_avx_vtestc_pd:
11865   case Intrinsic::x86_avx_vtestnzc_pd:
11866   case Intrinsic::x86_avx_vtestz_ps_256:
11867   case Intrinsic::x86_avx_vtestc_ps_256:
11868   case Intrinsic::x86_avx_vtestnzc_ps_256:
11869   case Intrinsic::x86_avx_vtestz_pd_256:
11870   case Intrinsic::x86_avx_vtestc_pd_256:
11871   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11872     bool IsTestPacked = false;
11873     unsigned X86CC;
11874     switch (IntNo) {
11875     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11876     case Intrinsic::x86_avx_vtestz_ps:
11877     case Intrinsic::x86_avx_vtestz_pd:
11878     case Intrinsic::x86_avx_vtestz_ps_256:
11879     case Intrinsic::x86_avx_vtestz_pd_256:
11880       IsTestPacked = true; // Fallthrough
11881     case Intrinsic::x86_sse41_ptestz:
11882     case Intrinsic::x86_avx_ptestz_256:
11883       // ZF = 1
11884       X86CC = X86::COND_E;
11885       break;
11886     case Intrinsic::x86_avx_vtestc_ps:
11887     case Intrinsic::x86_avx_vtestc_pd:
11888     case Intrinsic::x86_avx_vtestc_ps_256:
11889     case Intrinsic::x86_avx_vtestc_pd_256:
11890       IsTestPacked = true; // Fallthrough
11891     case Intrinsic::x86_sse41_ptestc:
11892     case Intrinsic::x86_avx_ptestc_256:
11893       // CF = 1
11894       X86CC = X86::COND_B;
11895       break;
11896     case Intrinsic::x86_avx_vtestnzc_ps:
11897     case Intrinsic::x86_avx_vtestnzc_pd:
11898     case Intrinsic::x86_avx_vtestnzc_ps_256:
11899     case Intrinsic::x86_avx_vtestnzc_pd_256:
11900       IsTestPacked = true; // Fallthrough
11901     case Intrinsic::x86_sse41_ptestnzc:
11902     case Intrinsic::x86_avx_ptestnzc_256:
11903       // ZF and CF = 0
11904       X86CC = X86::COND_A;
11905       break;
11906     }
11907
11908     SDValue LHS = Op.getOperand(1);
11909     SDValue RHS = Op.getOperand(2);
11910     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11911     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11912     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11913     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11914     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11915   }
11916   case Intrinsic::x86_avx512_kortestz_w:
11917   case Intrinsic::x86_avx512_kortestc_w: {
11918     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11919     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11920     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11921     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11922     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11923     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11924     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11925   }
11926
11927   // SSE/AVX shift intrinsics
11928   case Intrinsic::x86_sse2_psll_w:
11929   case Intrinsic::x86_sse2_psll_d:
11930   case Intrinsic::x86_sse2_psll_q:
11931   case Intrinsic::x86_avx2_psll_w:
11932   case Intrinsic::x86_avx2_psll_d:
11933   case Intrinsic::x86_avx2_psll_q:
11934   case Intrinsic::x86_sse2_psrl_w:
11935   case Intrinsic::x86_sse2_psrl_d:
11936   case Intrinsic::x86_sse2_psrl_q:
11937   case Intrinsic::x86_avx2_psrl_w:
11938   case Intrinsic::x86_avx2_psrl_d:
11939   case Intrinsic::x86_avx2_psrl_q:
11940   case Intrinsic::x86_sse2_psra_w:
11941   case Intrinsic::x86_sse2_psra_d:
11942   case Intrinsic::x86_avx2_psra_w:
11943   case Intrinsic::x86_avx2_psra_d: {
11944     unsigned Opcode;
11945     switch (IntNo) {
11946     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11947     case Intrinsic::x86_sse2_psll_w:
11948     case Intrinsic::x86_sse2_psll_d:
11949     case Intrinsic::x86_sse2_psll_q:
11950     case Intrinsic::x86_avx2_psll_w:
11951     case Intrinsic::x86_avx2_psll_d:
11952     case Intrinsic::x86_avx2_psll_q:
11953       Opcode = X86ISD::VSHL;
11954       break;
11955     case Intrinsic::x86_sse2_psrl_w:
11956     case Intrinsic::x86_sse2_psrl_d:
11957     case Intrinsic::x86_sse2_psrl_q:
11958     case Intrinsic::x86_avx2_psrl_w:
11959     case Intrinsic::x86_avx2_psrl_d:
11960     case Intrinsic::x86_avx2_psrl_q:
11961       Opcode = X86ISD::VSRL;
11962       break;
11963     case Intrinsic::x86_sse2_psra_w:
11964     case Intrinsic::x86_sse2_psra_d:
11965     case Intrinsic::x86_avx2_psra_w:
11966     case Intrinsic::x86_avx2_psra_d:
11967       Opcode = X86ISD::VSRA;
11968       break;
11969     }
11970     return DAG.getNode(Opcode, dl, Op.getValueType(),
11971                        Op.getOperand(1), Op.getOperand(2));
11972   }
11973
11974   // SSE/AVX immediate shift intrinsics
11975   case Intrinsic::x86_sse2_pslli_w:
11976   case Intrinsic::x86_sse2_pslli_d:
11977   case Intrinsic::x86_sse2_pslli_q:
11978   case Intrinsic::x86_avx2_pslli_w:
11979   case Intrinsic::x86_avx2_pslli_d:
11980   case Intrinsic::x86_avx2_pslli_q:
11981   case Intrinsic::x86_sse2_psrli_w:
11982   case Intrinsic::x86_sse2_psrli_d:
11983   case Intrinsic::x86_sse2_psrli_q:
11984   case Intrinsic::x86_avx2_psrli_w:
11985   case Intrinsic::x86_avx2_psrli_d:
11986   case Intrinsic::x86_avx2_psrli_q:
11987   case Intrinsic::x86_sse2_psrai_w:
11988   case Intrinsic::x86_sse2_psrai_d:
11989   case Intrinsic::x86_avx2_psrai_w:
11990   case Intrinsic::x86_avx2_psrai_d: {
11991     unsigned Opcode;
11992     switch (IntNo) {
11993     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11994     case Intrinsic::x86_sse2_pslli_w:
11995     case Intrinsic::x86_sse2_pslli_d:
11996     case Intrinsic::x86_sse2_pslli_q:
11997     case Intrinsic::x86_avx2_pslli_w:
11998     case Intrinsic::x86_avx2_pslli_d:
11999     case Intrinsic::x86_avx2_pslli_q:
12000       Opcode = X86ISD::VSHLI;
12001       break;
12002     case Intrinsic::x86_sse2_psrli_w:
12003     case Intrinsic::x86_sse2_psrli_d:
12004     case Intrinsic::x86_sse2_psrli_q:
12005     case Intrinsic::x86_avx2_psrli_w:
12006     case Intrinsic::x86_avx2_psrli_d:
12007     case Intrinsic::x86_avx2_psrli_q:
12008       Opcode = X86ISD::VSRLI;
12009       break;
12010     case Intrinsic::x86_sse2_psrai_w:
12011     case Intrinsic::x86_sse2_psrai_d:
12012     case Intrinsic::x86_avx2_psrai_w:
12013     case Intrinsic::x86_avx2_psrai_d:
12014       Opcode = X86ISD::VSRAI;
12015       break;
12016     }
12017     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12018                                Op.getOperand(1), Op.getOperand(2), DAG);
12019   }
12020
12021   case Intrinsic::x86_sse42_pcmpistria128:
12022   case Intrinsic::x86_sse42_pcmpestria128:
12023   case Intrinsic::x86_sse42_pcmpistric128:
12024   case Intrinsic::x86_sse42_pcmpestric128:
12025   case Intrinsic::x86_sse42_pcmpistrio128:
12026   case Intrinsic::x86_sse42_pcmpestrio128:
12027   case Intrinsic::x86_sse42_pcmpistris128:
12028   case Intrinsic::x86_sse42_pcmpestris128:
12029   case Intrinsic::x86_sse42_pcmpistriz128:
12030   case Intrinsic::x86_sse42_pcmpestriz128: {
12031     unsigned Opcode;
12032     unsigned X86CC;
12033     switch (IntNo) {
12034     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12035     case Intrinsic::x86_sse42_pcmpistria128:
12036       Opcode = X86ISD::PCMPISTRI;
12037       X86CC = X86::COND_A;
12038       break;
12039     case Intrinsic::x86_sse42_pcmpestria128:
12040       Opcode = X86ISD::PCMPESTRI;
12041       X86CC = X86::COND_A;
12042       break;
12043     case Intrinsic::x86_sse42_pcmpistric128:
12044       Opcode = X86ISD::PCMPISTRI;
12045       X86CC = X86::COND_B;
12046       break;
12047     case Intrinsic::x86_sse42_pcmpestric128:
12048       Opcode = X86ISD::PCMPESTRI;
12049       X86CC = X86::COND_B;
12050       break;
12051     case Intrinsic::x86_sse42_pcmpistrio128:
12052       Opcode = X86ISD::PCMPISTRI;
12053       X86CC = X86::COND_O;
12054       break;
12055     case Intrinsic::x86_sse42_pcmpestrio128:
12056       Opcode = X86ISD::PCMPESTRI;
12057       X86CC = X86::COND_O;
12058       break;
12059     case Intrinsic::x86_sse42_pcmpistris128:
12060       Opcode = X86ISD::PCMPISTRI;
12061       X86CC = X86::COND_S;
12062       break;
12063     case Intrinsic::x86_sse42_pcmpestris128:
12064       Opcode = X86ISD::PCMPESTRI;
12065       X86CC = X86::COND_S;
12066       break;
12067     case Intrinsic::x86_sse42_pcmpistriz128:
12068       Opcode = X86ISD::PCMPISTRI;
12069       X86CC = X86::COND_E;
12070       break;
12071     case Intrinsic::x86_sse42_pcmpestriz128:
12072       Opcode = X86ISD::PCMPESTRI;
12073       X86CC = X86::COND_E;
12074       break;
12075     }
12076     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12077     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12078     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12079     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12080                                 DAG.getConstant(X86CC, MVT::i8),
12081                                 SDValue(PCMP.getNode(), 1));
12082     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12083   }
12084
12085   case Intrinsic::x86_sse42_pcmpistri128:
12086   case Intrinsic::x86_sse42_pcmpestri128: {
12087     unsigned Opcode;
12088     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12089       Opcode = X86ISD::PCMPISTRI;
12090     else
12091       Opcode = X86ISD::PCMPESTRI;
12092
12093     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12094     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12095     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12096   }
12097   case Intrinsic::x86_fma_vfmadd_ps:
12098   case Intrinsic::x86_fma_vfmadd_pd:
12099   case Intrinsic::x86_fma_vfmsub_ps:
12100   case Intrinsic::x86_fma_vfmsub_pd:
12101   case Intrinsic::x86_fma_vfnmadd_ps:
12102   case Intrinsic::x86_fma_vfnmadd_pd:
12103   case Intrinsic::x86_fma_vfnmsub_ps:
12104   case Intrinsic::x86_fma_vfnmsub_pd:
12105   case Intrinsic::x86_fma_vfmaddsub_ps:
12106   case Intrinsic::x86_fma_vfmaddsub_pd:
12107   case Intrinsic::x86_fma_vfmsubadd_ps:
12108   case Intrinsic::x86_fma_vfmsubadd_pd:
12109   case Intrinsic::x86_fma_vfmadd_ps_256:
12110   case Intrinsic::x86_fma_vfmadd_pd_256:
12111   case Intrinsic::x86_fma_vfmsub_ps_256:
12112   case Intrinsic::x86_fma_vfmsub_pd_256:
12113   case Intrinsic::x86_fma_vfnmadd_ps_256:
12114   case Intrinsic::x86_fma_vfnmadd_pd_256:
12115   case Intrinsic::x86_fma_vfnmsub_ps_256:
12116   case Intrinsic::x86_fma_vfnmsub_pd_256:
12117   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12118   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12119   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12120   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12121   case Intrinsic::x86_fma_vfmadd_ps_512:
12122   case Intrinsic::x86_fma_vfmadd_pd_512:
12123   case Intrinsic::x86_fma_vfmsub_ps_512:
12124   case Intrinsic::x86_fma_vfmsub_pd_512:
12125   case Intrinsic::x86_fma_vfnmadd_ps_512:
12126   case Intrinsic::x86_fma_vfnmadd_pd_512:
12127   case Intrinsic::x86_fma_vfnmsub_ps_512:
12128   case Intrinsic::x86_fma_vfnmsub_pd_512:
12129   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12130   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12131   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12132   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12133     unsigned Opc;
12134     switch (IntNo) {
12135     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12136     case Intrinsic::x86_fma_vfmadd_ps:
12137     case Intrinsic::x86_fma_vfmadd_pd:
12138     case Intrinsic::x86_fma_vfmadd_ps_256:
12139     case Intrinsic::x86_fma_vfmadd_pd_256:
12140     case Intrinsic::x86_fma_vfmadd_ps_512:
12141     case Intrinsic::x86_fma_vfmadd_pd_512:
12142       Opc = X86ISD::FMADD;
12143       break;
12144     case Intrinsic::x86_fma_vfmsub_ps:
12145     case Intrinsic::x86_fma_vfmsub_pd:
12146     case Intrinsic::x86_fma_vfmsub_ps_256:
12147     case Intrinsic::x86_fma_vfmsub_pd_256:
12148     case Intrinsic::x86_fma_vfmsub_ps_512:
12149     case Intrinsic::x86_fma_vfmsub_pd_512:
12150       Opc = X86ISD::FMSUB;
12151       break;
12152     case Intrinsic::x86_fma_vfnmadd_ps:
12153     case Intrinsic::x86_fma_vfnmadd_pd:
12154     case Intrinsic::x86_fma_vfnmadd_ps_256:
12155     case Intrinsic::x86_fma_vfnmadd_pd_256:
12156     case Intrinsic::x86_fma_vfnmadd_ps_512:
12157     case Intrinsic::x86_fma_vfnmadd_pd_512:
12158       Opc = X86ISD::FNMADD;
12159       break;
12160     case Intrinsic::x86_fma_vfnmsub_ps:
12161     case Intrinsic::x86_fma_vfnmsub_pd:
12162     case Intrinsic::x86_fma_vfnmsub_ps_256:
12163     case Intrinsic::x86_fma_vfnmsub_pd_256:
12164     case Intrinsic::x86_fma_vfnmsub_ps_512:
12165     case Intrinsic::x86_fma_vfnmsub_pd_512:
12166       Opc = X86ISD::FNMSUB;
12167       break;
12168     case Intrinsic::x86_fma_vfmaddsub_ps:
12169     case Intrinsic::x86_fma_vfmaddsub_pd:
12170     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12171     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12172     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12173     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12174       Opc = X86ISD::FMADDSUB;
12175       break;
12176     case Intrinsic::x86_fma_vfmsubadd_ps:
12177     case Intrinsic::x86_fma_vfmsubadd_pd:
12178     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12179     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12180     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12181     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12182       Opc = X86ISD::FMSUBADD;
12183       break;
12184     }
12185
12186     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12187                        Op.getOperand(2), Op.getOperand(3));
12188   }
12189   }
12190 }
12191
12192 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12193                              SDValue Base, SDValue Index,
12194                              SDValue ScaleOp, SDValue Chain,
12195                              const X86Subtarget * Subtarget) {
12196   SDLoc dl(Op);
12197   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12198   assert(C && "Invalid scale type");
12199   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12200   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12201   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12202                              Index.getSimpleValueType().getVectorNumElements());
12203   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12204   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12205   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12206   SDValue Segment = DAG.getRegister(0, MVT::i32);
12207   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12208   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12209   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12210   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12211 }
12212
12213 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12214                               SDValue Src, SDValue Mask, SDValue Base,
12215                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12216                               const X86Subtarget * Subtarget) {
12217   SDLoc dl(Op);
12218   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12219   assert(C && "Invalid scale type");
12220   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12221   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12222                              Index.getSimpleValueType().getVectorNumElements());
12223   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12224   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12225   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12226   SDValue Segment = DAG.getRegister(0, MVT::i32);
12227   if (Src.getOpcode() == ISD::UNDEF)
12228     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12229   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12230   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12231   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12232   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12233 }
12234
12235 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12236                               SDValue Src, SDValue Base, SDValue Index,
12237                               SDValue ScaleOp, SDValue Chain) {
12238   SDLoc dl(Op);
12239   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12240   assert(C && "Invalid scale type");
12241   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12242   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12243   SDValue Segment = DAG.getRegister(0, MVT::i32);
12244   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12245                              Index.getSimpleValueType().getVectorNumElements());
12246   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12247   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12248   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12249   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12250   return SDValue(Res, 1);
12251 }
12252
12253 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12254                                SDValue Src, SDValue Mask, SDValue Base,
12255                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12256   SDLoc dl(Op);
12257   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12258   assert(C && "Invalid scale type");
12259   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12260   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12261   SDValue Segment = DAG.getRegister(0, MVT::i32);
12262   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12263                              Index.getSimpleValueType().getVectorNumElements());
12264   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12265   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12266   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12267   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12268   return SDValue(Res, 1);
12269 }
12270
12271 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12272 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12273 // also used to custom lower READCYCLECOUNTER nodes.
12274 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12275                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12276                               SmallVectorImpl<SDValue> &Results) {
12277   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12278   SDValue TheChain = N->getOperand(0);
12279   SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12280   SDValue LO, HI;
12281
12282   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12283   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12284   // and the EAX register is loaded with the low-order 32 bits.
12285   if (Subtarget->is64Bit()) {
12286     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12287     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12288                             LO.getValue(2));
12289   } else {
12290     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12291     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12292                             LO.getValue(2));
12293   }
12294   SDValue Chain = HI.getValue(1);
12295
12296   if (Opcode == X86ISD::RDTSCP_DAG) {
12297     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12298
12299     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12300     // the ECX register. Add 'ecx' explicitly to the chain.
12301     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12302                                      HI.getValue(2));
12303     // Explicitly store the content of ECX at the location passed in input
12304     // to the 'rdtscp' intrinsic.
12305     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12306                          MachinePointerInfo(), false, false, 0);
12307   }
12308
12309   if (Subtarget->is64Bit()) {
12310     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12311     // the EAX register is loaded with the low-order 32 bits.
12312     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12313                               DAG.getConstant(32, MVT::i8));
12314     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12315     Results.push_back(Chain);
12316     return;
12317   }
12318
12319   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12320   SDValue Ops[] = { LO, HI };
12321   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12322                              array_lengthof(Ops));
12323   Results.push_back(Pair);
12324   Results.push_back(Chain);
12325 }
12326
12327 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12328                                      SelectionDAG &DAG) {
12329   SmallVector<SDValue, 2> Results;
12330   SDLoc DL(Op);
12331   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12332                           Results);
12333   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12334 }
12335
12336 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12337                                       SelectionDAG &DAG) {
12338   SDLoc dl(Op);
12339   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12340   switch (IntNo) {
12341   default: return SDValue();    // Don't custom lower most intrinsics.
12342
12343   // RDRAND/RDSEED intrinsics.
12344   case Intrinsic::x86_rdrand_16:
12345   case Intrinsic::x86_rdrand_32:
12346   case Intrinsic::x86_rdrand_64:
12347   case Intrinsic::x86_rdseed_16:
12348   case Intrinsic::x86_rdseed_32:
12349   case Intrinsic::x86_rdseed_64: {
12350     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12351                        IntNo == Intrinsic::x86_rdseed_32 ||
12352                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12353                                                             X86ISD::RDRAND;
12354     // Emit the node with the right value type.
12355     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12356     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12357
12358     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12359     // Otherwise return the value from Rand, which is always 0, casted to i32.
12360     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12361                       DAG.getConstant(1, Op->getValueType(1)),
12362                       DAG.getConstant(X86::COND_B, MVT::i32),
12363                       SDValue(Result.getNode(), 1) };
12364     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12365                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12366                                   Ops, array_lengthof(Ops));
12367
12368     // Return { result, isValid, chain }.
12369     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12370                        SDValue(Result.getNode(), 2));
12371   }
12372   //int_gather(index, base, scale);
12373   case Intrinsic::x86_avx512_gather_qpd_512:
12374   case Intrinsic::x86_avx512_gather_qps_512:
12375   case Intrinsic::x86_avx512_gather_dpd_512:
12376   case Intrinsic::x86_avx512_gather_qpi_512:
12377   case Intrinsic::x86_avx512_gather_qpq_512:
12378   case Intrinsic::x86_avx512_gather_dpq_512:
12379   case Intrinsic::x86_avx512_gather_dps_512:
12380   case Intrinsic::x86_avx512_gather_dpi_512: {
12381     unsigned Opc;
12382     switch (IntNo) {
12383     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12384     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12385     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12386     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12387     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12388     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12389     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12390     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12391     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12392     }
12393     SDValue Chain = Op.getOperand(0);
12394     SDValue Index = Op.getOperand(2);
12395     SDValue Base  = Op.getOperand(3);
12396     SDValue Scale = Op.getOperand(4);
12397     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12398   }
12399   //int_gather_mask(v1, mask, index, base, scale);
12400   case Intrinsic::x86_avx512_gather_qps_mask_512:
12401   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12402   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12403   case Intrinsic::x86_avx512_gather_dps_mask_512:
12404   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12405   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12406   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12407   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12408     unsigned Opc;
12409     switch (IntNo) {
12410     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12411     case Intrinsic::x86_avx512_gather_qps_mask_512:
12412       Opc = X86::VGATHERQPSZrm; break;
12413     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12414       Opc = X86::VGATHERQPDZrm; break;
12415     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12416       Opc = X86::VGATHERDPDZrm; break;
12417     case Intrinsic::x86_avx512_gather_dps_mask_512:
12418       Opc = X86::VGATHERDPSZrm; break;
12419     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12420       Opc = X86::VPGATHERQDZrm; break;
12421     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12422       Opc = X86::VPGATHERQQZrm; break;
12423     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12424       Opc = X86::VPGATHERDDZrm; break;
12425     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12426       Opc = X86::VPGATHERDQZrm; break;
12427     }
12428     SDValue Chain = Op.getOperand(0);
12429     SDValue Src   = Op.getOperand(2);
12430     SDValue Mask  = Op.getOperand(3);
12431     SDValue Index = Op.getOperand(4);
12432     SDValue Base  = Op.getOperand(5);
12433     SDValue Scale = Op.getOperand(6);
12434     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12435                           Subtarget);
12436   }
12437   //int_scatter(base, index, v1, scale);
12438   case Intrinsic::x86_avx512_scatter_qpd_512:
12439   case Intrinsic::x86_avx512_scatter_qps_512:
12440   case Intrinsic::x86_avx512_scatter_dpd_512:
12441   case Intrinsic::x86_avx512_scatter_qpi_512:
12442   case Intrinsic::x86_avx512_scatter_qpq_512:
12443   case Intrinsic::x86_avx512_scatter_dpq_512:
12444   case Intrinsic::x86_avx512_scatter_dps_512:
12445   case Intrinsic::x86_avx512_scatter_dpi_512: {
12446     unsigned Opc;
12447     switch (IntNo) {
12448     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12449     case Intrinsic::x86_avx512_scatter_qpd_512:
12450       Opc = X86::VSCATTERQPDZmr; break;
12451     case Intrinsic::x86_avx512_scatter_qps_512:
12452       Opc = X86::VSCATTERQPSZmr; break;
12453     case Intrinsic::x86_avx512_scatter_dpd_512:
12454       Opc = X86::VSCATTERDPDZmr; break;
12455     case Intrinsic::x86_avx512_scatter_dps_512:
12456       Opc = X86::VSCATTERDPSZmr; break;
12457     case Intrinsic::x86_avx512_scatter_qpi_512:
12458       Opc = X86::VPSCATTERQDZmr; break;
12459     case Intrinsic::x86_avx512_scatter_qpq_512:
12460       Opc = X86::VPSCATTERQQZmr; break;
12461     case Intrinsic::x86_avx512_scatter_dpq_512:
12462       Opc = X86::VPSCATTERDQZmr; break;
12463     case Intrinsic::x86_avx512_scatter_dpi_512:
12464       Opc = X86::VPSCATTERDDZmr; break;
12465     }
12466     SDValue Chain = Op.getOperand(0);
12467     SDValue Base  = Op.getOperand(2);
12468     SDValue Index = Op.getOperand(3);
12469     SDValue Src   = Op.getOperand(4);
12470     SDValue Scale = Op.getOperand(5);
12471     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12472   }
12473   //int_scatter_mask(base, mask, index, v1, scale);
12474   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12475   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12476   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12477   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12478   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12479   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12480   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12481   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12482     unsigned Opc;
12483     switch (IntNo) {
12484     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12485     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12486       Opc = X86::VSCATTERQPDZmr; break;
12487     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12488       Opc = X86::VSCATTERQPSZmr; break;
12489     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12490       Opc = X86::VSCATTERDPDZmr; break;
12491     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12492       Opc = X86::VSCATTERDPSZmr; break;
12493     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12494       Opc = X86::VPSCATTERQDZmr; break;
12495     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12496       Opc = X86::VPSCATTERQQZmr; break;
12497     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12498       Opc = X86::VPSCATTERDQZmr; break;
12499     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12500       Opc = X86::VPSCATTERDDZmr; break;
12501     }
12502     SDValue Chain = Op.getOperand(0);
12503     SDValue Base  = Op.getOperand(2);
12504     SDValue Mask  = Op.getOperand(3);
12505     SDValue Index = Op.getOperand(4);
12506     SDValue Src   = Op.getOperand(5);
12507     SDValue Scale = Op.getOperand(6);
12508     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12509   }
12510   // Read Time Stamp Counter (RDTSC).
12511   case Intrinsic::x86_rdtsc:
12512   // Read Time Stamp Counter and Processor ID (RDTSCP).
12513   case Intrinsic::x86_rdtscp: {
12514     unsigned Opc;
12515     switch (IntNo) {
12516     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12517     case Intrinsic::x86_rdtsc:
12518       Opc = X86ISD::RDTSC_DAG; break;
12519     case Intrinsic::x86_rdtscp:
12520       Opc = X86ISD::RDTSCP_DAG; break;
12521     }
12522     SmallVector<SDValue, 2> Results;
12523     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12524     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12525   }
12526   // XTEST intrinsics.
12527   case Intrinsic::x86_xtest: {
12528     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12529     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12530     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12531                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12532                                 InTrans);
12533     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12534     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12535                        Ret, SDValue(InTrans.getNode(), 1));
12536   }
12537   }
12538 }
12539
12540 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12541                                            SelectionDAG &DAG) const {
12542   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12543   MFI->setReturnAddressIsTaken(true);
12544
12545   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12546     return SDValue();
12547
12548   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12549   SDLoc dl(Op);
12550   EVT PtrVT = getPointerTy();
12551
12552   if (Depth > 0) {
12553     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12554     const X86RegisterInfo *RegInfo =
12555       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12556     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12557     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12558                        DAG.getNode(ISD::ADD, dl, PtrVT,
12559                                    FrameAddr, Offset),
12560                        MachinePointerInfo(), false, false, false, 0);
12561   }
12562
12563   // Just load the return address.
12564   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12565   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12566                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12567 }
12568
12569 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12570   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12571   MFI->setFrameAddressIsTaken(true);
12572
12573   EVT VT = Op.getValueType();
12574   SDLoc dl(Op);  // FIXME probably not meaningful
12575   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12576   const X86RegisterInfo *RegInfo =
12577     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12578   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12579   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12580           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12581          "Invalid Frame Register!");
12582   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12583   while (Depth--)
12584     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12585                             MachinePointerInfo(),
12586                             false, false, false, 0);
12587   return FrameAddr;
12588 }
12589
12590 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12591                                                      SelectionDAG &DAG) const {
12592   const X86RegisterInfo *RegInfo =
12593     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12594   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12595 }
12596
12597 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12598   SDValue Chain     = Op.getOperand(0);
12599   SDValue Offset    = Op.getOperand(1);
12600   SDValue Handler   = Op.getOperand(2);
12601   SDLoc dl      (Op);
12602
12603   EVT PtrVT = getPointerTy();
12604   const X86RegisterInfo *RegInfo =
12605     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12606   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12607   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12608           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12609          "Invalid Frame Register!");
12610   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12611   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12612
12613   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12614                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12615   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12616   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12617                        false, false, 0);
12618   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12619
12620   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12621                      DAG.getRegister(StoreAddrReg, PtrVT));
12622 }
12623
12624 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12625                                                SelectionDAG &DAG) const {
12626   SDLoc DL(Op);
12627   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12628                      DAG.getVTList(MVT::i32, MVT::Other),
12629                      Op.getOperand(0), Op.getOperand(1));
12630 }
12631
12632 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12633                                                 SelectionDAG &DAG) const {
12634   SDLoc DL(Op);
12635   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12636                      Op.getOperand(0), Op.getOperand(1));
12637 }
12638
12639 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12640   return Op.getOperand(0);
12641 }
12642
12643 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12644                                                 SelectionDAG &DAG) const {
12645   SDValue Root = Op.getOperand(0);
12646   SDValue Trmp = Op.getOperand(1); // trampoline
12647   SDValue FPtr = Op.getOperand(2); // nested function
12648   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12649   SDLoc dl (Op);
12650
12651   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12652   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12653
12654   if (Subtarget->is64Bit()) {
12655     SDValue OutChains[6];
12656
12657     // Large code-model.
12658     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12659     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12660
12661     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12662     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12663
12664     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12665
12666     // Load the pointer to the nested function into R11.
12667     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12668     SDValue Addr = Trmp;
12669     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12670                                 Addr, MachinePointerInfo(TrmpAddr),
12671                                 false, false, 0);
12672
12673     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12674                        DAG.getConstant(2, MVT::i64));
12675     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12676                                 MachinePointerInfo(TrmpAddr, 2),
12677                                 false, false, 2);
12678
12679     // Load the 'nest' parameter value into R10.
12680     // R10 is specified in X86CallingConv.td
12681     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12682     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12683                        DAG.getConstant(10, MVT::i64));
12684     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12685                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12686                                 false, false, 0);
12687
12688     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12689                        DAG.getConstant(12, MVT::i64));
12690     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12691                                 MachinePointerInfo(TrmpAddr, 12),
12692                                 false, false, 2);
12693
12694     // Jump to the nested function.
12695     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12696     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12697                        DAG.getConstant(20, MVT::i64));
12698     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12699                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12700                                 false, false, 0);
12701
12702     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12703     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12704                        DAG.getConstant(22, MVT::i64));
12705     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12706                                 MachinePointerInfo(TrmpAddr, 22),
12707                                 false, false, 0);
12708
12709     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12710   } else {
12711     const Function *Func =
12712       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12713     CallingConv::ID CC = Func->getCallingConv();
12714     unsigned NestReg;
12715
12716     switch (CC) {
12717     default:
12718       llvm_unreachable("Unsupported calling convention");
12719     case CallingConv::C:
12720     case CallingConv::X86_StdCall: {
12721       // Pass 'nest' parameter in ECX.
12722       // Must be kept in sync with X86CallingConv.td
12723       NestReg = X86::ECX;
12724
12725       // Check that ECX wasn't needed by an 'inreg' parameter.
12726       FunctionType *FTy = Func->getFunctionType();
12727       const AttributeSet &Attrs = Func->getAttributes();
12728
12729       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12730         unsigned InRegCount = 0;
12731         unsigned Idx = 1;
12732
12733         for (FunctionType::param_iterator I = FTy->param_begin(),
12734              E = FTy->param_end(); I != E; ++I, ++Idx)
12735           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12736             // FIXME: should only count parameters that are lowered to integers.
12737             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12738
12739         if (InRegCount > 2) {
12740           report_fatal_error("Nest register in use - reduce number of inreg"
12741                              " parameters!");
12742         }
12743       }
12744       break;
12745     }
12746     case CallingConv::X86_FastCall:
12747     case CallingConv::X86_ThisCall:
12748     case CallingConv::Fast:
12749       // Pass 'nest' parameter in EAX.
12750       // Must be kept in sync with X86CallingConv.td
12751       NestReg = X86::EAX;
12752       break;
12753     }
12754
12755     SDValue OutChains[4];
12756     SDValue Addr, Disp;
12757
12758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12759                        DAG.getConstant(10, MVT::i32));
12760     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12761
12762     // This is storing the opcode for MOV32ri.
12763     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12764     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12765     OutChains[0] = DAG.getStore(Root, dl,
12766                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12767                                 Trmp, MachinePointerInfo(TrmpAddr),
12768                                 false, false, 0);
12769
12770     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12771                        DAG.getConstant(1, MVT::i32));
12772     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12773                                 MachinePointerInfo(TrmpAddr, 1),
12774                                 false, false, 1);
12775
12776     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12777     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12778                        DAG.getConstant(5, MVT::i32));
12779     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12780                                 MachinePointerInfo(TrmpAddr, 5),
12781                                 false, false, 1);
12782
12783     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12784                        DAG.getConstant(6, MVT::i32));
12785     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12786                                 MachinePointerInfo(TrmpAddr, 6),
12787                                 false, false, 1);
12788
12789     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12790   }
12791 }
12792
12793 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12794                                             SelectionDAG &DAG) const {
12795   /*
12796    The rounding mode is in bits 11:10 of FPSR, and has the following
12797    settings:
12798      00 Round to nearest
12799      01 Round to -inf
12800      10 Round to +inf
12801      11 Round to 0
12802
12803   FLT_ROUNDS, on the other hand, expects the following:
12804     -1 Undefined
12805      0 Round to 0
12806      1 Round to nearest
12807      2 Round to +inf
12808      3 Round to -inf
12809
12810   To perform the conversion, we do:
12811     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12812   */
12813
12814   MachineFunction &MF = DAG.getMachineFunction();
12815   const TargetMachine &TM = MF.getTarget();
12816   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12817   unsigned StackAlignment = TFI.getStackAlignment();
12818   MVT VT = Op.getSimpleValueType();
12819   SDLoc DL(Op);
12820
12821   // Save FP Control Word to stack slot
12822   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12823   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12824
12825   MachineMemOperand *MMO =
12826    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12827                            MachineMemOperand::MOStore, 2, 2);
12828
12829   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12830   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12831                                           DAG.getVTList(MVT::Other),
12832                                           Ops, array_lengthof(Ops), MVT::i16,
12833                                           MMO);
12834
12835   // Load FP Control Word from stack slot
12836   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12837                             MachinePointerInfo(), false, false, false, 0);
12838
12839   // Transform as necessary
12840   SDValue CWD1 =
12841     DAG.getNode(ISD::SRL, DL, MVT::i16,
12842                 DAG.getNode(ISD::AND, DL, MVT::i16,
12843                             CWD, DAG.getConstant(0x800, MVT::i16)),
12844                 DAG.getConstant(11, MVT::i8));
12845   SDValue CWD2 =
12846     DAG.getNode(ISD::SRL, DL, MVT::i16,
12847                 DAG.getNode(ISD::AND, DL, MVT::i16,
12848                             CWD, DAG.getConstant(0x400, MVT::i16)),
12849                 DAG.getConstant(9, MVT::i8));
12850
12851   SDValue RetVal =
12852     DAG.getNode(ISD::AND, DL, MVT::i16,
12853                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12854                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12855                             DAG.getConstant(1, MVT::i16)),
12856                 DAG.getConstant(3, MVT::i16));
12857
12858   return DAG.getNode((VT.getSizeInBits() < 16 ?
12859                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12860 }
12861
12862 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12863   MVT VT = Op.getSimpleValueType();
12864   EVT OpVT = VT;
12865   unsigned NumBits = VT.getSizeInBits();
12866   SDLoc dl(Op);
12867
12868   Op = Op.getOperand(0);
12869   if (VT == MVT::i8) {
12870     // Zero extend to i32 since there is not an i8 bsr.
12871     OpVT = MVT::i32;
12872     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12873   }
12874
12875   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12876   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12877   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12878
12879   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12880   SDValue Ops[] = {
12881     Op,
12882     DAG.getConstant(NumBits+NumBits-1, OpVT),
12883     DAG.getConstant(X86::COND_E, MVT::i8),
12884     Op.getValue(1)
12885   };
12886   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12887
12888   // Finally xor with NumBits-1.
12889   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12890
12891   if (VT == MVT::i8)
12892     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12893   return Op;
12894 }
12895
12896 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12897   MVT VT = Op.getSimpleValueType();
12898   EVT OpVT = VT;
12899   unsigned NumBits = VT.getSizeInBits();
12900   SDLoc dl(Op);
12901
12902   Op = Op.getOperand(0);
12903   if (VT == MVT::i8) {
12904     // Zero extend to i32 since there is not an i8 bsr.
12905     OpVT = MVT::i32;
12906     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12907   }
12908
12909   // Issue a bsr (scan bits in reverse).
12910   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12911   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12912
12913   // And xor with NumBits-1.
12914   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12915
12916   if (VT == MVT::i8)
12917     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12918   return Op;
12919 }
12920
12921 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12922   MVT VT = Op.getSimpleValueType();
12923   unsigned NumBits = VT.getSizeInBits();
12924   SDLoc dl(Op);
12925   Op = Op.getOperand(0);
12926
12927   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12928   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12929   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12930
12931   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12932   SDValue Ops[] = {
12933     Op,
12934     DAG.getConstant(NumBits, VT),
12935     DAG.getConstant(X86::COND_E, MVT::i8),
12936     Op.getValue(1)
12937   };
12938   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12939 }
12940
12941 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12942 // ones, and then concatenate the result back.
12943 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12944   MVT VT = Op.getSimpleValueType();
12945
12946   assert(VT.is256BitVector() && VT.isInteger() &&
12947          "Unsupported value type for operation");
12948
12949   unsigned NumElems = VT.getVectorNumElements();
12950   SDLoc dl(Op);
12951
12952   // Extract the LHS vectors
12953   SDValue LHS = Op.getOperand(0);
12954   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12955   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12956
12957   // Extract the RHS vectors
12958   SDValue RHS = Op.getOperand(1);
12959   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12960   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12961
12962   MVT EltVT = VT.getVectorElementType();
12963   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12964
12965   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12966                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12967                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12968 }
12969
12970 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12971   assert(Op.getSimpleValueType().is256BitVector() &&
12972          Op.getSimpleValueType().isInteger() &&
12973          "Only handle AVX 256-bit vector integer operation");
12974   return Lower256IntArith(Op, DAG);
12975 }
12976
12977 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12978   assert(Op.getSimpleValueType().is256BitVector() &&
12979          Op.getSimpleValueType().isInteger() &&
12980          "Only handle AVX 256-bit vector integer operation");
12981   return Lower256IntArith(Op, DAG);
12982 }
12983
12984 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12985                         SelectionDAG &DAG) {
12986   SDLoc dl(Op);
12987   MVT VT = Op.getSimpleValueType();
12988
12989   // Decompose 256-bit ops into smaller 128-bit ops.
12990   if (VT.is256BitVector() && !Subtarget->hasInt256())
12991     return Lower256IntArith(Op, DAG);
12992
12993   SDValue A = Op.getOperand(0);
12994   SDValue B = Op.getOperand(1);
12995
12996   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12997   if (VT == MVT::v4i32) {
12998     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12999            "Should not custom lower when pmuldq is available!");
13000
13001     // Extract the odd parts.
13002     static const int UnpackMask[] = { 1, -1, 3, -1 };
13003     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13004     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13005
13006     // Multiply the even parts.
13007     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13008     // Now multiply odd parts.
13009     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13010
13011     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13012     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13013
13014     // Merge the two vectors back together with a shuffle. This expands into 2
13015     // shuffles.
13016     static const int ShufMask[] = { 0, 4, 2, 6 };
13017     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13018   }
13019
13020   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13021          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13022
13023   //  Ahi = psrlqi(a, 32);
13024   //  Bhi = psrlqi(b, 32);
13025   //
13026   //  AloBlo = pmuludq(a, b);
13027   //  AloBhi = pmuludq(a, Bhi);
13028   //  AhiBlo = pmuludq(Ahi, b);
13029
13030   //  AloBhi = psllqi(AloBhi, 32);
13031   //  AhiBlo = psllqi(AhiBlo, 32);
13032   //  return AloBlo + AloBhi + AhiBlo;
13033
13034   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13035   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13036
13037   // Bit cast to 32-bit vectors for MULUDQ
13038   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13039                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13040   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13041   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13042   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13043   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13044
13045   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13046   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13047   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13048
13049   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13050   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13051
13052   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13053   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13054 }
13055
13056 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
13057   MVT VT = Op.getSimpleValueType();
13058   MVT EltTy = VT.getVectorElementType();
13059   unsigned NumElts = VT.getVectorNumElements();
13060   SDValue N0 = Op.getOperand(0);
13061   SDLoc dl(Op);
13062
13063   // Lower sdiv X, pow2-const.
13064   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
13065   if (!C)
13066     return SDValue();
13067
13068   APInt SplatValue, SplatUndef;
13069   unsigned SplatBitSize;
13070   bool HasAnyUndefs;
13071   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13072                           HasAnyUndefs) ||
13073       EltTy.getSizeInBits() < SplatBitSize)
13074     return SDValue();
13075
13076   if ((SplatValue != 0) &&
13077       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
13078     unsigned Lg2 = SplatValue.countTrailingZeros();
13079     // Splat the sign bit.
13080     SmallVector<SDValue, 16> Sz(NumElts,
13081                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
13082                                                 EltTy));
13083     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
13084                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
13085                                           NumElts));
13086     // Add (N0 < 0) ? abs2 - 1 : 0;
13087     SmallVector<SDValue, 16> Amt(NumElts,
13088                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13089                                                  EltTy));
13090     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13091                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13092                                           NumElts));
13093     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13094     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13095     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13096                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13097                                           NumElts));
13098
13099     // If we're dividing by a positive value, we're done.  Otherwise, we must
13100     // negate the result.
13101     if (SplatValue.isNonNegative())
13102       return SRA;
13103
13104     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13105     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13106     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13107   }
13108   return SDValue();
13109 }
13110
13111 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13112                                          const X86Subtarget *Subtarget) {
13113   MVT VT = Op.getSimpleValueType();
13114   SDLoc dl(Op);
13115   SDValue R = Op.getOperand(0);
13116   SDValue Amt = Op.getOperand(1);
13117
13118   // Optimize shl/srl/sra with constant shift amount.
13119   if (isSplatVector(Amt.getNode())) {
13120     SDValue SclrAmt = Amt->getOperand(0);
13121     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13122       uint64_t ShiftAmt = C->getZExtValue();
13123
13124       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13125           (Subtarget->hasInt256() &&
13126            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13127           (Subtarget->hasAVX512() &&
13128            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13129         if (Op.getOpcode() == ISD::SHL)
13130           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13131                                             DAG);
13132         if (Op.getOpcode() == ISD::SRL)
13133           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13134                                             DAG);
13135         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13136           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13137                                             DAG);
13138       }
13139
13140       if (VT == MVT::v16i8) {
13141         if (Op.getOpcode() == ISD::SHL) {
13142           // Make a large shift.
13143           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13144                                                    MVT::v8i16, R, ShiftAmt,
13145                                                    DAG);
13146           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13147           // Zero out the rightmost bits.
13148           SmallVector<SDValue, 16> V(16,
13149                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13150                                                      MVT::i8));
13151           return DAG.getNode(ISD::AND, dl, VT, SHL,
13152                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13153         }
13154         if (Op.getOpcode() == ISD::SRL) {
13155           // Make a large shift.
13156           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13157                                                    MVT::v8i16, R, ShiftAmt,
13158                                                    DAG);
13159           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13160           // Zero out the leftmost bits.
13161           SmallVector<SDValue, 16> V(16,
13162                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13163                                                      MVT::i8));
13164           return DAG.getNode(ISD::AND, dl, VT, SRL,
13165                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13166         }
13167         if (Op.getOpcode() == ISD::SRA) {
13168           if (ShiftAmt == 7) {
13169             // R s>> 7  ===  R s< 0
13170             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13171             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13172           }
13173
13174           // R s>> a === ((R u>> a) ^ m) - m
13175           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13176           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13177                                                          MVT::i8));
13178           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13179           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13180           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13181           return Res;
13182         }
13183         llvm_unreachable("Unknown shift opcode.");
13184       }
13185
13186       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13187         if (Op.getOpcode() == ISD::SHL) {
13188           // Make a large shift.
13189           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13190                                                    MVT::v16i16, R, ShiftAmt,
13191                                                    DAG);
13192           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13193           // Zero out the rightmost bits.
13194           SmallVector<SDValue, 32> V(32,
13195                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13196                                                      MVT::i8));
13197           return DAG.getNode(ISD::AND, dl, VT, SHL,
13198                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13199         }
13200         if (Op.getOpcode() == ISD::SRL) {
13201           // Make a large shift.
13202           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13203                                                    MVT::v16i16, R, ShiftAmt,
13204                                                    DAG);
13205           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13206           // Zero out the leftmost bits.
13207           SmallVector<SDValue, 32> V(32,
13208                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13209                                                      MVT::i8));
13210           return DAG.getNode(ISD::AND, dl, VT, SRL,
13211                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13212         }
13213         if (Op.getOpcode() == ISD::SRA) {
13214           if (ShiftAmt == 7) {
13215             // R s>> 7  ===  R s< 0
13216             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13217             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13218           }
13219
13220           // R s>> a === ((R u>> a) ^ m) - m
13221           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13222           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13223                                                          MVT::i8));
13224           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13225           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13226           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13227           return Res;
13228         }
13229         llvm_unreachable("Unknown shift opcode.");
13230       }
13231     }
13232   }
13233
13234   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13235   if (!Subtarget->is64Bit() &&
13236       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13237       Amt.getOpcode() == ISD::BITCAST &&
13238       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13239     Amt = Amt.getOperand(0);
13240     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13241                      VT.getVectorNumElements();
13242     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13243     uint64_t ShiftAmt = 0;
13244     for (unsigned i = 0; i != Ratio; ++i) {
13245       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13246       if (C == 0)
13247         return SDValue();
13248       // 6 == Log2(64)
13249       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13250     }
13251     // Check remaining shift amounts.
13252     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13253       uint64_t ShAmt = 0;
13254       for (unsigned j = 0; j != Ratio; ++j) {
13255         ConstantSDNode *C =
13256           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13257         if (C == 0)
13258           return SDValue();
13259         // 6 == Log2(64)
13260         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13261       }
13262       if (ShAmt != ShiftAmt)
13263         return SDValue();
13264     }
13265     switch (Op.getOpcode()) {
13266     default:
13267       llvm_unreachable("Unknown shift opcode!");
13268     case ISD::SHL:
13269       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13270                                         DAG);
13271     case ISD::SRL:
13272       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13273                                         DAG);
13274     case ISD::SRA:
13275       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13276                                         DAG);
13277     }
13278   }
13279
13280   return SDValue();
13281 }
13282
13283 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13284                                         const X86Subtarget* Subtarget) {
13285   MVT VT = Op.getSimpleValueType();
13286   SDLoc dl(Op);
13287   SDValue R = Op.getOperand(0);
13288   SDValue Amt = Op.getOperand(1);
13289
13290   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13291       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13292       (Subtarget->hasInt256() &&
13293        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13294         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13295        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13296     SDValue BaseShAmt;
13297     EVT EltVT = VT.getVectorElementType();
13298
13299     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13300       unsigned NumElts = VT.getVectorNumElements();
13301       unsigned i, j;
13302       for (i = 0; i != NumElts; ++i) {
13303         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13304           continue;
13305         break;
13306       }
13307       for (j = i; j != NumElts; ++j) {
13308         SDValue Arg = Amt.getOperand(j);
13309         if (Arg.getOpcode() == ISD::UNDEF) continue;
13310         if (Arg != Amt.getOperand(i))
13311           break;
13312       }
13313       if (i != NumElts && j == NumElts)
13314         BaseShAmt = Amt.getOperand(i);
13315     } else {
13316       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13317         Amt = Amt.getOperand(0);
13318       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13319                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13320         SDValue InVec = Amt.getOperand(0);
13321         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13322           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13323           unsigned i = 0;
13324           for (; i != NumElts; ++i) {
13325             SDValue Arg = InVec.getOperand(i);
13326             if (Arg.getOpcode() == ISD::UNDEF) continue;
13327             BaseShAmt = Arg;
13328             break;
13329           }
13330         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13331            if (ConstantSDNode *C =
13332                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13333              unsigned SplatIdx =
13334                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13335              if (C->getZExtValue() == SplatIdx)
13336                BaseShAmt = InVec.getOperand(1);
13337            }
13338         }
13339         if (BaseShAmt.getNode() == 0)
13340           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13341                                   DAG.getIntPtrConstant(0));
13342       }
13343     }
13344
13345     if (BaseShAmt.getNode()) {
13346       if (EltVT.bitsGT(MVT::i32))
13347         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13348       else if (EltVT.bitsLT(MVT::i32))
13349         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13350
13351       switch (Op.getOpcode()) {
13352       default:
13353         llvm_unreachable("Unknown shift opcode!");
13354       case ISD::SHL:
13355         switch (VT.SimpleTy) {
13356         default: return SDValue();
13357         case MVT::v2i64:
13358         case MVT::v4i32:
13359         case MVT::v8i16:
13360         case MVT::v4i64:
13361         case MVT::v8i32:
13362         case MVT::v16i16:
13363         case MVT::v16i32:
13364         case MVT::v8i64:
13365           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13366         }
13367       case ISD::SRA:
13368         switch (VT.SimpleTy) {
13369         default: return SDValue();
13370         case MVT::v4i32:
13371         case MVT::v8i16:
13372         case MVT::v8i32:
13373         case MVT::v16i16:
13374         case MVT::v16i32:
13375         case MVT::v8i64:
13376           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13377         }
13378       case ISD::SRL:
13379         switch (VT.SimpleTy) {
13380         default: return SDValue();
13381         case MVT::v2i64:
13382         case MVT::v4i32:
13383         case MVT::v8i16:
13384         case MVT::v4i64:
13385         case MVT::v8i32:
13386         case MVT::v16i16:
13387         case MVT::v16i32:
13388         case MVT::v8i64:
13389           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13390         }
13391       }
13392     }
13393   }
13394
13395   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13396   if (!Subtarget->is64Bit() &&
13397       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13398       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13399       Amt.getOpcode() == ISD::BITCAST &&
13400       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13401     Amt = Amt.getOperand(0);
13402     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13403                      VT.getVectorNumElements();
13404     std::vector<SDValue> Vals(Ratio);
13405     for (unsigned i = 0; i != Ratio; ++i)
13406       Vals[i] = Amt.getOperand(i);
13407     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13408       for (unsigned j = 0; j != Ratio; ++j)
13409         if (Vals[j] != Amt.getOperand(i + j))
13410           return SDValue();
13411     }
13412     switch (Op.getOpcode()) {
13413     default:
13414       llvm_unreachable("Unknown shift opcode!");
13415     case ISD::SHL:
13416       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13417     case ISD::SRL:
13418       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13419     case ISD::SRA:
13420       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13421     }
13422   }
13423
13424   return SDValue();
13425 }
13426
13427 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13428                           SelectionDAG &DAG) {
13429
13430   MVT VT = Op.getSimpleValueType();
13431   SDLoc dl(Op);
13432   SDValue R = Op.getOperand(0);
13433   SDValue Amt = Op.getOperand(1);
13434   SDValue V;
13435
13436   if (!Subtarget->hasSSE2())
13437     return SDValue();
13438
13439   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13440   if (V.getNode())
13441     return V;
13442
13443   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13444   if (V.getNode())
13445       return V;
13446
13447   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13448     return Op;
13449   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13450   if (Subtarget->hasInt256()) {
13451     if (Op.getOpcode() == ISD::SRL &&
13452         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13453          VT == MVT::v4i64 || VT == MVT::v8i32))
13454       return Op;
13455     if (Op.getOpcode() == ISD::SHL &&
13456         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13457          VT == MVT::v4i64 || VT == MVT::v8i32))
13458       return Op;
13459     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13460       return Op;
13461   }
13462
13463   // If possible, lower this packed shift into a vector multiply instead of
13464   // expanding it into a sequence of scalar shifts.
13465   // Do this only if the vector shift count is a constant build_vector.
13466   if (Op.getOpcode() == ISD::SHL && 
13467       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13468        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13469       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13470     SmallVector<SDValue, 8> Elts;
13471     EVT SVT = VT.getScalarType();
13472     unsigned SVTBits = SVT.getSizeInBits();
13473     const APInt &One = APInt(SVTBits, 1);
13474     unsigned NumElems = VT.getVectorNumElements();
13475
13476     for (unsigned i=0; i !=NumElems; ++i) {
13477       SDValue Op = Amt->getOperand(i);
13478       if (Op->getOpcode() == ISD::UNDEF) {
13479         Elts.push_back(Op);
13480         continue;
13481       }
13482
13483       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13484       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13485       uint64_t ShAmt = C.getZExtValue();
13486       if (ShAmt >= SVTBits) {
13487         Elts.push_back(DAG.getUNDEF(SVT));
13488         continue;
13489       }
13490       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13491     }
13492     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13493     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13494   }
13495
13496   // Lower SHL with variable shift amount.
13497   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13498     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13499
13500     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13501     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13502     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13503     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13504   }
13505
13506   // If possible, lower this shift as a sequence of two shifts by
13507   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13508   // Example:
13509   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13510   //
13511   // Could be rewritten as:
13512   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13513   //
13514   // The advantage is that the two shifts from the example would be
13515   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13516   // the vector shift into four scalar shifts plus four pairs of vector
13517   // insert/extract.
13518   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13519       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13520     unsigned TargetOpcode = X86ISD::MOVSS;
13521     bool CanBeSimplified;
13522     // The splat value for the first packed shift (the 'X' from the example).
13523     SDValue Amt1 = Amt->getOperand(0);
13524     // The splat value for the second packed shift (the 'Y' from the example).
13525     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13526                                         Amt->getOperand(2);
13527
13528     // See if it is possible to replace this node with a sequence of
13529     // two shifts followed by a MOVSS/MOVSD
13530     if (VT == MVT::v4i32) {
13531       // Check if it is legal to use a MOVSS.
13532       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13533                         Amt2 == Amt->getOperand(3);
13534       if (!CanBeSimplified) {
13535         // Otherwise, check if we can still simplify this node using a MOVSD.
13536         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13537                           Amt->getOperand(2) == Amt->getOperand(3);
13538         TargetOpcode = X86ISD::MOVSD;
13539         Amt2 = Amt->getOperand(2);
13540       }
13541     } else {
13542       // Do similar checks for the case where the machine value type
13543       // is MVT::v8i16.
13544       CanBeSimplified = Amt1 == Amt->getOperand(1);
13545       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13546         CanBeSimplified = Amt2 == Amt->getOperand(i);
13547
13548       if (!CanBeSimplified) {
13549         TargetOpcode = X86ISD::MOVSD;
13550         CanBeSimplified = true;
13551         Amt2 = Amt->getOperand(4);
13552         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13553           CanBeSimplified = Amt1 == Amt->getOperand(i);
13554         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13555           CanBeSimplified = Amt2 == Amt->getOperand(j);
13556       }
13557     }
13558     
13559     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13560         isa<ConstantSDNode>(Amt2)) {
13561       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13562       EVT CastVT = MVT::v4i32;
13563       SDValue Splat1 = 
13564         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13565       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13566       SDValue Splat2 = 
13567         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13568       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13569       if (TargetOpcode == X86ISD::MOVSD)
13570         CastVT = MVT::v2i64;
13571       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13572       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13573       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13574                                             BitCast1, DAG);
13575       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13576     }
13577   }
13578
13579   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13580     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13581
13582     // a = a << 5;
13583     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13584     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13585
13586     // Turn 'a' into a mask suitable for VSELECT
13587     SDValue VSelM = DAG.getConstant(0x80, VT);
13588     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13589     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13590
13591     SDValue CM1 = DAG.getConstant(0x0f, VT);
13592     SDValue CM2 = DAG.getConstant(0x3f, VT);
13593
13594     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13595     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13596     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13597     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13598     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13599
13600     // a += a
13601     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13602     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13603     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13604
13605     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13606     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13607     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13608     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13609     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13610
13611     // a += a
13612     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13613     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13614     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13615
13616     // return VSELECT(r, r+r, a);
13617     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13618                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13619     return R;
13620   }
13621
13622   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13623   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13624   // solution better.
13625   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13626     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13627     unsigned ExtOpc =
13628         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13629     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13630     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13631     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13632                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13633     }
13634
13635   // Decompose 256-bit shifts into smaller 128-bit shifts.
13636   if (VT.is256BitVector()) {
13637     unsigned NumElems = VT.getVectorNumElements();
13638     MVT EltVT = VT.getVectorElementType();
13639     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13640
13641     // Extract the two vectors
13642     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13643     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13644
13645     // Recreate the shift amount vectors
13646     SDValue Amt1, Amt2;
13647     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13648       // Constant shift amount
13649       SmallVector<SDValue, 4> Amt1Csts;
13650       SmallVector<SDValue, 4> Amt2Csts;
13651       for (unsigned i = 0; i != NumElems/2; ++i)
13652         Amt1Csts.push_back(Amt->getOperand(i));
13653       for (unsigned i = NumElems/2; i != NumElems; ++i)
13654         Amt2Csts.push_back(Amt->getOperand(i));
13655
13656       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13657                                  &Amt1Csts[0], NumElems/2);
13658       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13659                                  &Amt2Csts[0], NumElems/2);
13660     } else {
13661       // Variable shift amount
13662       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13663       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13664     }
13665
13666     // Issue new vector shifts for the smaller types
13667     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13668     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13669
13670     // Concatenate the result back
13671     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13672   }
13673
13674   return SDValue();
13675 }
13676
13677 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13678   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13679   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13680   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13681   // has only one use.
13682   SDNode *N = Op.getNode();
13683   SDValue LHS = N->getOperand(0);
13684   SDValue RHS = N->getOperand(1);
13685   unsigned BaseOp = 0;
13686   unsigned Cond = 0;
13687   SDLoc DL(Op);
13688   switch (Op.getOpcode()) {
13689   default: llvm_unreachable("Unknown ovf instruction!");
13690   case ISD::SADDO:
13691     // A subtract of one will be selected as a INC. Note that INC doesn't
13692     // set CF, so we can't do this for UADDO.
13693     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13694       if (C->isOne()) {
13695         BaseOp = X86ISD::INC;
13696         Cond = X86::COND_O;
13697         break;
13698       }
13699     BaseOp = X86ISD::ADD;
13700     Cond = X86::COND_O;
13701     break;
13702   case ISD::UADDO:
13703     BaseOp = X86ISD::ADD;
13704     Cond = X86::COND_B;
13705     break;
13706   case ISD::SSUBO:
13707     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13708     // set CF, so we can't do this for USUBO.
13709     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13710       if (C->isOne()) {
13711         BaseOp = X86ISD::DEC;
13712         Cond = X86::COND_O;
13713         break;
13714       }
13715     BaseOp = X86ISD::SUB;
13716     Cond = X86::COND_O;
13717     break;
13718   case ISD::USUBO:
13719     BaseOp = X86ISD::SUB;
13720     Cond = X86::COND_B;
13721     break;
13722   case ISD::SMULO:
13723     BaseOp = X86ISD::SMUL;
13724     Cond = X86::COND_O;
13725     break;
13726   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13727     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13728                                  MVT::i32);
13729     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13730
13731     SDValue SetCC =
13732       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13733                   DAG.getConstant(X86::COND_O, MVT::i32),
13734                   SDValue(Sum.getNode(), 2));
13735
13736     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13737   }
13738   }
13739
13740   // Also sets EFLAGS.
13741   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13742   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13743
13744   SDValue SetCC =
13745     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13746                 DAG.getConstant(Cond, MVT::i32),
13747                 SDValue(Sum.getNode(), 1));
13748
13749   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13750 }
13751
13752 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13753                                                   SelectionDAG &DAG) const {
13754   SDLoc dl(Op);
13755   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13756   MVT VT = Op.getSimpleValueType();
13757
13758   if (!Subtarget->hasSSE2() || !VT.isVector())
13759     return SDValue();
13760
13761   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13762                       ExtraVT.getScalarType().getSizeInBits();
13763
13764   switch (VT.SimpleTy) {
13765     default: return SDValue();
13766     case MVT::v8i32:
13767     case MVT::v16i16:
13768       if (!Subtarget->hasFp256())
13769         return SDValue();
13770       if (!Subtarget->hasInt256()) {
13771         // needs to be split
13772         unsigned NumElems = VT.getVectorNumElements();
13773
13774         // Extract the LHS vectors
13775         SDValue LHS = Op.getOperand(0);
13776         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13777         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13778
13779         MVT EltVT = VT.getVectorElementType();
13780         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13781
13782         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13783         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13784         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13785                                    ExtraNumElems/2);
13786         SDValue Extra = DAG.getValueType(ExtraVT);
13787
13788         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13789         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13790
13791         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13792       }
13793       // fall through
13794     case MVT::v4i32:
13795     case MVT::v8i16: {
13796       SDValue Op0 = Op.getOperand(0);
13797       SDValue Op00 = Op0.getOperand(0);
13798       SDValue Tmp1;
13799       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13800       if (Op0.getOpcode() == ISD::BITCAST &&
13801           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13802         // (sext (vzext x)) -> (vsext x)
13803         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13804         if (Tmp1.getNode()) {
13805           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13806           // This folding is only valid when the in-reg type is a vector of i8,
13807           // i16, or i32.
13808           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13809               ExtraEltVT == MVT::i32) {
13810             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13811             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13812                    "This optimization is invalid without a VZEXT.");
13813             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13814           }
13815           Op0 = Tmp1;
13816         }
13817       }
13818
13819       // If the above didn't work, then just use Shift-Left + Shift-Right.
13820       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13821                                         DAG);
13822       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13823                                         DAG);
13824     }
13825   }
13826 }
13827
13828 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13829                                  SelectionDAG &DAG) {
13830   SDLoc dl(Op);
13831   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13832     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13833   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13834     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13835
13836   // The only fence that needs an instruction is a sequentially-consistent
13837   // cross-thread fence.
13838   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13839     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13840     // no-sse2). There isn't any reason to disable it if the target processor
13841     // supports it.
13842     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13843       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13844
13845     SDValue Chain = Op.getOperand(0);
13846     SDValue Zero = DAG.getConstant(0, MVT::i32);
13847     SDValue Ops[] = {
13848       DAG.getRegister(X86::ESP, MVT::i32), // Base
13849       DAG.getTargetConstant(1, MVT::i8),   // Scale
13850       DAG.getRegister(0, MVT::i32),        // Index
13851       DAG.getTargetConstant(0, MVT::i32),  // Disp
13852       DAG.getRegister(0, MVT::i32),        // Segment.
13853       Zero,
13854       Chain
13855     };
13856     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13857     return SDValue(Res, 0);
13858   }
13859
13860   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13861   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13862 }
13863
13864 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13865                              SelectionDAG &DAG) {
13866   MVT T = Op.getSimpleValueType();
13867   SDLoc DL(Op);
13868   unsigned Reg = 0;
13869   unsigned size = 0;
13870   switch(T.SimpleTy) {
13871   default: llvm_unreachable("Invalid value type!");
13872   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13873   case MVT::i16: Reg = X86::AX;  size = 2; break;
13874   case MVT::i32: Reg = X86::EAX; size = 4; break;
13875   case MVT::i64:
13876     assert(Subtarget->is64Bit() && "Node not type legal!");
13877     Reg = X86::RAX; size = 8;
13878     break;
13879   }
13880   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13881                                     Op.getOperand(2), SDValue());
13882   SDValue Ops[] = { cpIn.getValue(0),
13883                     Op.getOperand(1),
13884                     Op.getOperand(3),
13885                     DAG.getTargetConstant(size, MVT::i8),
13886                     cpIn.getValue(1) };
13887   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13888   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13889   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13890                                            Ops, array_lengthof(Ops), T, MMO);
13891   SDValue cpOut =
13892     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13893   return cpOut;
13894 }
13895
13896 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13897                             SelectionDAG &DAG) {
13898   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13899   MVT DstVT = Op.getSimpleValueType();
13900   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13901          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13902   assert((DstVT == MVT::i64 ||
13903           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13904          "Unexpected custom BITCAST");
13905   // i64 <=> MMX conversions are Legal.
13906   if (SrcVT==MVT::i64 && DstVT.isVector())
13907     return Op;
13908   if (DstVT==MVT::i64 && SrcVT.isVector())
13909     return Op;
13910   // MMX <=> MMX conversions are Legal.
13911   if (SrcVT.isVector() && DstVT.isVector())
13912     return Op;
13913   // All other conversions need to be expanded.
13914   return SDValue();
13915 }
13916
13917 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13918   SDNode *Node = Op.getNode();
13919   SDLoc dl(Node);
13920   EVT T = Node->getValueType(0);
13921   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13922                               DAG.getConstant(0, T), Node->getOperand(2));
13923   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13924                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13925                        Node->getOperand(0),
13926                        Node->getOperand(1), negOp,
13927                        cast<AtomicSDNode>(Node)->getMemOperand(),
13928                        cast<AtomicSDNode>(Node)->getOrdering(),
13929                        cast<AtomicSDNode>(Node)->getSynchScope());
13930 }
13931
13932 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13933   SDNode *Node = Op.getNode();
13934   SDLoc dl(Node);
13935   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13936
13937   // Convert seq_cst store -> xchg
13938   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13939   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13940   //        (The only way to get a 16-byte store is cmpxchg16b)
13941   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13942   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13943       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13944     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13945                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13946                                  Node->getOperand(0),
13947                                  Node->getOperand(1), Node->getOperand(2),
13948                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13949                                  cast<AtomicSDNode>(Node)->getOrdering(),
13950                                  cast<AtomicSDNode>(Node)->getSynchScope());
13951     return Swap.getValue(1);
13952   }
13953   // Other atomic stores have a simple pattern.
13954   return Op;
13955 }
13956
13957 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13958   EVT VT = Op.getNode()->getSimpleValueType(0);
13959
13960   // Let legalize expand this if it isn't a legal type yet.
13961   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13962     return SDValue();
13963
13964   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13965
13966   unsigned Opc;
13967   bool ExtraOp = false;
13968   switch (Op.getOpcode()) {
13969   default: llvm_unreachable("Invalid code");
13970   case ISD::ADDC: Opc = X86ISD::ADD; break;
13971   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13972   case ISD::SUBC: Opc = X86ISD::SUB; break;
13973   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13974   }
13975
13976   if (!ExtraOp)
13977     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13978                        Op.getOperand(1));
13979   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13980                      Op.getOperand(1), Op.getOperand(2));
13981 }
13982
13983 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13984                             SelectionDAG &DAG) {
13985   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13986
13987   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13988   // which returns the values as { float, float } (in XMM0) or
13989   // { double, double } (which is returned in XMM0, XMM1).
13990   SDLoc dl(Op);
13991   SDValue Arg = Op.getOperand(0);
13992   EVT ArgVT = Arg.getValueType();
13993   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13994
13995   TargetLowering::ArgListTy Args;
13996   TargetLowering::ArgListEntry Entry;
13997
13998   Entry.Node = Arg;
13999   Entry.Ty = ArgTy;
14000   Entry.isSExt = false;
14001   Entry.isZExt = false;
14002   Args.push_back(Entry);
14003
14004   bool isF64 = ArgVT == MVT::f64;
14005   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14006   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14007   // the results are returned via SRet in memory.
14008   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14010   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14011
14012   Type *RetTy = isF64
14013     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14014     : (Type*)VectorType::get(ArgTy, 4);
14015   TargetLowering::
14016     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14017                          false, false, false, false, 0,
14018                          CallingConv::C, /*isTaillCall=*/false,
14019                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14020                          Callee, Args, DAG, dl);
14021   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14022
14023   if (isF64)
14024     // Returned in xmm0 and xmm1.
14025     return CallResult.first;
14026
14027   // Returned in bits 0:31 and 32:64 xmm0.
14028   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14029                                CallResult.first, DAG.getIntPtrConstant(0));
14030   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14031                                CallResult.first, DAG.getIntPtrConstant(1));
14032   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14033   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14034 }
14035
14036 /// LowerOperation - Provide custom lowering hooks for some operations.
14037 ///
14038 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14039   switch (Op.getOpcode()) {
14040   default: llvm_unreachable("Should not custom lower this!");
14041   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14042   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14043   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14044   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14045   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14046   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14047   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14048   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14049   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14050   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14051   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14052   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14053   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14054   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14055   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14056   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14057   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14058   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14059   case ISD::SHL_PARTS:
14060   case ISD::SRA_PARTS:
14061   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14062   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14063   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14064   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14065   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14066   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14067   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14068   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14069   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14070   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14071   case ISD::FABS:               return LowerFABS(Op, DAG);
14072   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14073   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14074   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14075   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14076   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14077   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14078   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14079   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14080   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14081   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14082   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14083   case ISD::INTRINSIC_VOID:
14084   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14085   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14086   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14087   case ISD::FRAME_TO_ARGS_OFFSET:
14088                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14089   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14090   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14091   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14092   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14093   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14094   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14095   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14096   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14097   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14098   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14099   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14100   case ISD::SRA:
14101   case ISD::SRL:
14102   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14103   case ISD::SADDO:
14104   case ISD::UADDO:
14105   case ISD::SSUBO:
14106   case ISD::USUBO:
14107   case ISD::SMULO:
14108   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14109   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14110   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14111   case ISD::ADDC:
14112   case ISD::ADDE:
14113   case ISD::SUBC:
14114   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14115   case ISD::ADD:                return LowerADD(Op, DAG);
14116   case ISD::SUB:                return LowerSUB(Op, DAG);
14117   case ISD::SDIV:               return LowerSDIV(Op, DAG);
14118   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14119   }
14120 }
14121
14122 static void ReplaceATOMIC_LOAD(SDNode *Node,
14123                                   SmallVectorImpl<SDValue> &Results,
14124                                   SelectionDAG &DAG) {
14125   SDLoc dl(Node);
14126   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14127
14128   // Convert wide load -> cmpxchg8b/cmpxchg16b
14129   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14130   //        (The only way to get a 16-byte load is cmpxchg16b)
14131   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14132   SDValue Zero = DAG.getConstant(0, VT);
14133   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14134                                Node->getOperand(0),
14135                                Node->getOperand(1), Zero, Zero,
14136                                cast<AtomicSDNode>(Node)->getMemOperand(),
14137                                cast<AtomicSDNode>(Node)->getOrdering(),
14138                                cast<AtomicSDNode>(Node)->getOrdering(),
14139                                cast<AtomicSDNode>(Node)->getSynchScope());
14140   Results.push_back(Swap.getValue(0));
14141   Results.push_back(Swap.getValue(1));
14142 }
14143
14144 static void
14145 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14146                         SelectionDAG &DAG, unsigned NewOp) {
14147   SDLoc dl(Node);
14148   assert (Node->getValueType(0) == MVT::i64 &&
14149           "Only know how to expand i64 atomics");
14150
14151   SDValue Chain = Node->getOperand(0);
14152   SDValue In1 = Node->getOperand(1);
14153   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14154                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14155   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14156                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14157   SDValue Ops[] = { Chain, In1, In2L, In2H };
14158   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14159   SDValue Result =
14160     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14161                             cast<MemSDNode>(Node)->getMemOperand());
14162   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14163   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14164   Results.push_back(Result.getValue(2));
14165 }
14166
14167 /// ReplaceNodeResults - Replace a node with an illegal result type
14168 /// with a new node built out of custom code.
14169 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14170                                            SmallVectorImpl<SDValue>&Results,
14171                                            SelectionDAG &DAG) const {
14172   SDLoc dl(N);
14173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14174   switch (N->getOpcode()) {
14175   default:
14176     llvm_unreachable("Do not know how to custom type legalize this operation!");
14177   case ISD::SIGN_EXTEND_INREG:
14178   case ISD::ADDC:
14179   case ISD::ADDE:
14180   case ISD::SUBC:
14181   case ISD::SUBE:
14182     // We don't want to expand or promote these.
14183     return;
14184   case ISD::FP_TO_SINT:
14185   case ISD::FP_TO_UINT: {
14186     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14187
14188     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14189       return;
14190
14191     std::pair<SDValue,SDValue> Vals =
14192         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14193     SDValue FIST = Vals.first, StackSlot = Vals.second;
14194     if (FIST.getNode() != 0) {
14195       EVT VT = N->getValueType(0);
14196       // Return a load from the stack slot.
14197       if (StackSlot.getNode() != 0)
14198         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14199                                       MachinePointerInfo(),
14200                                       false, false, false, 0));
14201       else
14202         Results.push_back(FIST);
14203     }
14204     return;
14205   }
14206   case ISD::UINT_TO_FP: {
14207     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14208     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14209         N->getValueType(0) != MVT::v2f32)
14210       return;
14211     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14212                                  N->getOperand(0));
14213     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14214                                      MVT::f64);
14215     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14216     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14217                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14218     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14219     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14220     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14221     return;
14222   }
14223   case ISD::FP_ROUND: {
14224     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14225         return;
14226     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14227     Results.push_back(V);
14228     return;
14229   }
14230   case ISD::INTRINSIC_W_CHAIN: {
14231     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14232     switch (IntNo) {
14233     default : llvm_unreachable("Do not know how to custom type "
14234                                "legalize this intrinsic operation!");
14235     case Intrinsic::x86_rdtsc:
14236       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14237                                      Results);
14238     case Intrinsic::x86_rdtscp:
14239       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14240                                      Results);
14241     }
14242   }
14243   case ISD::READCYCLECOUNTER: {
14244     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14245                                    Results);
14246   }
14247   case ISD::ATOMIC_CMP_SWAP: {
14248     EVT T = N->getValueType(0);
14249     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14250     bool Regs64bit = T == MVT::i128;
14251     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14252     SDValue cpInL, cpInH;
14253     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14254                         DAG.getConstant(0, HalfT));
14255     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14256                         DAG.getConstant(1, HalfT));
14257     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14258                              Regs64bit ? X86::RAX : X86::EAX,
14259                              cpInL, SDValue());
14260     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14261                              Regs64bit ? X86::RDX : X86::EDX,
14262                              cpInH, cpInL.getValue(1));
14263     SDValue swapInL, swapInH;
14264     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14265                           DAG.getConstant(0, HalfT));
14266     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14267                           DAG.getConstant(1, HalfT));
14268     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14269                                Regs64bit ? X86::RBX : X86::EBX,
14270                                swapInL, cpInH.getValue(1));
14271     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14272                                Regs64bit ? X86::RCX : X86::ECX,
14273                                swapInH, swapInL.getValue(1));
14274     SDValue Ops[] = { swapInH.getValue(0),
14275                       N->getOperand(1),
14276                       swapInH.getValue(1) };
14277     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14278     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14279     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14280                                   X86ISD::LCMPXCHG8_DAG;
14281     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14282                                              Ops, array_lengthof(Ops), T, MMO);
14283     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14284                                         Regs64bit ? X86::RAX : X86::EAX,
14285                                         HalfT, Result.getValue(1));
14286     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14287                                         Regs64bit ? X86::RDX : X86::EDX,
14288                                         HalfT, cpOutL.getValue(2));
14289     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14290     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14291     Results.push_back(cpOutH.getValue(1));
14292     return;
14293   }
14294   case ISD::ATOMIC_LOAD_ADD:
14295   case ISD::ATOMIC_LOAD_AND:
14296   case ISD::ATOMIC_LOAD_NAND:
14297   case ISD::ATOMIC_LOAD_OR:
14298   case ISD::ATOMIC_LOAD_SUB:
14299   case ISD::ATOMIC_LOAD_XOR:
14300   case ISD::ATOMIC_LOAD_MAX:
14301   case ISD::ATOMIC_LOAD_MIN:
14302   case ISD::ATOMIC_LOAD_UMAX:
14303   case ISD::ATOMIC_LOAD_UMIN:
14304   case ISD::ATOMIC_SWAP: {
14305     unsigned Opc;
14306     switch (N->getOpcode()) {
14307     default: llvm_unreachable("Unexpected opcode");
14308     case ISD::ATOMIC_LOAD_ADD:
14309       Opc = X86ISD::ATOMADD64_DAG;
14310       break;
14311     case ISD::ATOMIC_LOAD_AND:
14312       Opc = X86ISD::ATOMAND64_DAG;
14313       break;
14314     case ISD::ATOMIC_LOAD_NAND:
14315       Opc = X86ISD::ATOMNAND64_DAG;
14316       break;
14317     case ISD::ATOMIC_LOAD_OR:
14318       Opc = X86ISD::ATOMOR64_DAG;
14319       break;
14320     case ISD::ATOMIC_LOAD_SUB:
14321       Opc = X86ISD::ATOMSUB64_DAG;
14322       break;
14323     case ISD::ATOMIC_LOAD_XOR:
14324       Opc = X86ISD::ATOMXOR64_DAG;
14325       break;
14326     case ISD::ATOMIC_LOAD_MAX:
14327       Opc = X86ISD::ATOMMAX64_DAG;
14328       break;
14329     case ISD::ATOMIC_LOAD_MIN:
14330       Opc = X86ISD::ATOMMIN64_DAG;
14331       break;
14332     case ISD::ATOMIC_LOAD_UMAX:
14333       Opc = X86ISD::ATOMUMAX64_DAG;
14334       break;
14335     case ISD::ATOMIC_LOAD_UMIN:
14336       Opc = X86ISD::ATOMUMIN64_DAG;
14337       break;
14338     case ISD::ATOMIC_SWAP:
14339       Opc = X86ISD::ATOMSWAP64_DAG;
14340       break;
14341     }
14342     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14343     return;
14344   }
14345   case ISD::ATOMIC_LOAD:
14346     ReplaceATOMIC_LOAD(N, Results, DAG);
14347   }
14348 }
14349
14350 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14351   switch (Opcode) {
14352   default: return NULL;
14353   case X86ISD::BSF:                return "X86ISD::BSF";
14354   case X86ISD::BSR:                return "X86ISD::BSR";
14355   case X86ISD::SHLD:               return "X86ISD::SHLD";
14356   case X86ISD::SHRD:               return "X86ISD::SHRD";
14357   case X86ISD::FAND:               return "X86ISD::FAND";
14358   case X86ISD::FANDN:              return "X86ISD::FANDN";
14359   case X86ISD::FOR:                return "X86ISD::FOR";
14360   case X86ISD::FXOR:               return "X86ISD::FXOR";
14361   case X86ISD::FSRL:               return "X86ISD::FSRL";
14362   case X86ISD::FILD:               return "X86ISD::FILD";
14363   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14364   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14365   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14366   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14367   case X86ISD::FLD:                return "X86ISD::FLD";
14368   case X86ISD::FST:                return "X86ISD::FST";
14369   case X86ISD::CALL:               return "X86ISD::CALL";
14370   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14371   case X86ISD::BT:                 return "X86ISD::BT";
14372   case X86ISD::CMP:                return "X86ISD::CMP";
14373   case X86ISD::COMI:               return "X86ISD::COMI";
14374   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14375   case X86ISD::CMPM:               return "X86ISD::CMPM";
14376   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14377   case X86ISD::SETCC:              return "X86ISD::SETCC";
14378   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14379   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14380   case X86ISD::CMOV:               return "X86ISD::CMOV";
14381   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14382   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14383   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14384   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14385   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14386   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14387   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14388   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14389   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14390   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14391   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14392   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14393   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14394   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14395   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14396   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14397   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14398   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14399   case X86ISD::HADD:               return "X86ISD::HADD";
14400   case X86ISD::HSUB:               return "X86ISD::HSUB";
14401   case X86ISD::FHADD:              return "X86ISD::FHADD";
14402   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14403   case X86ISD::UMAX:               return "X86ISD::UMAX";
14404   case X86ISD::UMIN:               return "X86ISD::UMIN";
14405   case X86ISD::SMAX:               return "X86ISD::SMAX";
14406   case X86ISD::SMIN:               return "X86ISD::SMIN";
14407   case X86ISD::FMAX:               return "X86ISD::FMAX";
14408   case X86ISD::FMIN:               return "X86ISD::FMIN";
14409   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14410   case X86ISD::FMINC:              return "X86ISD::FMINC";
14411   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14412   case X86ISD::FRCP:               return "X86ISD::FRCP";
14413   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14414   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14415   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14416   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14417   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14418   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14419   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14420   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14421   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14422   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14423   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14424   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14425   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14426   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14427   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14428   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14429   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14430   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14431   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14432   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14433   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14434   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14435   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14436   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14437   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14438   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14439   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14440   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14441   case X86ISD::VSHL:               return "X86ISD::VSHL";
14442   case X86ISD::VSRL:               return "X86ISD::VSRL";
14443   case X86ISD::VSRA:               return "X86ISD::VSRA";
14444   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14445   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14446   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14447   case X86ISD::CMPP:               return "X86ISD::CMPP";
14448   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14449   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14450   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14451   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14452   case X86ISD::ADD:                return "X86ISD::ADD";
14453   case X86ISD::SUB:                return "X86ISD::SUB";
14454   case X86ISD::ADC:                return "X86ISD::ADC";
14455   case X86ISD::SBB:                return "X86ISD::SBB";
14456   case X86ISD::SMUL:               return "X86ISD::SMUL";
14457   case X86ISD::UMUL:               return "X86ISD::UMUL";
14458   case X86ISD::INC:                return "X86ISD::INC";
14459   case X86ISD::DEC:                return "X86ISD::DEC";
14460   case X86ISD::OR:                 return "X86ISD::OR";
14461   case X86ISD::XOR:                return "X86ISD::XOR";
14462   case X86ISD::AND:                return "X86ISD::AND";
14463   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14464   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14465   case X86ISD::PTEST:              return "X86ISD::PTEST";
14466   case X86ISD::TESTP:              return "X86ISD::TESTP";
14467   case X86ISD::TESTM:              return "X86ISD::TESTM";
14468   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14469   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14470   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14471   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14472   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14473   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14474   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14475   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14476   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14477   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14478   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14479   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14480   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14481   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14482   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14483   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14484   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14485   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14486   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14487   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14488   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14489   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14490   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14491   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14492   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14493   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14494   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14495   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14496   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14497   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14498   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14499   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14500   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14501   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14502   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14503   case X86ISD::SAHF:               return "X86ISD::SAHF";
14504   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14505   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14506   case X86ISD::FMADD:              return "X86ISD::FMADD";
14507   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14508   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14509   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14510   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14511   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14512   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14513   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14514   case X86ISD::XTEST:              return "X86ISD::XTEST";
14515   }
14516 }
14517
14518 // isLegalAddressingMode - Return true if the addressing mode represented
14519 // by AM is legal for this target, for a load/store of the specified type.
14520 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14521                                               Type *Ty) const {
14522   // X86 supports extremely general addressing modes.
14523   CodeModel::Model M = getTargetMachine().getCodeModel();
14524   Reloc::Model R = getTargetMachine().getRelocationModel();
14525
14526   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14527   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14528     return false;
14529
14530   if (AM.BaseGV) {
14531     unsigned GVFlags =
14532       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14533
14534     // If a reference to this global requires an extra load, we can't fold it.
14535     if (isGlobalStubReference(GVFlags))
14536       return false;
14537
14538     // If BaseGV requires a register for the PIC base, we cannot also have a
14539     // BaseReg specified.
14540     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14541       return false;
14542
14543     // If lower 4G is not available, then we must use rip-relative addressing.
14544     if ((M != CodeModel::Small || R != Reloc::Static) &&
14545         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14546       return false;
14547   }
14548
14549   switch (AM.Scale) {
14550   case 0:
14551   case 1:
14552   case 2:
14553   case 4:
14554   case 8:
14555     // These scales always work.
14556     break;
14557   case 3:
14558   case 5:
14559   case 9:
14560     // These scales are formed with basereg+scalereg.  Only accept if there is
14561     // no basereg yet.
14562     if (AM.HasBaseReg)
14563       return false;
14564     break;
14565   default:  // Other stuff never works.
14566     return false;
14567   }
14568
14569   return true;
14570 }
14571
14572 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14573   unsigned Bits = Ty->getScalarSizeInBits();
14574
14575   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14576   // particularly cheaper than those without.
14577   if (Bits == 8)
14578     return false;
14579
14580   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14581   // variable shifts just as cheap as scalar ones.
14582   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14583     return false;
14584
14585   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14586   // fully general vector.
14587   return true;
14588 }
14589
14590 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14591   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14592     return false;
14593   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14594   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14595   return NumBits1 > NumBits2;
14596 }
14597
14598 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14599   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14600     return false;
14601
14602   if (!isTypeLegal(EVT::getEVT(Ty1)))
14603     return false;
14604
14605   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14606
14607   // Assuming the caller doesn't have a zeroext or signext return parameter,
14608   // truncation all the way down to i1 is valid.
14609   return true;
14610 }
14611
14612 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14613   return isInt<32>(Imm);
14614 }
14615
14616 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14617   // Can also use sub to handle negated immediates.
14618   return isInt<32>(Imm);
14619 }
14620
14621 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14622   if (!VT1.isInteger() || !VT2.isInteger())
14623     return false;
14624   unsigned NumBits1 = VT1.getSizeInBits();
14625   unsigned NumBits2 = VT2.getSizeInBits();
14626   return NumBits1 > NumBits2;
14627 }
14628
14629 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14630   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14631   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14632 }
14633
14634 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14635   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14636   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14637 }
14638
14639 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14640   EVT VT1 = Val.getValueType();
14641   if (isZExtFree(VT1, VT2))
14642     return true;
14643
14644   if (Val.getOpcode() != ISD::LOAD)
14645     return false;
14646
14647   if (!VT1.isSimple() || !VT1.isInteger() ||
14648       !VT2.isSimple() || !VT2.isInteger())
14649     return false;
14650
14651   switch (VT1.getSimpleVT().SimpleTy) {
14652   default: break;
14653   case MVT::i8:
14654   case MVT::i16:
14655   case MVT::i32:
14656     // X86 has 8, 16, and 32-bit zero-extending loads.
14657     return true;
14658   }
14659
14660   return false;
14661 }
14662
14663 bool
14664 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14665   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14666     return false;
14667
14668   VT = VT.getScalarType();
14669
14670   if (!VT.isSimple())
14671     return false;
14672
14673   switch (VT.getSimpleVT().SimpleTy) {
14674   case MVT::f32:
14675   case MVT::f64:
14676     return true;
14677   default:
14678     break;
14679   }
14680
14681   return false;
14682 }
14683
14684 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14685   // i16 instructions are longer (0x66 prefix) and potentially slower.
14686   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14687 }
14688
14689 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14690 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14691 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14692 /// are assumed to be legal.
14693 bool
14694 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14695                                       EVT VT) const {
14696   if (!VT.isSimple())
14697     return false;
14698
14699   MVT SVT = VT.getSimpleVT();
14700
14701   // Very little shuffling can be done for 64-bit vectors right now.
14702   if (VT.getSizeInBits() == 64)
14703     return false;
14704
14705   // FIXME: pshufb, blends, shifts.
14706   return (SVT.getVectorNumElements() == 2 ||
14707           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14708           isMOVLMask(M, SVT) ||
14709           isSHUFPMask(M, SVT) ||
14710           isPSHUFDMask(M, SVT) ||
14711           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14712           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14713           isPALIGNRMask(M, SVT, Subtarget) ||
14714           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14715           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14716           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14717           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14718 }
14719
14720 bool
14721 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14722                                           EVT VT) const {
14723   if (!VT.isSimple())
14724     return false;
14725
14726   MVT SVT = VT.getSimpleVT();
14727   unsigned NumElts = SVT.getVectorNumElements();
14728   // FIXME: This collection of masks seems suspect.
14729   if (NumElts == 2)
14730     return true;
14731   if (NumElts == 4 && SVT.is128BitVector()) {
14732     return (isMOVLMask(Mask, SVT)  ||
14733             isCommutedMOVLMask(Mask, SVT, true) ||
14734             isSHUFPMask(Mask, SVT) ||
14735             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14736   }
14737   return false;
14738 }
14739
14740 //===----------------------------------------------------------------------===//
14741 //                           X86 Scheduler Hooks
14742 //===----------------------------------------------------------------------===//
14743
14744 /// Utility function to emit xbegin specifying the start of an RTM region.
14745 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14746                                      const TargetInstrInfo *TII) {
14747   DebugLoc DL = MI->getDebugLoc();
14748
14749   const BasicBlock *BB = MBB->getBasicBlock();
14750   MachineFunction::iterator I = MBB;
14751   ++I;
14752
14753   // For the v = xbegin(), we generate
14754   //
14755   // thisMBB:
14756   //  xbegin sinkMBB
14757   //
14758   // mainMBB:
14759   //  eax = -1
14760   //
14761   // sinkMBB:
14762   //  v = eax
14763
14764   MachineBasicBlock *thisMBB = MBB;
14765   MachineFunction *MF = MBB->getParent();
14766   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14767   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14768   MF->insert(I, mainMBB);
14769   MF->insert(I, sinkMBB);
14770
14771   // Transfer the remainder of BB and its successor edges to sinkMBB.
14772   sinkMBB->splice(sinkMBB->begin(), MBB,
14773                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14774   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14775
14776   // thisMBB:
14777   //  xbegin sinkMBB
14778   //  # fallthrough to mainMBB
14779   //  # abortion to sinkMBB
14780   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14781   thisMBB->addSuccessor(mainMBB);
14782   thisMBB->addSuccessor(sinkMBB);
14783
14784   // mainMBB:
14785   //  EAX = -1
14786   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14787   mainMBB->addSuccessor(sinkMBB);
14788
14789   // sinkMBB:
14790   // EAX is live into the sinkMBB
14791   sinkMBB->addLiveIn(X86::EAX);
14792   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14793           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14794     .addReg(X86::EAX);
14795
14796   MI->eraseFromParent();
14797   return sinkMBB;
14798 }
14799
14800 // Get CMPXCHG opcode for the specified data type.
14801 static unsigned getCmpXChgOpcode(EVT VT) {
14802   switch (VT.getSimpleVT().SimpleTy) {
14803   case MVT::i8:  return X86::LCMPXCHG8;
14804   case MVT::i16: return X86::LCMPXCHG16;
14805   case MVT::i32: return X86::LCMPXCHG32;
14806   case MVT::i64: return X86::LCMPXCHG64;
14807   default:
14808     break;
14809   }
14810   llvm_unreachable("Invalid operand size!");
14811 }
14812
14813 // Get LOAD opcode for the specified data type.
14814 static unsigned getLoadOpcode(EVT VT) {
14815   switch (VT.getSimpleVT().SimpleTy) {
14816   case MVT::i8:  return X86::MOV8rm;
14817   case MVT::i16: return X86::MOV16rm;
14818   case MVT::i32: return X86::MOV32rm;
14819   case MVT::i64: return X86::MOV64rm;
14820   default:
14821     break;
14822   }
14823   llvm_unreachable("Invalid operand size!");
14824 }
14825
14826 // Get opcode of the non-atomic one from the specified atomic instruction.
14827 static unsigned getNonAtomicOpcode(unsigned Opc) {
14828   switch (Opc) {
14829   case X86::ATOMAND8:  return X86::AND8rr;
14830   case X86::ATOMAND16: return X86::AND16rr;
14831   case X86::ATOMAND32: return X86::AND32rr;
14832   case X86::ATOMAND64: return X86::AND64rr;
14833   case X86::ATOMOR8:   return X86::OR8rr;
14834   case X86::ATOMOR16:  return X86::OR16rr;
14835   case X86::ATOMOR32:  return X86::OR32rr;
14836   case X86::ATOMOR64:  return X86::OR64rr;
14837   case X86::ATOMXOR8:  return X86::XOR8rr;
14838   case X86::ATOMXOR16: return X86::XOR16rr;
14839   case X86::ATOMXOR32: return X86::XOR32rr;
14840   case X86::ATOMXOR64: return X86::XOR64rr;
14841   }
14842   llvm_unreachable("Unhandled atomic-load-op opcode!");
14843 }
14844
14845 // Get opcode of the non-atomic one from the specified atomic instruction with
14846 // extra opcode.
14847 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14848                                                unsigned &ExtraOpc) {
14849   switch (Opc) {
14850   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14851   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14852   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14853   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14854   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14855   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14856   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14857   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14858   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14859   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14860   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14861   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14862   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14863   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14864   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14865   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14866   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14867   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14868   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14869   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14870   }
14871   llvm_unreachable("Unhandled atomic-load-op opcode!");
14872 }
14873
14874 // Get opcode of the non-atomic one from the specified atomic instruction for
14875 // 64-bit data type on 32-bit target.
14876 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14877   switch (Opc) {
14878   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14879   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14880   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14881   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14882   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14883   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14884   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14885   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14886   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14887   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14888   }
14889   llvm_unreachable("Unhandled atomic-load-op opcode!");
14890 }
14891
14892 // Get opcode of the non-atomic one from the specified atomic instruction for
14893 // 64-bit data type on 32-bit target with extra opcode.
14894 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14895                                                    unsigned &HiOpc,
14896                                                    unsigned &ExtraOpc) {
14897   switch (Opc) {
14898   case X86::ATOMNAND6432:
14899     ExtraOpc = X86::NOT32r;
14900     HiOpc = X86::AND32rr;
14901     return X86::AND32rr;
14902   }
14903   llvm_unreachable("Unhandled atomic-load-op opcode!");
14904 }
14905
14906 // Get pseudo CMOV opcode from the specified data type.
14907 static unsigned getPseudoCMOVOpc(EVT VT) {
14908   switch (VT.getSimpleVT().SimpleTy) {
14909   case MVT::i8:  return X86::CMOV_GR8;
14910   case MVT::i16: return X86::CMOV_GR16;
14911   case MVT::i32: return X86::CMOV_GR32;
14912   default:
14913     break;
14914   }
14915   llvm_unreachable("Unknown CMOV opcode!");
14916 }
14917
14918 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14919 // They will be translated into a spin-loop or compare-exchange loop from
14920 //
14921 //    ...
14922 //    dst = atomic-fetch-op MI.addr, MI.val
14923 //    ...
14924 //
14925 // to
14926 //
14927 //    ...
14928 //    t1 = LOAD MI.addr
14929 // loop:
14930 //    t4 = phi(t1, t3 / loop)
14931 //    t2 = OP MI.val, t4
14932 //    EAX = t4
14933 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14934 //    t3 = EAX
14935 //    JNE loop
14936 // sink:
14937 //    dst = t3
14938 //    ...
14939 MachineBasicBlock *
14940 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14941                                        MachineBasicBlock *MBB) const {
14942   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14943   DebugLoc DL = MI->getDebugLoc();
14944
14945   MachineFunction *MF = MBB->getParent();
14946   MachineRegisterInfo &MRI = MF->getRegInfo();
14947
14948   const BasicBlock *BB = MBB->getBasicBlock();
14949   MachineFunction::iterator I = MBB;
14950   ++I;
14951
14952   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14953          "Unexpected number of operands");
14954
14955   assert(MI->hasOneMemOperand() &&
14956          "Expected atomic-load-op to have one memoperand");
14957
14958   // Memory Reference
14959   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14960   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14961
14962   unsigned DstReg, SrcReg;
14963   unsigned MemOpndSlot;
14964
14965   unsigned CurOp = 0;
14966
14967   DstReg = MI->getOperand(CurOp++).getReg();
14968   MemOpndSlot = CurOp;
14969   CurOp += X86::AddrNumOperands;
14970   SrcReg = MI->getOperand(CurOp++).getReg();
14971
14972   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14973   MVT::SimpleValueType VT = *RC->vt_begin();
14974   unsigned t1 = MRI.createVirtualRegister(RC);
14975   unsigned t2 = MRI.createVirtualRegister(RC);
14976   unsigned t3 = MRI.createVirtualRegister(RC);
14977   unsigned t4 = MRI.createVirtualRegister(RC);
14978   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14979
14980   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14981   unsigned LOADOpc = getLoadOpcode(VT);
14982
14983   // For the atomic load-arith operator, we generate
14984   //
14985   //  thisMBB:
14986   //    t1 = LOAD [MI.addr]
14987   //  mainMBB:
14988   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14989   //    t1 = OP MI.val, EAX
14990   //    EAX = t4
14991   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14992   //    t3 = EAX
14993   //    JNE mainMBB
14994   //  sinkMBB:
14995   //    dst = t3
14996
14997   MachineBasicBlock *thisMBB = MBB;
14998   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14999   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15000   MF->insert(I, mainMBB);
15001   MF->insert(I, sinkMBB);
15002
15003   MachineInstrBuilder MIB;
15004
15005   // Transfer the remainder of BB and its successor edges to sinkMBB.
15006   sinkMBB->splice(sinkMBB->begin(), MBB,
15007                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15008   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15009
15010   // thisMBB:
15011   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15012   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15013     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15014     if (NewMO.isReg())
15015       NewMO.setIsKill(false);
15016     MIB.addOperand(NewMO);
15017   }
15018   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15019     unsigned flags = (*MMOI)->getFlags();
15020     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15021     MachineMemOperand *MMO =
15022       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15023                                (*MMOI)->getSize(),
15024                                (*MMOI)->getBaseAlignment(),
15025                                (*MMOI)->getTBAAInfo(),
15026                                (*MMOI)->getRanges());
15027     MIB.addMemOperand(MMO);
15028   }
15029
15030   thisMBB->addSuccessor(mainMBB);
15031
15032   // mainMBB:
15033   MachineBasicBlock *origMainMBB = mainMBB;
15034
15035   // Add a PHI.
15036   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15037                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15038
15039   unsigned Opc = MI->getOpcode();
15040   switch (Opc) {
15041   default:
15042     llvm_unreachable("Unhandled atomic-load-op opcode!");
15043   case X86::ATOMAND8:
15044   case X86::ATOMAND16:
15045   case X86::ATOMAND32:
15046   case X86::ATOMAND64:
15047   case X86::ATOMOR8:
15048   case X86::ATOMOR16:
15049   case X86::ATOMOR32:
15050   case X86::ATOMOR64:
15051   case X86::ATOMXOR8:
15052   case X86::ATOMXOR16:
15053   case X86::ATOMXOR32:
15054   case X86::ATOMXOR64: {
15055     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15056     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15057       .addReg(t4);
15058     break;
15059   }
15060   case X86::ATOMNAND8:
15061   case X86::ATOMNAND16:
15062   case X86::ATOMNAND32:
15063   case X86::ATOMNAND64: {
15064     unsigned Tmp = MRI.createVirtualRegister(RC);
15065     unsigned NOTOpc;
15066     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15067     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15068       .addReg(t4);
15069     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15070     break;
15071   }
15072   case X86::ATOMMAX8:
15073   case X86::ATOMMAX16:
15074   case X86::ATOMMAX32:
15075   case X86::ATOMMAX64:
15076   case X86::ATOMMIN8:
15077   case X86::ATOMMIN16:
15078   case X86::ATOMMIN32:
15079   case X86::ATOMMIN64:
15080   case X86::ATOMUMAX8:
15081   case X86::ATOMUMAX16:
15082   case X86::ATOMUMAX32:
15083   case X86::ATOMUMAX64:
15084   case X86::ATOMUMIN8:
15085   case X86::ATOMUMIN16:
15086   case X86::ATOMUMIN32:
15087   case X86::ATOMUMIN64: {
15088     unsigned CMPOpc;
15089     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15090
15091     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15092       .addReg(SrcReg)
15093       .addReg(t4);
15094
15095     if (Subtarget->hasCMov()) {
15096       if (VT != MVT::i8) {
15097         // Native support
15098         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15099           .addReg(SrcReg)
15100           .addReg(t4);
15101       } else {
15102         // Promote i8 to i32 to use CMOV32
15103         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15104         const TargetRegisterClass *RC32 =
15105           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15106         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15107         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15108         unsigned Tmp = MRI.createVirtualRegister(RC32);
15109
15110         unsigned Undef = MRI.createVirtualRegister(RC32);
15111         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15112
15113         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15114           .addReg(Undef)
15115           .addReg(SrcReg)
15116           .addImm(X86::sub_8bit);
15117         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15118           .addReg(Undef)
15119           .addReg(t4)
15120           .addImm(X86::sub_8bit);
15121
15122         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15123           .addReg(SrcReg32)
15124           .addReg(AccReg32);
15125
15126         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15127           .addReg(Tmp, 0, X86::sub_8bit);
15128       }
15129     } else {
15130       // Use pseudo select and lower them.
15131       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15132              "Invalid atomic-load-op transformation!");
15133       unsigned SelOpc = getPseudoCMOVOpc(VT);
15134       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15135       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15136       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15137               .addReg(SrcReg).addReg(t4)
15138               .addImm(CC);
15139       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15140       // Replace the original PHI node as mainMBB is changed after CMOV
15141       // lowering.
15142       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15143         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15144       Phi->eraseFromParent();
15145     }
15146     break;
15147   }
15148   }
15149
15150   // Copy PhyReg back from virtual register.
15151   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15152     .addReg(t4);
15153
15154   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15155   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15156     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15157     if (NewMO.isReg())
15158       NewMO.setIsKill(false);
15159     MIB.addOperand(NewMO);
15160   }
15161   MIB.addReg(t2);
15162   MIB.setMemRefs(MMOBegin, MMOEnd);
15163
15164   // Copy PhyReg back to virtual register.
15165   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15166     .addReg(PhyReg);
15167
15168   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15169
15170   mainMBB->addSuccessor(origMainMBB);
15171   mainMBB->addSuccessor(sinkMBB);
15172
15173   // sinkMBB:
15174   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15175           TII->get(TargetOpcode::COPY), DstReg)
15176     .addReg(t3);
15177
15178   MI->eraseFromParent();
15179   return sinkMBB;
15180 }
15181
15182 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15183 // instructions. They will be translated into a spin-loop or compare-exchange
15184 // loop from
15185 //
15186 //    ...
15187 //    dst = atomic-fetch-op MI.addr, MI.val
15188 //    ...
15189 //
15190 // to
15191 //
15192 //    ...
15193 //    t1L = LOAD [MI.addr + 0]
15194 //    t1H = LOAD [MI.addr + 4]
15195 // loop:
15196 //    t4L = phi(t1L, t3L / loop)
15197 //    t4H = phi(t1H, t3H / loop)
15198 //    t2L = OP MI.val.lo, t4L
15199 //    t2H = OP MI.val.hi, t4H
15200 //    EAX = t4L
15201 //    EDX = t4H
15202 //    EBX = t2L
15203 //    ECX = t2H
15204 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15205 //    t3L = EAX
15206 //    t3H = EDX
15207 //    JNE loop
15208 // sink:
15209 //    dstL = t3L
15210 //    dstH = t3H
15211 //    ...
15212 MachineBasicBlock *
15213 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15214                                            MachineBasicBlock *MBB) const {
15215   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15216   DebugLoc DL = MI->getDebugLoc();
15217
15218   MachineFunction *MF = MBB->getParent();
15219   MachineRegisterInfo &MRI = MF->getRegInfo();
15220
15221   const BasicBlock *BB = MBB->getBasicBlock();
15222   MachineFunction::iterator I = MBB;
15223   ++I;
15224
15225   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15226          "Unexpected number of operands");
15227
15228   assert(MI->hasOneMemOperand() &&
15229          "Expected atomic-load-op32 to have one memoperand");
15230
15231   // Memory Reference
15232   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15233   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15234
15235   unsigned DstLoReg, DstHiReg;
15236   unsigned SrcLoReg, SrcHiReg;
15237   unsigned MemOpndSlot;
15238
15239   unsigned CurOp = 0;
15240
15241   DstLoReg = MI->getOperand(CurOp++).getReg();
15242   DstHiReg = MI->getOperand(CurOp++).getReg();
15243   MemOpndSlot = CurOp;
15244   CurOp += X86::AddrNumOperands;
15245   SrcLoReg = MI->getOperand(CurOp++).getReg();
15246   SrcHiReg = MI->getOperand(CurOp++).getReg();
15247
15248   const TargetRegisterClass *RC = &X86::GR32RegClass;
15249   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15250
15251   unsigned t1L = MRI.createVirtualRegister(RC);
15252   unsigned t1H = MRI.createVirtualRegister(RC);
15253   unsigned t2L = MRI.createVirtualRegister(RC);
15254   unsigned t2H = MRI.createVirtualRegister(RC);
15255   unsigned t3L = MRI.createVirtualRegister(RC);
15256   unsigned t3H = MRI.createVirtualRegister(RC);
15257   unsigned t4L = MRI.createVirtualRegister(RC);
15258   unsigned t4H = MRI.createVirtualRegister(RC);
15259
15260   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15261   unsigned LOADOpc = X86::MOV32rm;
15262
15263   // For the atomic load-arith operator, we generate
15264   //
15265   //  thisMBB:
15266   //    t1L = LOAD [MI.addr + 0]
15267   //    t1H = LOAD [MI.addr + 4]
15268   //  mainMBB:
15269   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15270   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15271   //    t2L = OP MI.val.lo, t4L
15272   //    t2H = OP MI.val.hi, t4H
15273   //    EBX = t2L
15274   //    ECX = t2H
15275   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15276   //    t3L = EAX
15277   //    t3H = EDX
15278   //    JNE loop
15279   //  sinkMBB:
15280   //    dstL = t3L
15281   //    dstH = t3H
15282
15283   MachineBasicBlock *thisMBB = MBB;
15284   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15285   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15286   MF->insert(I, mainMBB);
15287   MF->insert(I, sinkMBB);
15288
15289   MachineInstrBuilder MIB;
15290
15291   // Transfer the remainder of BB and its successor edges to sinkMBB.
15292   sinkMBB->splice(sinkMBB->begin(), MBB,
15293                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15294   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15295
15296   // thisMBB:
15297   // Lo
15298   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15299   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15300     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15301     if (NewMO.isReg())
15302       NewMO.setIsKill(false);
15303     MIB.addOperand(NewMO);
15304   }
15305   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15306     unsigned flags = (*MMOI)->getFlags();
15307     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15308     MachineMemOperand *MMO =
15309       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15310                                (*MMOI)->getSize(),
15311                                (*MMOI)->getBaseAlignment(),
15312                                (*MMOI)->getTBAAInfo(),
15313                                (*MMOI)->getRanges());
15314     MIB.addMemOperand(MMO);
15315   };
15316   MachineInstr *LowMI = MIB;
15317
15318   // Hi
15319   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15320   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15321     if (i == X86::AddrDisp) {
15322       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15323     } else {
15324       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15325       if (NewMO.isReg())
15326         NewMO.setIsKill(false);
15327       MIB.addOperand(NewMO);
15328     }
15329   }
15330   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15331
15332   thisMBB->addSuccessor(mainMBB);
15333
15334   // mainMBB:
15335   MachineBasicBlock *origMainMBB = mainMBB;
15336
15337   // Add PHIs.
15338   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15339                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15340   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15341                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15342
15343   unsigned Opc = MI->getOpcode();
15344   switch (Opc) {
15345   default:
15346     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15347   case X86::ATOMAND6432:
15348   case X86::ATOMOR6432:
15349   case X86::ATOMXOR6432:
15350   case X86::ATOMADD6432:
15351   case X86::ATOMSUB6432: {
15352     unsigned HiOpc;
15353     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15354     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15355       .addReg(SrcLoReg);
15356     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15357       .addReg(SrcHiReg);
15358     break;
15359   }
15360   case X86::ATOMNAND6432: {
15361     unsigned HiOpc, NOTOpc;
15362     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15363     unsigned TmpL = MRI.createVirtualRegister(RC);
15364     unsigned TmpH = MRI.createVirtualRegister(RC);
15365     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15366       .addReg(t4L);
15367     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15368       .addReg(t4H);
15369     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15370     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15371     break;
15372   }
15373   case X86::ATOMMAX6432:
15374   case X86::ATOMMIN6432:
15375   case X86::ATOMUMAX6432:
15376   case X86::ATOMUMIN6432: {
15377     unsigned HiOpc;
15378     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15379     unsigned cL = MRI.createVirtualRegister(RC8);
15380     unsigned cH = MRI.createVirtualRegister(RC8);
15381     unsigned cL32 = MRI.createVirtualRegister(RC);
15382     unsigned cH32 = MRI.createVirtualRegister(RC);
15383     unsigned cc = MRI.createVirtualRegister(RC);
15384     // cl := cmp src_lo, lo
15385     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15386       .addReg(SrcLoReg).addReg(t4L);
15387     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15388     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15389     // ch := cmp src_hi, hi
15390     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15391       .addReg(SrcHiReg).addReg(t4H);
15392     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15393     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15394     // cc := if (src_hi == hi) ? cl : ch;
15395     if (Subtarget->hasCMov()) {
15396       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15397         .addReg(cH32).addReg(cL32);
15398     } else {
15399       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15400               .addReg(cH32).addReg(cL32)
15401               .addImm(X86::COND_E);
15402       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15403     }
15404     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15405     if (Subtarget->hasCMov()) {
15406       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15407         .addReg(SrcLoReg).addReg(t4L);
15408       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15409         .addReg(SrcHiReg).addReg(t4H);
15410     } else {
15411       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15412               .addReg(SrcLoReg).addReg(t4L)
15413               .addImm(X86::COND_NE);
15414       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15415       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15416       // 2nd CMOV lowering.
15417       mainMBB->addLiveIn(X86::EFLAGS);
15418       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15419               .addReg(SrcHiReg).addReg(t4H)
15420               .addImm(X86::COND_NE);
15421       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15422       // Replace the original PHI node as mainMBB is changed after CMOV
15423       // lowering.
15424       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15425         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15426       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15427         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15428       PhiL->eraseFromParent();
15429       PhiH->eraseFromParent();
15430     }
15431     break;
15432   }
15433   case X86::ATOMSWAP6432: {
15434     unsigned HiOpc;
15435     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15436     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15437     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15438     break;
15439   }
15440   }
15441
15442   // Copy EDX:EAX back from HiReg:LoReg
15443   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15444   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15445   // Copy ECX:EBX from t1H:t1L
15446   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15447   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15448
15449   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15450   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15451     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15452     if (NewMO.isReg())
15453       NewMO.setIsKill(false);
15454     MIB.addOperand(NewMO);
15455   }
15456   MIB.setMemRefs(MMOBegin, MMOEnd);
15457
15458   // Copy EDX:EAX back to t3H:t3L
15459   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15460   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15461
15462   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15463
15464   mainMBB->addSuccessor(origMainMBB);
15465   mainMBB->addSuccessor(sinkMBB);
15466
15467   // sinkMBB:
15468   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15469           TII->get(TargetOpcode::COPY), DstLoReg)
15470     .addReg(t3L);
15471   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15472           TII->get(TargetOpcode::COPY), DstHiReg)
15473     .addReg(t3H);
15474
15475   MI->eraseFromParent();
15476   return sinkMBB;
15477 }
15478
15479 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15480 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15481 // in the .td file.
15482 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15483                                        const TargetInstrInfo *TII) {
15484   unsigned Opc;
15485   switch (MI->getOpcode()) {
15486   default: llvm_unreachable("illegal opcode!");
15487   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15488   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15489   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15490   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15491   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15492   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15493   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15494   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15495   }
15496
15497   DebugLoc dl = MI->getDebugLoc();
15498   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15499
15500   unsigned NumArgs = MI->getNumOperands();
15501   for (unsigned i = 1; i < NumArgs; ++i) {
15502     MachineOperand &Op = MI->getOperand(i);
15503     if (!(Op.isReg() && Op.isImplicit()))
15504       MIB.addOperand(Op);
15505   }
15506   if (MI->hasOneMemOperand())
15507     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15508
15509   BuildMI(*BB, MI, dl,
15510     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15511     .addReg(X86::XMM0);
15512
15513   MI->eraseFromParent();
15514   return BB;
15515 }
15516
15517 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15518 // defs in an instruction pattern
15519 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15520                                        const TargetInstrInfo *TII) {
15521   unsigned Opc;
15522   switch (MI->getOpcode()) {
15523   default: llvm_unreachable("illegal opcode!");
15524   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15525   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15526   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15527   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15528   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15529   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15530   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15531   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15532   }
15533
15534   DebugLoc dl = MI->getDebugLoc();
15535   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15536
15537   unsigned NumArgs = MI->getNumOperands(); // remove the results
15538   for (unsigned i = 1; i < NumArgs; ++i) {
15539     MachineOperand &Op = MI->getOperand(i);
15540     if (!(Op.isReg() && Op.isImplicit()))
15541       MIB.addOperand(Op);
15542   }
15543   if (MI->hasOneMemOperand())
15544     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15545
15546   BuildMI(*BB, MI, dl,
15547     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15548     .addReg(X86::ECX);
15549
15550   MI->eraseFromParent();
15551   return BB;
15552 }
15553
15554 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15555                                        const TargetInstrInfo *TII,
15556                                        const X86Subtarget* Subtarget) {
15557   DebugLoc dl = MI->getDebugLoc();
15558
15559   // Address into RAX/EAX, other two args into ECX, EDX.
15560   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15561   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15562   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15563   for (int i = 0; i < X86::AddrNumOperands; ++i)
15564     MIB.addOperand(MI->getOperand(i));
15565
15566   unsigned ValOps = X86::AddrNumOperands;
15567   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15568     .addReg(MI->getOperand(ValOps).getReg());
15569   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15570     .addReg(MI->getOperand(ValOps+1).getReg());
15571
15572   // The instruction doesn't actually take any operands though.
15573   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15574
15575   MI->eraseFromParent(); // The pseudo is gone now.
15576   return BB;
15577 }
15578
15579 MachineBasicBlock *
15580 X86TargetLowering::EmitVAARG64WithCustomInserter(
15581                    MachineInstr *MI,
15582                    MachineBasicBlock *MBB) const {
15583   // Emit va_arg instruction on X86-64.
15584
15585   // Operands to this pseudo-instruction:
15586   // 0  ) Output        : destination address (reg)
15587   // 1-5) Input         : va_list address (addr, i64mem)
15588   // 6  ) ArgSize       : Size (in bytes) of vararg type
15589   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15590   // 8  ) Align         : Alignment of type
15591   // 9  ) EFLAGS (implicit-def)
15592
15593   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15594   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15595
15596   unsigned DestReg = MI->getOperand(0).getReg();
15597   MachineOperand &Base = MI->getOperand(1);
15598   MachineOperand &Scale = MI->getOperand(2);
15599   MachineOperand &Index = MI->getOperand(3);
15600   MachineOperand &Disp = MI->getOperand(4);
15601   MachineOperand &Segment = MI->getOperand(5);
15602   unsigned ArgSize = MI->getOperand(6).getImm();
15603   unsigned ArgMode = MI->getOperand(7).getImm();
15604   unsigned Align = MI->getOperand(8).getImm();
15605
15606   // Memory Reference
15607   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15608   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15609   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15610
15611   // Machine Information
15612   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15613   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15614   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15615   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15616   DebugLoc DL = MI->getDebugLoc();
15617
15618   // struct va_list {
15619   //   i32   gp_offset
15620   //   i32   fp_offset
15621   //   i64   overflow_area (address)
15622   //   i64   reg_save_area (address)
15623   // }
15624   // sizeof(va_list) = 24
15625   // alignment(va_list) = 8
15626
15627   unsigned TotalNumIntRegs = 6;
15628   unsigned TotalNumXMMRegs = 8;
15629   bool UseGPOffset = (ArgMode == 1);
15630   bool UseFPOffset = (ArgMode == 2);
15631   unsigned MaxOffset = TotalNumIntRegs * 8 +
15632                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15633
15634   /* Align ArgSize to a multiple of 8 */
15635   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15636   bool NeedsAlign = (Align > 8);
15637
15638   MachineBasicBlock *thisMBB = MBB;
15639   MachineBasicBlock *overflowMBB;
15640   MachineBasicBlock *offsetMBB;
15641   MachineBasicBlock *endMBB;
15642
15643   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15644   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15645   unsigned OffsetReg = 0;
15646
15647   if (!UseGPOffset && !UseFPOffset) {
15648     // If we only pull from the overflow region, we don't create a branch.
15649     // We don't need to alter control flow.
15650     OffsetDestReg = 0; // unused
15651     OverflowDestReg = DestReg;
15652
15653     offsetMBB = NULL;
15654     overflowMBB = thisMBB;
15655     endMBB = thisMBB;
15656   } else {
15657     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15658     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15659     // If not, pull from overflow_area. (branch to overflowMBB)
15660     //
15661     //       thisMBB
15662     //         |     .
15663     //         |        .
15664     //     offsetMBB   overflowMBB
15665     //         |        .
15666     //         |     .
15667     //        endMBB
15668
15669     // Registers for the PHI in endMBB
15670     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15671     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15672
15673     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15674     MachineFunction *MF = MBB->getParent();
15675     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15676     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15677     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15678
15679     MachineFunction::iterator MBBIter = MBB;
15680     ++MBBIter;
15681
15682     // Insert the new basic blocks
15683     MF->insert(MBBIter, offsetMBB);
15684     MF->insert(MBBIter, overflowMBB);
15685     MF->insert(MBBIter, endMBB);
15686
15687     // Transfer the remainder of MBB and its successor edges to endMBB.
15688     endMBB->splice(endMBB->begin(), thisMBB,
15689                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15690     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15691
15692     // Make offsetMBB and overflowMBB successors of thisMBB
15693     thisMBB->addSuccessor(offsetMBB);
15694     thisMBB->addSuccessor(overflowMBB);
15695
15696     // endMBB is a successor of both offsetMBB and overflowMBB
15697     offsetMBB->addSuccessor(endMBB);
15698     overflowMBB->addSuccessor(endMBB);
15699
15700     // Load the offset value into a register
15701     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15702     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15703       .addOperand(Base)
15704       .addOperand(Scale)
15705       .addOperand(Index)
15706       .addDisp(Disp, UseFPOffset ? 4 : 0)
15707       .addOperand(Segment)
15708       .setMemRefs(MMOBegin, MMOEnd);
15709
15710     // Check if there is enough room left to pull this argument.
15711     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15712       .addReg(OffsetReg)
15713       .addImm(MaxOffset + 8 - ArgSizeA8);
15714
15715     // Branch to "overflowMBB" if offset >= max
15716     // Fall through to "offsetMBB" otherwise
15717     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15718       .addMBB(overflowMBB);
15719   }
15720
15721   // In offsetMBB, emit code to use the reg_save_area.
15722   if (offsetMBB) {
15723     assert(OffsetReg != 0);
15724
15725     // Read the reg_save_area address.
15726     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15727     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15728       .addOperand(Base)
15729       .addOperand(Scale)
15730       .addOperand(Index)
15731       .addDisp(Disp, 16)
15732       .addOperand(Segment)
15733       .setMemRefs(MMOBegin, MMOEnd);
15734
15735     // Zero-extend the offset
15736     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15737       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15738         .addImm(0)
15739         .addReg(OffsetReg)
15740         .addImm(X86::sub_32bit);
15741
15742     // Add the offset to the reg_save_area to get the final address.
15743     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15744       .addReg(OffsetReg64)
15745       .addReg(RegSaveReg);
15746
15747     // Compute the offset for the next argument
15748     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15749     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15750       .addReg(OffsetReg)
15751       .addImm(UseFPOffset ? 16 : 8);
15752
15753     // Store it back into the va_list.
15754     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15755       .addOperand(Base)
15756       .addOperand(Scale)
15757       .addOperand(Index)
15758       .addDisp(Disp, UseFPOffset ? 4 : 0)
15759       .addOperand(Segment)
15760       .addReg(NextOffsetReg)
15761       .setMemRefs(MMOBegin, MMOEnd);
15762
15763     // Jump to endMBB
15764     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15765       .addMBB(endMBB);
15766   }
15767
15768   //
15769   // Emit code to use overflow area
15770   //
15771
15772   // Load the overflow_area address into a register.
15773   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15774   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15775     .addOperand(Base)
15776     .addOperand(Scale)
15777     .addOperand(Index)
15778     .addDisp(Disp, 8)
15779     .addOperand(Segment)
15780     .setMemRefs(MMOBegin, MMOEnd);
15781
15782   // If we need to align it, do so. Otherwise, just copy the address
15783   // to OverflowDestReg.
15784   if (NeedsAlign) {
15785     // Align the overflow address
15786     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15787     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15788
15789     // aligned_addr = (addr + (align-1)) & ~(align-1)
15790     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15791       .addReg(OverflowAddrReg)
15792       .addImm(Align-1);
15793
15794     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15795       .addReg(TmpReg)
15796       .addImm(~(uint64_t)(Align-1));
15797   } else {
15798     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15799       .addReg(OverflowAddrReg);
15800   }
15801
15802   // Compute the next overflow address after this argument.
15803   // (the overflow address should be kept 8-byte aligned)
15804   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15805   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15806     .addReg(OverflowDestReg)
15807     .addImm(ArgSizeA8);
15808
15809   // Store the new overflow address.
15810   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15811     .addOperand(Base)
15812     .addOperand(Scale)
15813     .addOperand(Index)
15814     .addDisp(Disp, 8)
15815     .addOperand(Segment)
15816     .addReg(NextAddrReg)
15817     .setMemRefs(MMOBegin, MMOEnd);
15818
15819   // If we branched, emit the PHI to the front of endMBB.
15820   if (offsetMBB) {
15821     BuildMI(*endMBB, endMBB->begin(), DL,
15822             TII->get(X86::PHI), DestReg)
15823       .addReg(OffsetDestReg).addMBB(offsetMBB)
15824       .addReg(OverflowDestReg).addMBB(overflowMBB);
15825   }
15826
15827   // Erase the pseudo instruction
15828   MI->eraseFromParent();
15829
15830   return endMBB;
15831 }
15832
15833 MachineBasicBlock *
15834 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15835                                                  MachineInstr *MI,
15836                                                  MachineBasicBlock *MBB) const {
15837   // Emit code to save XMM registers to the stack. The ABI says that the
15838   // number of registers to save is given in %al, so it's theoretically
15839   // possible to do an indirect jump trick to avoid saving all of them,
15840   // however this code takes a simpler approach and just executes all
15841   // of the stores if %al is non-zero. It's less code, and it's probably
15842   // easier on the hardware branch predictor, and stores aren't all that
15843   // expensive anyway.
15844
15845   // Create the new basic blocks. One block contains all the XMM stores,
15846   // and one block is the final destination regardless of whether any
15847   // stores were performed.
15848   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15849   MachineFunction *F = MBB->getParent();
15850   MachineFunction::iterator MBBIter = MBB;
15851   ++MBBIter;
15852   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15853   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15854   F->insert(MBBIter, XMMSaveMBB);
15855   F->insert(MBBIter, EndMBB);
15856
15857   // Transfer the remainder of MBB and its successor edges to EndMBB.
15858   EndMBB->splice(EndMBB->begin(), MBB,
15859                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15860   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15861
15862   // The original block will now fall through to the XMM save block.
15863   MBB->addSuccessor(XMMSaveMBB);
15864   // The XMMSaveMBB will fall through to the end block.
15865   XMMSaveMBB->addSuccessor(EndMBB);
15866
15867   // Now add the instructions.
15868   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15869   DebugLoc DL = MI->getDebugLoc();
15870
15871   unsigned CountReg = MI->getOperand(0).getReg();
15872   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15873   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15874
15875   if (!Subtarget->isTargetWin64()) {
15876     // If %al is 0, branch around the XMM save block.
15877     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15878     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15879     MBB->addSuccessor(EndMBB);
15880   }
15881
15882   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15883   // that was just emitted, but clearly shouldn't be "saved".
15884   assert((MI->getNumOperands() <= 3 ||
15885           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15886           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15887          && "Expected last argument to be EFLAGS");
15888   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15889   // In the XMM save block, save all the XMM argument registers.
15890   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15891     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15892     MachineMemOperand *MMO =
15893       F->getMachineMemOperand(
15894           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15895         MachineMemOperand::MOStore,
15896         /*Size=*/16, /*Align=*/16);
15897     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15898       .addFrameIndex(RegSaveFrameIndex)
15899       .addImm(/*Scale=*/1)
15900       .addReg(/*IndexReg=*/0)
15901       .addImm(/*Disp=*/Offset)
15902       .addReg(/*Segment=*/0)
15903       .addReg(MI->getOperand(i).getReg())
15904       .addMemOperand(MMO);
15905   }
15906
15907   MI->eraseFromParent();   // The pseudo instruction is gone now.
15908
15909   return EndMBB;
15910 }
15911
15912 // The EFLAGS operand of SelectItr might be missing a kill marker
15913 // because there were multiple uses of EFLAGS, and ISel didn't know
15914 // which to mark. Figure out whether SelectItr should have had a
15915 // kill marker, and set it if it should. Returns the correct kill
15916 // marker value.
15917 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15918                                      MachineBasicBlock* BB,
15919                                      const TargetRegisterInfo* TRI) {
15920   // Scan forward through BB for a use/def of EFLAGS.
15921   MachineBasicBlock::iterator miI(std::next(SelectItr));
15922   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15923     const MachineInstr& mi = *miI;
15924     if (mi.readsRegister(X86::EFLAGS))
15925       return false;
15926     if (mi.definesRegister(X86::EFLAGS))
15927       break; // Should have kill-flag - update below.
15928   }
15929
15930   // If we hit the end of the block, check whether EFLAGS is live into a
15931   // successor.
15932   if (miI == BB->end()) {
15933     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15934                                           sEnd = BB->succ_end();
15935          sItr != sEnd; ++sItr) {
15936       MachineBasicBlock* succ = *sItr;
15937       if (succ->isLiveIn(X86::EFLAGS))
15938         return false;
15939     }
15940   }
15941
15942   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15943   // out. SelectMI should have a kill flag on EFLAGS.
15944   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15945   return true;
15946 }
15947
15948 MachineBasicBlock *
15949 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15950                                      MachineBasicBlock *BB) const {
15951   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15952   DebugLoc DL = MI->getDebugLoc();
15953
15954   // To "insert" a SELECT_CC instruction, we actually have to insert the
15955   // diamond control-flow pattern.  The incoming instruction knows the
15956   // destination vreg to set, the condition code register to branch on, the
15957   // true/false values to select between, and a branch opcode to use.
15958   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15959   MachineFunction::iterator It = BB;
15960   ++It;
15961
15962   //  thisMBB:
15963   //  ...
15964   //   TrueVal = ...
15965   //   cmpTY ccX, r1, r2
15966   //   bCC copy1MBB
15967   //   fallthrough --> copy0MBB
15968   MachineBasicBlock *thisMBB = BB;
15969   MachineFunction *F = BB->getParent();
15970   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15971   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15972   F->insert(It, copy0MBB);
15973   F->insert(It, sinkMBB);
15974
15975   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15976   // live into the sink and copy blocks.
15977   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15978   if (!MI->killsRegister(X86::EFLAGS) &&
15979       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15980     copy0MBB->addLiveIn(X86::EFLAGS);
15981     sinkMBB->addLiveIn(X86::EFLAGS);
15982   }
15983
15984   // Transfer the remainder of BB and its successor edges to sinkMBB.
15985   sinkMBB->splice(sinkMBB->begin(), BB,
15986                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
15987   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15988
15989   // Add the true and fallthrough blocks as its successors.
15990   BB->addSuccessor(copy0MBB);
15991   BB->addSuccessor(sinkMBB);
15992
15993   // Create the conditional branch instruction.
15994   unsigned Opc =
15995     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15996   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15997
15998   //  copy0MBB:
15999   //   %FalseValue = ...
16000   //   # fallthrough to sinkMBB
16001   copy0MBB->addSuccessor(sinkMBB);
16002
16003   //  sinkMBB:
16004   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16005   //  ...
16006   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16007           TII->get(X86::PHI), MI->getOperand(0).getReg())
16008     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16009     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16010
16011   MI->eraseFromParent();   // The pseudo instruction is gone now.
16012   return sinkMBB;
16013 }
16014
16015 MachineBasicBlock *
16016 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16017                                         bool Is64Bit) const {
16018   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16019   DebugLoc DL = MI->getDebugLoc();
16020   MachineFunction *MF = BB->getParent();
16021   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16022
16023   assert(MF->shouldSplitStack());
16024
16025   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16026   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16027
16028   // BB:
16029   //  ... [Till the alloca]
16030   // If stacklet is not large enough, jump to mallocMBB
16031   //
16032   // bumpMBB:
16033   //  Allocate by subtracting from RSP
16034   //  Jump to continueMBB
16035   //
16036   // mallocMBB:
16037   //  Allocate by call to runtime
16038   //
16039   // continueMBB:
16040   //  ...
16041   //  [rest of original BB]
16042   //
16043
16044   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16045   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16046   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16047
16048   MachineRegisterInfo &MRI = MF->getRegInfo();
16049   const TargetRegisterClass *AddrRegClass =
16050     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16051
16052   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16053     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16054     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16055     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16056     sizeVReg = MI->getOperand(1).getReg(),
16057     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16058
16059   MachineFunction::iterator MBBIter = BB;
16060   ++MBBIter;
16061
16062   MF->insert(MBBIter, bumpMBB);
16063   MF->insert(MBBIter, mallocMBB);
16064   MF->insert(MBBIter, continueMBB);
16065
16066   continueMBB->splice(continueMBB->begin(), BB,
16067                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16068   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16069
16070   // Add code to the main basic block to check if the stack limit has been hit,
16071   // and if so, jump to mallocMBB otherwise to bumpMBB.
16072   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16073   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16074     .addReg(tmpSPVReg).addReg(sizeVReg);
16075   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16076     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16077     .addReg(SPLimitVReg);
16078   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16079
16080   // bumpMBB simply decreases the stack pointer, since we know the current
16081   // stacklet has enough space.
16082   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16083     .addReg(SPLimitVReg);
16084   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16085     .addReg(SPLimitVReg);
16086   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16087
16088   // Calls into a routine in libgcc to allocate more space from the heap.
16089   const uint32_t *RegMask =
16090     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16091   if (Is64Bit) {
16092     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16093       .addReg(sizeVReg);
16094     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16095       .addExternalSymbol("__morestack_allocate_stack_space")
16096       .addRegMask(RegMask)
16097       .addReg(X86::RDI, RegState::Implicit)
16098       .addReg(X86::RAX, RegState::ImplicitDefine);
16099   } else {
16100     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16101       .addImm(12);
16102     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16103     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16104       .addExternalSymbol("__morestack_allocate_stack_space")
16105       .addRegMask(RegMask)
16106       .addReg(X86::EAX, RegState::ImplicitDefine);
16107   }
16108
16109   if (!Is64Bit)
16110     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16111       .addImm(16);
16112
16113   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16114     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16115   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16116
16117   // Set up the CFG correctly.
16118   BB->addSuccessor(bumpMBB);
16119   BB->addSuccessor(mallocMBB);
16120   mallocMBB->addSuccessor(continueMBB);
16121   bumpMBB->addSuccessor(continueMBB);
16122
16123   // Take care of the PHI nodes.
16124   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16125           MI->getOperand(0).getReg())
16126     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16127     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16128
16129   // Delete the original pseudo instruction.
16130   MI->eraseFromParent();
16131
16132   // And we're done.
16133   return continueMBB;
16134 }
16135
16136 MachineBasicBlock *
16137 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16138                                           MachineBasicBlock *BB) const {
16139   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16140   DebugLoc DL = MI->getDebugLoc();
16141
16142   assert(!Subtarget->isTargetMacho());
16143
16144   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16145   // non-trivial part is impdef of ESP.
16146
16147   if (Subtarget->isTargetWin64()) {
16148     if (Subtarget->isTargetCygMing()) {
16149       // ___chkstk(Mingw64):
16150       // Clobbers R10, R11, RAX and EFLAGS.
16151       // Updates RSP.
16152       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16153         .addExternalSymbol("___chkstk")
16154         .addReg(X86::RAX, RegState::Implicit)
16155         .addReg(X86::RSP, RegState::Implicit)
16156         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16157         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16158         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16159     } else {
16160       // __chkstk(MSVCRT): does not update stack pointer.
16161       // Clobbers R10, R11 and EFLAGS.
16162       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16163         .addExternalSymbol("__chkstk")
16164         .addReg(X86::RAX, RegState::Implicit)
16165         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16166       // RAX has the offset to be subtracted from RSP.
16167       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16168         .addReg(X86::RSP)
16169         .addReg(X86::RAX);
16170     }
16171   } else {
16172     const char *StackProbeSymbol =
16173       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16174
16175     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16176       .addExternalSymbol(StackProbeSymbol)
16177       .addReg(X86::EAX, RegState::Implicit)
16178       .addReg(X86::ESP, RegState::Implicit)
16179       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16180       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16181       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16182   }
16183
16184   MI->eraseFromParent();   // The pseudo instruction is gone now.
16185   return BB;
16186 }
16187
16188 MachineBasicBlock *
16189 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16190                                       MachineBasicBlock *BB) const {
16191   // This is pretty easy.  We're taking the value that we received from
16192   // our load from the relocation, sticking it in either RDI (x86-64)
16193   // or EAX and doing an indirect call.  The return value will then
16194   // be in the normal return register.
16195   const X86InstrInfo *TII
16196     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16197   DebugLoc DL = MI->getDebugLoc();
16198   MachineFunction *F = BB->getParent();
16199
16200   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16201   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16202
16203   // Get a register mask for the lowered call.
16204   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16205   // proper register mask.
16206   const uint32_t *RegMask =
16207     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16208   if (Subtarget->is64Bit()) {
16209     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16210                                       TII->get(X86::MOV64rm), X86::RDI)
16211     .addReg(X86::RIP)
16212     .addImm(0).addReg(0)
16213     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16214                       MI->getOperand(3).getTargetFlags())
16215     .addReg(0);
16216     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16217     addDirectMem(MIB, X86::RDI);
16218     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16219   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16220     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16221                                       TII->get(X86::MOV32rm), X86::EAX)
16222     .addReg(0)
16223     .addImm(0).addReg(0)
16224     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16225                       MI->getOperand(3).getTargetFlags())
16226     .addReg(0);
16227     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16228     addDirectMem(MIB, X86::EAX);
16229     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16230   } else {
16231     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16232                                       TII->get(X86::MOV32rm), X86::EAX)
16233     .addReg(TII->getGlobalBaseReg(F))
16234     .addImm(0).addReg(0)
16235     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16236                       MI->getOperand(3).getTargetFlags())
16237     .addReg(0);
16238     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16239     addDirectMem(MIB, X86::EAX);
16240     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16241   }
16242
16243   MI->eraseFromParent(); // The pseudo instruction is gone now.
16244   return BB;
16245 }
16246
16247 MachineBasicBlock *
16248 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16249                                     MachineBasicBlock *MBB) const {
16250   DebugLoc DL = MI->getDebugLoc();
16251   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16252
16253   MachineFunction *MF = MBB->getParent();
16254   MachineRegisterInfo &MRI = MF->getRegInfo();
16255
16256   const BasicBlock *BB = MBB->getBasicBlock();
16257   MachineFunction::iterator I = MBB;
16258   ++I;
16259
16260   // Memory Reference
16261   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16262   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16263
16264   unsigned DstReg;
16265   unsigned MemOpndSlot = 0;
16266
16267   unsigned CurOp = 0;
16268
16269   DstReg = MI->getOperand(CurOp++).getReg();
16270   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16271   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16272   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16273   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16274
16275   MemOpndSlot = CurOp;
16276
16277   MVT PVT = getPointerTy();
16278   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16279          "Invalid Pointer Size!");
16280
16281   // For v = setjmp(buf), we generate
16282   //
16283   // thisMBB:
16284   //  buf[LabelOffset] = restoreMBB
16285   //  SjLjSetup restoreMBB
16286   //
16287   // mainMBB:
16288   //  v_main = 0
16289   //
16290   // sinkMBB:
16291   //  v = phi(main, restore)
16292   //
16293   // restoreMBB:
16294   //  v_restore = 1
16295
16296   MachineBasicBlock *thisMBB = MBB;
16297   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16298   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16299   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16300   MF->insert(I, mainMBB);
16301   MF->insert(I, sinkMBB);
16302   MF->push_back(restoreMBB);
16303
16304   MachineInstrBuilder MIB;
16305
16306   // Transfer the remainder of BB and its successor edges to sinkMBB.
16307   sinkMBB->splice(sinkMBB->begin(), MBB,
16308                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16309   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16310
16311   // thisMBB:
16312   unsigned PtrStoreOpc = 0;
16313   unsigned LabelReg = 0;
16314   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16315   Reloc::Model RM = getTargetMachine().getRelocationModel();
16316   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16317                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16318
16319   // Prepare IP either in reg or imm.
16320   if (!UseImmLabel) {
16321     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16322     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16323     LabelReg = MRI.createVirtualRegister(PtrRC);
16324     if (Subtarget->is64Bit()) {
16325       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16326               .addReg(X86::RIP)
16327               .addImm(0)
16328               .addReg(0)
16329               .addMBB(restoreMBB)
16330               .addReg(0);
16331     } else {
16332       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16333       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16334               .addReg(XII->getGlobalBaseReg(MF))
16335               .addImm(0)
16336               .addReg(0)
16337               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16338               .addReg(0);
16339     }
16340   } else
16341     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16342   // Store IP
16343   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16344   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16345     if (i == X86::AddrDisp)
16346       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16347     else
16348       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16349   }
16350   if (!UseImmLabel)
16351     MIB.addReg(LabelReg);
16352   else
16353     MIB.addMBB(restoreMBB);
16354   MIB.setMemRefs(MMOBegin, MMOEnd);
16355   // Setup
16356   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16357           .addMBB(restoreMBB);
16358
16359   const X86RegisterInfo *RegInfo =
16360     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16361   MIB.addRegMask(RegInfo->getNoPreservedMask());
16362   thisMBB->addSuccessor(mainMBB);
16363   thisMBB->addSuccessor(restoreMBB);
16364
16365   // mainMBB:
16366   //  EAX = 0
16367   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16368   mainMBB->addSuccessor(sinkMBB);
16369
16370   // sinkMBB:
16371   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16372           TII->get(X86::PHI), DstReg)
16373     .addReg(mainDstReg).addMBB(mainMBB)
16374     .addReg(restoreDstReg).addMBB(restoreMBB);
16375
16376   // restoreMBB:
16377   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16378   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16379   restoreMBB->addSuccessor(sinkMBB);
16380
16381   MI->eraseFromParent();
16382   return sinkMBB;
16383 }
16384
16385 MachineBasicBlock *
16386 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16387                                      MachineBasicBlock *MBB) const {
16388   DebugLoc DL = MI->getDebugLoc();
16389   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16390
16391   MachineFunction *MF = MBB->getParent();
16392   MachineRegisterInfo &MRI = MF->getRegInfo();
16393
16394   // Memory Reference
16395   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16396   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16397
16398   MVT PVT = getPointerTy();
16399   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16400          "Invalid Pointer Size!");
16401
16402   const TargetRegisterClass *RC =
16403     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16404   unsigned Tmp = MRI.createVirtualRegister(RC);
16405   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16406   const X86RegisterInfo *RegInfo =
16407     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16408   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16409   unsigned SP = RegInfo->getStackRegister();
16410
16411   MachineInstrBuilder MIB;
16412
16413   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16414   const int64_t SPOffset = 2 * PVT.getStoreSize();
16415
16416   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16417   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16418
16419   // Reload FP
16420   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16421   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16422     MIB.addOperand(MI->getOperand(i));
16423   MIB.setMemRefs(MMOBegin, MMOEnd);
16424   // Reload IP
16425   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16426   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16427     if (i == X86::AddrDisp)
16428       MIB.addDisp(MI->getOperand(i), LabelOffset);
16429     else
16430       MIB.addOperand(MI->getOperand(i));
16431   }
16432   MIB.setMemRefs(MMOBegin, MMOEnd);
16433   // Reload SP
16434   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16435   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16436     if (i == X86::AddrDisp)
16437       MIB.addDisp(MI->getOperand(i), SPOffset);
16438     else
16439       MIB.addOperand(MI->getOperand(i));
16440   }
16441   MIB.setMemRefs(MMOBegin, MMOEnd);
16442   // Jump
16443   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16444
16445   MI->eraseFromParent();
16446   return MBB;
16447 }
16448
16449 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16450 // accumulator loops. Writing back to the accumulator allows the coalescer
16451 // to remove extra copies in the loop.   
16452 MachineBasicBlock *
16453 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16454                                  MachineBasicBlock *MBB) const {
16455   MachineOperand &AddendOp = MI->getOperand(3);
16456
16457   // Bail out early if the addend isn't a register - we can't switch these.
16458   if (!AddendOp.isReg())
16459     return MBB;
16460
16461   MachineFunction &MF = *MBB->getParent();
16462   MachineRegisterInfo &MRI = MF.getRegInfo();
16463
16464   // Check whether the addend is defined by a PHI:
16465   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16466   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16467   if (!AddendDef.isPHI())
16468     return MBB;
16469
16470   // Look for the following pattern:
16471   // loop:
16472   //   %addend = phi [%entry, 0], [%loop, %result]
16473   //   ...
16474   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16475
16476   // Replace with:
16477   //   loop:
16478   //   %addend = phi [%entry, 0], [%loop, %result]
16479   //   ...
16480   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16481
16482   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16483     assert(AddendDef.getOperand(i).isReg());
16484     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16485     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16486     if (&PHISrcInst == MI) {
16487       // Found a matching instruction.
16488       unsigned NewFMAOpc = 0;
16489       switch (MI->getOpcode()) {
16490         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16491         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16492         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16493         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16494         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16495         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16496         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16497         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16498         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16499         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16500         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16501         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16502         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16503         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16504         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16505         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16506         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16507         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16508         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16509         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16510         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16511         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16512         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16513         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16514         default: llvm_unreachable("Unrecognized FMA variant.");
16515       }
16516
16517       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16518       MachineInstrBuilder MIB =
16519         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16520         .addOperand(MI->getOperand(0))
16521         .addOperand(MI->getOperand(3))
16522         .addOperand(MI->getOperand(2))
16523         .addOperand(MI->getOperand(1));
16524       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16525       MI->eraseFromParent();
16526     }
16527   }
16528
16529   return MBB;
16530 }
16531
16532 MachineBasicBlock *
16533 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16534                                                MachineBasicBlock *BB) const {
16535   switch (MI->getOpcode()) {
16536   default: llvm_unreachable("Unexpected instr type to insert");
16537   case X86::TAILJMPd64:
16538   case X86::TAILJMPr64:
16539   case X86::TAILJMPm64:
16540     llvm_unreachable("TAILJMP64 would not be touched here.");
16541   case X86::TCRETURNdi64:
16542   case X86::TCRETURNri64:
16543   case X86::TCRETURNmi64:
16544     return BB;
16545   case X86::WIN_ALLOCA:
16546     return EmitLoweredWinAlloca(MI, BB);
16547   case X86::SEG_ALLOCA_32:
16548     return EmitLoweredSegAlloca(MI, BB, false);
16549   case X86::SEG_ALLOCA_64:
16550     return EmitLoweredSegAlloca(MI, BB, true);
16551   case X86::TLSCall_32:
16552   case X86::TLSCall_64:
16553     return EmitLoweredTLSCall(MI, BB);
16554   case X86::CMOV_GR8:
16555   case X86::CMOV_FR32:
16556   case X86::CMOV_FR64:
16557   case X86::CMOV_V4F32:
16558   case X86::CMOV_V2F64:
16559   case X86::CMOV_V2I64:
16560   case X86::CMOV_V8F32:
16561   case X86::CMOV_V4F64:
16562   case X86::CMOV_V4I64:
16563   case X86::CMOV_V16F32:
16564   case X86::CMOV_V8F64:
16565   case X86::CMOV_V8I64:
16566   case X86::CMOV_GR16:
16567   case X86::CMOV_GR32:
16568   case X86::CMOV_RFP32:
16569   case X86::CMOV_RFP64:
16570   case X86::CMOV_RFP80:
16571     return EmitLoweredSelect(MI, BB);
16572
16573   case X86::FP32_TO_INT16_IN_MEM:
16574   case X86::FP32_TO_INT32_IN_MEM:
16575   case X86::FP32_TO_INT64_IN_MEM:
16576   case X86::FP64_TO_INT16_IN_MEM:
16577   case X86::FP64_TO_INT32_IN_MEM:
16578   case X86::FP64_TO_INT64_IN_MEM:
16579   case X86::FP80_TO_INT16_IN_MEM:
16580   case X86::FP80_TO_INT32_IN_MEM:
16581   case X86::FP80_TO_INT64_IN_MEM: {
16582     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16583     DebugLoc DL = MI->getDebugLoc();
16584
16585     // Change the floating point control register to use "round towards zero"
16586     // mode when truncating to an integer value.
16587     MachineFunction *F = BB->getParent();
16588     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16589     addFrameReference(BuildMI(*BB, MI, DL,
16590                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16591
16592     // Load the old value of the high byte of the control word...
16593     unsigned OldCW =
16594       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16595     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16596                       CWFrameIdx);
16597
16598     // Set the high part to be round to zero...
16599     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16600       .addImm(0xC7F);
16601
16602     // Reload the modified control word now...
16603     addFrameReference(BuildMI(*BB, MI, DL,
16604                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16605
16606     // Restore the memory image of control word to original value
16607     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16608       .addReg(OldCW);
16609
16610     // Get the X86 opcode to use.
16611     unsigned Opc;
16612     switch (MI->getOpcode()) {
16613     default: llvm_unreachable("illegal opcode!");
16614     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16615     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16616     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16617     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16618     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16619     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16620     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16621     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16622     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16623     }
16624
16625     X86AddressMode AM;
16626     MachineOperand &Op = MI->getOperand(0);
16627     if (Op.isReg()) {
16628       AM.BaseType = X86AddressMode::RegBase;
16629       AM.Base.Reg = Op.getReg();
16630     } else {
16631       AM.BaseType = X86AddressMode::FrameIndexBase;
16632       AM.Base.FrameIndex = Op.getIndex();
16633     }
16634     Op = MI->getOperand(1);
16635     if (Op.isImm())
16636       AM.Scale = Op.getImm();
16637     Op = MI->getOperand(2);
16638     if (Op.isImm())
16639       AM.IndexReg = Op.getImm();
16640     Op = MI->getOperand(3);
16641     if (Op.isGlobal()) {
16642       AM.GV = Op.getGlobal();
16643     } else {
16644       AM.Disp = Op.getImm();
16645     }
16646     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16647                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16648
16649     // Reload the original control word now.
16650     addFrameReference(BuildMI(*BB, MI, DL,
16651                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16652
16653     MI->eraseFromParent();   // The pseudo instruction is gone now.
16654     return BB;
16655   }
16656     // String/text processing lowering.
16657   case X86::PCMPISTRM128REG:
16658   case X86::VPCMPISTRM128REG:
16659   case X86::PCMPISTRM128MEM:
16660   case X86::VPCMPISTRM128MEM:
16661   case X86::PCMPESTRM128REG:
16662   case X86::VPCMPESTRM128REG:
16663   case X86::PCMPESTRM128MEM:
16664   case X86::VPCMPESTRM128MEM:
16665     assert(Subtarget->hasSSE42() &&
16666            "Target must have SSE4.2 or AVX features enabled");
16667     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16668
16669   // String/text processing lowering.
16670   case X86::PCMPISTRIREG:
16671   case X86::VPCMPISTRIREG:
16672   case X86::PCMPISTRIMEM:
16673   case X86::VPCMPISTRIMEM:
16674   case X86::PCMPESTRIREG:
16675   case X86::VPCMPESTRIREG:
16676   case X86::PCMPESTRIMEM:
16677   case X86::VPCMPESTRIMEM:
16678     assert(Subtarget->hasSSE42() &&
16679            "Target must have SSE4.2 or AVX features enabled");
16680     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16681
16682   // Thread synchronization.
16683   case X86::MONITOR:
16684     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16685
16686   // xbegin
16687   case X86::XBEGIN:
16688     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16689
16690   // Atomic Lowering.
16691   case X86::ATOMAND8:
16692   case X86::ATOMAND16:
16693   case X86::ATOMAND32:
16694   case X86::ATOMAND64:
16695     // Fall through
16696   case X86::ATOMOR8:
16697   case X86::ATOMOR16:
16698   case X86::ATOMOR32:
16699   case X86::ATOMOR64:
16700     // Fall through
16701   case X86::ATOMXOR16:
16702   case X86::ATOMXOR8:
16703   case X86::ATOMXOR32:
16704   case X86::ATOMXOR64:
16705     // Fall through
16706   case X86::ATOMNAND8:
16707   case X86::ATOMNAND16:
16708   case X86::ATOMNAND32:
16709   case X86::ATOMNAND64:
16710     // Fall through
16711   case X86::ATOMMAX8:
16712   case X86::ATOMMAX16:
16713   case X86::ATOMMAX32:
16714   case X86::ATOMMAX64:
16715     // Fall through
16716   case X86::ATOMMIN8:
16717   case X86::ATOMMIN16:
16718   case X86::ATOMMIN32:
16719   case X86::ATOMMIN64:
16720     // Fall through
16721   case X86::ATOMUMAX8:
16722   case X86::ATOMUMAX16:
16723   case X86::ATOMUMAX32:
16724   case X86::ATOMUMAX64:
16725     // Fall through
16726   case X86::ATOMUMIN8:
16727   case X86::ATOMUMIN16:
16728   case X86::ATOMUMIN32:
16729   case X86::ATOMUMIN64:
16730     return EmitAtomicLoadArith(MI, BB);
16731
16732   // This group does 64-bit operations on a 32-bit host.
16733   case X86::ATOMAND6432:
16734   case X86::ATOMOR6432:
16735   case X86::ATOMXOR6432:
16736   case X86::ATOMNAND6432:
16737   case X86::ATOMADD6432:
16738   case X86::ATOMSUB6432:
16739   case X86::ATOMMAX6432:
16740   case X86::ATOMMIN6432:
16741   case X86::ATOMUMAX6432:
16742   case X86::ATOMUMIN6432:
16743   case X86::ATOMSWAP6432:
16744     return EmitAtomicLoadArith6432(MI, BB);
16745
16746   case X86::VASTART_SAVE_XMM_REGS:
16747     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16748
16749   case X86::VAARG_64:
16750     return EmitVAARG64WithCustomInserter(MI, BB);
16751
16752   case X86::EH_SjLj_SetJmp32:
16753   case X86::EH_SjLj_SetJmp64:
16754     return emitEHSjLjSetJmp(MI, BB);
16755
16756   case X86::EH_SjLj_LongJmp32:
16757   case X86::EH_SjLj_LongJmp64:
16758     return emitEHSjLjLongJmp(MI, BB);
16759
16760   case TargetOpcode::STACKMAP:
16761   case TargetOpcode::PATCHPOINT:
16762     return emitPatchPoint(MI, BB);
16763
16764   case X86::VFMADDPDr213r:
16765   case X86::VFMADDPSr213r:
16766   case X86::VFMADDSDr213r:
16767   case X86::VFMADDSSr213r:
16768   case X86::VFMSUBPDr213r:
16769   case X86::VFMSUBPSr213r:
16770   case X86::VFMSUBSDr213r:
16771   case X86::VFMSUBSSr213r:
16772   case X86::VFNMADDPDr213r:
16773   case X86::VFNMADDPSr213r:
16774   case X86::VFNMADDSDr213r:
16775   case X86::VFNMADDSSr213r:
16776   case X86::VFNMSUBPDr213r:
16777   case X86::VFNMSUBPSr213r:
16778   case X86::VFNMSUBSDr213r:
16779   case X86::VFNMSUBSSr213r:
16780   case X86::VFMADDPDr213rY:
16781   case X86::VFMADDPSr213rY:
16782   case X86::VFMSUBPDr213rY:
16783   case X86::VFMSUBPSr213rY:
16784   case X86::VFNMADDPDr213rY:
16785   case X86::VFNMADDPSr213rY:
16786   case X86::VFNMSUBPDr213rY:
16787   case X86::VFNMSUBPSr213rY:
16788     return emitFMA3Instr(MI, BB);
16789   }
16790 }
16791
16792 //===----------------------------------------------------------------------===//
16793 //                           X86 Optimization Hooks
16794 //===----------------------------------------------------------------------===//
16795
16796 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16797                                                        APInt &KnownZero,
16798                                                        APInt &KnownOne,
16799                                                        const SelectionDAG &DAG,
16800                                                        unsigned Depth) const {
16801   unsigned BitWidth = KnownZero.getBitWidth();
16802   unsigned Opc = Op.getOpcode();
16803   assert((Opc >= ISD::BUILTIN_OP_END ||
16804           Opc == ISD::INTRINSIC_WO_CHAIN ||
16805           Opc == ISD::INTRINSIC_W_CHAIN ||
16806           Opc == ISD::INTRINSIC_VOID) &&
16807          "Should use MaskedValueIsZero if you don't know whether Op"
16808          " is a target node!");
16809
16810   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16811   switch (Opc) {
16812   default: break;
16813   case X86ISD::ADD:
16814   case X86ISD::SUB:
16815   case X86ISD::ADC:
16816   case X86ISD::SBB:
16817   case X86ISD::SMUL:
16818   case X86ISD::UMUL:
16819   case X86ISD::INC:
16820   case X86ISD::DEC:
16821   case X86ISD::OR:
16822   case X86ISD::XOR:
16823   case X86ISD::AND:
16824     // These nodes' second result is a boolean.
16825     if (Op.getResNo() == 0)
16826       break;
16827     // Fallthrough
16828   case X86ISD::SETCC:
16829     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16830     break;
16831   case ISD::INTRINSIC_WO_CHAIN: {
16832     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16833     unsigned NumLoBits = 0;
16834     switch (IntId) {
16835     default: break;
16836     case Intrinsic::x86_sse_movmsk_ps:
16837     case Intrinsic::x86_avx_movmsk_ps_256:
16838     case Intrinsic::x86_sse2_movmsk_pd:
16839     case Intrinsic::x86_avx_movmsk_pd_256:
16840     case Intrinsic::x86_mmx_pmovmskb:
16841     case Intrinsic::x86_sse2_pmovmskb_128:
16842     case Intrinsic::x86_avx2_pmovmskb: {
16843       // High bits of movmskp{s|d}, pmovmskb are known zero.
16844       switch (IntId) {
16845         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16846         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16847         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16848         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16849         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16850         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16851         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16852         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16853       }
16854       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16855       break;
16856     }
16857     }
16858     break;
16859   }
16860   }
16861 }
16862
16863 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16864   SDValue Op,
16865   const SelectionDAG &,
16866   unsigned Depth) const {
16867   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16868   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16869     return Op.getValueType().getScalarType().getSizeInBits();
16870
16871   // Fallback case.
16872   return 1;
16873 }
16874
16875 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16876 /// node is a GlobalAddress + offset.
16877 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16878                                        const GlobalValue* &GA,
16879                                        int64_t &Offset) const {
16880   if (N->getOpcode() == X86ISD::Wrapper) {
16881     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16882       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16883       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16884       return true;
16885     }
16886   }
16887   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16888 }
16889
16890 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16891 /// same as extracting the high 128-bit part of 256-bit vector and then
16892 /// inserting the result into the low part of a new 256-bit vector
16893 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16894   EVT VT = SVOp->getValueType(0);
16895   unsigned NumElems = VT.getVectorNumElements();
16896
16897   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16898   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16899     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16900         SVOp->getMaskElt(j) >= 0)
16901       return false;
16902
16903   return true;
16904 }
16905
16906 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16907 /// same as extracting the low 128-bit part of 256-bit vector and then
16908 /// inserting the result into the high part of a new 256-bit vector
16909 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16910   EVT VT = SVOp->getValueType(0);
16911   unsigned NumElems = VT.getVectorNumElements();
16912
16913   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16914   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16915     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16916         SVOp->getMaskElt(j) >= 0)
16917       return false;
16918
16919   return true;
16920 }
16921
16922 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16923 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16924                                         TargetLowering::DAGCombinerInfo &DCI,
16925                                         const X86Subtarget* Subtarget) {
16926   SDLoc dl(N);
16927   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16928   SDValue V1 = SVOp->getOperand(0);
16929   SDValue V2 = SVOp->getOperand(1);
16930   EVT VT = SVOp->getValueType(0);
16931   unsigned NumElems = VT.getVectorNumElements();
16932
16933   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16934       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16935     //
16936     //                   0,0,0,...
16937     //                      |
16938     //    V      UNDEF    BUILD_VECTOR    UNDEF
16939     //     \      /           \           /
16940     //  CONCAT_VECTOR         CONCAT_VECTOR
16941     //         \                  /
16942     //          \                /
16943     //          RESULT: V + zero extended
16944     //
16945     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16946         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16947         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16948       return SDValue();
16949
16950     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16951       return SDValue();
16952
16953     // To match the shuffle mask, the first half of the mask should
16954     // be exactly the first vector, and all the rest a splat with the
16955     // first element of the second one.
16956     for (unsigned i = 0; i != NumElems/2; ++i)
16957       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16958           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16959         return SDValue();
16960
16961     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16962     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16963       if (Ld->hasNUsesOfValue(1, 0)) {
16964         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16965         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16966         SDValue ResNode =
16967           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16968                                   array_lengthof(Ops),
16969                                   Ld->getMemoryVT(),
16970                                   Ld->getPointerInfo(),
16971                                   Ld->getAlignment(),
16972                                   false/*isVolatile*/, true/*ReadMem*/,
16973                                   false/*WriteMem*/);
16974
16975         // Make sure the newly-created LOAD is in the same position as Ld in
16976         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16977         // and update uses of Ld's output chain to use the TokenFactor.
16978         if (Ld->hasAnyUseOfValue(1)) {
16979           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16980                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16981           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16982           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16983                                  SDValue(ResNode.getNode(), 1));
16984         }
16985
16986         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16987       }
16988     }
16989
16990     // Emit a zeroed vector and insert the desired subvector on its
16991     // first half.
16992     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16993     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16994     return DCI.CombineTo(N, InsV);
16995   }
16996
16997   //===--------------------------------------------------------------------===//
16998   // Combine some shuffles into subvector extracts and inserts:
16999   //
17000
17001   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17002   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17003     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17004     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17005     return DCI.CombineTo(N, InsV);
17006   }
17007
17008   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17009   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17010     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17011     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17012     return DCI.CombineTo(N, InsV);
17013   }
17014
17015   return SDValue();
17016 }
17017
17018 /// PerformShuffleCombine - Performs several different shuffle combines.
17019 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17020                                      TargetLowering::DAGCombinerInfo &DCI,
17021                                      const X86Subtarget *Subtarget) {
17022   SDLoc dl(N);
17023   EVT VT = N->getValueType(0);
17024
17025   // Don't create instructions with illegal types after legalize types has run.
17026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17027   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17028     return SDValue();
17029
17030   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17031   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17032       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17033     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17034
17035   // Only handle 128 wide vector from here on.
17036   if (!VT.is128BitVector())
17037     return SDValue();
17038
17039   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17040   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17041   // consecutive, non-overlapping, and in the right order.
17042   SmallVector<SDValue, 16> Elts;
17043   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17044     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17045
17046   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17047 }
17048
17049 /// PerformTruncateCombine - Converts truncate operation to
17050 /// a sequence of vector shuffle operations.
17051 /// It is possible when we truncate 256-bit vector to 128-bit vector
17052 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17053                                       TargetLowering::DAGCombinerInfo &DCI,
17054                                       const X86Subtarget *Subtarget)  {
17055   return SDValue();
17056 }
17057
17058 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17059 /// specific shuffle of a load can be folded into a single element load.
17060 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17061 /// shuffles have been customed lowered so we need to handle those here.
17062 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17063                                          TargetLowering::DAGCombinerInfo &DCI) {
17064   if (DCI.isBeforeLegalizeOps())
17065     return SDValue();
17066
17067   SDValue InVec = N->getOperand(0);
17068   SDValue EltNo = N->getOperand(1);
17069
17070   if (!isa<ConstantSDNode>(EltNo))
17071     return SDValue();
17072
17073   EVT VT = InVec.getValueType();
17074
17075   bool HasShuffleIntoBitcast = false;
17076   if (InVec.getOpcode() == ISD::BITCAST) {
17077     // Don't duplicate a load with other uses.
17078     if (!InVec.hasOneUse())
17079       return SDValue();
17080     EVT BCVT = InVec.getOperand(0).getValueType();
17081     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17082       return SDValue();
17083     InVec = InVec.getOperand(0);
17084     HasShuffleIntoBitcast = true;
17085   }
17086
17087   if (!isTargetShuffle(InVec.getOpcode()))
17088     return SDValue();
17089
17090   // Don't duplicate a load with other uses.
17091   if (!InVec.hasOneUse())
17092     return SDValue();
17093
17094   SmallVector<int, 16> ShuffleMask;
17095   bool UnaryShuffle;
17096   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17097                             UnaryShuffle))
17098     return SDValue();
17099
17100   // Select the input vector, guarding against out of range extract vector.
17101   unsigned NumElems = VT.getVectorNumElements();
17102   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17103   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17104   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17105                                          : InVec.getOperand(1);
17106
17107   // If inputs to shuffle are the same for both ops, then allow 2 uses
17108   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17109
17110   if (LdNode.getOpcode() == ISD::BITCAST) {
17111     // Don't duplicate a load with other uses.
17112     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17113       return SDValue();
17114
17115     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17116     LdNode = LdNode.getOperand(0);
17117   }
17118
17119   if (!ISD::isNormalLoad(LdNode.getNode()))
17120     return SDValue();
17121
17122   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17123
17124   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17125     return SDValue();
17126
17127   if (HasShuffleIntoBitcast) {
17128     // If there's a bitcast before the shuffle, check if the load type and
17129     // alignment is valid.
17130     unsigned Align = LN0->getAlignment();
17131     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17132     unsigned NewAlign = TLI.getDataLayout()->
17133       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17134
17135     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17136       return SDValue();
17137   }
17138
17139   // All checks match so transform back to vector_shuffle so that DAG combiner
17140   // can finish the job
17141   SDLoc dl(N);
17142
17143   // Create shuffle node taking into account the case that its a unary shuffle
17144   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17145   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17146                                  InVec.getOperand(0), Shuffle,
17147                                  &ShuffleMask[0]);
17148   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17149   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17150                      EltNo);
17151 }
17152
17153 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17154 /// generation and convert it from being a bunch of shuffles and extracts
17155 /// to a simple store and scalar loads to extract the elements.
17156 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17157                                          TargetLowering::DAGCombinerInfo &DCI) {
17158   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17159   if (NewOp.getNode())
17160     return NewOp;
17161
17162   SDValue InputVector = N->getOperand(0);
17163
17164   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17165   // from mmx to v2i32 has a single usage.
17166   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17167       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17168       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17169     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17170                        N->getValueType(0),
17171                        InputVector.getNode()->getOperand(0));
17172
17173   // Only operate on vectors of 4 elements, where the alternative shuffling
17174   // gets to be more expensive.
17175   if (InputVector.getValueType() != MVT::v4i32)
17176     return SDValue();
17177
17178   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17179   // single use which is a sign-extend or zero-extend, and all elements are
17180   // used.
17181   SmallVector<SDNode *, 4> Uses;
17182   unsigned ExtractedElements = 0;
17183   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17184        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17185     if (UI.getUse().getResNo() != InputVector.getResNo())
17186       return SDValue();
17187
17188     SDNode *Extract = *UI;
17189     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17190       return SDValue();
17191
17192     if (Extract->getValueType(0) != MVT::i32)
17193       return SDValue();
17194     if (!Extract->hasOneUse())
17195       return SDValue();
17196     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17197         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17198       return SDValue();
17199     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17200       return SDValue();
17201
17202     // Record which element was extracted.
17203     ExtractedElements |=
17204       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17205
17206     Uses.push_back(Extract);
17207   }
17208
17209   // If not all the elements were used, this may not be worthwhile.
17210   if (ExtractedElements != 15)
17211     return SDValue();
17212
17213   // Ok, we've now decided to do the transformation.
17214   SDLoc dl(InputVector);
17215
17216   // Store the value to a temporary stack slot.
17217   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17218   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17219                             MachinePointerInfo(), false, false, 0);
17220
17221   // Replace each use (extract) with a load of the appropriate element.
17222   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17223        UE = Uses.end(); UI != UE; ++UI) {
17224     SDNode *Extract = *UI;
17225
17226     // cOMpute the element's address.
17227     SDValue Idx = Extract->getOperand(1);
17228     unsigned EltSize =
17229         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17230     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17231     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17232     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17233
17234     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17235                                      StackPtr, OffsetVal);
17236
17237     // Load the scalar.
17238     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17239                                      ScalarAddr, MachinePointerInfo(),
17240                                      false, false, false, 0);
17241
17242     // Replace the exact with the load.
17243     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17244   }
17245
17246   // The replacement was made in place; don't return anything.
17247   return SDValue();
17248 }
17249
17250 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17251 static std::pair<unsigned, bool>
17252 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17253                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17254   if (!VT.isVector())
17255     return std::make_pair(0, false);
17256
17257   bool NeedSplit = false;
17258   switch (VT.getSimpleVT().SimpleTy) {
17259   default: return std::make_pair(0, false);
17260   case MVT::v32i8:
17261   case MVT::v16i16:
17262   case MVT::v8i32:
17263     if (!Subtarget->hasAVX2())
17264       NeedSplit = true;
17265     if (!Subtarget->hasAVX())
17266       return std::make_pair(0, false);
17267     break;
17268   case MVT::v16i8:
17269   case MVT::v8i16:
17270   case MVT::v4i32:
17271     if (!Subtarget->hasSSE2())
17272       return std::make_pair(0, false);
17273   }
17274
17275   // SSE2 has only a small subset of the operations.
17276   bool hasUnsigned = Subtarget->hasSSE41() ||
17277                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17278   bool hasSigned = Subtarget->hasSSE41() ||
17279                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17280
17281   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17282
17283   unsigned Opc = 0;
17284   // Check for x CC y ? x : y.
17285   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17286       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17287     switch (CC) {
17288     default: break;
17289     case ISD::SETULT:
17290     case ISD::SETULE:
17291       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17292     case ISD::SETUGT:
17293     case ISD::SETUGE:
17294       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17295     case ISD::SETLT:
17296     case ISD::SETLE:
17297       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17298     case ISD::SETGT:
17299     case ISD::SETGE:
17300       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17301     }
17302   // Check for x CC y ? y : x -- a min/max with reversed arms.
17303   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17304              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17305     switch (CC) {
17306     default: break;
17307     case ISD::SETULT:
17308     case ISD::SETULE:
17309       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17310     case ISD::SETUGT:
17311     case ISD::SETUGE:
17312       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17313     case ISD::SETLT:
17314     case ISD::SETLE:
17315       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17316     case ISD::SETGT:
17317     case ISD::SETGE:
17318       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17319     }
17320   }
17321
17322   return std::make_pair(Opc, NeedSplit);
17323 }
17324
17325 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17326 /// nodes.
17327 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17328                                     TargetLowering::DAGCombinerInfo &DCI,
17329                                     const X86Subtarget *Subtarget) {
17330   SDLoc DL(N);
17331   SDValue Cond = N->getOperand(0);
17332   // Get the LHS/RHS of the select.
17333   SDValue LHS = N->getOperand(1);
17334   SDValue RHS = N->getOperand(2);
17335   EVT VT = LHS.getValueType();
17336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17337
17338   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17339   // instructions match the semantics of the common C idiom x<y?x:y but not
17340   // x<=y?x:y, because of how they handle negative zero (which can be
17341   // ignored in unsafe-math mode).
17342   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17343       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17344       (Subtarget->hasSSE2() ||
17345        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17346     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17347
17348     unsigned Opcode = 0;
17349     // Check for x CC y ? x : y.
17350     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17351         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17352       switch (CC) {
17353       default: break;
17354       case ISD::SETULT:
17355         // Converting this to a min would handle NaNs incorrectly, and swapping
17356         // the operands would cause it to handle comparisons between positive
17357         // and negative zero incorrectly.
17358         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17359           if (!DAG.getTarget().Options.UnsafeFPMath &&
17360               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17361             break;
17362           std::swap(LHS, RHS);
17363         }
17364         Opcode = X86ISD::FMIN;
17365         break;
17366       case ISD::SETOLE:
17367         // Converting this to a min would handle comparisons between positive
17368         // and negative zero incorrectly.
17369         if (!DAG.getTarget().Options.UnsafeFPMath &&
17370             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17371           break;
17372         Opcode = X86ISD::FMIN;
17373         break;
17374       case ISD::SETULE:
17375         // Converting this to a min would handle both negative zeros and NaNs
17376         // incorrectly, but we can swap the operands to fix both.
17377         std::swap(LHS, RHS);
17378       case ISD::SETOLT:
17379       case ISD::SETLT:
17380       case ISD::SETLE:
17381         Opcode = X86ISD::FMIN;
17382         break;
17383
17384       case ISD::SETOGE:
17385         // Converting this to a max would handle comparisons between positive
17386         // and negative zero incorrectly.
17387         if (!DAG.getTarget().Options.UnsafeFPMath &&
17388             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17389           break;
17390         Opcode = X86ISD::FMAX;
17391         break;
17392       case ISD::SETUGT:
17393         // Converting this to a max would handle NaNs incorrectly, and swapping
17394         // the operands would cause it to handle comparisons between positive
17395         // and negative zero incorrectly.
17396         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17397           if (!DAG.getTarget().Options.UnsafeFPMath &&
17398               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17399             break;
17400           std::swap(LHS, RHS);
17401         }
17402         Opcode = X86ISD::FMAX;
17403         break;
17404       case ISD::SETUGE:
17405         // Converting this to a max would handle both negative zeros and NaNs
17406         // incorrectly, but we can swap the operands to fix both.
17407         std::swap(LHS, RHS);
17408       case ISD::SETOGT:
17409       case ISD::SETGT:
17410       case ISD::SETGE:
17411         Opcode = X86ISD::FMAX;
17412         break;
17413       }
17414     // Check for x CC y ? y : x -- a min/max with reversed arms.
17415     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17416                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17417       switch (CC) {
17418       default: break;
17419       case ISD::SETOGE:
17420         // Converting this to a min would handle comparisons between positive
17421         // and negative zero incorrectly, and swapping the operands would
17422         // cause it to handle NaNs incorrectly.
17423         if (!DAG.getTarget().Options.UnsafeFPMath &&
17424             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17425           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17426             break;
17427           std::swap(LHS, RHS);
17428         }
17429         Opcode = X86ISD::FMIN;
17430         break;
17431       case ISD::SETUGT:
17432         // Converting this to a min would handle NaNs incorrectly.
17433         if (!DAG.getTarget().Options.UnsafeFPMath &&
17434             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17435           break;
17436         Opcode = X86ISD::FMIN;
17437         break;
17438       case ISD::SETUGE:
17439         // Converting this to a min would handle both negative zeros and NaNs
17440         // incorrectly, but we can swap the operands to fix both.
17441         std::swap(LHS, RHS);
17442       case ISD::SETOGT:
17443       case ISD::SETGT:
17444       case ISD::SETGE:
17445         Opcode = X86ISD::FMIN;
17446         break;
17447
17448       case ISD::SETULT:
17449         // Converting this to a max would handle NaNs incorrectly.
17450         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17451           break;
17452         Opcode = X86ISD::FMAX;
17453         break;
17454       case ISD::SETOLE:
17455         // Converting this to a max would handle comparisons between positive
17456         // and negative zero incorrectly, and swapping the operands would
17457         // cause it to handle NaNs incorrectly.
17458         if (!DAG.getTarget().Options.UnsafeFPMath &&
17459             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17460           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17461             break;
17462           std::swap(LHS, RHS);
17463         }
17464         Opcode = X86ISD::FMAX;
17465         break;
17466       case ISD::SETULE:
17467         // Converting this to a max would handle both negative zeros and NaNs
17468         // incorrectly, but we can swap the operands to fix both.
17469         std::swap(LHS, RHS);
17470       case ISD::SETOLT:
17471       case ISD::SETLT:
17472       case ISD::SETLE:
17473         Opcode = X86ISD::FMAX;
17474         break;
17475       }
17476     }
17477
17478     if (Opcode)
17479       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17480   }
17481
17482   EVT CondVT = Cond.getValueType();
17483   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17484       CondVT.getVectorElementType() == MVT::i1) {
17485     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17486     // lowering on AVX-512. In this case we convert it to
17487     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17488     // The same situation for all 128 and 256-bit vectors of i8 and i16
17489     EVT OpVT = LHS.getValueType();
17490     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17491         (OpVT.getVectorElementType() == MVT::i8 ||
17492          OpVT.getVectorElementType() == MVT::i16)) {
17493       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17494       DCI.AddToWorklist(Cond.getNode());
17495       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17496     }
17497   }
17498   // If this is a select between two integer constants, try to do some
17499   // optimizations.
17500   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17501     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17502       // Don't do this for crazy integer types.
17503       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17504         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17505         // so that TrueC (the true value) is larger than FalseC.
17506         bool NeedsCondInvert = false;
17507
17508         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17509             // Efficiently invertible.
17510             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17511              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17512               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17513           NeedsCondInvert = true;
17514           std::swap(TrueC, FalseC);
17515         }
17516
17517         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17518         if (FalseC->getAPIntValue() == 0 &&
17519             TrueC->getAPIntValue().isPowerOf2()) {
17520           if (NeedsCondInvert) // Invert the condition if needed.
17521             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17522                                DAG.getConstant(1, Cond.getValueType()));
17523
17524           // Zero extend the condition if needed.
17525           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17526
17527           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17528           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17529                              DAG.getConstant(ShAmt, MVT::i8));
17530         }
17531
17532         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17533         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17534           if (NeedsCondInvert) // Invert the condition if needed.
17535             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17536                                DAG.getConstant(1, Cond.getValueType()));
17537
17538           // Zero extend the condition if needed.
17539           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17540                              FalseC->getValueType(0), Cond);
17541           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17542                              SDValue(FalseC, 0));
17543         }
17544
17545         // Optimize cases that will turn into an LEA instruction.  This requires
17546         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17547         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17548           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17549           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17550
17551           bool isFastMultiplier = false;
17552           if (Diff < 10) {
17553             switch ((unsigned char)Diff) {
17554               default: break;
17555               case 1:  // result = add base, cond
17556               case 2:  // result = lea base(    , cond*2)
17557               case 3:  // result = lea base(cond, cond*2)
17558               case 4:  // result = lea base(    , cond*4)
17559               case 5:  // result = lea base(cond, cond*4)
17560               case 8:  // result = lea base(    , cond*8)
17561               case 9:  // result = lea base(cond, cond*8)
17562                 isFastMultiplier = true;
17563                 break;
17564             }
17565           }
17566
17567           if (isFastMultiplier) {
17568             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17569             if (NeedsCondInvert) // Invert the condition if needed.
17570               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17571                                  DAG.getConstant(1, Cond.getValueType()));
17572
17573             // Zero extend the condition if needed.
17574             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17575                                Cond);
17576             // Scale the condition by the difference.
17577             if (Diff != 1)
17578               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17579                                  DAG.getConstant(Diff, Cond.getValueType()));
17580
17581             // Add the base if non-zero.
17582             if (FalseC->getAPIntValue() != 0)
17583               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17584                                  SDValue(FalseC, 0));
17585             return Cond;
17586           }
17587         }
17588       }
17589   }
17590
17591   // Canonicalize max and min:
17592   // (x > y) ? x : y -> (x >= y) ? x : y
17593   // (x < y) ? x : y -> (x <= y) ? x : y
17594   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17595   // the need for an extra compare
17596   // against zero. e.g.
17597   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17598   // subl   %esi, %edi
17599   // testl  %edi, %edi
17600   // movl   $0, %eax
17601   // cmovgl %edi, %eax
17602   // =>
17603   // xorl   %eax, %eax
17604   // subl   %esi, $edi
17605   // cmovsl %eax, %edi
17606   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17607       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17608       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17609     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17610     switch (CC) {
17611     default: break;
17612     case ISD::SETLT:
17613     case ISD::SETGT: {
17614       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17615       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17616                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17617       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17618     }
17619     }
17620   }
17621
17622   // Early exit check
17623   if (!TLI.isTypeLegal(VT))
17624     return SDValue();
17625
17626   // Match VSELECTs into subs with unsigned saturation.
17627   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17628       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17629       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17630        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17631     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17632
17633     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17634     // left side invert the predicate to simplify logic below.
17635     SDValue Other;
17636     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17637       Other = RHS;
17638       CC = ISD::getSetCCInverse(CC, true);
17639     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17640       Other = LHS;
17641     }
17642
17643     if (Other.getNode() && Other->getNumOperands() == 2 &&
17644         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17645       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17646       SDValue CondRHS = Cond->getOperand(1);
17647
17648       // Look for a general sub with unsigned saturation first.
17649       // x >= y ? x-y : 0 --> subus x, y
17650       // x >  y ? x-y : 0 --> subus x, y
17651       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17652           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17653         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17654
17655       // If the RHS is a constant we have to reverse the const canonicalization.
17656       // x > C-1 ? x+-C : 0 --> subus x, C
17657       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17658           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17659         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17660         if (CondRHS.getConstantOperandVal(0) == -A-1)
17661           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17662                              DAG.getConstant(-A, VT));
17663       }
17664
17665       // Another special case: If C was a sign bit, the sub has been
17666       // canonicalized into a xor.
17667       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17668       //        it's safe to decanonicalize the xor?
17669       // x s< 0 ? x^C : 0 --> subus x, C
17670       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17671           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17672           isSplatVector(OpRHS.getNode())) {
17673         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17674         if (A.isSignBit())
17675           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17676       }
17677     }
17678   }
17679
17680   // Try to match a min/max vector operation.
17681   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17682     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17683     unsigned Opc = ret.first;
17684     bool NeedSplit = ret.second;
17685
17686     if (Opc && NeedSplit) {
17687       unsigned NumElems = VT.getVectorNumElements();
17688       // Extract the LHS vectors
17689       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17690       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17691
17692       // Extract the RHS vectors
17693       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17694       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17695
17696       // Create min/max for each subvector
17697       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17698       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17699
17700       // Merge the result
17701       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17702     } else if (Opc)
17703       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17704   }
17705
17706   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17707   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17708       // Check if SETCC has already been promoted
17709       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17710       // Check that condition value type matches vselect operand type
17711       CondVT == VT) { 
17712
17713     assert(Cond.getValueType().isVector() &&
17714            "vector select expects a vector selector!");
17715
17716     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17717     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17718
17719     if (!TValIsAllOnes && !FValIsAllZeros) {
17720       // Try invert the condition if true value is not all 1s and false value
17721       // is not all 0s.
17722       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17723       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17724
17725       if (TValIsAllZeros || FValIsAllOnes) {
17726         SDValue CC = Cond.getOperand(2);
17727         ISD::CondCode NewCC =
17728           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17729                                Cond.getOperand(0).getValueType().isInteger());
17730         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17731         std::swap(LHS, RHS);
17732         TValIsAllOnes = FValIsAllOnes;
17733         FValIsAllZeros = TValIsAllZeros;
17734       }
17735     }
17736
17737     if (TValIsAllOnes || FValIsAllZeros) {
17738       SDValue Ret;
17739
17740       if (TValIsAllOnes && FValIsAllZeros)
17741         Ret = Cond;
17742       else if (TValIsAllOnes)
17743         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17744                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17745       else if (FValIsAllZeros)
17746         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17747                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17748
17749       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17750     }
17751   }
17752
17753   // Try to fold this VSELECT into a MOVSS/MOVSD
17754   if (N->getOpcode() == ISD::VSELECT &&
17755       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17756     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17757         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17758       bool CanFold = false;
17759       unsigned NumElems = Cond.getNumOperands();
17760       SDValue A = LHS;
17761       SDValue B = RHS;
17762       
17763       if (isZero(Cond.getOperand(0))) {
17764         CanFold = true;
17765
17766         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17767         // fold (vselect <0,-1> -> (movsd A, B)
17768         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17769           CanFold = isAllOnes(Cond.getOperand(i));
17770       } else if (isAllOnes(Cond.getOperand(0))) {
17771         CanFold = true;
17772         std::swap(A, B);
17773
17774         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17775         // fold (vselect <-1,0> -> (movsd B, A)
17776         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17777           CanFold = isZero(Cond.getOperand(i));
17778       }
17779
17780       if (CanFold) {
17781         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17782           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17783         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17784       }
17785
17786       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17787         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17788         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17789         //                             (v2i64 (bitcast B)))))
17790         //
17791         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17792         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17793         //                             (v2f64 (bitcast B)))))
17794         //
17795         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17796         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17797         //                             (v2i64 (bitcast A)))))
17798         //
17799         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17800         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17801         //                             (v2f64 (bitcast A)))))
17802
17803         CanFold = (isZero(Cond.getOperand(0)) &&
17804                    isZero(Cond.getOperand(1)) &&
17805                    isAllOnes(Cond.getOperand(2)) &&
17806                    isAllOnes(Cond.getOperand(3)));
17807
17808         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17809             isAllOnes(Cond.getOperand(1)) &&
17810             isZero(Cond.getOperand(2)) &&
17811             isZero(Cond.getOperand(3))) {
17812           CanFold = true;
17813           std::swap(LHS, RHS);
17814         }
17815
17816         if (CanFold) {
17817           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17818           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17819           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17820           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17821                                                 NewB, DAG);
17822           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17823         }
17824       }
17825     }
17826   }
17827
17828   // If we know that this node is legal then we know that it is going to be
17829   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17830   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17831   // to simplify previous instructions.
17832   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17833       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17834     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17835
17836     // Don't optimize vector selects that map to mask-registers.
17837     if (BitWidth == 1)
17838       return SDValue();
17839
17840     // Check all uses of that condition operand to check whether it will be
17841     // consumed by non-BLEND instructions, which may depend on all bits are set
17842     // properly.
17843     for (SDNode::use_iterator I = Cond->use_begin(),
17844                               E = Cond->use_end(); I != E; ++I)
17845       if (I->getOpcode() != ISD::VSELECT)
17846         // TODO: Add other opcodes eventually lowered into BLEND.
17847         return SDValue();
17848
17849     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17850     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17851
17852     APInt KnownZero, KnownOne;
17853     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17854                                           DCI.isBeforeLegalizeOps());
17855     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17856         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17857       DCI.CommitTargetLoweringOpt(TLO);
17858   }
17859
17860   return SDValue();
17861 }
17862
17863 // Check whether a boolean test is testing a boolean value generated by
17864 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17865 // code.
17866 //
17867 // Simplify the following patterns:
17868 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17869 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17870 // to (Op EFLAGS Cond)
17871 //
17872 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17873 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17874 // to (Op EFLAGS !Cond)
17875 //
17876 // where Op could be BRCOND or CMOV.
17877 //
17878 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17879   // Quit if not CMP and SUB with its value result used.
17880   if (Cmp.getOpcode() != X86ISD::CMP &&
17881       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17882       return SDValue();
17883
17884   // Quit if not used as a boolean value.
17885   if (CC != X86::COND_E && CC != X86::COND_NE)
17886     return SDValue();
17887
17888   // Check CMP operands. One of them should be 0 or 1 and the other should be
17889   // an SetCC or extended from it.
17890   SDValue Op1 = Cmp.getOperand(0);
17891   SDValue Op2 = Cmp.getOperand(1);
17892
17893   SDValue SetCC;
17894   const ConstantSDNode* C = 0;
17895   bool needOppositeCond = (CC == X86::COND_E);
17896   bool checkAgainstTrue = false; // Is it a comparison against 1?
17897
17898   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17899     SetCC = Op2;
17900   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17901     SetCC = Op1;
17902   else // Quit if all operands are not constants.
17903     return SDValue();
17904
17905   if (C->getZExtValue() == 1) {
17906     needOppositeCond = !needOppositeCond;
17907     checkAgainstTrue = true;
17908   } else if (C->getZExtValue() != 0)
17909     // Quit if the constant is neither 0 or 1.
17910     return SDValue();
17911
17912   bool truncatedToBoolWithAnd = false;
17913   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17914   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17915          SetCC.getOpcode() == ISD::TRUNCATE ||
17916          SetCC.getOpcode() == ISD::AND) {
17917     if (SetCC.getOpcode() == ISD::AND) {
17918       int OpIdx = -1;
17919       ConstantSDNode *CS;
17920       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17921           CS->getZExtValue() == 1)
17922         OpIdx = 1;
17923       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17924           CS->getZExtValue() == 1)
17925         OpIdx = 0;
17926       if (OpIdx == -1)
17927         break;
17928       SetCC = SetCC.getOperand(OpIdx);
17929       truncatedToBoolWithAnd = true;
17930     } else
17931       SetCC = SetCC.getOperand(0);
17932   }
17933
17934   switch (SetCC.getOpcode()) {
17935   case X86ISD::SETCC_CARRY:
17936     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17937     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17938     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17939     // truncated to i1 using 'and'.
17940     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17941       break;
17942     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17943            "Invalid use of SETCC_CARRY!");
17944     // FALL THROUGH
17945   case X86ISD::SETCC:
17946     // Set the condition code or opposite one if necessary.
17947     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17948     if (needOppositeCond)
17949       CC = X86::GetOppositeBranchCondition(CC);
17950     return SetCC.getOperand(1);
17951   case X86ISD::CMOV: {
17952     // Check whether false/true value has canonical one, i.e. 0 or 1.
17953     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17954     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17955     // Quit if true value is not a constant.
17956     if (!TVal)
17957       return SDValue();
17958     // Quit if false value is not a constant.
17959     if (!FVal) {
17960       SDValue Op = SetCC.getOperand(0);
17961       // Skip 'zext' or 'trunc' node.
17962       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17963           Op.getOpcode() == ISD::TRUNCATE)
17964         Op = Op.getOperand(0);
17965       // A special case for rdrand/rdseed, where 0 is set if false cond is
17966       // found.
17967       if ((Op.getOpcode() != X86ISD::RDRAND &&
17968            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17969         return SDValue();
17970     }
17971     // Quit if false value is not the constant 0 or 1.
17972     bool FValIsFalse = true;
17973     if (FVal && FVal->getZExtValue() != 0) {
17974       if (FVal->getZExtValue() != 1)
17975         return SDValue();
17976       // If FVal is 1, opposite cond is needed.
17977       needOppositeCond = !needOppositeCond;
17978       FValIsFalse = false;
17979     }
17980     // Quit if TVal is not the constant opposite of FVal.
17981     if (FValIsFalse && TVal->getZExtValue() != 1)
17982       return SDValue();
17983     if (!FValIsFalse && TVal->getZExtValue() != 0)
17984       return SDValue();
17985     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17986     if (needOppositeCond)
17987       CC = X86::GetOppositeBranchCondition(CC);
17988     return SetCC.getOperand(3);
17989   }
17990   }
17991
17992   return SDValue();
17993 }
17994
17995 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17996 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17997                                   TargetLowering::DAGCombinerInfo &DCI,
17998                                   const X86Subtarget *Subtarget) {
17999   SDLoc DL(N);
18000
18001   // If the flag operand isn't dead, don't touch this CMOV.
18002   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18003     return SDValue();
18004
18005   SDValue FalseOp = N->getOperand(0);
18006   SDValue TrueOp = N->getOperand(1);
18007   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18008   SDValue Cond = N->getOperand(3);
18009
18010   if (CC == X86::COND_E || CC == X86::COND_NE) {
18011     switch (Cond.getOpcode()) {
18012     default: break;
18013     case X86ISD::BSR:
18014     case X86ISD::BSF:
18015       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18016       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18017         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18018     }
18019   }
18020
18021   SDValue Flags;
18022
18023   Flags = checkBoolTestSetCCCombine(Cond, CC);
18024   if (Flags.getNode() &&
18025       // Extra check as FCMOV only supports a subset of X86 cond.
18026       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18027     SDValue Ops[] = { FalseOp, TrueOp,
18028                       DAG.getConstant(CC, MVT::i8), Flags };
18029     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18030                        Ops, array_lengthof(Ops));
18031   }
18032
18033   // If this is a select between two integer constants, try to do some
18034   // optimizations.  Note that the operands are ordered the opposite of SELECT
18035   // operands.
18036   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18037     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18038       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18039       // larger than FalseC (the false value).
18040       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18041         CC = X86::GetOppositeBranchCondition(CC);
18042         std::swap(TrueC, FalseC);
18043         std::swap(TrueOp, FalseOp);
18044       }
18045
18046       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18047       // This is efficient for any integer data type (including i8/i16) and
18048       // shift amount.
18049       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18050         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18051                            DAG.getConstant(CC, MVT::i8), Cond);
18052
18053         // Zero extend the condition if needed.
18054         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18055
18056         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18057         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18058                            DAG.getConstant(ShAmt, MVT::i8));
18059         if (N->getNumValues() == 2)  // Dead flag value?
18060           return DCI.CombineTo(N, Cond, SDValue());
18061         return Cond;
18062       }
18063
18064       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18065       // for any integer data type, including i8/i16.
18066       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18067         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18068                            DAG.getConstant(CC, MVT::i8), Cond);
18069
18070         // Zero extend the condition if needed.
18071         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18072                            FalseC->getValueType(0), Cond);
18073         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18074                            SDValue(FalseC, 0));
18075
18076         if (N->getNumValues() == 2)  // Dead flag value?
18077           return DCI.CombineTo(N, Cond, SDValue());
18078         return Cond;
18079       }
18080
18081       // Optimize cases that will turn into an LEA instruction.  This requires
18082       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18083       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18084         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18085         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18086
18087         bool isFastMultiplier = false;
18088         if (Diff < 10) {
18089           switch ((unsigned char)Diff) {
18090           default: break;
18091           case 1:  // result = add base, cond
18092           case 2:  // result = lea base(    , cond*2)
18093           case 3:  // result = lea base(cond, cond*2)
18094           case 4:  // result = lea base(    , cond*4)
18095           case 5:  // result = lea base(cond, cond*4)
18096           case 8:  // result = lea base(    , cond*8)
18097           case 9:  // result = lea base(cond, cond*8)
18098             isFastMultiplier = true;
18099             break;
18100           }
18101         }
18102
18103         if (isFastMultiplier) {
18104           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18105           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18106                              DAG.getConstant(CC, MVT::i8), Cond);
18107           // Zero extend the condition if needed.
18108           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18109                              Cond);
18110           // Scale the condition by the difference.
18111           if (Diff != 1)
18112             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18113                                DAG.getConstant(Diff, Cond.getValueType()));
18114
18115           // Add the base if non-zero.
18116           if (FalseC->getAPIntValue() != 0)
18117             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18118                                SDValue(FalseC, 0));
18119           if (N->getNumValues() == 2)  // Dead flag value?
18120             return DCI.CombineTo(N, Cond, SDValue());
18121           return Cond;
18122         }
18123       }
18124     }
18125   }
18126
18127   // Handle these cases:
18128   //   (select (x != c), e, c) -> select (x != c), e, x),
18129   //   (select (x == c), c, e) -> select (x == c), x, e)
18130   // where the c is an integer constant, and the "select" is the combination
18131   // of CMOV and CMP.
18132   //
18133   // The rationale for this change is that the conditional-move from a constant
18134   // needs two instructions, however, conditional-move from a register needs
18135   // only one instruction.
18136   //
18137   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18138   //  some instruction-combining opportunities. This opt needs to be
18139   //  postponed as late as possible.
18140   //
18141   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18142     // the DCI.xxxx conditions are provided to postpone the optimization as
18143     // late as possible.
18144
18145     ConstantSDNode *CmpAgainst = 0;
18146     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18147         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18148         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18149
18150       if (CC == X86::COND_NE &&
18151           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18152         CC = X86::GetOppositeBranchCondition(CC);
18153         std::swap(TrueOp, FalseOp);
18154       }
18155
18156       if (CC == X86::COND_E &&
18157           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18158         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18159                           DAG.getConstant(CC, MVT::i8), Cond };
18160         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18161                            array_lengthof(Ops));
18162       }
18163     }
18164   }
18165
18166   return SDValue();
18167 }
18168
18169 /// PerformMulCombine - Optimize a single multiply with constant into two
18170 /// in order to implement it with two cheaper instructions, e.g.
18171 /// LEA + SHL, LEA + LEA.
18172 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18173                                  TargetLowering::DAGCombinerInfo &DCI) {
18174   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18175     return SDValue();
18176
18177   EVT VT = N->getValueType(0);
18178   if (VT != MVT::i64)
18179     return SDValue();
18180
18181   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18182   if (!C)
18183     return SDValue();
18184   uint64_t MulAmt = C->getZExtValue();
18185   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18186     return SDValue();
18187
18188   uint64_t MulAmt1 = 0;
18189   uint64_t MulAmt2 = 0;
18190   if ((MulAmt % 9) == 0) {
18191     MulAmt1 = 9;
18192     MulAmt2 = MulAmt / 9;
18193   } else if ((MulAmt % 5) == 0) {
18194     MulAmt1 = 5;
18195     MulAmt2 = MulAmt / 5;
18196   } else if ((MulAmt % 3) == 0) {
18197     MulAmt1 = 3;
18198     MulAmt2 = MulAmt / 3;
18199   }
18200   if (MulAmt2 &&
18201       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18202     SDLoc DL(N);
18203
18204     if (isPowerOf2_64(MulAmt2) &&
18205         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18206       // If second multiplifer is pow2, issue it first. We want the multiply by
18207       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18208       // is an add.
18209       std::swap(MulAmt1, MulAmt2);
18210
18211     SDValue NewMul;
18212     if (isPowerOf2_64(MulAmt1))
18213       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18214                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18215     else
18216       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18217                            DAG.getConstant(MulAmt1, VT));
18218
18219     if (isPowerOf2_64(MulAmt2))
18220       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18221                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18222     else
18223       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18224                            DAG.getConstant(MulAmt2, VT));
18225
18226     // Do not add new nodes to DAG combiner worklist.
18227     DCI.CombineTo(N, NewMul, false);
18228   }
18229   return SDValue();
18230 }
18231
18232 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18233   SDValue N0 = N->getOperand(0);
18234   SDValue N1 = N->getOperand(1);
18235   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18236   EVT VT = N0.getValueType();
18237
18238   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18239   // since the result of setcc_c is all zero's or all ones.
18240   if (VT.isInteger() && !VT.isVector() &&
18241       N1C && N0.getOpcode() == ISD::AND &&
18242       N0.getOperand(1).getOpcode() == ISD::Constant) {
18243     SDValue N00 = N0.getOperand(0);
18244     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18245         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18246           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18247          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18248       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18249       APInt ShAmt = N1C->getAPIntValue();
18250       Mask = Mask.shl(ShAmt);
18251       if (Mask != 0)
18252         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18253                            N00, DAG.getConstant(Mask, VT));
18254     }
18255   }
18256
18257   // Hardware support for vector shifts is sparse which makes us scalarize the
18258   // vector operations in many cases. Also, on sandybridge ADD is faster than
18259   // shl.
18260   // (shl V, 1) -> add V,V
18261   if (isSplatVector(N1.getNode())) {
18262     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18263     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18264     // We shift all of the values by one. In many cases we do not have
18265     // hardware support for this operation. This is better expressed as an ADD
18266     // of two values.
18267     if (N1C && (1 == N1C->getZExtValue())) {
18268       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18269     }
18270   }
18271
18272   return SDValue();
18273 }
18274
18275 /// \brief Returns a vector of 0s if the node in input is a vector logical
18276 /// shift by a constant amount which is known to be bigger than or equal
18277 /// to the vector element size in bits.
18278 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18279                                       const X86Subtarget *Subtarget) {
18280   EVT VT = N->getValueType(0);
18281
18282   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18283       (!Subtarget->hasInt256() ||
18284        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18285     return SDValue();
18286
18287   SDValue Amt = N->getOperand(1);
18288   SDLoc DL(N);
18289   if (isSplatVector(Amt.getNode())) {
18290     SDValue SclrAmt = Amt->getOperand(0);
18291     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18292       APInt ShiftAmt = C->getAPIntValue();
18293       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18294
18295       // SSE2/AVX2 logical shifts always return a vector of 0s
18296       // if the shift amount is bigger than or equal to
18297       // the element size. The constant shift amount will be
18298       // encoded as a 8-bit immediate.
18299       if (ShiftAmt.trunc(8).uge(MaxAmount))
18300         return getZeroVector(VT, Subtarget, DAG, DL);
18301     }
18302   }
18303
18304   return SDValue();
18305 }
18306
18307 /// PerformShiftCombine - Combine shifts.
18308 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18309                                    TargetLowering::DAGCombinerInfo &DCI,
18310                                    const X86Subtarget *Subtarget) {
18311   if (N->getOpcode() == ISD::SHL) {
18312     SDValue V = PerformSHLCombine(N, DAG);
18313     if (V.getNode()) return V;
18314   }
18315
18316   if (N->getOpcode() != ISD::SRA) {
18317     // Try to fold this logical shift into a zero vector.
18318     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18319     if (V.getNode()) return V;
18320   }
18321
18322   return SDValue();
18323 }
18324
18325 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18326 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18327 // and friends.  Likewise for OR -> CMPNEQSS.
18328 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18329                             TargetLowering::DAGCombinerInfo &DCI,
18330                             const X86Subtarget *Subtarget) {
18331   unsigned opcode;
18332
18333   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18334   // we're requiring SSE2 for both.
18335   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18336     SDValue N0 = N->getOperand(0);
18337     SDValue N1 = N->getOperand(1);
18338     SDValue CMP0 = N0->getOperand(1);
18339     SDValue CMP1 = N1->getOperand(1);
18340     SDLoc DL(N);
18341
18342     // The SETCCs should both refer to the same CMP.
18343     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18344       return SDValue();
18345
18346     SDValue CMP00 = CMP0->getOperand(0);
18347     SDValue CMP01 = CMP0->getOperand(1);
18348     EVT     VT    = CMP00.getValueType();
18349
18350     if (VT == MVT::f32 || VT == MVT::f64) {
18351       bool ExpectingFlags = false;
18352       // Check for any users that want flags:
18353       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18354            !ExpectingFlags && UI != UE; ++UI)
18355         switch (UI->getOpcode()) {
18356         default:
18357         case ISD::BR_CC:
18358         case ISD::BRCOND:
18359         case ISD::SELECT:
18360           ExpectingFlags = true;
18361           break;
18362         case ISD::CopyToReg:
18363         case ISD::SIGN_EXTEND:
18364         case ISD::ZERO_EXTEND:
18365         case ISD::ANY_EXTEND:
18366           break;
18367         }
18368
18369       if (!ExpectingFlags) {
18370         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18371         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18372
18373         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18374           X86::CondCode tmp = cc0;
18375           cc0 = cc1;
18376           cc1 = tmp;
18377         }
18378
18379         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18380             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18381           // FIXME: need symbolic constants for these magic numbers.
18382           // See X86ATTInstPrinter.cpp:printSSECC().
18383           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18384           if (Subtarget->hasAVX512()) {
18385             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18386                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18387             if (N->getValueType(0) != MVT::i1)
18388               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18389                                  FSetCC);
18390             return FSetCC;
18391           }
18392           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18393                                               CMP00.getValueType(), CMP00, CMP01,
18394                                               DAG.getConstant(x86cc, MVT::i8));
18395
18396           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18397           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18398
18399           if (is64BitFP && !Subtarget->is64Bit()) {
18400             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18401             // 64-bit integer, since that's not a legal type. Since
18402             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18403             // bits, but can do this little dance to extract the lowest 32 bits
18404             // and work with those going forward.
18405             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18406                                            OnesOrZeroesF);
18407             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18408                                            Vector64);
18409             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18410                                         Vector32, DAG.getIntPtrConstant(0));
18411             IntVT = MVT::i32;
18412           }
18413
18414           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18415           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18416                                       DAG.getConstant(1, IntVT));
18417           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18418           return OneBitOfTruth;
18419         }
18420       }
18421     }
18422   }
18423   return SDValue();
18424 }
18425
18426 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18427 /// so it can be folded inside ANDNP.
18428 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18429   EVT VT = N->getValueType(0);
18430
18431   // Match direct AllOnes for 128 and 256-bit vectors
18432   if (ISD::isBuildVectorAllOnes(N))
18433     return true;
18434
18435   // Look through a bit convert.
18436   if (N->getOpcode() == ISD::BITCAST)
18437     N = N->getOperand(0).getNode();
18438
18439   // Sometimes the operand may come from a insert_subvector building a 256-bit
18440   // allones vector
18441   if (VT.is256BitVector() &&
18442       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18443     SDValue V1 = N->getOperand(0);
18444     SDValue V2 = N->getOperand(1);
18445
18446     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18447         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18448         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18449         ISD::isBuildVectorAllOnes(V2.getNode()))
18450       return true;
18451   }
18452
18453   return false;
18454 }
18455
18456 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18457 // register. In most cases we actually compare or select YMM-sized registers
18458 // and mixing the two types creates horrible code. This method optimizes
18459 // some of the transition sequences.
18460 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18461                                  TargetLowering::DAGCombinerInfo &DCI,
18462                                  const X86Subtarget *Subtarget) {
18463   EVT VT = N->getValueType(0);
18464   if (!VT.is256BitVector())
18465     return SDValue();
18466
18467   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18468           N->getOpcode() == ISD::ZERO_EXTEND ||
18469           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18470
18471   SDValue Narrow = N->getOperand(0);
18472   EVT NarrowVT = Narrow->getValueType(0);
18473   if (!NarrowVT.is128BitVector())
18474     return SDValue();
18475
18476   if (Narrow->getOpcode() != ISD::XOR &&
18477       Narrow->getOpcode() != ISD::AND &&
18478       Narrow->getOpcode() != ISD::OR)
18479     return SDValue();
18480
18481   SDValue N0  = Narrow->getOperand(0);
18482   SDValue N1  = Narrow->getOperand(1);
18483   SDLoc DL(Narrow);
18484
18485   // The Left side has to be a trunc.
18486   if (N0.getOpcode() != ISD::TRUNCATE)
18487     return SDValue();
18488
18489   // The type of the truncated inputs.
18490   EVT WideVT = N0->getOperand(0)->getValueType(0);
18491   if (WideVT != VT)
18492     return SDValue();
18493
18494   // The right side has to be a 'trunc' or a constant vector.
18495   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18496   bool RHSConst = (isSplatVector(N1.getNode()) &&
18497                    isa<ConstantSDNode>(N1->getOperand(0)));
18498   if (!RHSTrunc && !RHSConst)
18499     return SDValue();
18500
18501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18502
18503   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18504     return SDValue();
18505
18506   // Set N0 and N1 to hold the inputs to the new wide operation.
18507   N0 = N0->getOperand(0);
18508   if (RHSConst) {
18509     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18510                      N1->getOperand(0));
18511     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18512     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18513   } else if (RHSTrunc) {
18514     N1 = N1->getOperand(0);
18515   }
18516
18517   // Generate the wide operation.
18518   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18519   unsigned Opcode = N->getOpcode();
18520   switch (Opcode) {
18521   case ISD::ANY_EXTEND:
18522     return Op;
18523   case ISD::ZERO_EXTEND: {
18524     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18525     APInt Mask = APInt::getAllOnesValue(InBits);
18526     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18527     return DAG.getNode(ISD::AND, DL, VT,
18528                        Op, DAG.getConstant(Mask, VT));
18529   }
18530   case ISD::SIGN_EXTEND:
18531     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18532                        Op, DAG.getValueType(NarrowVT));
18533   default:
18534     llvm_unreachable("Unexpected opcode");
18535   }
18536 }
18537
18538 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18539                                  TargetLowering::DAGCombinerInfo &DCI,
18540                                  const X86Subtarget *Subtarget) {
18541   EVT VT = N->getValueType(0);
18542   if (DCI.isBeforeLegalizeOps())
18543     return SDValue();
18544
18545   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18546   if (R.getNode())
18547     return R;
18548
18549   // Create BEXTR instructions
18550   // BEXTR is ((X >> imm) & (2**size-1))
18551   if (VT == MVT::i32 || VT == MVT::i64) {
18552     SDValue N0 = N->getOperand(0);
18553     SDValue N1 = N->getOperand(1);
18554     SDLoc DL(N);
18555
18556     // Check for BEXTR.
18557     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18558         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18559       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18560       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18561       if (MaskNode && ShiftNode) {
18562         uint64_t Mask = MaskNode->getZExtValue();
18563         uint64_t Shift = ShiftNode->getZExtValue();
18564         if (isMask_64(Mask)) {
18565           uint64_t MaskSize = CountPopulation_64(Mask);
18566           if (Shift + MaskSize <= VT.getSizeInBits())
18567             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18568                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18569         }
18570       }
18571     } // BEXTR
18572
18573     return SDValue();
18574   }
18575
18576   // Want to form ANDNP nodes:
18577   // 1) In the hopes of then easily combining them with OR and AND nodes
18578   //    to form PBLEND/PSIGN.
18579   // 2) To match ANDN packed intrinsics
18580   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18581     return SDValue();
18582
18583   SDValue N0 = N->getOperand(0);
18584   SDValue N1 = N->getOperand(1);
18585   SDLoc DL(N);
18586
18587   // Check LHS for vnot
18588   if (N0.getOpcode() == ISD::XOR &&
18589       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18590       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18591     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18592
18593   // Check RHS for vnot
18594   if (N1.getOpcode() == ISD::XOR &&
18595       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18596       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18597     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18598
18599   return SDValue();
18600 }
18601
18602 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18603                                 TargetLowering::DAGCombinerInfo &DCI,
18604                                 const X86Subtarget *Subtarget) {
18605   if (DCI.isBeforeLegalizeOps())
18606     return SDValue();
18607
18608   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18609   if (R.getNode())
18610     return R;
18611
18612   SDValue N0 = N->getOperand(0);
18613   SDValue N1 = N->getOperand(1);
18614   EVT VT = N->getValueType(0);
18615
18616   // look for psign/blend
18617   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18618     if (!Subtarget->hasSSSE3() ||
18619         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18620       return SDValue();
18621
18622     // Canonicalize pandn to RHS
18623     if (N0.getOpcode() == X86ISD::ANDNP)
18624       std::swap(N0, N1);
18625     // or (and (m, y), (pandn m, x))
18626     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18627       SDValue Mask = N1.getOperand(0);
18628       SDValue X    = N1.getOperand(1);
18629       SDValue Y;
18630       if (N0.getOperand(0) == Mask)
18631         Y = N0.getOperand(1);
18632       if (N0.getOperand(1) == Mask)
18633         Y = N0.getOperand(0);
18634
18635       // Check to see if the mask appeared in both the AND and ANDNP and
18636       if (!Y.getNode())
18637         return SDValue();
18638
18639       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18640       // Look through mask bitcast.
18641       if (Mask.getOpcode() == ISD::BITCAST)
18642         Mask = Mask.getOperand(0);
18643       if (X.getOpcode() == ISD::BITCAST)
18644         X = X.getOperand(0);
18645       if (Y.getOpcode() == ISD::BITCAST)
18646         Y = Y.getOperand(0);
18647
18648       EVT MaskVT = Mask.getValueType();
18649
18650       // Validate that the Mask operand is a vector sra node.
18651       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18652       // there is no psrai.b
18653       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18654       unsigned SraAmt = ~0;
18655       if (Mask.getOpcode() == ISD::SRA) {
18656         SDValue Amt = Mask.getOperand(1);
18657         if (isSplatVector(Amt.getNode())) {
18658           SDValue SclrAmt = Amt->getOperand(0);
18659           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18660             SraAmt = C->getZExtValue();
18661         }
18662       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18663         SDValue SraC = Mask.getOperand(1);
18664         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18665       }
18666       if ((SraAmt + 1) != EltBits)
18667         return SDValue();
18668
18669       SDLoc DL(N);
18670
18671       // Now we know we at least have a plendvb with the mask val.  See if
18672       // we can form a psignb/w/d.
18673       // psign = x.type == y.type == mask.type && y = sub(0, x);
18674       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18675           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18676           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18677         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18678                "Unsupported VT for PSIGN");
18679         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18680         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18681       }
18682       // PBLENDVB only available on SSE 4.1
18683       if (!Subtarget->hasSSE41())
18684         return SDValue();
18685
18686       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18687
18688       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18689       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18690       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18691       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18692       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18693     }
18694   }
18695
18696   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18697     return SDValue();
18698
18699   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18700   MachineFunction &MF = DAG.getMachineFunction();
18701   bool OptForSize = MF.getFunction()->getAttributes().
18702     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18703
18704   // SHLD/SHRD instructions have lower register pressure, but on some
18705   // platforms they have higher latency than the equivalent
18706   // series of shifts/or that would otherwise be generated.
18707   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18708   // have higher latencies and we are not optimizing for size.
18709   if (!OptForSize && Subtarget->isSHLDSlow())
18710     return SDValue();
18711
18712   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18713     std::swap(N0, N1);
18714   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18715     return SDValue();
18716   if (!N0.hasOneUse() || !N1.hasOneUse())
18717     return SDValue();
18718
18719   SDValue ShAmt0 = N0.getOperand(1);
18720   if (ShAmt0.getValueType() != MVT::i8)
18721     return SDValue();
18722   SDValue ShAmt1 = N1.getOperand(1);
18723   if (ShAmt1.getValueType() != MVT::i8)
18724     return SDValue();
18725   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18726     ShAmt0 = ShAmt0.getOperand(0);
18727   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18728     ShAmt1 = ShAmt1.getOperand(0);
18729
18730   SDLoc DL(N);
18731   unsigned Opc = X86ISD::SHLD;
18732   SDValue Op0 = N0.getOperand(0);
18733   SDValue Op1 = N1.getOperand(0);
18734   if (ShAmt0.getOpcode() == ISD::SUB) {
18735     Opc = X86ISD::SHRD;
18736     std::swap(Op0, Op1);
18737     std::swap(ShAmt0, ShAmt1);
18738   }
18739
18740   unsigned Bits = VT.getSizeInBits();
18741   if (ShAmt1.getOpcode() == ISD::SUB) {
18742     SDValue Sum = ShAmt1.getOperand(0);
18743     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18744       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18745       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18746         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18747       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18748         return DAG.getNode(Opc, DL, VT,
18749                            Op0, Op1,
18750                            DAG.getNode(ISD::TRUNCATE, DL,
18751                                        MVT::i8, ShAmt0));
18752     }
18753   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18754     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18755     if (ShAmt0C &&
18756         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18757       return DAG.getNode(Opc, DL, VT,
18758                          N0.getOperand(0), N1.getOperand(0),
18759                          DAG.getNode(ISD::TRUNCATE, DL,
18760                                        MVT::i8, ShAmt0));
18761   }
18762
18763   return SDValue();
18764 }
18765
18766 // Generate NEG and CMOV for integer abs.
18767 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18768   EVT VT = N->getValueType(0);
18769
18770   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18771   // 8-bit integer abs to NEG and CMOV.
18772   if (VT.isInteger() && VT.getSizeInBits() == 8)
18773     return SDValue();
18774
18775   SDValue N0 = N->getOperand(0);
18776   SDValue N1 = N->getOperand(1);
18777   SDLoc DL(N);
18778
18779   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18780   // and change it to SUB and CMOV.
18781   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18782       N0.getOpcode() == ISD::ADD &&
18783       N0.getOperand(1) == N1 &&
18784       N1.getOpcode() == ISD::SRA &&
18785       N1.getOperand(0) == N0.getOperand(0))
18786     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18787       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18788         // Generate SUB & CMOV.
18789         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18790                                   DAG.getConstant(0, VT), N0.getOperand(0));
18791
18792         SDValue Ops[] = { N0.getOperand(0), Neg,
18793                           DAG.getConstant(X86::COND_GE, MVT::i8),
18794                           SDValue(Neg.getNode(), 1) };
18795         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18796                            Ops, array_lengthof(Ops));
18797       }
18798   return SDValue();
18799 }
18800
18801 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18802 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18803                                  TargetLowering::DAGCombinerInfo &DCI,
18804                                  const X86Subtarget *Subtarget) {
18805   if (DCI.isBeforeLegalizeOps())
18806     return SDValue();
18807
18808   if (Subtarget->hasCMov()) {
18809     SDValue RV = performIntegerAbsCombine(N, DAG);
18810     if (RV.getNode())
18811       return RV;
18812   }
18813
18814   return SDValue();
18815 }
18816
18817 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18818 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18819                                   TargetLowering::DAGCombinerInfo &DCI,
18820                                   const X86Subtarget *Subtarget) {
18821   LoadSDNode *Ld = cast<LoadSDNode>(N);
18822   EVT RegVT = Ld->getValueType(0);
18823   EVT MemVT = Ld->getMemoryVT();
18824   SDLoc dl(Ld);
18825   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18826   unsigned RegSz = RegVT.getSizeInBits();
18827
18828   // On Sandybridge unaligned 256bit loads are inefficient.
18829   ISD::LoadExtType Ext = Ld->getExtensionType();
18830   unsigned Alignment = Ld->getAlignment();
18831   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18832   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18833       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18834     unsigned NumElems = RegVT.getVectorNumElements();
18835     if (NumElems < 2)
18836       return SDValue();
18837
18838     SDValue Ptr = Ld->getBasePtr();
18839     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18840
18841     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18842                                   NumElems/2);
18843     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18844                                 Ld->getPointerInfo(), Ld->isVolatile(),
18845                                 Ld->isNonTemporal(), Ld->isInvariant(),
18846                                 Alignment);
18847     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18848     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18849                                 Ld->getPointerInfo(), Ld->isVolatile(),
18850                                 Ld->isNonTemporal(), Ld->isInvariant(),
18851                                 std::min(16U, Alignment));
18852     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18853                              Load1.getValue(1),
18854                              Load2.getValue(1));
18855
18856     SDValue NewVec = DAG.getUNDEF(RegVT);
18857     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18858     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18859     return DCI.CombineTo(N, NewVec, TF, true);
18860   }
18861
18862   // If this is a vector EXT Load then attempt to optimize it using a
18863   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18864   // expansion is still better than scalar code.
18865   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18866   // emit a shuffle and a arithmetic shift.
18867   // TODO: It is possible to support ZExt by zeroing the undef values
18868   // during the shuffle phase or after the shuffle.
18869   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18870       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18871     assert(MemVT != RegVT && "Cannot extend to the same type");
18872     assert(MemVT.isVector() && "Must load a vector from memory");
18873
18874     unsigned NumElems = RegVT.getVectorNumElements();
18875     unsigned MemSz = MemVT.getSizeInBits();
18876     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18877
18878     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18879       return SDValue();
18880
18881     // All sizes must be a power of two.
18882     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18883       return SDValue();
18884
18885     // Attempt to load the original value using scalar loads.
18886     // Find the largest scalar type that divides the total loaded size.
18887     MVT SclrLoadTy = MVT::i8;
18888     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18889          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18890       MVT Tp = (MVT::SimpleValueType)tp;
18891       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18892         SclrLoadTy = Tp;
18893       }
18894     }
18895
18896     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18897     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18898         (64 <= MemSz))
18899       SclrLoadTy = MVT::f64;
18900
18901     // Calculate the number of scalar loads that we need to perform
18902     // in order to load our vector from memory.
18903     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18904     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18905       return SDValue();
18906
18907     unsigned loadRegZize = RegSz;
18908     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18909       loadRegZize /= 2;
18910
18911     // Represent our vector as a sequence of elements which are the
18912     // largest scalar that we can load.
18913     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18914       loadRegZize/SclrLoadTy.getSizeInBits());
18915
18916     // Represent the data using the same element type that is stored in
18917     // memory. In practice, we ''widen'' MemVT.
18918     EVT WideVecVT =
18919           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18920                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18921
18922     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18923       "Invalid vector type");
18924
18925     // We can't shuffle using an illegal type.
18926     if (!TLI.isTypeLegal(WideVecVT))
18927       return SDValue();
18928
18929     SmallVector<SDValue, 8> Chains;
18930     SDValue Ptr = Ld->getBasePtr();
18931     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18932                                         TLI.getPointerTy());
18933     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18934
18935     for (unsigned i = 0; i < NumLoads; ++i) {
18936       // Perform a single load.
18937       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18938                                        Ptr, Ld->getPointerInfo(),
18939                                        Ld->isVolatile(), Ld->isNonTemporal(),
18940                                        Ld->isInvariant(), Ld->getAlignment());
18941       Chains.push_back(ScalarLoad.getValue(1));
18942       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18943       // another round of DAGCombining.
18944       if (i == 0)
18945         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18946       else
18947         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18948                           ScalarLoad, DAG.getIntPtrConstant(i));
18949
18950       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18951     }
18952
18953     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18954                                Chains.size());
18955
18956     // Bitcast the loaded value to a vector of the original element type, in
18957     // the size of the target vector type.
18958     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18959     unsigned SizeRatio = RegSz/MemSz;
18960
18961     if (Ext == ISD::SEXTLOAD) {
18962       // If we have SSE4.1 we can directly emit a VSEXT node.
18963       if (Subtarget->hasSSE41()) {
18964         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18965         return DCI.CombineTo(N, Sext, TF, true);
18966       }
18967
18968       // Otherwise we'll shuffle the small elements in the high bits of the
18969       // larger type and perform an arithmetic shift. If the shift is not legal
18970       // it's better to scalarize.
18971       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18972         return SDValue();
18973
18974       // Redistribute the loaded elements into the different locations.
18975       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18976       for (unsigned i = 0; i != NumElems; ++i)
18977         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18978
18979       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18980                                            DAG.getUNDEF(WideVecVT),
18981                                            &ShuffleVec[0]);
18982
18983       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18984
18985       // Build the arithmetic shift.
18986       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18987                      MemVT.getVectorElementType().getSizeInBits();
18988       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18989                           DAG.getConstant(Amt, RegVT));
18990
18991       return DCI.CombineTo(N, Shuff, TF, true);
18992     }
18993
18994     // Redistribute the loaded elements into the different locations.
18995     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18996     for (unsigned i = 0; i != NumElems; ++i)
18997       ShuffleVec[i*SizeRatio] = i;
18998
18999     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19000                                          DAG.getUNDEF(WideVecVT),
19001                                          &ShuffleVec[0]);
19002
19003     // Bitcast to the requested type.
19004     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19005     // Replace the original load with the new sequence
19006     // and return the new chain.
19007     return DCI.CombineTo(N, Shuff, TF, true);
19008   }
19009
19010   return SDValue();
19011 }
19012
19013 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19014 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19015                                    const X86Subtarget *Subtarget) {
19016   StoreSDNode *St = cast<StoreSDNode>(N);
19017   EVT VT = St->getValue().getValueType();
19018   EVT StVT = St->getMemoryVT();
19019   SDLoc dl(St);
19020   SDValue StoredVal = St->getOperand(1);
19021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19022
19023   // If we are saving a concatenation of two XMM registers, perform two stores.
19024   // On Sandy Bridge, 256-bit memory operations are executed by two
19025   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19026   // memory  operation.
19027   unsigned Alignment = St->getAlignment();
19028   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19029   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19030       StVT == VT && !IsAligned) {
19031     unsigned NumElems = VT.getVectorNumElements();
19032     if (NumElems < 2)
19033       return SDValue();
19034
19035     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19036     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19037
19038     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19039     SDValue Ptr0 = St->getBasePtr();
19040     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19041
19042     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19043                                 St->getPointerInfo(), St->isVolatile(),
19044                                 St->isNonTemporal(), Alignment);
19045     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19046                                 St->getPointerInfo(), St->isVolatile(),
19047                                 St->isNonTemporal(),
19048                                 std::min(16U, Alignment));
19049     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19050   }
19051
19052   // Optimize trunc store (of multiple scalars) to shuffle and store.
19053   // First, pack all of the elements in one place. Next, store to memory
19054   // in fewer chunks.
19055   if (St->isTruncatingStore() && VT.isVector()) {
19056     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19057     unsigned NumElems = VT.getVectorNumElements();
19058     assert(StVT != VT && "Cannot truncate to the same type");
19059     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19060     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19061
19062     // From, To sizes and ElemCount must be pow of two
19063     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19064     // We are going to use the original vector elt for storing.
19065     // Accumulated smaller vector elements must be a multiple of the store size.
19066     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19067
19068     unsigned SizeRatio  = FromSz / ToSz;
19069
19070     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19071
19072     // Create a type on which we perform the shuffle
19073     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19074             StVT.getScalarType(), NumElems*SizeRatio);
19075
19076     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19077
19078     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19079     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19080     for (unsigned i = 0; i != NumElems; ++i)
19081       ShuffleVec[i] = i * SizeRatio;
19082
19083     // Can't shuffle using an illegal type.
19084     if (!TLI.isTypeLegal(WideVecVT))
19085       return SDValue();
19086
19087     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19088                                          DAG.getUNDEF(WideVecVT),
19089                                          &ShuffleVec[0]);
19090     // At this point all of the data is stored at the bottom of the
19091     // register. We now need to save it to mem.
19092
19093     // Find the largest store unit
19094     MVT StoreType = MVT::i8;
19095     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19096          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19097       MVT Tp = (MVT::SimpleValueType)tp;
19098       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19099         StoreType = Tp;
19100     }
19101
19102     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19103     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19104         (64 <= NumElems * ToSz))
19105       StoreType = MVT::f64;
19106
19107     // Bitcast the original vector into a vector of store-size units
19108     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19109             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19110     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19111     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19112     SmallVector<SDValue, 8> Chains;
19113     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19114                                         TLI.getPointerTy());
19115     SDValue Ptr = St->getBasePtr();
19116
19117     // Perform one or more big stores into memory.
19118     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19119       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19120                                    StoreType, ShuffWide,
19121                                    DAG.getIntPtrConstant(i));
19122       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19123                                 St->getPointerInfo(), St->isVolatile(),
19124                                 St->isNonTemporal(), St->getAlignment());
19125       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19126       Chains.push_back(Ch);
19127     }
19128
19129     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19130                                Chains.size());
19131   }
19132
19133   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19134   // the FP state in cases where an emms may be missing.
19135   // A preferable solution to the general problem is to figure out the right
19136   // places to insert EMMS.  This qualifies as a quick hack.
19137
19138   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19139   if (VT.getSizeInBits() != 64)
19140     return SDValue();
19141
19142   const Function *F = DAG.getMachineFunction().getFunction();
19143   bool NoImplicitFloatOps = F->getAttributes().
19144     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19145   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19146                      && Subtarget->hasSSE2();
19147   if ((VT.isVector() ||
19148        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19149       isa<LoadSDNode>(St->getValue()) &&
19150       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19151       St->getChain().hasOneUse() && !St->isVolatile()) {
19152     SDNode* LdVal = St->getValue().getNode();
19153     LoadSDNode *Ld = 0;
19154     int TokenFactorIndex = -1;
19155     SmallVector<SDValue, 8> Ops;
19156     SDNode* ChainVal = St->getChain().getNode();
19157     // Must be a store of a load.  We currently handle two cases:  the load
19158     // is a direct child, and it's under an intervening TokenFactor.  It is
19159     // possible to dig deeper under nested TokenFactors.
19160     if (ChainVal == LdVal)
19161       Ld = cast<LoadSDNode>(St->getChain());
19162     else if (St->getValue().hasOneUse() &&
19163              ChainVal->getOpcode() == ISD::TokenFactor) {
19164       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19165         if (ChainVal->getOperand(i).getNode() == LdVal) {
19166           TokenFactorIndex = i;
19167           Ld = cast<LoadSDNode>(St->getValue());
19168         } else
19169           Ops.push_back(ChainVal->getOperand(i));
19170       }
19171     }
19172
19173     if (!Ld || !ISD::isNormalLoad(Ld))
19174       return SDValue();
19175
19176     // If this is not the MMX case, i.e. we are just turning i64 load/store
19177     // into f64 load/store, avoid the transformation if there are multiple
19178     // uses of the loaded value.
19179     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19180       return SDValue();
19181
19182     SDLoc LdDL(Ld);
19183     SDLoc StDL(N);
19184     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19185     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19186     // pair instead.
19187     if (Subtarget->is64Bit() || F64IsLegal) {
19188       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19189       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19190                                   Ld->getPointerInfo(), Ld->isVolatile(),
19191                                   Ld->isNonTemporal(), Ld->isInvariant(),
19192                                   Ld->getAlignment());
19193       SDValue NewChain = NewLd.getValue(1);
19194       if (TokenFactorIndex != -1) {
19195         Ops.push_back(NewChain);
19196         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19197                                Ops.size());
19198       }
19199       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19200                           St->getPointerInfo(),
19201                           St->isVolatile(), St->isNonTemporal(),
19202                           St->getAlignment());
19203     }
19204
19205     // Otherwise, lower to two pairs of 32-bit loads / stores.
19206     SDValue LoAddr = Ld->getBasePtr();
19207     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19208                                  DAG.getConstant(4, MVT::i32));
19209
19210     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19211                                Ld->getPointerInfo(),
19212                                Ld->isVolatile(), Ld->isNonTemporal(),
19213                                Ld->isInvariant(), Ld->getAlignment());
19214     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19215                                Ld->getPointerInfo().getWithOffset(4),
19216                                Ld->isVolatile(), Ld->isNonTemporal(),
19217                                Ld->isInvariant(),
19218                                MinAlign(Ld->getAlignment(), 4));
19219
19220     SDValue NewChain = LoLd.getValue(1);
19221     if (TokenFactorIndex != -1) {
19222       Ops.push_back(LoLd);
19223       Ops.push_back(HiLd);
19224       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19225                              Ops.size());
19226     }
19227
19228     LoAddr = St->getBasePtr();
19229     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19230                          DAG.getConstant(4, MVT::i32));
19231
19232     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19233                                 St->getPointerInfo(),
19234                                 St->isVolatile(), St->isNonTemporal(),
19235                                 St->getAlignment());
19236     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19237                                 St->getPointerInfo().getWithOffset(4),
19238                                 St->isVolatile(),
19239                                 St->isNonTemporal(),
19240                                 MinAlign(St->getAlignment(), 4));
19241     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19242   }
19243   return SDValue();
19244 }
19245
19246 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19247 /// and return the operands for the horizontal operation in LHS and RHS.  A
19248 /// horizontal operation performs the binary operation on successive elements
19249 /// of its first operand, then on successive elements of its second operand,
19250 /// returning the resulting values in a vector.  For example, if
19251 ///   A = < float a0, float a1, float a2, float a3 >
19252 /// and
19253 ///   B = < float b0, float b1, float b2, float b3 >
19254 /// then the result of doing a horizontal operation on A and B is
19255 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19256 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19257 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19258 /// set to A, RHS to B, and the routine returns 'true'.
19259 /// Note that the binary operation should have the property that if one of the
19260 /// operands is UNDEF then the result is UNDEF.
19261 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19262   // Look for the following pattern: if
19263   //   A = < float a0, float a1, float a2, float a3 >
19264   //   B = < float b0, float b1, float b2, float b3 >
19265   // and
19266   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19267   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19268   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19269   // which is A horizontal-op B.
19270
19271   // At least one of the operands should be a vector shuffle.
19272   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19273       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19274     return false;
19275
19276   MVT VT = LHS.getSimpleValueType();
19277
19278   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19279          "Unsupported vector type for horizontal add/sub");
19280
19281   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19282   // operate independently on 128-bit lanes.
19283   unsigned NumElts = VT.getVectorNumElements();
19284   unsigned NumLanes = VT.getSizeInBits()/128;
19285   unsigned NumLaneElts = NumElts / NumLanes;
19286   assert((NumLaneElts % 2 == 0) &&
19287          "Vector type should have an even number of elements in each lane");
19288   unsigned HalfLaneElts = NumLaneElts/2;
19289
19290   // View LHS in the form
19291   //   LHS = VECTOR_SHUFFLE A, B, LMask
19292   // If LHS is not a shuffle then pretend it is the shuffle
19293   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19294   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19295   // type VT.
19296   SDValue A, B;
19297   SmallVector<int, 16> LMask(NumElts);
19298   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19299     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19300       A = LHS.getOperand(0);
19301     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19302       B = LHS.getOperand(1);
19303     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19304     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19305   } else {
19306     if (LHS.getOpcode() != ISD::UNDEF)
19307       A = LHS;
19308     for (unsigned i = 0; i != NumElts; ++i)
19309       LMask[i] = i;
19310   }
19311
19312   // Likewise, view RHS in the form
19313   //   RHS = VECTOR_SHUFFLE C, D, RMask
19314   SDValue C, D;
19315   SmallVector<int, 16> RMask(NumElts);
19316   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19317     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19318       C = RHS.getOperand(0);
19319     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19320       D = RHS.getOperand(1);
19321     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19322     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19323   } else {
19324     if (RHS.getOpcode() != ISD::UNDEF)
19325       C = RHS;
19326     for (unsigned i = 0; i != NumElts; ++i)
19327       RMask[i] = i;
19328   }
19329
19330   // Check that the shuffles are both shuffling the same vectors.
19331   if (!(A == C && B == D) && !(A == D && B == C))
19332     return false;
19333
19334   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19335   if (!A.getNode() && !B.getNode())
19336     return false;
19337
19338   // If A and B occur in reverse order in RHS, then "swap" them (which means
19339   // rewriting the mask).
19340   if (A != C)
19341     CommuteVectorShuffleMask(RMask, NumElts);
19342
19343   // At this point LHS and RHS are equivalent to
19344   //   LHS = VECTOR_SHUFFLE A, B, LMask
19345   //   RHS = VECTOR_SHUFFLE A, B, RMask
19346   // Check that the masks correspond to performing a horizontal operation.
19347   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19348     for (unsigned i = 0; i != NumLaneElts; ++i) {
19349       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19350
19351       // Ignore any UNDEF components.
19352       if (LIdx < 0 || RIdx < 0 ||
19353           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19354           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19355         continue;
19356
19357       // Check that successive elements are being operated on.  If not, this is
19358       // not a horizontal operation.
19359       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19360       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19361       if (!(LIdx == Index && RIdx == Index + 1) &&
19362           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19363         return false;
19364     }
19365   }
19366
19367   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19368   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19369   return true;
19370 }
19371
19372 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19373 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19374                                   const X86Subtarget *Subtarget) {
19375   EVT VT = N->getValueType(0);
19376   SDValue LHS = N->getOperand(0);
19377   SDValue RHS = N->getOperand(1);
19378
19379   // Try to synthesize horizontal adds from adds of shuffles.
19380   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19381        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19382       isHorizontalBinOp(LHS, RHS, true))
19383     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19384   return SDValue();
19385 }
19386
19387 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19388 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19389                                   const X86Subtarget *Subtarget) {
19390   EVT VT = N->getValueType(0);
19391   SDValue LHS = N->getOperand(0);
19392   SDValue RHS = N->getOperand(1);
19393
19394   // Try to synthesize horizontal subs from subs of shuffles.
19395   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19396        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19397       isHorizontalBinOp(LHS, RHS, false))
19398     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19399   return SDValue();
19400 }
19401
19402 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19403 /// X86ISD::FXOR nodes.
19404 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19405   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19406   // F[X]OR(0.0, x) -> x
19407   // F[X]OR(x, 0.0) -> x
19408   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19409     if (C->getValueAPF().isPosZero())
19410       return N->getOperand(1);
19411   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19412     if (C->getValueAPF().isPosZero())
19413       return N->getOperand(0);
19414   return SDValue();
19415 }
19416
19417 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19418 /// X86ISD::FMAX nodes.
19419 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19420   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19421
19422   // Only perform optimizations if UnsafeMath is used.
19423   if (!DAG.getTarget().Options.UnsafeFPMath)
19424     return SDValue();
19425
19426   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19427   // into FMINC and FMAXC, which are Commutative operations.
19428   unsigned NewOp = 0;
19429   switch (N->getOpcode()) {
19430     default: llvm_unreachable("unknown opcode");
19431     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19432     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19433   }
19434
19435   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19436                      N->getOperand(0), N->getOperand(1));
19437 }
19438
19439 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19440 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19441   // FAND(0.0, x) -> 0.0
19442   // FAND(x, 0.0) -> 0.0
19443   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19444     if (C->getValueAPF().isPosZero())
19445       return N->getOperand(0);
19446   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19447     if (C->getValueAPF().isPosZero())
19448       return N->getOperand(1);
19449   return SDValue();
19450 }
19451
19452 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19453 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19454   // FANDN(x, 0.0) -> 0.0
19455   // FANDN(0.0, x) -> x
19456   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19457     if (C->getValueAPF().isPosZero())
19458       return N->getOperand(1);
19459   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19460     if (C->getValueAPF().isPosZero())
19461       return N->getOperand(1);
19462   return SDValue();
19463 }
19464
19465 static SDValue PerformBTCombine(SDNode *N,
19466                                 SelectionDAG &DAG,
19467                                 TargetLowering::DAGCombinerInfo &DCI) {
19468   // BT ignores high bits in the bit index operand.
19469   SDValue Op1 = N->getOperand(1);
19470   if (Op1.hasOneUse()) {
19471     unsigned BitWidth = Op1.getValueSizeInBits();
19472     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19473     APInt KnownZero, KnownOne;
19474     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19475                                           !DCI.isBeforeLegalizeOps());
19476     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19477     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19478         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19479       DCI.CommitTargetLoweringOpt(TLO);
19480   }
19481   return SDValue();
19482 }
19483
19484 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19485   SDValue Op = N->getOperand(0);
19486   if (Op.getOpcode() == ISD::BITCAST)
19487     Op = Op.getOperand(0);
19488   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19489   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19490       VT.getVectorElementType().getSizeInBits() ==
19491       OpVT.getVectorElementType().getSizeInBits()) {
19492     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19493   }
19494   return SDValue();
19495 }
19496
19497 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19498                                                const X86Subtarget *Subtarget) {
19499   EVT VT = N->getValueType(0);
19500   if (!VT.isVector())
19501     return SDValue();
19502
19503   SDValue N0 = N->getOperand(0);
19504   SDValue N1 = N->getOperand(1);
19505   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19506   SDLoc dl(N);
19507
19508   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19509   // both SSE and AVX2 since there is no sign-extended shift right
19510   // operation on a vector with 64-bit elements.
19511   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19512   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19513   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19514       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19515     SDValue N00 = N0.getOperand(0);
19516
19517     // EXTLOAD has a better solution on AVX2,
19518     // it may be replaced with X86ISD::VSEXT node.
19519     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19520       if (!ISD::isNormalLoad(N00.getNode()))
19521         return SDValue();
19522
19523     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19524         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19525                                   N00, N1);
19526       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19527     }
19528   }
19529   return SDValue();
19530 }
19531
19532 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19533                                   TargetLowering::DAGCombinerInfo &DCI,
19534                                   const X86Subtarget *Subtarget) {
19535   if (!DCI.isBeforeLegalizeOps())
19536     return SDValue();
19537
19538   if (!Subtarget->hasFp256())
19539     return SDValue();
19540
19541   EVT VT = N->getValueType(0);
19542   if (VT.isVector() && VT.getSizeInBits() == 256) {
19543     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19544     if (R.getNode())
19545       return R;
19546   }
19547
19548   return SDValue();
19549 }
19550
19551 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19552                                  const X86Subtarget* Subtarget) {
19553   SDLoc dl(N);
19554   EVT VT = N->getValueType(0);
19555
19556   // Let legalize expand this if it isn't a legal type yet.
19557   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19558     return SDValue();
19559
19560   EVT ScalarVT = VT.getScalarType();
19561   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19562       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19563     return SDValue();
19564
19565   SDValue A = N->getOperand(0);
19566   SDValue B = N->getOperand(1);
19567   SDValue C = N->getOperand(2);
19568
19569   bool NegA = (A.getOpcode() == ISD::FNEG);
19570   bool NegB = (B.getOpcode() == ISD::FNEG);
19571   bool NegC = (C.getOpcode() == ISD::FNEG);
19572
19573   // Negative multiplication when NegA xor NegB
19574   bool NegMul = (NegA != NegB);
19575   if (NegA)
19576     A = A.getOperand(0);
19577   if (NegB)
19578     B = B.getOperand(0);
19579   if (NegC)
19580     C = C.getOperand(0);
19581
19582   unsigned Opcode;
19583   if (!NegMul)
19584     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19585   else
19586     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19587
19588   return DAG.getNode(Opcode, dl, VT, A, B, C);
19589 }
19590
19591 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19592                                   TargetLowering::DAGCombinerInfo &DCI,
19593                                   const X86Subtarget *Subtarget) {
19594   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19595   //           (and (i32 x86isd::setcc_carry), 1)
19596   // This eliminates the zext. This transformation is necessary because
19597   // ISD::SETCC is always legalized to i8.
19598   SDLoc dl(N);
19599   SDValue N0 = N->getOperand(0);
19600   EVT VT = N->getValueType(0);
19601
19602   if (N0.getOpcode() == ISD::AND &&
19603       N0.hasOneUse() &&
19604       N0.getOperand(0).hasOneUse()) {
19605     SDValue N00 = N0.getOperand(0);
19606     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19607       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19608       if (!C || C->getZExtValue() != 1)
19609         return SDValue();
19610       return DAG.getNode(ISD::AND, dl, VT,
19611                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19612                                      N00.getOperand(0), N00.getOperand(1)),
19613                          DAG.getConstant(1, VT));
19614     }
19615   }
19616
19617   if (N0.getOpcode() == ISD::TRUNCATE &&
19618       N0.hasOneUse() &&
19619       N0.getOperand(0).hasOneUse()) {
19620     SDValue N00 = N0.getOperand(0);
19621     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19622       return DAG.getNode(ISD::AND, dl, VT,
19623                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19624                                      N00.getOperand(0), N00.getOperand(1)),
19625                          DAG.getConstant(1, VT));
19626     }
19627   }
19628   if (VT.is256BitVector()) {
19629     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19630     if (R.getNode())
19631       return R;
19632   }
19633
19634   return SDValue();
19635 }
19636
19637 // Optimize x == -y --> x+y == 0
19638 //          x != -y --> x+y != 0
19639 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19640                                       const X86Subtarget* Subtarget) {
19641   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19642   SDValue LHS = N->getOperand(0);
19643   SDValue RHS = N->getOperand(1);
19644   EVT VT = N->getValueType(0);
19645   SDLoc DL(N);
19646
19647   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19648     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19649       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19650         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19651                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19652         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19653                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19654       }
19655   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19656     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19657       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19658         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19659                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19660         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19661                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19662       }
19663
19664   if (VT.getScalarType() == MVT::i1) {
19665     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19666       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19667     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19668     if (!IsSEXT0 && !IsVZero0)
19669       return SDValue();
19670     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19671       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19672     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19673
19674     if (!IsSEXT1 && !IsVZero1)
19675       return SDValue();
19676
19677     if (IsSEXT0 && IsVZero1) {
19678       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19679       if (CC == ISD::SETEQ)
19680         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19681       return LHS.getOperand(0);
19682     }
19683     if (IsSEXT1 && IsVZero0) {
19684       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19685       if (CC == ISD::SETEQ)
19686         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19687       return RHS.getOperand(0);
19688     }
19689   }
19690
19691   return SDValue();
19692 }
19693
19694 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19695 // as "sbb reg,reg", since it can be extended without zext and produces
19696 // an all-ones bit which is more useful than 0/1 in some cases.
19697 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19698                                MVT VT) {
19699   if (VT == MVT::i8)
19700     return DAG.getNode(ISD::AND, DL, VT,
19701                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19702                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19703                        DAG.getConstant(1, VT));
19704   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19705   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19706                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19707                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19708 }
19709
19710 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19711 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19712                                    TargetLowering::DAGCombinerInfo &DCI,
19713                                    const X86Subtarget *Subtarget) {
19714   SDLoc DL(N);
19715   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19716   SDValue EFLAGS = N->getOperand(1);
19717
19718   if (CC == X86::COND_A) {
19719     // Try to convert COND_A into COND_B in an attempt to facilitate
19720     // materializing "setb reg".
19721     //
19722     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19723     // cannot take an immediate as its first operand.
19724     //
19725     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19726         EFLAGS.getValueType().isInteger() &&
19727         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19728       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19729                                    EFLAGS.getNode()->getVTList(),
19730                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19731       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19732       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19733     }
19734   }
19735
19736   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19737   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19738   // cases.
19739   if (CC == X86::COND_B)
19740     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19741
19742   SDValue Flags;
19743
19744   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19745   if (Flags.getNode()) {
19746     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19747     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19748   }
19749
19750   return SDValue();
19751 }
19752
19753 // Optimize branch condition evaluation.
19754 //
19755 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19756                                     TargetLowering::DAGCombinerInfo &DCI,
19757                                     const X86Subtarget *Subtarget) {
19758   SDLoc DL(N);
19759   SDValue Chain = N->getOperand(0);
19760   SDValue Dest = N->getOperand(1);
19761   SDValue EFLAGS = N->getOperand(3);
19762   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19763
19764   SDValue Flags;
19765
19766   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19767   if (Flags.getNode()) {
19768     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19769     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19770                        Flags);
19771   }
19772
19773   return SDValue();
19774 }
19775
19776 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19777                                         const X86TargetLowering *XTLI) {
19778   SDValue Op0 = N->getOperand(0);
19779   EVT InVT = Op0->getValueType(0);
19780
19781   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19782   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19783     SDLoc dl(N);
19784     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19785     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19786     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19787   }
19788
19789   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19790   // a 32-bit target where SSE doesn't support i64->FP operations.
19791   if (Op0.getOpcode() == ISD::LOAD) {
19792     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19793     EVT VT = Ld->getValueType(0);
19794     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19795         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19796         !XTLI->getSubtarget()->is64Bit() &&
19797         VT == MVT::i64) {
19798       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19799                                           Ld->getChain(), Op0, DAG);
19800       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19801       return FILDChain;
19802     }
19803   }
19804   return SDValue();
19805 }
19806
19807 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19808 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19809                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19810   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19811   // the result is either zero or one (depending on the input carry bit).
19812   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19813   if (X86::isZeroNode(N->getOperand(0)) &&
19814       X86::isZeroNode(N->getOperand(1)) &&
19815       // We don't have a good way to replace an EFLAGS use, so only do this when
19816       // dead right now.
19817       SDValue(N, 1).use_empty()) {
19818     SDLoc DL(N);
19819     EVT VT = N->getValueType(0);
19820     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19821     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19822                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19823                                            DAG.getConstant(X86::COND_B,MVT::i8),
19824                                            N->getOperand(2)),
19825                                DAG.getConstant(1, VT));
19826     return DCI.CombineTo(N, Res1, CarryOut);
19827   }
19828
19829   return SDValue();
19830 }
19831
19832 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19833 //      (add Y, (setne X, 0)) -> sbb -1, Y
19834 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19835 //      (sub (setne X, 0), Y) -> adc -1, Y
19836 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19837   SDLoc DL(N);
19838
19839   // Look through ZExts.
19840   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19841   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19842     return SDValue();
19843
19844   SDValue SetCC = Ext.getOperand(0);
19845   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19846     return SDValue();
19847
19848   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19849   if (CC != X86::COND_E && CC != X86::COND_NE)
19850     return SDValue();
19851
19852   SDValue Cmp = SetCC.getOperand(1);
19853   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19854       !X86::isZeroNode(Cmp.getOperand(1)) ||
19855       !Cmp.getOperand(0).getValueType().isInteger())
19856     return SDValue();
19857
19858   SDValue CmpOp0 = Cmp.getOperand(0);
19859   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19860                                DAG.getConstant(1, CmpOp0.getValueType()));
19861
19862   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19863   if (CC == X86::COND_NE)
19864     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19865                        DL, OtherVal.getValueType(), OtherVal,
19866                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19867   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19868                      DL, OtherVal.getValueType(), OtherVal,
19869                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19870 }
19871
19872 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19873 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19874                                  const X86Subtarget *Subtarget) {
19875   EVT VT = N->getValueType(0);
19876   SDValue Op0 = N->getOperand(0);
19877   SDValue Op1 = N->getOperand(1);
19878
19879   // Try to synthesize horizontal adds from adds of shuffles.
19880   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19881        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19882       isHorizontalBinOp(Op0, Op1, true))
19883     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19884
19885   return OptimizeConditionalInDecrement(N, DAG);
19886 }
19887
19888 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19889                                  const X86Subtarget *Subtarget) {
19890   SDValue Op0 = N->getOperand(0);
19891   SDValue Op1 = N->getOperand(1);
19892
19893   // X86 can't encode an immediate LHS of a sub. See if we can push the
19894   // negation into a preceding instruction.
19895   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19896     // If the RHS of the sub is a XOR with one use and a constant, invert the
19897     // immediate. Then add one to the LHS of the sub so we can turn
19898     // X-Y -> X+~Y+1, saving one register.
19899     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19900         isa<ConstantSDNode>(Op1.getOperand(1))) {
19901       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19902       EVT VT = Op0.getValueType();
19903       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19904                                    Op1.getOperand(0),
19905                                    DAG.getConstant(~XorC, VT));
19906       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19907                          DAG.getConstant(C->getAPIntValue()+1, VT));
19908     }
19909   }
19910
19911   // Try to synthesize horizontal adds from adds of shuffles.
19912   EVT VT = N->getValueType(0);
19913   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19914        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19915       isHorizontalBinOp(Op0, Op1, true))
19916     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19917
19918   return OptimizeConditionalInDecrement(N, DAG);
19919 }
19920
19921 /// performVZEXTCombine - Performs build vector combines
19922 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19923                                         TargetLowering::DAGCombinerInfo &DCI,
19924                                         const X86Subtarget *Subtarget) {
19925   // (vzext (bitcast (vzext (x)) -> (vzext x)
19926   SDValue In = N->getOperand(0);
19927   while (In.getOpcode() == ISD::BITCAST)
19928     In = In.getOperand(0);
19929
19930   if (In.getOpcode() != X86ISD::VZEXT)
19931     return SDValue();
19932
19933   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19934                      In.getOperand(0));
19935 }
19936
19937 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19938                                              DAGCombinerInfo &DCI) const {
19939   SelectionDAG &DAG = DCI.DAG;
19940   switch (N->getOpcode()) {
19941   default: break;
19942   case ISD::EXTRACT_VECTOR_ELT:
19943     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19944   case ISD::VSELECT:
19945   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19946   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19947   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19948   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19949   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19950   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19951   case ISD::SHL:
19952   case ISD::SRA:
19953   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19954   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19955   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19956   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19957   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19958   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19959   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19960   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19961   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19962   case X86ISD::FXOR:
19963   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19964   case X86ISD::FMIN:
19965   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19966   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19967   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19968   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19969   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19970   case ISD::ANY_EXTEND:
19971   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19972   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19973   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19974   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19975   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19976   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19977   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19978   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19979   case X86ISD::SHUFP:       // Handle all target specific shuffles
19980   case X86ISD::PALIGNR:
19981   case X86ISD::UNPCKH:
19982   case X86ISD::UNPCKL:
19983   case X86ISD::MOVHLPS:
19984   case X86ISD::MOVLHPS:
19985   case X86ISD::PSHUFD:
19986   case X86ISD::PSHUFHW:
19987   case X86ISD::PSHUFLW:
19988   case X86ISD::MOVSS:
19989   case X86ISD::MOVSD:
19990   case X86ISD::VPERMILP:
19991   case X86ISD::VPERM2X128:
19992   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19993   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19994   }
19995
19996   return SDValue();
19997 }
19998
19999 /// isTypeDesirableForOp - Return true if the target has native support for
20000 /// the specified value type and it is 'desirable' to use the type for the
20001 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20002 /// instruction encodings are longer and some i16 instructions are slow.
20003 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20004   if (!isTypeLegal(VT))
20005     return false;
20006   if (VT != MVT::i16)
20007     return true;
20008
20009   switch (Opc) {
20010   default:
20011     return true;
20012   case ISD::LOAD:
20013   case ISD::SIGN_EXTEND:
20014   case ISD::ZERO_EXTEND:
20015   case ISD::ANY_EXTEND:
20016   case ISD::SHL:
20017   case ISD::SRL:
20018   case ISD::SUB:
20019   case ISD::ADD:
20020   case ISD::MUL:
20021   case ISD::AND:
20022   case ISD::OR:
20023   case ISD::XOR:
20024     return false;
20025   }
20026 }
20027
20028 /// IsDesirableToPromoteOp - This method query the target whether it is
20029 /// beneficial for dag combiner to promote the specified node. If true, it
20030 /// should return the desired promotion type by reference.
20031 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20032   EVT VT = Op.getValueType();
20033   if (VT != MVT::i16)
20034     return false;
20035
20036   bool Promote = false;
20037   bool Commute = false;
20038   switch (Op.getOpcode()) {
20039   default: break;
20040   case ISD::LOAD: {
20041     LoadSDNode *LD = cast<LoadSDNode>(Op);
20042     // If the non-extending load has a single use and it's not live out, then it
20043     // might be folded.
20044     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20045                                                      Op.hasOneUse()*/) {
20046       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20047              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20048         // The only case where we'd want to promote LOAD (rather then it being
20049         // promoted as an operand is when it's only use is liveout.
20050         if (UI->getOpcode() != ISD::CopyToReg)
20051           return false;
20052       }
20053     }
20054     Promote = true;
20055     break;
20056   }
20057   case ISD::SIGN_EXTEND:
20058   case ISD::ZERO_EXTEND:
20059   case ISD::ANY_EXTEND:
20060     Promote = true;
20061     break;
20062   case ISD::SHL:
20063   case ISD::SRL: {
20064     SDValue N0 = Op.getOperand(0);
20065     // Look out for (store (shl (load), x)).
20066     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20067       return false;
20068     Promote = true;
20069     break;
20070   }
20071   case ISD::ADD:
20072   case ISD::MUL:
20073   case ISD::AND:
20074   case ISD::OR:
20075   case ISD::XOR:
20076     Commute = true;
20077     // fallthrough
20078   case ISD::SUB: {
20079     SDValue N0 = Op.getOperand(0);
20080     SDValue N1 = Op.getOperand(1);
20081     if (!Commute && MayFoldLoad(N1))
20082       return false;
20083     // Avoid disabling potential load folding opportunities.
20084     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20085       return false;
20086     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20087       return false;
20088     Promote = true;
20089   }
20090   }
20091
20092   PVT = MVT::i32;
20093   return Promote;
20094 }
20095
20096 //===----------------------------------------------------------------------===//
20097 //                           X86 Inline Assembly Support
20098 //===----------------------------------------------------------------------===//
20099
20100 namespace {
20101   // Helper to match a string separated by whitespace.
20102   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20103     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20104
20105     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20106       StringRef piece(*args[i]);
20107       if (!s.startswith(piece)) // Check if the piece matches.
20108         return false;
20109
20110       s = s.substr(piece.size());
20111       StringRef::size_type pos = s.find_first_not_of(" \t");
20112       if (pos == 0) // We matched a prefix.
20113         return false;
20114
20115       s = s.substr(pos);
20116     }
20117
20118     return s.empty();
20119   }
20120   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20121 }
20122
20123 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20124
20125   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20126     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20127         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20128         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20129
20130       if (AsmPieces.size() == 3)
20131         return true;
20132       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20133         return true;
20134     }
20135   }
20136   return false;
20137 }
20138
20139 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20140   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20141
20142   std::string AsmStr = IA->getAsmString();
20143
20144   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20145   if (!Ty || Ty->getBitWidth() % 16 != 0)
20146     return false;
20147
20148   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20149   SmallVector<StringRef, 4> AsmPieces;
20150   SplitString(AsmStr, AsmPieces, ";\n");
20151
20152   switch (AsmPieces.size()) {
20153   default: return false;
20154   case 1:
20155     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20156     // we will turn this bswap into something that will be lowered to logical
20157     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20158     // lower so don't worry about this.
20159     // bswap $0
20160     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20161         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20162         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20163         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20164         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20165         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20166       // No need to check constraints, nothing other than the equivalent of
20167       // "=r,0" would be valid here.
20168       return IntrinsicLowering::LowerToByteSwap(CI);
20169     }
20170
20171     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20172     if (CI->getType()->isIntegerTy(16) &&
20173         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20174         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20175          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20176       AsmPieces.clear();
20177       const std::string &ConstraintsStr = IA->getConstraintString();
20178       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20179       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20180       if (clobbersFlagRegisters(AsmPieces))
20181         return IntrinsicLowering::LowerToByteSwap(CI);
20182     }
20183     break;
20184   case 3:
20185     if (CI->getType()->isIntegerTy(32) &&
20186         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20187         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20188         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20189         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20190       AsmPieces.clear();
20191       const std::string &ConstraintsStr = IA->getConstraintString();
20192       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20193       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20194       if (clobbersFlagRegisters(AsmPieces))
20195         return IntrinsicLowering::LowerToByteSwap(CI);
20196     }
20197
20198     if (CI->getType()->isIntegerTy(64)) {
20199       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20200       if (Constraints.size() >= 2 &&
20201           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20202           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20203         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20204         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20205             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20206             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20207           return IntrinsicLowering::LowerToByteSwap(CI);
20208       }
20209     }
20210     break;
20211   }
20212   return false;
20213 }
20214
20215 /// getConstraintType - Given a constraint letter, return the type of
20216 /// constraint it is for this target.
20217 X86TargetLowering::ConstraintType
20218 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20219   if (Constraint.size() == 1) {
20220     switch (Constraint[0]) {
20221     case 'R':
20222     case 'q':
20223     case 'Q':
20224     case 'f':
20225     case 't':
20226     case 'u':
20227     case 'y':
20228     case 'x':
20229     case 'Y':
20230     case 'l':
20231       return C_RegisterClass;
20232     case 'a':
20233     case 'b':
20234     case 'c':
20235     case 'd':
20236     case 'S':
20237     case 'D':
20238     case 'A':
20239       return C_Register;
20240     case 'I':
20241     case 'J':
20242     case 'K':
20243     case 'L':
20244     case 'M':
20245     case 'N':
20246     case 'G':
20247     case 'C':
20248     case 'e':
20249     case 'Z':
20250       return C_Other;
20251     default:
20252       break;
20253     }
20254   }
20255   return TargetLowering::getConstraintType(Constraint);
20256 }
20257
20258 /// Examine constraint type and operand type and determine a weight value.
20259 /// This object must already have been set up with the operand type
20260 /// and the current alternative constraint selected.
20261 TargetLowering::ConstraintWeight
20262   X86TargetLowering::getSingleConstraintMatchWeight(
20263     AsmOperandInfo &info, const char *constraint) const {
20264   ConstraintWeight weight = CW_Invalid;
20265   Value *CallOperandVal = info.CallOperandVal;
20266     // If we don't have a value, we can't do a match,
20267     // but allow it at the lowest weight.
20268   if (CallOperandVal == NULL)
20269     return CW_Default;
20270   Type *type = CallOperandVal->getType();
20271   // Look at the constraint type.
20272   switch (*constraint) {
20273   default:
20274     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20275   case 'R':
20276   case 'q':
20277   case 'Q':
20278   case 'a':
20279   case 'b':
20280   case 'c':
20281   case 'd':
20282   case 'S':
20283   case 'D':
20284   case 'A':
20285     if (CallOperandVal->getType()->isIntegerTy())
20286       weight = CW_SpecificReg;
20287     break;
20288   case 'f':
20289   case 't':
20290   case 'u':
20291     if (type->isFloatingPointTy())
20292       weight = CW_SpecificReg;
20293     break;
20294   case 'y':
20295     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20296       weight = CW_SpecificReg;
20297     break;
20298   case 'x':
20299   case 'Y':
20300     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20301         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20302       weight = CW_Register;
20303     break;
20304   case 'I':
20305     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20306       if (C->getZExtValue() <= 31)
20307         weight = CW_Constant;
20308     }
20309     break;
20310   case 'J':
20311     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20312       if (C->getZExtValue() <= 63)
20313         weight = CW_Constant;
20314     }
20315     break;
20316   case 'K':
20317     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20318       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20319         weight = CW_Constant;
20320     }
20321     break;
20322   case 'L':
20323     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20324       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20325         weight = CW_Constant;
20326     }
20327     break;
20328   case 'M':
20329     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20330       if (C->getZExtValue() <= 3)
20331         weight = CW_Constant;
20332     }
20333     break;
20334   case 'N':
20335     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20336       if (C->getZExtValue() <= 0xff)
20337         weight = CW_Constant;
20338     }
20339     break;
20340   case 'G':
20341   case 'C':
20342     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20343       weight = CW_Constant;
20344     }
20345     break;
20346   case 'e':
20347     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20348       if ((C->getSExtValue() >= -0x80000000LL) &&
20349           (C->getSExtValue() <= 0x7fffffffLL))
20350         weight = CW_Constant;
20351     }
20352     break;
20353   case 'Z':
20354     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20355       if (C->getZExtValue() <= 0xffffffff)
20356         weight = CW_Constant;
20357     }
20358     break;
20359   }
20360   return weight;
20361 }
20362
20363 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20364 /// with another that has more specific requirements based on the type of the
20365 /// corresponding operand.
20366 const char *X86TargetLowering::
20367 LowerXConstraint(EVT ConstraintVT) const {
20368   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20369   // 'f' like normal targets.
20370   if (ConstraintVT.isFloatingPoint()) {
20371     if (Subtarget->hasSSE2())
20372       return "Y";
20373     if (Subtarget->hasSSE1())
20374       return "x";
20375   }
20376
20377   return TargetLowering::LowerXConstraint(ConstraintVT);
20378 }
20379
20380 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20381 /// vector.  If it is invalid, don't add anything to Ops.
20382 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20383                                                      std::string &Constraint,
20384                                                      std::vector<SDValue>&Ops,
20385                                                      SelectionDAG &DAG) const {
20386   SDValue Result(0, 0);
20387
20388   // Only support length 1 constraints for now.
20389   if (Constraint.length() > 1) return;
20390
20391   char ConstraintLetter = Constraint[0];
20392   switch (ConstraintLetter) {
20393   default: break;
20394   case 'I':
20395     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20396       if (C->getZExtValue() <= 31) {
20397         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20398         break;
20399       }
20400     }
20401     return;
20402   case 'J':
20403     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20404       if (C->getZExtValue() <= 63) {
20405         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20406         break;
20407       }
20408     }
20409     return;
20410   case 'K':
20411     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20412       if (isInt<8>(C->getSExtValue())) {
20413         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20414         break;
20415       }
20416     }
20417     return;
20418   case 'N':
20419     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20420       if (C->getZExtValue() <= 255) {
20421         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20422         break;
20423       }
20424     }
20425     return;
20426   case 'e': {
20427     // 32-bit signed value
20428     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20429       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20430                                            C->getSExtValue())) {
20431         // Widen to 64 bits here to get it sign extended.
20432         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20433         break;
20434       }
20435     // FIXME gcc accepts some relocatable values here too, but only in certain
20436     // memory models; it's complicated.
20437     }
20438     return;
20439   }
20440   case 'Z': {
20441     // 32-bit unsigned value
20442     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20443       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20444                                            C->getZExtValue())) {
20445         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20446         break;
20447       }
20448     }
20449     // FIXME gcc accepts some relocatable values here too, but only in certain
20450     // memory models; it's complicated.
20451     return;
20452   }
20453   case 'i': {
20454     // Literal immediates are always ok.
20455     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20456       // Widen to 64 bits here to get it sign extended.
20457       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20458       break;
20459     }
20460
20461     // In any sort of PIC mode addresses need to be computed at runtime by
20462     // adding in a register or some sort of table lookup.  These can't
20463     // be used as immediates.
20464     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20465       return;
20466
20467     // If we are in non-pic codegen mode, we allow the address of a global (with
20468     // an optional displacement) to be used with 'i'.
20469     GlobalAddressSDNode *GA = 0;
20470     int64_t Offset = 0;
20471
20472     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20473     while (1) {
20474       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20475         Offset += GA->getOffset();
20476         break;
20477       } else if (Op.getOpcode() == ISD::ADD) {
20478         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20479           Offset += C->getZExtValue();
20480           Op = Op.getOperand(0);
20481           continue;
20482         }
20483       } else if (Op.getOpcode() == ISD::SUB) {
20484         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20485           Offset += -C->getZExtValue();
20486           Op = Op.getOperand(0);
20487           continue;
20488         }
20489       }
20490
20491       // Otherwise, this isn't something we can handle, reject it.
20492       return;
20493     }
20494
20495     const GlobalValue *GV = GA->getGlobal();
20496     // If we require an extra load to get this address, as in PIC mode, we
20497     // can't accept it.
20498     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20499                                                         getTargetMachine())))
20500       return;
20501
20502     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20503                                         GA->getValueType(0), Offset);
20504     break;
20505   }
20506   }
20507
20508   if (Result.getNode()) {
20509     Ops.push_back(Result);
20510     return;
20511   }
20512   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20513 }
20514
20515 std::pair<unsigned, const TargetRegisterClass*>
20516 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20517                                                 MVT VT) const {
20518   // First, see if this is a constraint that directly corresponds to an LLVM
20519   // register class.
20520   if (Constraint.size() == 1) {
20521     // GCC Constraint Letters
20522     switch (Constraint[0]) {
20523     default: break;
20524       // TODO: Slight differences here in allocation order and leaving
20525       // RIP in the class. Do they matter any more here than they do
20526       // in the normal allocation?
20527     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20528       if (Subtarget->is64Bit()) {
20529         if (VT == MVT::i32 || VT == MVT::f32)
20530           return std::make_pair(0U, &X86::GR32RegClass);
20531         if (VT == MVT::i16)
20532           return std::make_pair(0U, &X86::GR16RegClass);
20533         if (VT == MVT::i8 || VT == MVT::i1)
20534           return std::make_pair(0U, &X86::GR8RegClass);
20535         if (VT == MVT::i64 || VT == MVT::f64)
20536           return std::make_pair(0U, &X86::GR64RegClass);
20537         break;
20538       }
20539       // 32-bit fallthrough
20540     case 'Q':   // Q_REGS
20541       if (VT == MVT::i32 || VT == MVT::f32)
20542         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20543       if (VT == MVT::i16)
20544         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20545       if (VT == MVT::i8 || VT == MVT::i1)
20546         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20547       if (VT == MVT::i64)
20548         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20549       break;
20550     case 'r':   // GENERAL_REGS
20551     case 'l':   // INDEX_REGS
20552       if (VT == MVT::i8 || VT == MVT::i1)
20553         return std::make_pair(0U, &X86::GR8RegClass);
20554       if (VT == MVT::i16)
20555         return std::make_pair(0U, &X86::GR16RegClass);
20556       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20557         return std::make_pair(0U, &X86::GR32RegClass);
20558       return std::make_pair(0U, &X86::GR64RegClass);
20559     case 'R':   // LEGACY_REGS
20560       if (VT == MVT::i8 || VT == MVT::i1)
20561         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20562       if (VT == MVT::i16)
20563         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20564       if (VT == MVT::i32 || !Subtarget->is64Bit())
20565         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20566       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20567     case 'f':  // FP Stack registers.
20568       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20569       // value to the correct fpstack register class.
20570       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20571         return std::make_pair(0U, &X86::RFP32RegClass);
20572       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20573         return std::make_pair(0U, &X86::RFP64RegClass);
20574       return std::make_pair(0U, &X86::RFP80RegClass);
20575     case 'y':   // MMX_REGS if MMX allowed.
20576       if (!Subtarget->hasMMX()) break;
20577       return std::make_pair(0U, &X86::VR64RegClass);
20578     case 'Y':   // SSE_REGS if SSE2 allowed
20579       if (!Subtarget->hasSSE2()) break;
20580       // FALL THROUGH.
20581     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20582       if (!Subtarget->hasSSE1()) break;
20583
20584       switch (VT.SimpleTy) {
20585       default: break;
20586       // Scalar SSE types.
20587       case MVT::f32:
20588       case MVT::i32:
20589         return std::make_pair(0U, &X86::FR32RegClass);
20590       case MVT::f64:
20591       case MVT::i64:
20592         return std::make_pair(0U, &X86::FR64RegClass);
20593       // Vector types.
20594       case MVT::v16i8:
20595       case MVT::v8i16:
20596       case MVT::v4i32:
20597       case MVT::v2i64:
20598       case MVT::v4f32:
20599       case MVT::v2f64:
20600         return std::make_pair(0U, &X86::VR128RegClass);
20601       // AVX types.
20602       case MVT::v32i8:
20603       case MVT::v16i16:
20604       case MVT::v8i32:
20605       case MVT::v4i64:
20606       case MVT::v8f32:
20607       case MVT::v4f64:
20608         return std::make_pair(0U, &X86::VR256RegClass);
20609       case MVT::v8f64:
20610       case MVT::v16f32:
20611       case MVT::v16i32:
20612       case MVT::v8i64:
20613         return std::make_pair(0U, &X86::VR512RegClass);
20614       }
20615       break;
20616     }
20617   }
20618
20619   // Use the default implementation in TargetLowering to convert the register
20620   // constraint into a member of a register class.
20621   std::pair<unsigned, const TargetRegisterClass*> Res;
20622   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20623
20624   // Not found as a standard register?
20625   if (Res.second == 0) {
20626     // Map st(0) -> st(7) -> ST0
20627     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20628         tolower(Constraint[1]) == 's' &&
20629         tolower(Constraint[2]) == 't' &&
20630         Constraint[3] == '(' &&
20631         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20632         Constraint[5] == ')' &&
20633         Constraint[6] == '}') {
20634
20635       Res.first = X86::ST0+Constraint[4]-'0';
20636       Res.second = &X86::RFP80RegClass;
20637       return Res;
20638     }
20639
20640     // GCC allows "st(0)" to be called just plain "st".
20641     if (StringRef("{st}").equals_lower(Constraint)) {
20642       Res.first = X86::ST0;
20643       Res.second = &X86::RFP80RegClass;
20644       return Res;
20645     }
20646
20647     // flags -> EFLAGS
20648     if (StringRef("{flags}").equals_lower(Constraint)) {
20649       Res.first = X86::EFLAGS;
20650       Res.second = &X86::CCRRegClass;
20651       return Res;
20652     }
20653
20654     // 'A' means EAX + EDX.
20655     if (Constraint == "A") {
20656       Res.first = X86::EAX;
20657       Res.second = &X86::GR32_ADRegClass;
20658       return Res;
20659     }
20660     return Res;
20661   }
20662
20663   // Otherwise, check to see if this is a register class of the wrong value
20664   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20665   // turn into {ax},{dx}.
20666   if (Res.second->hasType(VT))
20667     return Res;   // Correct type already, nothing to do.
20668
20669   // All of the single-register GCC register classes map their values onto
20670   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20671   // really want an 8-bit or 32-bit register, map to the appropriate register
20672   // class and return the appropriate register.
20673   if (Res.second == &X86::GR16RegClass) {
20674     if (VT == MVT::i8 || VT == MVT::i1) {
20675       unsigned DestReg = 0;
20676       switch (Res.first) {
20677       default: break;
20678       case X86::AX: DestReg = X86::AL; break;
20679       case X86::DX: DestReg = X86::DL; break;
20680       case X86::CX: DestReg = X86::CL; break;
20681       case X86::BX: DestReg = X86::BL; break;
20682       }
20683       if (DestReg) {
20684         Res.first = DestReg;
20685         Res.second = &X86::GR8RegClass;
20686       }
20687     } else if (VT == MVT::i32 || VT == MVT::f32) {
20688       unsigned DestReg = 0;
20689       switch (Res.first) {
20690       default: break;
20691       case X86::AX: DestReg = X86::EAX; break;
20692       case X86::DX: DestReg = X86::EDX; break;
20693       case X86::CX: DestReg = X86::ECX; break;
20694       case X86::BX: DestReg = X86::EBX; break;
20695       case X86::SI: DestReg = X86::ESI; break;
20696       case X86::DI: DestReg = X86::EDI; break;
20697       case X86::BP: DestReg = X86::EBP; break;
20698       case X86::SP: DestReg = X86::ESP; break;
20699       }
20700       if (DestReg) {
20701         Res.first = DestReg;
20702         Res.second = &X86::GR32RegClass;
20703       }
20704     } else if (VT == MVT::i64 || VT == MVT::f64) {
20705       unsigned DestReg = 0;
20706       switch (Res.first) {
20707       default: break;
20708       case X86::AX: DestReg = X86::RAX; break;
20709       case X86::DX: DestReg = X86::RDX; break;
20710       case X86::CX: DestReg = X86::RCX; break;
20711       case X86::BX: DestReg = X86::RBX; break;
20712       case X86::SI: DestReg = X86::RSI; break;
20713       case X86::DI: DestReg = X86::RDI; break;
20714       case X86::BP: DestReg = X86::RBP; break;
20715       case X86::SP: DestReg = X86::RSP; break;
20716       }
20717       if (DestReg) {
20718         Res.first = DestReg;
20719         Res.second = &X86::GR64RegClass;
20720       }
20721     }
20722   } else if (Res.second == &X86::FR32RegClass ||
20723              Res.second == &X86::FR64RegClass ||
20724              Res.second == &X86::VR128RegClass ||
20725              Res.second == &X86::VR256RegClass ||
20726              Res.second == &X86::FR32XRegClass ||
20727              Res.second == &X86::FR64XRegClass ||
20728              Res.second == &X86::VR128XRegClass ||
20729              Res.second == &X86::VR256XRegClass ||
20730              Res.second == &X86::VR512RegClass) {
20731     // Handle references to XMM physical registers that got mapped into the
20732     // wrong class.  This can happen with constraints like {xmm0} where the
20733     // target independent register mapper will just pick the first match it can
20734     // find, ignoring the required type.
20735
20736     if (VT == MVT::f32 || VT == MVT::i32)
20737       Res.second = &X86::FR32RegClass;
20738     else if (VT == MVT::f64 || VT == MVT::i64)
20739       Res.second = &X86::FR64RegClass;
20740     else if (X86::VR128RegClass.hasType(VT))
20741       Res.second = &X86::VR128RegClass;
20742     else if (X86::VR256RegClass.hasType(VT))
20743       Res.second = &X86::VR256RegClass;
20744     else if (X86::VR512RegClass.hasType(VT))
20745       Res.second = &X86::VR512RegClass;
20746   }
20747
20748   return Res;
20749 }